agentic-qe 3.15.11 → 3.15.12

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 (431) hide show
  1. package/.claude/hooks/aqe-hook.cjs +38 -2
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +149 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/cli/bundle.js +6 -6
  6. package/dist/cli/chunks/adapter-HL7MOCQN.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-TIDSQ3ZK.js → agent-booster-wasm-5VZCKTIJ.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-G3EPBVA7.js → agent-handler-K3C6CQCD.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-ARC5C7GW.js → agent-memory-branch-NVFQ25WS.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-OZ2DXB4G.js +2 -0
  11. package/dist/cli/chunks/{arena-K4I4QDXB.js → arena-QGWIJADQ.js} +2 -2
  12. package/dist/cli/chunks/{arena-36DTATJV.js → arena-TSZVDSXS.js} +4 -4
  13. package/dist/cli/chunks/{audit-WQSJSJZF.js → audit-KIEE2SHJ.js} +3 -3
  14. package/dist/cli/chunks/base-WIM7G3HC.js +2 -0
  15. package/dist/cli/chunks/{better-sqlite3-BB4K67MT.js → better-sqlite3-BNB32NW3.js} +2 -2
  16. package/dist/cli/chunks/{brain-handler-CU3GOIU3.js → brain-handler-MPC5SPYI.js} +3 -3
  17. package/dist/cli/chunks/{branch-enumerator-NJQX7ZNB.js → branch-enumerator-LZ7UXKAY.js} +2 -2
  18. package/dist/cli/chunks/{browser-6YJF4FQW.js → browser-VDHAW4RK.js} +2 -2
  19. package/dist/cli/chunks/browser-workflow-QRKCFVR3.js +2 -0
  20. package/dist/cli/chunks/{chunk-V7DA4HAK.js → chunk-23PQF7NN.js} +1 -1
  21. package/dist/cli/chunks/{chunk-IENZSO3K.js → chunk-26672ISV.js} +2 -2
  22. package/dist/cli/chunks/{chunk-OURITHFV.js → chunk-2ASQRBK2.js} +2 -2
  23. package/dist/cli/chunks/{chunk-VBK2YAYY.js → chunk-2E2QO44T.js} +2 -2
  24. package/dist/cli/chunks/{chunk-NT7JRHMH.js → chunk-2IVE5AR3.js} +1 -1
  25. package/dist/cli/chunks/{chunk-672XOJDG.js → chunk-2JYUA27M.js} +1 -1
  26. package/dist/cli/chunks/{chunk-OHR7C777.js → chunk-2PPSS4JD.js} +2 -2
  27. package/dist/cli/chunks/{chunk-FUYOOKTH.js → chunk-32UTHIY5.js} +3 -3
  28. package/dist/cli/chunks/{chunk-UKKYMW3S.js → chunk-33I2ZP6E.js} +2 -2
  29. package/dist/cli/chunks/{chunk-76SNL7GU.js → chunk-35MIUSXQ.js} +2 -2
  30. package/dist/cli/chunks/{chunk-4X4MWMHB.js → chunk-35NW676P.js} +2 -2
  31. package/dist/cli/chunks/{chunk-BZPE3LDO.js → chunk-3EWQN37E.js} +2 -2
  32. package/dist/cli/chunks/{chunk-5N25I53C.js → chunk-3IU4LDZR.js} +2 -2
  33. package/dist/cli/chunks/{chunk-NKTWKYHB.js → chunk-47RMGDG4.js} +2 -2
  34. package/dist/cli/chunks/chunk-4A76VPU4.js +3 -0
  35. package/dist/cli/chunks/{chunk-4RH5I24Q.js → chunk-4CB3QPZM.js} +2 -2
  36. package/dist/cli/chunks/{chunk-U3LJNNVJ.js → chunk-4HWUECVD.js} +2 -2
  37. package/dist/cli/chunks/{chunk-T5KHJ3J7.js → chunk-4KUOYDY2.js} +2 -2
  38. package/dist/cli/chunks/{chunk-XNLIWQYE.js → chunk-4LWMAAWK.js} +2 -2
  39. package/dist/cli/chunks/{chunk-KKYO2NKV.js → chunk-4PU5GTZW.js} +2 -2
  40. package/dist/cli/chunks/{chunk-VWUZSNVC.js → chunk-4SA7M34P.js} +1 -1
  41. package/dist/cli/chunks/{chunk-5WYZHDIZ.js → chunk-4Y6OEBJZ.js} +1 -1
  42. package/dist/cli/chunks/{chunk-J4JMCZVA.js → chunk-5A66EGEW.js} +2 -2
  43. package/dist/cli/chunks/{chunk-HFFPYC4G.js → chunk-5ADXFUMO.js} +2 -2
  44. package/dist/cli/chunks/{chunk-KJCIMNHS.js → chunk-5S4UIDFK.js} +1 -1
  45. package/dist/cli/chunks/{chunk-YBBT3YYG.js → chunk-5TAEW5OV.js} +1 -1
  46. package/dist/cli/chunks/{chunk-FLU5FDSC.js → chunk-5Z23ZMXZ.js} +59 -59
  47. package/dist/cli/chunks/{chunk-YNOCQ2SL.js → chunk-65TH6RPD.js} +1 -1
  48. package/dist/cli/chunks/{chunk-XGPTZUKQ.js → chunk-66PXR3NI.js} +2 -2
  49. package/dist/cli/chunks/{chunk-ITPGWGQS.js → chunk-6E6HB4N4.js} +4 -4
  50. package/dist/cli/chunks/{chunk-EJPK7OTR.js → chunk-6QRI3JVE.js} +2 -2
  51. package/dist/cli/chunks/{chunk-ZP75ASUU.js → chunk-7DNR4KKR.js} +1 -1
  52. package/dist/cli/chunks/{chunk-V5AADCBC.js → chunk-7JFDLL2F.js} +1 -1
  53. package/dist/cli/chunks/chunk-7OEFBWAG.js +5 -0
  54. package/dist/cli/chunks/{chunk-EIDJNT5C.js → chunk-7QEUHNKO.js} +1 -1
  55. package/dist/cli/chunks/{chunk-7R5HC56U.js → chunk-7TA5MUPW.js} +1 -1
  56. package/dist/cli/chunks/{chunk-LCVEEII4.js → chunk-A2JCRXTK.js} +2 -2
  57. package/dist/cli/chunks/{chunk-JUMICXM6.js → chunk-A5Y7DAVQ.js} +2 -2
  58. package/dist/cli/chunks/{chunk-FZHSG75I.js → chunk-ADUAJIAU.js} +2 -2
  59. package/dist/cli/chunks/{chunk-TFW7CCKS.js → chunk-AJEXPFAB.js} +1 -1
  60. package/dist/cli/chunks/{chunk-JGJXXAS6.js → chunk-BC4T6SCV.js} +4 -4
  61. package/dist/cli/chunks/{chunk-4RAQ7PJA.js → chunk-BMG2JLSQ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-Y7B5EUIJ.js → chunk-BOSMELJX.js} +2 -2
  63. package/dist/cli/chunks/{chunk-CIAL4YRY.js → chunk-BYRCB5JT.js} +2 -2
  64. package/dist/cli/chunks/{chunk-XS2XF3YG.js → chunk-C3YOVASQ.js} +1 -1
  65. package/dist/cli/chunks/{chunk-FL32MTKT.js → chunk-C74M4WUI.js} +2 -2
  66. package/dist/cli/chunks/{chunk-S6IYEBAI.js → chunk-CA5UNWQF.js} +2 -2
  67. package/dist/cli/chunks/{chunk-5MTWCCZJ.js → chunk-CDA5Z74H.js} +2 -2
  68. package/dist/cli/chunks/{chunk-DOFREOPQ.js → chunk-CPIBIR3X.js} +2 -2
  69. package/dist/cli/chunks/{chunk-UMVSWQNB.js → chunk-CU36D7TN.js} +2 -2
  70. package/dist/cli/chunks/{chunk-G4CKPWF6.js → chunk-DAUEK66C.js} +1 -1
  71. package/dist/cli/chunks/{chunk-2KFFEKSI.js → chunk-DRCBRUGN.js} +2 -2
  72. package/dist/cli/chunks/{chunk-EH2S6AOR.js → chunk-DZGPUGUG.js} +2 -2
  73. package/dist/cli/chunks/{chunk-HYXUN7BW.js → chunk-EF6OERRR.js} +1 -1
  74. package/dist/cli/chunks/{chunk-G77MLBDF.js → chunk-EN7GRVEQ.js} +2 -2
  75. package/dist/cli/chunks/{chunk-XDI5X3FR.js → chunk-ENGL7FIJ.js} +1 -1
  76. package/dist/cli/chunks/{chunk-HDNWSKHA.js → chunk-FAGKBOX2.js} +2 -2
  77. package/dist/cli/chunks/{chunk-FWSGPE3V.js → chunk-FNUFTWEO.js} +3 -3
  78. package/dist/cli/chunks/{chunk-AUUJBXWX.js → chunk-FZJCBSN4.js} +2 -2
  79. package/dist/cli/chunks/{chunk-ERN43HOX.js → chunk-G24SWTAX.js} +35 -35
  80. package/dist/cli/chunks/{chunk-VEEYL2CZ.js → chunk-G3AABG4Q.js} +2 -2
  81. package/dist/cli/chunks/{chunk-35M2X3C5.js → chunk-GJKZ7UQO.js} +2 -2
  82. package/dist/cli/chunks/{chunk-OV5RPLKV.js → chunk-GKFV6CUD.js} +2 -2
  83. package/dist/cli/chunks/{chunk-4HJKQIX5.js → chunk-HLGFHHWV.js} +2 -2
  84. package/dist/cli/chunks/{chunk-R5LGV6GZ.js → chunk-HM3LSFTY.js} +2 -2
  85. package/dist/cli/chunks/{chunk-M7XFBSIK.js → chunk-HSA5IGGW.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GWJWSLDA.js → chunk-HZBXJFGN.js} +2 -2
  87. package/dist/cli/chunks/{chunk-4MUBW4RT.js → chunk-IA55PFLG.js} +2 -2
  88. package/dist/cli/chunks/{chunk-RBZCA7SD.js → chunk-ICKUINKD.js} +2 -2
  89. package/dist/cli/chunks/{chunk-KDI5JOYZ.js → chunk-IETBWYHW.js} +2 -2
  90. package/dist/cli/chunks/{chunk-325QCVDI.js → chunk-IL7GQNNE.js} +2 -2
  91. package/dist/cli/chunks/{chunk-BTVWA35P.js → chunk-INZARYUD.js} +2 -2
  92. package/dist/cli/chunks/{chunk-G2IJFNZS.js → chunk-IPA7K556.js} +2 -2
  93. package/dist/cli/chunks/{chunk-UTTSH4NH.js → chunk-IVTQF55W.js} +3 -3
  94. package/dist/cli/chunks/{chunk-2CW7VRPH.js → chunk-J7Y7ZBIT.js} +5 -5
  95. package/dist/cli/chunks/{chunk-M5RQ6U3G.js → chunk-JGIJPDGD.js} +2 -2
  96. package/dist/cli/chunks/{chunk-RQMCZQN2.js → chunk-JNXK47OL.js} +2 -2
  97. package/dist/cli/chunks/{chunk-X4J73KP3.js → chunk-JOWUS2X5.js} +1 -1
  98. package/dist/cli/chunks/{chunk-ZMC543GI.js → chunk-JR6CUKAI.js} +2 -2
  99. package/dist/cli/chunks/chunk-JRYWLOBD.js +21 -0
  100. package/dist/cli/chunks/{chunk-ETVAYGCB.js → chunk-JW5PDJ5O.js} +3 -3
  101. package/dist/cli/chunks/{chunk-OD5D4LSZ.js → chunk-K3A3NWT3.js} +2 -2
  102. package/dist/cli/chunks/{chunk-LPU6PAJE.js → chunk-KA5SHLMW.js} +2 -2
  103. package/dist/cli/chunks/{chunk-NPZOBSAN.js → chunk-KGA7VAI4.js} +2 -2
  104. package/dist/cli/chunks/{chunk-ZMHCMJ4J.js → chunk-KJDI5CHX.js} +2 -2
  105. package/dist/cli/chunks/{chunk-KSLLHFVY.js → chunk-L3PV7VXK.js} +1 -1
  106. package/dist/cli/chunks/{chunk-LD5CFK53.js → chunk-L7NGKANW.js} +2 -2
  107. package/dist/cli/chunks/{chunk-6NA3KZZT.js → chunk-LFBA735S.js} +7 -7
  108. package/dist/cli/chunks/{chunk-Z2EA7A4Z.js → chunk-MAJXZYGK.js} +1 -1
  109. package/dist/cli/chunks/{chunk-TCYSBC7Y.js → chunk-MCPEC6OO.js} +1 -1
  110. package/dist/cli/chunks/{chunk-LBX7M4LW.js → chunk-MCPXNUDK.js} +2 -2
  111. package/dist/cli/chunks/{chunk-5YLOLACR.js → chunk-MMEALJ4D.js} +2 -2
  112. package/dist/cli/chunks/{chunk-IOZRKXR5.js → chunk-MYF5CNGV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-X3PZCXWG.js → chunk-MYUMJ2ZI.js} +1 -1
  114. package/dist/cli/chunks/{chunk-VYTILW4R.js → chunk-N7O3PF6Y.js} +2 -2
  115. package/dist/cli/chunks/{chunk-GVKVJJQX.js → chunk-NA3F6FEO.js} +2 -2
  116. package/dist/cli/chunks/{chunk-TL6OFMXF.js → chunk-NNBQZR73.js} +2 -2
  117. package/dist/cli/chunks/{chunk-KXS3Y2AX.js → chunk-NV74SICL.js} +2 -2
  118. package/dist/cli/chunks/chunk-NVRYELCY.js +13 -0
  119. package/dist/cli/chunks/{chunk-OH5V5EJW.js → chunk-NX4BCSOZ.js} +2 -2
  120. package/dist/cli/chunks/{chunk-XJKZ7FTR.js → chunk-O3IM4WRZ.js} +2 -2
  121. package/dist/cli/chunks/{chunk-3RHOPP7A.js → chunk-O4QJMANM.js} +1 -1
  122. package/dist/cli/chunks/{chunk-O4JAKWWM.js → chunk-OHVYINGM.js} +17 -17
  123. package/dist/cli/chunks/{chunk-APPZATXA.js → chunk-P5E26N2X.js} +2 -2
  124. package/dist/cli/chunks/{chunk-5ERFHEEE.js → chunk-P7UFJ6DO.js} +1 -1
  125. package/dist/cli/chunks/{chunk-5MNASJOH.js → chunk-PGSJBXTD.js} +2 -2
  126. package/dist/cli/chunks/{chunk-WCAVIJ64.js → chunk-PT2NXS43.js} +1 -1
  127. package/dist/cli/chunks/{chunk-EWPUQCN4.js → chunk-PTBOLBM4.js} +2 -2
  128. package/dist/cli/chunks/{chunk-EK5GMOSO.js → chunk-PX5OPXY6.js} +1 -1
  129. package/dist/cli/chunks/chunk-QCPVUNN3.js +2 -0
  130. package/dist/cli/chunks/{chunk-K2HBNYAZ.js → chunk-QSGEBCDB.js} +2 -2
  131. package/dist/cli/chunks/{chunk-G4FAPO57.js → chunk-QUJJYTJH.js} +2 -2
  132. package/dist/cli/chunks/{chunk-H7BLYMNU.js → chunk-QWG3SILX.js} +3 -3
  133. package/dist/cli/chunks/{chunk-LXQ3B4RY.js → chunk-RCOLPF3B.js} +2 -2
  134. package/dist/cli/chunks/{chunk-E44NNCEU.js → chunk-RYHG3I7J.js} +2 -2
  135. package/dist/cli/chunks/{chunk-RTFKTKSO.js → chunk-SBHM5X2S.js} +2 -2
  136. package/dist/cli/chunks/{chunk-DOBZPSKE.js → chunk-SDRJJUPO.js} +1 -1
  137. package/dist/cli/chunks/{chunk-RTY7VSZB.js → chunk-SG2TX72G.js} +2 -2
  138. package/dist/cli/chunks/{chunk-NTB342NJ.js → chunk-SITL5YZV.js} +4 -4
  139. package/dist/cli/chunks/{chunk-WM3SRRA6.js → chunk-SPC4RBLF.js} +2 -2
  140. package/dist/cli/chunks/{chunk-ITL3IN2E.js → chunk-SQVZ3TRU.js} +2 -2
  141. package/dist/cli/chunks/{chunk-CO3DX2AX.js → chunk-SUX5XB2Z.js} +2 -2
  142. package/dist/cli/chunks/{chunk-KSE5TDM5.js → chunk-T4EN5VVK.js} +2 -2
  143. package/dist/cli/chunks/{chunk-5HQP4SLM.js → chunk-TGMXUZZC.js} +2 -2
  144. package/dist/cli/chunks/{chunk-YOCULVHR.js → chunk-TLRHAMX5.js} +1 -1
  145. package/dist/cli/chunks/{chunk-GBFUANTC.js → chunk-TOWOJGEI.js} +1 -1
  146. package/dist/cli/chunks/{chunk-4UBVAJFO.js → chunk-TSOQ2QLT.js} +2 -2
  147. package/dist/cli/chunks/{chunk-SMVVAVN2.js → chunk-TVA5GRIU.js} +2 -2
  148. package/dist/cli/chunks/{chunk-K7V2WZNF.js → chunk-TXEUVUMO.js} +1 -1
  149. package/dist/cli/chunks/{chunk-LQ4NUC6Q.js → chunk-U6IXYQO4.js} +2 -2
  150. package/dist/cli/chunks/{chunk-HDJUYAZG.js → chunk-U7ZHDGXG.js} +1 -1
  151. package/dist/cli/chunks/{chunk-2VLYUF7U.js → chunk-UCSK2RMI.js} +2 -2
  152. package/dist/cli/chunks/{chunk-4UX35V7P.js → chunk-UIKQPO4Y.js} +2 -2
  153. package/dist/cli/chunks/chunk-UJNGGFGX.js +2 -0
  154. package/dist/cli/chunks/{chunk-AFFN6E6Q.js → chunk-ULCW6IVQ.js} +2 -2
  155. package/dist/cli/chunks/{chunk-WCVCOT4E.js → chunk-UREDS662.js} +2 -2
  156. package/dist/cli/chunks/{chunk-E6PF35JZ.js → chunk-URSTP3WI.js} +2 -2
  157. package/dist/cli/chunks/{chunk-I36CRDHF.js → chunk-UUZZXHUF.js} +2 -2
  158. package/dist/cli/chunks/{chunk-MIK4RBEH.js → chunk-UZED4YZ5.js} +1 -1
  159. package/dist/cli/chunks/{chunk-ZQHDA4O7.js → chunk-VF7FTD64.js} +1 -1
  160. package/dist/cli/chunks/{chunk-AMZKAJLJ.js → chunk-VUR5THML.js} +2 -2
  161. package/dist/cli/chunks/{chunk-H43AFUKL.js → chunk-VXVTFKRA.js} +2 -2
  162. package/dist/cli/chunks/chunk-VZBC6DP7.js +2 -0
  163. package/dist/cli/chunks/{chunk-DDEOZPWJ.js → chunk-W4II6SIH.js} +2 -2
  164. package/dist/cli/chunks/{chunk-55CH76ZO.js → chunk-W5HQIYQU.js} +3 -3
  165. package/dist/cli/chunks/{chunk-YPX2TV3M.js → chunk-W7H55PY4.js} +1 -1
  166. package/dist/cli/chunks/{chunk-CFWGGRE7.js → chunk-WDEXOLK2.js} +1 -1
  167. package/dist/cli/chunks/{chunk-XGBU3KEM.js → chunk-WGTEZT7G.js} +2 -2
  168. package/dist/cli/chunks/{chunk-NC6K7SCQ.js → chunk-WLRU6ESI.js} +2 -2
  169. package/dist/cli/chunks/{chunk-JFLU7L3W.js → chunk-WTAUF6O4.js} +2 -2
  170. package/dist/cli/chunks/chunk-XCNSGSKV.js +3 -0
  171. package/dist/cli/chunks/{chunk-57LNKSW7.js → chunk-XZOYKB22.js} +2 -2
  172. package/dist/cli/chunks/chunk-YIDAXOUX.js +8 -0
  173. package/dist/cli/chunks/{chunk-25P77WA5.js → chunk-YLKIXEPP.js} +1 -1
  174. package/dist/cli/chunks/{chunk-R5GRABPQ.js → chunk-YNVEDFPQ.js} +1 -1
  175. package/dist/cli/chunks/{chunk-NQZNMCZU.js → chunk-YUA6ZKKY.js} +2 -2
  176. package/dist/cli/chunks/{chunk-OYJC3YON.js → chunk-YVJEUX3I.js} +2 -2
  177. package/dist/cli/chunks/{chunk-QDESWOZP.js → chunk-YWWMNTBF.js} +2 -2
  178. package/dist/cli/chunks/{chunk-7HEMJHPP.js → chunk-ZGROHCOW.js} +1 -1
  179. package/dist/cli/chunks/{chunk-AP3ADWDK.js → chunk-ZPVGX4DI.js} +2 -2
  180. package/dist/cli/chunks/{chunk-M5XYIQYZ.js → chunk-ZROAMFX2.js} +2 -2
  181. package/dist/cli/chunks/{chunk-I4K2HTQU.js → chunk-ZYOYR3UR.js} +1 -1
  182. package/dist/cli/chunks/ci-BZNWW3I3.js +81 -0
  183. package/dist/cli/chunks/{ci-config-J665XNOX.js → ci-config-LOHNXOKV.js} +2 -2
  184. package/dist/cli/chunks/{ci-output-PEQQQWVD.js → ci-output-LCOQBSJL.js} +2 -2
  185. package/dist/cli/chunks/{circuit-breaker-HHB2JSKH.js → circuit-breaker-7LRXTLFE.js} +2 -2
  186. package/dist/cli/chunks/{claude-flow-setup-JKUJRWPN.js → claude-flow-setup-HBU4VWC3.js} +2 -2
  187. package/dist/cli/chunks/client-4PNYDFYS.js +2 -0
  188. package/dist/cli/chunks/{cline-installer-Y77BWTAN.js → cline-installer-CO6MLH6X.js} +2 -2
  189. package/dist/cli/chunks/{code-LV2HAGJY.js → code-SIXBS6JM.js} +3 -3
  190. package/dist/cli/chunks/{code-index-extractor-4GKKSETB.js → code-index-extractor-GWJKZ2IQ.js} +2 -2
  191. package/dist/cli/chunks/{codex-installer-WMKBYE5Y.js → codex-installer-6NINVWXJ.js} +2 -2
  192. package/dist/cli/chunks/{completions-SBGFAOIJ.js → completions-7VIX3GML.js} +2 -2
  193. package/dist/cli/chunks/{complexity-analyzer-AQHFIJXC.js → complexity-analyzer-FBQR6ZP2.js} +2 -2
  194. package/dist/cli/chunks/{continuedev-installer-26AYFS2E.js → continuedev-installer-VA7RIXW5.js} +2 -2
  195. package/dist/cli/chunks/{copilot-installer-4UD3DK55.js → copilot-installer-4QEBC4MU.js} +2 -2
  196. package/dist/cli/chunks/core-handlers-ODO6LUWQ.js +2 -0
  197. package/dist/cli/chunks/{cost-tracker-TP4NZCG4.js → cost-tracker-GRYKHPWL.js} +2 -2
  198. package/dist/cli/chunks/{coverage-B2KIXHAI.js → coverage-USPMNKOU.js} +11 -10
  199. package/dist/cli/chunks/cross-domain-router-DT4MHJKK.js +2 -0
  200. package/dist/cli/chunks/{cursor-installer-AVZEQZ4W.js → cursor-installer-ZXIPSZVH.js} +2 -2
  201. package/dist/cli/chunks/{daemon-XM2A7LQU.js → daemon-D7F3RGI5.js} +3 -3
  202. package/dist/cli/chunks/{daemon-P574WWBW.js → daemon-N2VRHPSJ.js} +4 -4
  203. package/dist/cli/chunks/{dag-attention-scheduler-MIWOZ6ET.js → dag-attention-scheduler-NL6BA7BY.js} +2 -2
  204. package/dist/cli/chunks/{detect-TYR7HT23.js → detect-XC2HCIIT.js} +2 -2
  205. package/dist/cli/chunks/{dist-node-2DGVQGLS.js → dist-node-A3Y26MEI.js} +2 -2
  206. package/dist/cli/chunks/{domain-handler-RRA4ZOMF.js → domain-handler-WV6SFXRB.js} +2 -2
  207. package/dist/cli/chunks/{domain-plugins-IVZEZ5RB.js → domain-plugins-KJIF6Z2B.js} +2 -2
  208. package/dist/cli/chunks/{domain-transfer-DOBI67K6.js → domain-transfer-L3F6AES2.js} +2 -2
  209. package/dist/cli/chunks/dream-QOB3JCOM.js +2 -0
  210. package/dist/cli/chunks/{embed-and-insert-pattern-VNIEOVPO.js → embed-and-insert-pattern-PA3Y4KGO.js} +2 -2
  211. package/dist/cli/chunks/{eval-QV4LVPUF.js → eval-YGEZNUVE.js} +2 -2
  212. package/dist/cli/chunks/{experience-capture-middleware-DAPKT763.js → experience-capture-middleware-D4T7NW6B.js} +3 -3
  213. package/dist/cli/chunks/{fast-paths-WVRFPHX7.js → fast-paths-6JYK7RYQ.js} +2 -2
  214. package/dist/cli/chunks/{feature-flags-O7ZXDDCD.js → feature-flags-DKXMDVPE.js} +2 -2
  215. package/dist/cli/chunks/{feature-flags-DEFTUIYT.js → feature-flags-RBH2GDSR.js} +2 -2
  216. package/dist/cli/chunks/file-discovery-BN76S2PR.js +2 -0
  217. package/dist/cli/chunks/fleet-43YMXACN.js +46 -0
  218. package/dist/cli/chunks/{gnn-wrapper-LS4LZJDR.js → gnn-wrapper-MV54UC4C.js} +2 -2
  219. package/dist/cli/chunks/{heartbeat-handler-RFTERD4K.js → heartbeat-handler-7DKMVQQH.js} +4 -4
  220. package/dist/cli/chunks/heartbeat-scheduler-3NNP4WCP.js +2 -0
  221. package/dist/cli/chunks/hnsw-adapter-MZR7Y4WF.js +2 -0
  222. package/dist/cli/chunks/hnsw-index-HE4AX22U.js +2 -0
  223. package/dist/cli/chunks/{hnsw-legacy-bridge-GPKGFFHY.js → hnsw-legacy-bridge-6IWREDQC.js} +2 -2
  224. package/dist/cli/chunks/{hnswlib-node-PHL3F2PR.js → hnswlib-node-5BIESSCK.js} +2 -2
  225. package/dist/cli/chunks/{hooks-GYJ6D4QM.js → hooks-3EETRM62.js} +28 -28
  226. package/dist/cli/chunks/hybrid-backend-IHUHB3Y2.js +2 -0
  227. package/dist/cli/chunks/{hypergraph-engine-YGEQPCKJ.js → hypergraph-engine-RSWCB2D3.js} +2 -2
  228. package/dist/cli/chunks/{hypergraph-handler-ZIMM647V.js → hypergraph-handler-552LXKL3.js} +3 -3
  229. package/dist/cli/chunks/impact-analyzer-FI6GI6PD.js +2 -0
  230. package/dist/cli/chunks/{init-guard-VOMBXJXG.js → init-guard-OTDBJ5HD.js} +2 -2
  231. package/dist/cli/chunks/{init-handler-PSMUBWK5.js → init-handler-3FK3TKEA.js} +6 -6
  232. package/dist/cli/chunks/init-wizard-WLQKH5Y5.js +2 -0
  233. package/dist/cli/chunks/kernel-2WZOQEZS.js +2 -0
  234. package/dist/cli/chunks/{kilocode-installer-2YNTFBWJ.js → kilocode-installer-KZ2O4LF3.js} +2 -2
  235. package/dist/cli/chunks/{kiro-installer-XHJDPVAZ.js → kiro-installer-MLCCXRF7.js} +2 -2
  236. package/dist/cli/chunks/knowledge-graph-G3LVKK6P.js +2 -0
  237. package/dist/cli/chunks/{learning-GNSIDRNG.js → learning-QUCMBD77.js} +3 -3
  238. package/dist/cli/chunks/{llm-router-LQDM7IU2.js → llm-router-PDEV3UP2.js} +4 -4
  239. package/dist/cli/chunks/llm-router-service-MM75HKWJ.js +2 -0
  240. package/dist/cli/chunks/{load-YATHI72E.js → load-XFVVLO7E.js} +2 -2
  241. package/dist/cli/chunks/load-test-BEWEE44J.js +2 -0
  242. package/dist/cli/chunks/{mcp-4Y6GDLYK.js → mcp-74G3CL2S.js} +2 -2
  243. package/dist/cli/chunks/{memory-OUW3L7H2.js → memory-XIFM6JNX.js} +5 -5
  244. package/dist/cli/chunks/memory-backend-NYKBBKZR.js +2 -0
  245. package/dist/cli/chunks/{memory-handlers-G3LFF53U.js → memory-handlers-ZCKURV6S.js} +2 -2
  246. package/dist/cli/chunks/{multi-model-executor-UBZJXAD2.js → multi-model-executor-7L4W3O2Q.js} +2 -2
  247. package/dist/cli/chunks/{opencode-installer-AMMNWVH5.js → opencode-installer-BPG422LF.js} +2 -2
  248. package/dist/cli/chunks/{orchestrator-Y44WDOER.js → orchestrator-OEAFLAEV.js} +58 -20
  249. package/dist/cli/chunks/pattern-null-store-QGPUIV6M.js +2 -0
  250. package/dist/cli/chunks/{pattern-usage-recorder-ESR42RME.js → pattern-usage-recorder-LOPNCULT.js} +2 -2
  251. package/dist/cli/chunks/{pipeline-EDTS6OSC.js → pipeline-VWTYUZB7.js} +2 -2
  252. package/dist/cli/chunks/{platform-5WONJSUX.js → platform-WFJJ3X2E.js} +2 -2
  253. package/dist/cli/chunks/{plugin-IJXPCLD4.js → plugin-744TPUSG.js} +2 -2
  254. package/dist/cli/chunks/{prime-radiant-advanced-wasm-5ECKGZK6.js → prime-radiant-advanced-wasm-BD5BLNDR.js} +2 -2
  255. package/dist/cli/chunks/project-root-C7ELXZRK.js +2 -0
  256. package/dist/cli/chunks/protocol-executor-SUVE33BM.js +2 -0
  257. package/dist/cli/chunks/{protocol-handler-DRD3GVNW.js → protocol-handler-JIBILI74.js} +2 -2
  258. package/dist/cli/chunks/{prove-KTGW2HMJ.js → prove-MNOL5FYW.js} +2 -2
  259. package/dist/cli/chunks/qe-reasoning-bank-YWZMMGJB.js +2 -0
  260. package/dist/cli/chunks/{quality-DV2WPRRS.js → quality-JEGBDGGX.js} +2 -2
  261. package/dist/cli/chunks/{quality-gate-HFUAFVZC.js → quality-gate-SYJ6ROMI.js} +3 -3
  262. package/dist/cli/chunks/queen-coordinator-ZFAKXRN7.js +2 -0
  263. package/dist/cli/chunks/real-embeddings-ZWXS5ZFV.js +2 -0
  264. package/dist/cli/chunks/{ref-validation-QWSKS5OY.js → ref-validation-RRHUFW2N.js} +2 -2
  265. package/dist/cli/chunks/{roocode-installer-RBAYRCHX.js → roocode-installer-XFO6JSVN.js} +2 -2
  266. package/dist/cli/chunks/router-4FTAVYLJ.js +2 -0
  267. package/dist/cli/chunks/routing-feedback-IO2KOWMJ.js +2 -0
  268. package/dist/cli/chunks/{routing-handler-FMPP3XKO.js → routing-handler-L2K3JASE.js} +2 -2
  269. package/dist/cli/chunks/{ruvector-commands-KZZT4HWF.js → ruvector-commands-A6CINHGM.js} +2 -2
  270. package/dist/cli/chunks/rvf-dual-writer-KCIRNE7C.js +2 -0
  271. package/dist/cli/chunks/rvf-migration-adapter-MFC5WTJU.js +2 -0
  272. package/dist/cli/chunks/{rvf-migration-coordinator-7CHEV35N.js → rvf-migration-coordinator-T4RY7L53.js} +2 -2
  273. package/dist/cli/chunks/rvf-native-adapter-I3KWHE7X.js +2 -0
  274. package/dist/cli/chunks/{rvf-store-integrity-Q2TH52SN.js → rvf-store-integrity-IR33TGQS.js} +2 -2
  275. package/dist/cli/chunks/safe-db-QXDZ6QY3.js +2 -0
  276. package/dist/cli/chunks/schedule-CZKD6RIY.js +2 -0
  277. package/dist/cli/chunks/scheduler-BLA3Q4CH.js +2 -0
  278. package/dist/cli/chunks/{security-CUEA3UIM.js → security-Z5GDE2IH.js} +3 -3
  279. package/dist/cli/chunks/{shared-rvf-adapter-DROMBRV2.js → shared-rvf-adapter-SIZMEHPM.js} +2 -2
  280. package/dist/cli/chunks/{shared-rvf-dual-writer-DBNABOP7.js → shared-rvf-dual-writer-HLM65RDS.js} +2 -2
  281. package/dist/cli/chunks/sqlite-persistence-XIUYDJC4.js +2 -0
  282. package/dist/cli/chunks/{standalone-memory-IAHA3M6B.js → standalone-memory-SKSZG7P5.js} +2 -2
  283. package/dist/cli/chunks/{status-handler-AFUCASTX.js → status-handler-766YOOMJ.js} +2 -2
  284. package/dist/cli/chunks/{structural-health-AQRV6JJ6.js → structural-health-M45FNOLT.js} +2 -2
  285. package/dist/cli/chunks/{sync-GX7FMJHL.js → sync-6CJ24B5T.js} +2 -2
  286. package/dist/cli/chunks/{sync-XW5TLZ7M.js → sync-B2U366I3.js} +2 -2
  287. package/dist/cli/chunks/{task-handler-TFKVUTNF.js → task-handler-P6IFLCKP.js} +17 -15
  288. package/dist/cli/chunks/task-handlers-DPWMUKFC.js +9 -0
  289. package/dist/cli/chunks/{test-D2XDJNDX.js → test-TODH7KRF.js} +4 -4
  290. package/dist/cli/chunks/test-runner-process-46IPK3GH.js +2 -0
  291. package/dist/cli/chunks/{test-scheduling-TS6I2PR7.js → test-scheduling-VMVMVRHT.js} +3 -3
  292. package/dist/cli/chunks/{token-bootstrap-HBBLPCZ3.js → token-bootstrap-XQW7BMCK.js} +2 -2
  293. package/dist/cli/chunks/{token-usage-3MBUX4PR.js → token-usage-JCZEIRKO.js} +2 -2
  294. package/dist/cli/chunks/{transformers-ZWMQO3L2.js → transformers-U2ML3OHE.js} +2 -2
  295. package/dist/cli/chunks/tree-sitter-wasm-parser-MOI2WWNJ.js +2 -0
  296. package/dist/cli/chunks/{types-5YEMGPSQ.js → types-GGEPCHP6.js} +2 -2
  297. package/dist/cli/chunks/unified-memory-FL26RTV3.js +2 -0
  298. package/dist/cli/chunks/unified-memory-hnsw-E2BPTH3U.js +2 -0
  299. package/dist/cli/chunks/unified-persistence-5ZOUPKHF.js +2 -0
  300. package/dist/cli/chunks/{upgrade-2TPBKIHI.js → upgrade-T5GRM7HS.js} +2 -2
  301. package/dist/cli/chunks/{validate-XRAXXFW6.js → validate-XMUJPLP3.js} +2 -2
  302. package/dist/cli/chunks/{validate-swarm-IYSCS3BZ.js → validate-swarm-KJLF7JEH.js} +2 -2
  303. package/dist/cli/chunks/visual-security-IJVPO5FA.js +2 -0
  304. package/dist/cli/chunks/{web-tree-sitter-PZQ3ZG2P.js → web-tree-sitter-LOHVZ7G5.js} +2 -2
  305. package/dist/cli/chunks/{windsurf-installer-U6XWFRVT.js → windsurf-installer-33FBTXJU.js} +2 -2
  306. package/dist/cli/chunks/witness-chain-5FAFCQKP.js +2 -0
  307. package/dist/cli/chunks/witness-chain-V2M32W5D.js +2 -0
  308. package/dist/cli/chunks/{witness-chain-repair-K7YX2AO6.js → witness-chain-repair-VWBO4NXE.js} +2 -2
  309. package/dist/cli/chunks/{witness-chain-verifier-GUTC3W7N.js → witness-chain-verifier-BHJ3ZAEK.js} +2 -2
  310. package/dist/cli/chunks/{witness-key-manager-YBNKMOP6.js → witness-key-manager-WNVPH2Z3.js} +2 -2
  311. package/dist/cli/chunks/{workflow-UAJUILFQ.js → workflow-6QR5MQTO.js} +4 -4
  312. package/dist/cli/chunks/workflow-orchestrator-3JLF3IX7.js +2 -0
  313. package/dist/cli/chunks/{wrappers-AVZ3GPAL.js → wrappers-EHOL62TS.js} +2 -2
  314. package/dist/cli/commands/ci.js +7 -0
  315. package/dist/cli/commands/coverage.js +7 -1
  316. package/dist/cli/commands/fleet.js +2 -2
  317. package/dist/cli/commands/hooks-handlers/stats-hooks.d.ts +4 -3
  318. package/dist/cli/commands/hooks-handlers/stats-hooks.js +22 -4
  319. package/dist/cli/handlers/task-handler.js +6 -0
  320. package/dist/cli/utils/coverage-verdict.d.ts +11 -2
  321. package/dist/cli/utils/coverage-verdict.js +26 -6
  322. package/dist/cli/utils/fleet-operation.d.ts +5 -0
  323. package/dist/cli/utils/fleet-operation.js +7 -1
  324. package/dist/cli/utils/fleet-result.d.ts +5 -3
  325. package/dist/cli/utils/fleet-result.js +9 -3
  326. package/dist/coordination/handlers/coverage-collection.d.ts +2 -0
  327. package/dist/coordination/handlers/coverage-collection.js +2 -1
  328. package/dist/coordination/handlers/coverage-evidence.d.ts +75 -0
  329. package/dist/coordination/handlers/coverage-evidence.js +159 -0
  330. package/dist/coordination/handlers/coverage-handlers.js +16 -3
  331. package/dist/coordination/handlers/coverage-scope.d.ts +40 -0
  332. package/dist/coordination/handlers/coverage-scope.js +321 -0
  333. package/dist/coordination/handlers/coverage-target.d.ts +9 -0
  334. package/dist/coordination/handlers/coverage-target.js +15 -5
  335. package/dist/coordination/handlers/handler-utils.d.ts +5 -0
  336. package/dist/coordination/handlers/handler-utils.js +8 -4
  337. package/dist/domains/code-intelligence/services/metric-collector/listing-process-owner.js +4 -1
  338. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +8 -0
  339. package/dist/domains/code-intelligence/services/semantic-analyzer.js +10 -7
  340. package/dist/init/phases/10-workers.js +42 -4
  341. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +23 -1
  342. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +50 -15
  343. package/dist/integrations/agentic-flow/reasoning-bank/index.d.ts +7 -2
  344. package/dist/integrations/agentic-flow/reasoning-bank/index.js +8 -0
  345. package/dist/learning/embedder-endpoint-client.d.ts +8 -0
  346. package/dist/learning/embedder-endpoint-client.js +20 -0
  347. package/dist/learning/embedder-recovery.d.ts +63 -0
  348. package/dist/learning/embedder-recovery.js +94 -0
  349. package/dist/learning/qe-reasoning-bank-types.d.ts +5 -0
  350. package/dist/learning/qe-reasoning-bank.d.ts +21 -0
  351. package/dist/learning/qe-reasoning-bank.js +54 -8
  352. package/dist/learning/real-embeddings.d.ts +23 -0
  353. package/dist/learning/real-embeddings.js +69 -2
  354. package/dist/learning/real-qe-reasoning-bank.d.ts +24 -4
  355. package/dist/learning/real-qe-reasoning-bank.js +58 -20
  356. package/dist/logging/redaction.js +142 -12
  357. package/dist/mcp/bundle.js +504 -492
  358. package/dist/mcp/daemon-mode.d.ts +126 -0
  359. package/dist/mcp/daemon-mode.js +257 -0
  360. package/dist/mcp/entry.d.ts +4 -0
  361. package/dist/mcp/entry.js +50 -2
  362. package/dist/mcp/handlers/domain-handler-configs.js +5 -0
  363. package/dist/mcp/handlers/orchestrate-routes.d.ts +6 -1
  364. package/dist/mcp/handlers/orchestrate-routes.js +53 -0
  365. package/dist/mcp/handlers/task-handlers.d.ts +11 -2
  366. package/dist/mcp/handlers/task-handlers.js +50 -5
  367. package/dist/mcp/protocol-server.js +3 -0
  368. package/dist/mcp/services/reasoning-bank-service.d.ts +6 -1
  369. package/dist/mcp/services/reasoning-bank-service.js +9 -0
  370. package/dist/mcp/types.d.ts +14 -0
  371. package/dist/routing/advisor/redaction.js +22 -2
  372. package/dist/shared/llm/providers/response-deadline.js +16 -2
  373. package/dist/shared/types/index.js +3 -1
  374. package/dist/strange-loop/infra-healing/infra-aware-agent-provider.js +8 -1
  375. package/package.json +3 -3
  376. package/dist/cli/chunks/adapter-V4GSGOOK.js +0 -2
  377. package/dist/cli/chunks/aqe-learning-engine-6WQTM5YR.js +0 -2
  378. package/dist/cli/chunks/base-AK7BXBX2.js +0 -2
  379. package/dist/cli/chunks/browser-workflow-VTDFBW7T.js +0 -2
  380. package/dist/cli/chunks/chunk-2DTX7YAZ.js +0 -6
  381. package/dist/cli/chunks/chunk-72ZBJD2E.js +0 -3
  382. package/dist/cli/chunks/chunk-EBPJY4DI.js +0 -3
  383. package/dist/cli/chunks/chunk-HJ3XNTTJ.js +0 -2
  384. package/dist/cli/chunks/chunk-IO5537OM.js +0 -2
  385. package/dist/cli/chunks/chunk-IW6WDGHM.js +0 -2
  386. package/dist/cli/chunks/chunk-LRL56ZYL.js +0 -21
  387. package/dist/cli/chunks/chunk-VLD7Z2ED.js +0 -13
  388. package/dist/cli/chunks/chunk-VO3DRK4P.js +0 -3
  389. package/dist/cli/chunks/ci-6GUFAZMJ.js +0 -81
  390. package/dist/cli/chunks/client-HL2COSFM.js +0 -2
  391. package/dist/cli/chunks/core-handlers-IX7ATLM6.js +0 -2
  392. package/dist/cli/chunks/cross-domain-router-YYKLAPJO.js +0 -2
  393. package/dist/cli/chunks/dream-T6EP7B3F.js +0 -2
  394. package/dist/cli/chunks/file-discovery-JYMVTDMU.js +0 -2
  395. package/dist/cli/chunks/fleet-FVAUMKUT.js +0 -46
  396. package/dist/cli/chunks/heartbeat-scheduler-4N5MUJ7S.js +0 -2
  397. package/dist/cli/chunks/hnsw-adapter-ZPAJDSLR.js +0 -2
  398. package/dist/cli/chunks/hnsw-index-4CTH6RHB.js +0 -2
  399. package/dist/cli/chunks/hybrid-backend-AW6UTXQS.js +0 -2
  400. package/dist/cli/chunks/impact-analyzer-MZK3JMSV.js +0 -2
  401. package/dist/cli/chunks/init-wizard-FUC7KDVX.js +0 -2
  402. package/dist/cli/chunks/kernel-ZCPMCVMW.js +0 -2
  403. package/dist/cli/chunks/knowledge-graph-NUJKEDNF.js +0 -2
  404. package/dist/cli/chunks/llm-router-service-B2BFBQ76.js +0 -2
  405. package/dist/cli/chunks/load-test-ZHQ2MUGO.js +0 -2
  406. package/dist/cli/chunks/memory-backend-AAMQG6WH.js +0 -2
  407. package/dist/cli/chunks/pattern-null-store-RFNVA46O.js +0 -2
  408. package/dist/cli/chunks/project-root-7QL4KP5C.js +0 -2
  409. package/dist/cli/chunks/protocol-executor-2NW5BD4R.js +0 -2
  410. package/dist/cli/chunks/qe-reasoning-bank-G2JZOGKD.js +0 -2
  411. package/dist/cli/chunks/queen-coordinator-GRG5FT2A.js +0 -2
  412. package/dist/cli/chunks/real-embeddings-RQRVOKVM.js +0 -2
  413. package/dist/cli/chunks/router-LQB5SWAF.js +0 -2
  414. package/dist/cli/chunks/routing-feedback-OEEXA55N.js +0 -2
  415. package/dist/cli/chunks/rvf-dual-writer-BZK4M7BO.js +0 -2
  416. package/dist/cli/chunks/rvf-migration-adapter-EZZUJL2E.js +0 -2
  417. package/dist/cli/chunks/rvf-native-adapter-6COXTQZ3.js +0 -2
  418. package/dist/cli/chunks/safe-db-PE6G3L55.js +0 -2
  419. package/dist/cli/chunks/schedule-OLKQ6QYW.js +0 -2
  420. package/dist/cli/chunks/scheduler-LSGBDFAT.js +0 -2
  421. package/dist/cli/chunks/sqlite-persistence-HH4DNTYH.js +0 -2
  422. package/dist/cli/chunks/task-handlers-SS4ZDXNF.js +0 -9
  423. package/dist/cli/chunks/test-runner-process-PSSBNNGR.js +0 -2
  424. package/dist/cli/chunks/tree-sitter-wasm-parser-TYRQRJ2W.js +0 -2
  425. package/dist/cli/chunks/unified-memory-AGDZQ5XD.js +0 -2
  426. package/dist/cli/chunks/unified-memory-hnsw-X5TJ3JDE.js +0 -2
  427. package/dist/cli/chunks/unified-persistence-UCV7YETW.js +0 -2
  428. package/dist/cli/chunks/visual-security-ZLXRIQZV.js +0 -2
  429. package/dist/cli/chunks/witness-chain-CVIWYTD2.js +0 -2
  430. package/dist/cli/chunks/witness-chain-VBKORKOX.js +0 -2
  431. package/dist/cli/chunks/workflow-orchestrator-3ZN7MVCE.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.11");process.exit(0)}
2
- import{a as I,b as _,c as X,d as M,f as ie}from"./chunk-NTB342NJ.js";import{a as K,e as Z}from"./chunk-JGJXXAS6.js";import{c as ee,d as te,e as re,f as ne}from"./chunk-35M2X3C5.js";import{b as D,g as $,j as H}from"./chunk-7HEMJHPP.js";import{b as k}from"./chunk-CO3DX2AX.js";import{c as Y,i as J}from"./chunk-AUUJBXWX.js";import{r as U,v as be}from"./chunk-LD5CFK53.js";import{p as T}from"./chunk-VLD7Z2ED.js";import{c as C,d as E}from"./chunk-IW6WDGHM.js";import{a as G}from"./chunk-IO5537OM.js";import{c as A}from"./chunk-FZHSG75I.js";import{S as ye,b as j}from"./chunk-76SNL7GU.js";import{a as f,b as B,e as z}from"./chunk-DDEOZPWJ.js";G();z();function ae(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:m}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:m,capped:o.length>s}}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.15.12");process.exit(0)}
2
+ import{a as I,b as _,c as X,d as M,f as ee,h as ae}from"./chunk-SITL5YZV.js";import{a as K,e as Z}from"./chunk-BC4T6SCV.js";import{c as te,d as re,e as ne,f as ie}from"./chunk-GJKZ7UQO.js";import{b as D,g as $,j as H}from"./chunk-ZGROHCOW.js";import{b as k}from"./chunk-SUX5XB2Z.js";import{c as Y,i as J}from"./chunk-FZJCBSN4.js";import{r as U,v as ve}from"./chunk-L7NGKANW.js";import{s as T}from"./chunk-NVRYELCY.js";import{c as C,d as E}from"./chunk-VZBC6DP7.js";import{a as G}from"./chunk-UJNGGFGX.js";import{c as A}from"./chunk-ADUAJIAU.js";import{S as ye,b as j}from"./chunk-35MIUSXQ.js";import{a as f,b as B,e as z}from"./chunk-W4II6SIH.js";G();z();function oe(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:g}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:g,capped:o.length>s}}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
@@ -278,7 +278,7 @@ On promotion:
278
278
  - Move from short-term to long-term tier
279
279
  - Boost confidence by 10%
280
280
  - Enable for cross-domain transfer to related domains
281
- - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as oe}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},ve=.4,Pe=20,Re=3;function Se(i){return 1/(1+Math.exp(-i))}function we(i,e){if(!e||e.visits===0)return{score:i,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/Pe,1)*ve,t=Se(e.qValue);return{score:i*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function se(i){let e=i.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,n=i.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*n,0),1),baseEpsilon:t,safetyMultiplier:n}}function ce(i,e){if(e<=0||i.length<2)return;let r=Math.round(e*1e6);if(r<=0||oe(0,1e6)>=r)return;let t=Math.min(4,i.length),n=oe(1,t),a=i[n];i[n]=i[0],i[0]=a,i[0].exploration=!0,i[0].reasoning=[...i[0].reasoning,"(exploration)"]}function le(i){let e=i.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function ue(i){return`${i.taskType}|${i.priority??"normal"}|${i.domain??"any"}`}function O(i,e,r,t,n=x,a,o){let s=[];for(let[l,u]of Object.entries(n)){let c=0,m=[],d=i.filter(y=>u.domains.includes(y)).length,h=Math.min(i.length,Re),b=d>0?Math.min(d/h,1)*.4:0;if(c+=b*t.similarity,b>0&&m.push(`Domain match: ${(b*100).toFixed(0)}%`),e&&e.length>0){let y=e.filter(v=>u.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,p=y>0?y/e.length*.3:0;c+=p*t.capabilities,p>0&&m.push(`Capability match: ${(p*100).toFixed(0)}%`)}else c+=.15*t.capabilities;if(c+=u.performanceScore*.3*t.performance,m.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),a&&u.languages&&u.languages.length>0){let y=t.language??1,p=a.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===p)){let P=.15*y;c+=P,m.push(`Language match: ${a}`)}}let S=r.get(l)||0;if(S>0){let y=Math.min(.1,S*.02);c+=y,m.push(`Pattern matches: ${S}`)}let w=c;if(o){let y=o(l),p=we(w,y);c=p.score,p.qWeight>0&&m.push(`Q-bonus (w=${p.qWeight.toFixed(2)}, v=${p.qVisits})`),s.push({agent:l,score:c,reasoning:m,staticScore:w,qWeight:p.qWeight,qValue:p.qValue,qVisits:p.qVisits})}else s.push({agent:l,score:c,reasoning:m,staticScore:w})}return s.sort((l,u)=>u.score-l.score),s}var Q={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","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"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function de(){try{return!ne()||!re()||ee().getVerticesByType("agent").length===0?!1:te().isCritical()}catch{return!1}}be();function pe(i,e){if(i.length===e)return i;if(i.length>e){let r=i.length/e,t=new Array(e).fill(0);for(let n=0;n<e;n++){let a=Math.floor(n*r),o=Math.floor((n+1)*r),s=0;for(let l=a;l<o;l++)s+=i[l];t[n]=s/(o-a)}return F(t)}else{let r=new Array(e).fill(0),t=(i.length-1)/(e-1);for(let n=0;n<e;n++){let a=n*t,o=Math.floor(a),s=Math.min(o+1,i.length-1),l=a-o;r[n]=i[o]*(1-l)+i[s]*l}return F(r)}}function me(i,e){let r=new Array(e).fill(0),t=i.toLowerCase().trim();for(let n=0;n<3;n++)for(let a=0;a<t.length;a++){let o=t.charCodeAt(a),s=o*(a+1)*(n+1)%e;r[s]+=Math.sin(o*(n+1))/(a+1)}return F(r)}function F(i){let e=Math.sqrt(i.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<i.length;r++)i[r]/=e;return i}G();z();ye();var R=A.create("PatternPromotion");async function ge(i,e){let r=$(i);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),o=[...t.success?t.value.map(l=>l.pattern):[],i].map(l=>({id:l.id,embedding:l.embedding||[],weight:l.confidence,metadata:{name:l.name,domain:l.qeDomain}})),s=await e.coherenceService.checkCoherence(o);if(s.energy>=e.coherenceThreshold){let l={patternId:i.id,patternName:i.name,reason:"coherence_violation",energy:s.energy,existingPatternConflicts:s.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${i.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:l}),R.info("Pattern promotion blocked due to coherence violation",{name:i.name,energy:s.energy}),!1}}return!0}async function V(i,e){let r=await e.patternStore.promote(i);if(r.success){try{e.getSqliteStore().promotePattern(i)}catch(t){R.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(j().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let n=new L(t),a=await e.getPattern(i);if(a){let o=await e.searchPatterns("",{domain:a.qeDomain,tier:"long-term",limit:20});if(o.success)for(let{pattern:s}of o.value)s.id!==i&&n.recordCoOccurrence(i,s.id)}}}catch(t){R.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(i);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(i,t.embedding)}catch(t){R.warn("RVF dual-write on promote failed (non-fatal)",{patternId:i,error:f(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:i},"reasoning-bank")).catch(t=>{R.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),R.info("Promoted pattern to long-term",{patternId:i}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${i}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:i,newTier:"long-term"}}),r}else return R.error("Failed to promote pattern",r.error,{patternId:i}),r}async function fe(i){let{signal:e}=i;e?.throwIfAborted();let r=await i.patternStore.getStats(),t=0,n=0;for(let[a,o]of Object.entries(Q)){e?.throwIfAborted();let s=a,l=r.byDomain[s]||0;if(l===0)continue;let u=await i.searchPatterns("",{domain:s,limit:50});if(u.success)for(let c of o){if(e?.throwIfAborted(),(r.byDomain[c]||0)>=l){n++;continue}for(let{pattern:d}of u.value){e?.throwIfAborted();let h=await i.searchPatterns(d.name,{domain:c,limit:1});if(h.success&&h.value.length>0&&h.value[0].score>.8){n++;continue}let b=Math.max(.3,(d.confidence||.5)*.8);(await i.storePattern({patternType:d.patternType,qeDomain:c,name:`${d.name} (from ${s})`,description:`${d.description} [Transferred from ${s} domain]`,template:d.template,context:{...d.context,relatedDomains:[s,c],tags:[...d.context.tags,"cross-domain-transfer",`source:${s}`]},confidence:b})).success?t++:n++}}}return R.info("Cross-domain transfer complete",{transferred:t,skipped:n}),{transferred:t,skipped:n}}var Ee=`
281
+ - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as se}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},Pe=.4,Re=20,we=3;function Se(i){return 1/(1+Math.exp(-i))}function Ee(i,e){if(!e||e.visits===0)return{score:i,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/Re,1)*Pe,t=Se(e.qValue);return{score:i*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function ce(i){let e=i.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,n=i.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*n,0),1),baseEpsilon:t,safetyMultiplier:n}}function le(i,e){if(e<=0||i.length<2)return;let r=Math.round(e*1e6);if(r<=0||se(0,1e6)>=r)return;let t=Math.min(4,i.length),n=se(1,t),a=i[n];i[n]=i[0],i[0]=a,i[0].exploration=!0,i[0].reasoning=[...i[0].reasoning,"(exploration)"]}function ue(i){let e=i.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function de(i){return`${i.taskType}|${i.priority??"normal"}|${i.domain??"any"}`}function O(i,e,r,t,n=x,a,o){let s=[];for(let[l,u]of Object.entries(n)){let c=0,g=[],d=i.filter(b=>u.domains.includes(b)).length,h=Math.min(i.length,we),y=d>0?Math.min(d/h,1)*.4:0;if(c+=y*t.similarity,y>0&&g.push(`Domain match: ${(y*100).toFixed(0)}%`),e&&e.length>0){let b=e.filter(v=>u.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,p=b>0?b/e.length*.3:0;c+=p*t.capabilities,p>0&&g.push(`Capability match: ${(p*100).toFixed(0)}%`)}else c+=.15*t.capabilities;if(c+=u.performanceScore*.3*t.performance,g.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),a&&u.languages&&u.languages.length>0){let b=t.language??1,p=a.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===p)){let P=.15*b;c+=P,g.push(`Language match: ${a}`)}}let w=r.get(l)||0;if(w>0){let b=Math.min(.1,w*.02);c+=b,g.push(`Pattern matches: ${w}`)}let S=c;if(o){let b=o(l),p=Ee(S,b);c=p.score,p.qWeight>0&&g.push(`Q-bonus (w=${p.qWeight.toFixed(2)}, v=${p.qVisits})`),s.push({agent:l,score:c,reasoning:g,staticScore:S,qWeight:p.qWeight,qValue:p.qValue,qVisits:p.qVisits})}else s.push({agent:l,score:c,reasoning:g,staticScore:S})}return s.sort((l,u)=>u.score-l.score),s}var Q={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","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"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function pe(){try{return!ie()||!ne()||te().getVerticesByType("agent").length===0?!1:re().isCritical()}catch{return!1}}ve();function me(i,e){if(i.length===e)return i;if(i.length>e){let r=i.length/e,t=new Array(e).fill(0);for(let n=0;n<e;n++){let a=Math.floor(n*r),o=Math.floor((n+1)*r),s=0;for(let l=a;l<o;l++)s+=i[l];t[n]=s/(o-a)}return F(t)}else{let r=new Array(e).fill(0),t=(i.length-1)/(e-1);for(let n=0;n<e;n++){let a=n*t,o=Math.floor(a),s=Math.min(o+1,i.length-1),l=a-o;r[n]=i[o]*(1-l)+i[s]*l}return F(r)}}function ge(i,e){let r=new Array(e).fill(0),t=i.toLowerCase().trim();for(let n=0;n<3;n++)for(let a=0;a<t.length;a++){let o=t.charCodeAt(a),s=o*(a+1)*(n+1)%e;r[s]+=Math.sin(o*(n+1))/(a+1)}return F(r)}function F(i){let e=Math.sqrt(i.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<i.length;r++)i[r]/=e;return i}G();z();ye();var R=A.create("PatternPromotion");async function fe(i,e){let r=$(i);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),o=[...t.success?t.value.map(l=>l.pattern):[],i].map(l=>({id:l.id,embedding:l.embedding||[],weight:l.confidence,metadata:{name:l.name,domain:l.qeDomain}})),s=await e.coherenceService.checkCoherence(o);if(s.energy>=e.coherenceThreshold){let l={patternId:i.id,patternName:i.name,reason:"coherence_violation",energy:s.energy,existingPatternConflicts:s.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${i.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:l}),R.info("Pattern promotion blocked due to coherence violation",{name:i.name,energy:s.energy}),!1}}return!0}async function V(i,e){let r=await e.patternStore.promote(i);if(r.success){try{e.getSqliteStore().promotePattern(i)}catch(t){R.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(j().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let n=new L(t),a=await e.getPattern(i);if(a){let o=await e.searchPatterns("",{domain:a.qeDomain,tier:"long-term",limit:20});if(o.success)for(let{pattern:s}of o.value)s.id!==i&&n.recordCoOccurrence(i,s.id)}}}catch(t){R.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(i);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(i,t.embedding)}catch(t){R.warn("RVF dual-write on promote failed (non-fatal)",{patternId:i,error:f(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:i},"reasoning-bank")).catch(t=>{R.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),R.info("Promoted pattern to long-term",{patternId:i}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${i}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:i,newTier:"long-term"}}),r}else return R.error("Failed to promote pattern",r.error,{patternId:i}),r}async function he(i){let{signal:e}=i;e?.throwIfAborted();let r=await i.patternStore.getStats(),t=0,n=0;for(let[a,o]of Object.entries(Q)){e?.throwIfAborted();let s=a,l=r.byDomain[s]||0;if(l===0)continue;let u=await i.searchPatterns("",{domain:s,limit:50});if(u.success)for(let c of o){if(e?.throwIfAborted(),(r.byDomain[c]||0)>=l){n++;continue}for(let{pattern:d}of u.value){e?.throwIfAborted();let h=await i.searchPatterns(d.name,{domain:c,limit:1});if(h.success&&h.value.length>0&&h.value[0].score>.8){n++;continue}let y=Math.max(.3,(d.confidence||.5)*.8);(await i.storePattern({patternType:d.patternType,qeDomain:c,name:`${d.name} (from ${s})`,description:`${d.description} [Transferred from ${s} domain]`,template:d.template,context:{...d.context,relatedDomains:[s,c],tags:[...d.context.tags,"cross-domain-transfer",`source:${s}`]},confidence:y})).success?t++:n++}}}return R.info("Cross-domain transfer complete",{transferred:t,skipped:n}),{transferred:t,skipped:n}}var ke=`
282
282
  CREATE TABLE IF NOT EXISTS pattern_citations (
283
283
  source_pattern_id TEXT NOT NULL,
284
284
  target_pattern_id TEXT NOT NULL,
@@ -289,7 +289,7 @@ On promotion:
289
289
  );
290
290
  CREATE INDEX IF NOT EXISTS idx_citations_source ON pattern_citations(source_pattern_id);
291
291
  CREATE INDEX IF NOT EXISTS idx_citations_target ON pattern_citations(target_pattern_id);
292
- `,L=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(Ee),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,n]=e<r?[e,r]:[r,e];this.db.prepare(`
292
+ `,L=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(ke),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,n]=e<r?[e,r]:[r,e];this.db.prepare(`
293
293
  INSERT INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
294
294
  VALUES (?, ?, 1.0, 'co-occurrence')
295
295
  ON CONFLICT(source_pattern_id, target_pattern_id)
@@ -304,17 +304,17 @@ On promotion:
304
304
  `).all(),t=new Map;for(let u of r){let c=t.get(u.qe_domain)??[];c.push(u.id),t.set(u.qe_domain,c)}let n=this.db.prepare(`
305
305
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
306
306
  VALUES (?, ?, 1.0, 'co-occurrence')
307
- `),a=this.db.transaction(u=>{for(let[c,m]of u)n.run(c,m).changes>0&&e++}),o=[];for(let[,u]of t){let c=u.slice(0,50);for(let m=0;m<c.length;m++)for(let d=m+1;d<c.length;d++){let[h,b]=c[m]<c[d]?[c[m],c[d]]:[c[d],c[m]];o.push([h,b])}}a(o);let s=this.db.prepare(`
307
+ `),a=this.db.transaction(u=>{for(let[c,g]of u)n.run(c,g).changes>0&&e++}),o=[];for(let[,u]of t){let c=u.slice(0,50);for(let g=0;g<c.length;g++)for(let d=g+1;d<c.length;d++){let[h,y]=c[g]<c[d]?[c[g],c[d]]:[c[d],c[g]];o.push([h,y])}}a(o);let s=this.db.prepare(`
308
308
  SELECT source_pattern_id, target_pattern_id, relationship_type
309
309
  FROM pattern_relationships
310
310
  WHERE relationship_type IN ('merged', 'derived', 'superseded')
311
311
  `).all(),l=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let u of s)l.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=A.create("QEReasoningBank"),W=class{constructor(e,r,t={},n){this.memory=e;this.eventBus=r;this.coherenceService=n;this.config={...N,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=Z(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;embeddingProvenance=new WeakMap;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=J(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,measuredOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let a=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:a.totalPatterns})}}catch(t){if(r?.aborted)throw t;g.warn("Cross-domain seeding failed (non-fatal)",{error:t})}g.info("Initialized")}lastVectorReconcile=null;getLastVectorReconcile(){return this.lastVectorReconcile}reconcileVectorIndex(){let e=this.patternStore.getAdapter?.(),r=T()?.spaceId;if(!e||!r)return null;try{let t=Number(process.env.AQE_RVF_BACKFILL_LIMIT),n=Number.isFinite(t)&&t>0?Math.floor(t):1e3,a=ae(e,this.getSqliteStore(),r,n);return a.missing>0&&g.info("Reconciled RVF index with SQLite vectors",{...a}),this.lastVectorReconcile=a,a}catch(t){return g.warn("RVF reconcile failed (non-fatal)",{error:f(t)}),null}}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let n=(()=>{let s=process.env.AQE_RVF_BACKFILL_LIMIT,l=s?Number(s):NaN;return Number.isFinite(l)&&l>0?Math.floor(l):1e3})(),o=this.getSqliteStore().getRecentEmbeddings(n).filter(({embedding:s})=>s&&s.length>0).map(({patternId:s,embedding:l})=>({id:s,vector:l instanceof Float32Array?l:new Float32Array(l)}));if(o.length>0){let{accepted:s,rejected:l}=t.ingest(o);g.info("Backfilled RVF from SQLite",{requested:o.length,accepted:s,cap:n,truncated:o.length>=n}),l>0&&g.warn("RVF backfill partially rejected",{accepted:s,rejected:l})}}catch(n){g.warn("RVF backfill failed (non-fatal)",{error:f(n)})}else t&&this.reconcileVectorIndex();return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(n){if(e?.aborted)throw n;g.warn("Failed to load pattern",{name:t.name,error:n})}}g.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),fe({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let n=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);this.embeddingProvenance.has(n)||!!T()?.spaceId?e={...e,embedding:n}:g.debug("No embedding runtime provenance; storing pattern without a vector",{name:e.name})}let r=await this.patternStore.create(e),t=r.success?r.value:null;if(!r.success&&r.error instanceof K&&r.error.disposition==="COMMITTED_PENDING_INDEX")try{t=await this.patternStore.get(r.error.patternId)}catch(n){g.warn("Committed pattern lookup failed",{patternId:r.error.patternId,error:f(n)})}if(t){let n=t;if(k().then(a=>a.append("PATTERN_CREATE",{patternId:n.id,domain:n.qeDomain,confidence:n.confidence,name:n.name},"reasoning-bank")).catch(a=>{g.warn("Witness chain PATTERN_CREATE failed",{error:f(a)})}),this.rvfDualWriter&&n.embedding&&n.embedding.length>0)try{this.rvfDualWriter.writePattern(n.id,n.embedding)}catch(a){g.warn("RVF dual-write failed (non-fatal)",{patternId:n.id,error:f(a)})}}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,n=!0;if(typeof e=="string")if(e.trim()==="")n=!1,t="";else{let a=await this.embed(e);t=this.embeddingProvenance.has(a)?a:e,n=Array.isArray(t)}return this.patternStore.search(t,{...r,textQuery:typeof e=="string"&&e.trim()?e:r?.textQuery,useVectorSearch:n,embeddingSpaceId:typeof e=="string"?Array.isArray(t)?this.embeddingProvenance.get(t):void 0:r?.embeddingSpaceId})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return C(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,Y(e.metrics)==="measured"&&(this.stats.measuredOutcomes++,e.success&&this.stats.successfulOutcomes++),k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let n=await this.getPattern(e.patternId),a=this.getPromotionDeps();n&&await ge(n,a)&&(await V(e.patternId,a),g.info("Pattern promoted to long-term",{name:n.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?V(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:D(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),n=this.embeddingProvenance.get(t),a=await this.patternStore.search(n?t:e.task,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!!n,textQuery:e.task,embeddingSpaceId:n}),o=a.success?a.value.map(p=>p.pattern):[],s=new Map;for(let[p,v]of Object.entries(x)){let P=o.filter(he=>v.domains.includes(he.qeDomain)).length;P>0&&s.set(p,P)}let l=ue({taskType:le(e.task),priority:"normal",domain:r[0]}),u=this.buildQValueLookup(l),c=O(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,u),m=1;try{let p=de(),v=se({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:p});m=v.safetyMultiplier,ce(c,v.epsilon)}catch{}let d=c[0],h=c.slice(1,4),b=[];if(this.config.enableGuidance&&r.length>0){let p=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});b.push(...p.slice(0,5))}this.stats.totalRoutingConfidence+=d.score;let S=c.reduce((p,v)=>p+(v.qWeight??0),0),w=c.length>0?S/c.length:0,y={recommendedAgent:d.agent,confidence:d.score,alternatives:h.map(p=>({agent:p.agent,score:p.score})),domains:r,patterns:o,guidance:b,reasoning:d.reasoning.join("; "),exploration:d.exploration===!0,criticality:m,qWeight:w};return C(ie(e.includePatternGuidance,y,a.success?a.value:[]))}catch(r){return E(B(r))}}buildQValueLookup(e){try{let r=U();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let a=t.prepare(`
314
+ `);for(let u of s)l.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var m=A.create("QEReasoningBank"),W=class{constructor(e,r,t={},n){this.memory=e;this.eventBus=r;this.coherenceService=n;this.config={...N,...t},this.embedderRecovery=new ee({retryIntervalMs:this.config.embedderRetryIntervalMs,onRecovered:()=>m.info("Embedder available again: patterns are stored and searched with vectors"),onRetryFailed:a=>m.debug("Embedder still unavailable",{error:f(a)})}),t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=Z(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;embeddingProvenance=new WeakMap;embedderRecovery;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=J(),this.sqliteStore.initialize().catch(e=>{m.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,measuredOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){m.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let a=await this.patternStore.getStats();m.info("Cross-domain transfer already complete",{totalPatterns:a.totalPatterns})}}catch(t){if(r?.aborted)throw t;m.warn("Cross-domain seeding failed (non-fatal)",{error:t})}m.info("Initialized")}lastVectorReconcile=null;getLastVectorReconcile(){return this.lastVectorReconcile}reconcileVectorIndex(){let e=this.patternStore.getAdapter?.(),r=T()?.spaceId;if(!e||!r)return null;try{let t=Number(process.env.AQE_RVF_BACKFILL_LIMIT),n=Number.isFinite(t)&&t>0?Math.floor(t):1e3,a=oe(e,this.getSqliteStore(),r,n);return a.missing>0&&m.info("Reconciled RVF index with SQLite vectors",{...a}),this.lastVectorReconcile=a,a}catch(t){return m.warn("RVF reconcile failed (non-fatal)",{error:f(t)}),null}}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){m.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let n=(()=>{let s=process.env.AQE_RVF_BACKFILL_LIMIT,l=s?Number(s):NaN;return Number.isFinite(l)&&l>0?Math.floor(l):1e3})(),o=this.getSqliteStore().getRecentEmbeddings(n).filter(({embedding:s})=>s&&s.length>0).map(({patternId:s,embedding:l})=>({id:s,vector:l instanceof Float32Array?l:new Float32Array(l)}));if(o.length>0){let{accepted:s,rejected:l}=t.ingest(o);m.info("Backfilled RVF from SQLite",{requested:o.length,accepted:s,cap:n,truncated:o.length>=n}),l>0&&m.warn("RVF backfill partially rejected",{accepted:s,rejected:l})}}catch(n){m.warn("RVF backfill failed (non-fatal)",{error:f(n)})}else t&&this.reconcileVectorIndex();return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(n){if(e?.aborted)throw n;m.warn("Failed to load pattern",{name:t.name,error:n})}}m.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),he({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let n=await this.embedForPatterns(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);n!==null&&(this.embeddingProvenance.has(n)||!!T()?.spaceId)?e={...e,embedding:n}:m.debug("No embedding runtime provenance; storing pattern without a vector",{name:e.name})}let r=await this.patternStore.create(e),t=r.success?r.value:null;if(!r.success&&r.error instanceof K&&r.error.disposition==="COMMITTED_PENDING_INDEX")try{t=await this.patternStore.get(r.error.patternId)}catch(n){m.warn("Committed pattern lookup failed",{patternId:r.error.patternId,error:f(n)})}if(t){let n=t;if(k().then(a=>a.append("PATTERN_CREATE",{patternId:n.id,domain:n.qeDomain,confidence:n.confidence,name:n.name},"reasoning-bank")).catch(a=>{m.warn("Witness chain PATTERN_CREATE failed",{error:f(a)})}),this.rvfDualWriter&&n.embedding&&n.embedding.length>0)try{this.rvfDualWriter.writePattern(n.id,n.embedding)}catch(a){m.warn("RVF dual-write failed (non-fatal)",{patternId:n.id,error:f(a)})}}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,n=!0;if(typeof e=="string")if(e.trim()==="")n=!1,t="";else{let a=await this.embedForPatterns(e);t=a&&this.embeddingProvenance.has(a)?a:e,n=Array.isArray(t)}return this.patternStore.search(t,{...r,textQuery:typeof e=="string"&&e.trim()?e:r?.textQuery,useVectorSearch:n,embeddingSpaceId:typeof e=="string"?Array.isArray(t)?this.embeddingProvenance.get(t):void 0:r?.embeddingSpaceId})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return C(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,Y(e.metrics)==="measured"&&(this.stats.measuredOutcomes++,e.success&&this.stats.successfulOutcomes++),k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{m.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let n=await this.getPattern(e.patternId),a=this.getPromotionDeps();n&&await fe(n,a)&&(await V(e.patternId,a),m.info("Pattern promoted to long-term",{name:n.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?V(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:D(e.task);r.length===0&&r.push("test-generation");let t=await this.embedForPatterns(e.task),n=t?this.embeddingProvenance.get(t):void 0,a=await this.patternStore.search(t&&n?t:e.task,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!!n,textQuery:e.task,embeddingSpaceId:n}),o=a.success?a.value.map(p=>p.pattern):[],s=new Map;for(let[p,v]of Object.entries(x)){let P=o.filter(be=>v.domains.includes(be.qeDomain)).length;P>0&&s.set(p,P)}let l=de({taskType:ue(e.task),priority:"normal",domain:r[0]}),u=this.buildQValueLookup(l),c=O(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,u),g=1;try{let p=pe(),v=ce({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:p});g=v.safetyMultiplier,le(c,v.epsilon)}catch{}let d=c[0],h=c.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let p=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...p.slice(0,5))}this.stats.totalRoutingConfidence+=d.score;let w=c.reduce((p,v)=>p+(v.qWeight??0),0),S=c.length>0?w/c.length:0,b={recommendedAgent:d.agent,confidence:d.score,alternatives:h.map(p=>({agent:p.agent,score:p.score})),domains:r,patterns:o,guidance:y,reasoning:d.reasoning.join("; "),exploration:d.exploration===!0,criticality:g,qWeight:S};return C(ae(e.includePatternGuidance,b,a.success?a.value:[]))}catch(r){return E(B(r))}}buildQValueLookup(e){try{let r=U();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let a=t.prepare(`
315
315
  SELECT q_value, visits FROM rl_q_values
316
316
  WHERE algorithm = 'q-learning'
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-RQRVOKVM.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return pe(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-RQRVOKVM.js");if(t())throw r;process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return me(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of H)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},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 qt(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,le as d,O as e,Q as f,W as g,qt as h};
320
+ `);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-ZWXS5ZFV.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return me(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-ZWXS5ZFV.js");if(t())throw r;process.env.DEBUG&&m.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return ge(e,this.config.embeddingDimension)}async embedForPatterns(e){if(!this.embedderRecovery.isAvailable())return null;try{return await this.embed(e)}catch(r){let t=f(r),n="Embedder failed: storing and searching patterns by text only";return this.embedderRecovery.markUnavailable(t)?m.warn(n,{error:t}):m.debug(n,{error:t}),null}}getEmbedderFailure(){return this.embedderRecovery.unavailableReason}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of H)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},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 Dt(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,ue as d,O as e,Q as f,W as g,Dt as h};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.11");process.exit(0)}
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.15.12");process.exit(0)}
2
2
  import{existsSync as o,openSync as d,readSync as f,closeSync as p,renameSync as S,unlinkSync as l}from"fs";var b="FLVR",c=4,g=["",".idmap.json",".manifest.json",".space.json"];function m(n,e){let r;try{r=d(n,"r");let t=Buffer.alloc(e);return f(r,t,0,e,0)<e?null:t}catch{return null}finally{if(r!==void 0)try{p(r)}catch{}}}function a(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function i(n){let e=m(`${n}.lock`,c+4);if(!e||e.subarray(0,4).toString("latin1")!==b)return null;let r=e.readUInt32LE(c);return r>0?r:null}function k(n){let e=i(n);return e===null?!1:a(e)}function E(n){let e=n instanceof Error?n.message:String(n);return e.includes("LockHeld")||e.includes("0x0300")}function y(n){let e=n instanceof Error?n.message:String(n);return/ManifestNotFound|InvalidMagic|ChecksumMismatch|CorruptStore/i.test(e)}function L(n){let e=i(n);if(e===null||a(e))return!1;try{return i(n)!==e?!1:(l(`${n}.lock`),!0)}catch{return!1}}function x(n,e,r){if(!o(n)||!y(r))return null;if(k(n))return console.warn(`[RVF] ${n} is unusable but its lock is held by a live process \u2014 leaving it alone and degrading to SQLite for this run.`),null;let t=`${n}.corrupt-${process.pid}`;for(let s of g){let u=`${n}${s}`;if(o(u))try{S(u,`${t}${s}`)}catch{}}try{o(`${n}.lock`)&&l(`${n}.lock`)}catch{}return console.warn(`[RVF] Quarantined unusable store ${n} \u2192 ${t} (${e}). It is a derived cache and will be rebuilt from the unified DB. Please report a recurrence with the quarantined files (issue #563).`),t}export{i as a,k as b,E as c,y as d,L as e,x as f};
@@ -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.15.11");process.exit(0)}
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.15.12");process.exit(0)}
2
2
  import{existsSync as u,readdirSync as l}from"fs";import{join as i}from"path";var f=".agentic-qe",o=".claude";function x(s,t,a){return t===f?!0:t===o?a||u(i(s,f)):!1}function d(s,t=[],a=12){let y=new Set(t),g=[],m=(r,e,c)=>{if(u(i(r,o))&&(c===0||u(i(r,f)))&&g.push(e?`${e}/${o}`:o),c>=a)return;let p;try{p=l(r,{withFileTypes:!0})}catch{return}for(let n of p)!n.isDirectory()||n.name.startsWith(".")||y.has(n.name)||m(i(r,n.name),e?`${e}/${n.name}`:n.name,c+1)};return m(s,"",0),g}export{f as a,o as b,x as c,d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.11");process.exit(0)}
2
- var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-6COXTQZ3.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-AGDZQ5XD.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-BZK4M7BO.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-O7ZXDDCD.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-EZZUJL2E.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-DROMBRV2.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-AK7BXBX2.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
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.15.12");process.exit(0)}
2
+ var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-I3KWHE7X.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-FL26RTV3.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-KCIRNE7C.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-DKXMDVPE.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-MFC5WTJU.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-SIZMEHPM.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-WIM7G3HC.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.11");process.exit(0)}
2
- import{a as v}from"./chunk-HDNWSKHA.js";import{h as U}from"./chunk-AP3ADWDK.js";import{c as D,d as R,e as h,g as x}from"./chunk-OURITHFV.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-V4GSGOOK.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ 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.15.12");process.exit(0)}
2
+ import{a as v}from"./chunk-FAGKBOX2.js";import{h as U}from"./chunk-ZPVGX4DI.js";import{c as D,d as R,e as h,g as x}from"./chunk-2ASQRBK2.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-HL7MOCQN.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ 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.15.11");process.exit(0)}
2
- import{b as i,c}from"./chunk-XGBU3KEM.js";import{i as l}from"./chunk-7R5HC56U.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;i(t)}db;recordNull(t){this.db.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.15.12");process.exit(0)}
2
+ import{b as i,c}from"./chunk-WGTEZT7G.js";import{i as l}from"./chunk-7TA5MUPW.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;i(t)}db;recordNull(t){this.db.prepare(`
3
3
  INSERT INTO qe_pattern_nulls (id, pattern_id, context_fingerprint, failure_mode, trajectory_ref, evidence_class)
4
4
  VALUES (?, ?, ?, ?, ?, ?)
5
5
  ON CONFLICT(pattern_id, context_fingerprint) DO UPDATE SET
@@ -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.15.11");process.exit(0)}
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.15.12");process.exit(0)}
2
2
  var l="defect-intelligence",d=["critical","high","medium","low","info"],m=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function u(e){if(!m(e))return null;let{file:i,probability:t,riskLevel:r}=e;if(typeof i!="string"||i.length===0||typeof t!="number"||!Number.isFinite(t)||t<0||t>1||!d.includes(r))return null;let c=Array.isArray(e.factors)?e.factors.filter(o=>m(o)&&typeof o.name=="string"&&typeof o.contribution=="number"&&Number.isFinite(o.contribution)):[],a=Array.isArray(e.recommendations)?e.recommendations.filter(o=>typeof o=="string"):[];return{file:i,probability:t,riskLevel:r,factors:c,recommendations:a}}function f(e,i){if(!m(e)||typeof e.id!="string"||typeof e.timestamp!="string")return null;let t=Date.parse(e.timestamp);if(!Number.isFinite(t)||t>i+6e4||i-t>6048e5||!Array.isArray(e.predictions)||e.predictions.length===0)return null;let r=e.predictions.map(u);return r.some(c=>c===null)?null:{id:e.id,timestamp:e.timestamp,predictions:r,...e.predictionMethod==="static-code-indicators"?{predictionMethod:"static-code-indicators",estimated:!0,filesSkipped:typeof e.filesSkipped=="number"&&Number.isSafeInteger(e.filesSkipped)&&e.filesSkipped>=0?e.filesSkipped:0}:{}}}async function A(e,i="defect-intelligence:predictor"){let t=`${i}:prediction:`,r=await e.search(`${t}*`,Number.MAX_SAFE_INTEGER,{namespace:l}),c=Date.now(),a=[],o=[];for(let n of r){let s=n.startsWith(`${l}:${t}`)?n.slice(l.length+1):n;if(!s.startsWith(t))continue;let p=f(await e.get(s,{namespace:l}),c);p?a.push({key:s,timestamp:Date.parse(p.timestamp),id:p.id}):o.push(s)}a.sort((n,s)=>s.timestamp-n.timestamp||(n.id===s.id?n.key===s.key?0:n.key>s.key?-1:1:n.id>s.id?-1:1));for(let n of[...o,...a.slice(32).map(s=>s.key)])await e.delete(n,{namespace:l})}function g(e){let i=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${i.replace(/\*/g,".*").replace(/\?/g,".")}$`,"s")}function y(e,i,t){return g(t).test(e)?e:e.startsWith(`${i}:`)?e.slice(i.length+1):e}var k=1e4,h=32;async function b(e,i,t={}){let r=Math.max(1,Math.floor(t.pageSize??k)),c=await e.search(i,r,t.retrieve);for(let n=1;c.length>=r;n++){if(n>=h)throw new Error(`searchAllKeys('${i}'): the backend never returned a short page after ${n} requests (last limit ${r}); refusing to return a possibly incomplete key list`);r*=2,c=await e.search(i,r,t.retrieve)}let a=t.retrieve?.namespace,o=a?c.map(n=>y(n,a,i)):c;return[...new Set(o)].sort()}export{f as a,A as b,y as c,b as d};
@@ -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.15.11");process.exit(0)}
2
- import{i as b,l as D,n as Q}from"./chunk-5MNASJOH.js";import{v as X}from"./chunk-LD5CFK53.js";import{d as _,e as Y}from"./chunk-FZHSG75I.js";import{c as w}from"./chunk-EH2S6AOR.js";var W=["claude","claude-code","codex","openai","ollama","openrouter","bedrock","azure-openai","gemini","cognitum"];function x(r){return W.includes(r)}function p(r,o,e){let t=new Error(r);return t.name="LLMError",t.code=o,t.provider=e?.provider,t.model=e?.model,t.retryable=e?.retryable??!1,t.retryAfterMs=e?.retryAfterMs,t.cause=e?.cause,t}function Te(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var y=new Map,Z=new Set(["anthropic"]),N=/^[a-z0-9][a-z0-9-]{0,62}$/;function M(r){if(typeof r!="string"||r.trim().length===0)return"provider type must be a non-empty string";if(r!==r.toLowerCase())return`provider type "${r}" must be lowercase (AQE_LLM_PROVIDER is matched case-insensitively)`;if(!N.test(r))return`provider type "${r}" must match ${N.source} (lowercase alphanumeric and dashes)`;if(x(r))return`provider type "${r}" is built in and cannot be overridden`;if(Z.has(r))return`provider type "${r}" is reserved`}function ee(r,o,e={}){let t=M(r);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});if(typeof o!="function")throw p(`provider "${r}" must be registered with a factory function`,"INVALID_REGISTRATION",{retryable:!1});y.set(r,{...e,type:r,factory:o,source:e.source??"api"})}function F(r,o,e={}){try{ee(r,o,e);return}catch(t){return t instanceof Error?t.message:String(t)}}function B(r){return y.delete(r)}function $(r){return y.has(r)}function ke(r){return y.get(r)}function h(){return[...y.keys()]}var re=["isAvailable","healthCheck","generate","complete","getConfig","getSupportedModels","getCostPerToken","dispose"];function te(r,o){if(!o||typeof o!="object")return`provider "${r}" factory returned ${o===null?"null":typeof o}, expected an LLMProvider`;let e=o,t=re.filter(i=>typeof e[i]!="function");if(t.length>0)return`provider "${r}" is missing required LLMProvider method(s): ${t.join(", ")}`;if(typeof e.type!="string"||e.type.length===0)return`provider "${r}" must expose a non-empty \`type\``;if(e.type!==r)return`provider "${r}" reports type "${e.type}" \u2014 a provider must not claim an identity other than the one it was registered under`}function Le(r){let o=y.get(r);if(!o)throw p(`Unknown provider type: ${r}`,"PROVIDER_UNAVAILABLE",{retryable:!1});let e=o.factory(o.config),t=te(r,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});return e}function Ae(r){let o=y.get(r);if(o)return{mode:o.billingMode??"metered-api",source:o.source,detail:o.sourceDetail}}Q();function q(r){return r==="onnx"||x(r)}var T=["claude","claude-code","codex","openai","ollama","openrouter","gemini","azure-openai","bedrock","cognitum","onnx"];var oe={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},ne=[{provider:"claude",models:[b,D[1]],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-6-sol","gpt-6-luna"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-5","openai/gpt-6-sol"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["qwen3-coder:30b","qwen3:30b-a3b"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],ie={id:"default-fallback-chain",entries:ne,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},U={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:b,fallbackChain:ie,fallbackBehavior:oe,providers:{claude:{enabled:!0,defaultModel:b},"claude-code":{enabled:!1,defaultModel:b},openai:{enabled:!0,defaultModel:"gpt-6-sol"},ollama:{enabled:!0,defaultModel:"qwen3-coder:30b"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-5"},gemini:{enabled:!1,defaultModel:"gemini-2.5-flash"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},cognitum:{enabled:!1,defaultModel:"cognitum-auto"},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},Ue=[{canonicalId:"claude-opus-5",canonicalName:"Claude Opus 5",providerIds:{claude:"claude-opus-5",openrouter:"anthropic/claude-opus-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-5",canonicalName:"Claude Sonnet 5",providerIds:{claude:"claude-sonnet-5",openrouter:"anthropic/claude-sonnet-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:2,outputCostPer1M:10},{canonicalId:"claude-opus-5-5",canonicalName:"Claude Opus 5.5",providerIds:{claude:"claude-opus-5-5",openrouter:"anthropic/claude-opus-5.5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:4,outputCostPer1M:20},{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];import{spawn as se}from"node:child_process";import{accessSync as ae,constants as de,statSync as le}from"node:fs";import{delimiter as ue,join as pe}from"node:path";var ce=18e4,me=2,E="default";function R(r,o){if(!o||typeof o!="object")return`externalProviders["${r}"] must be an object`;let e=o;if(e.kind!=="cli")return`externalProviders["${r}"].kind must be "cli" (got ${JSON.stringify(e.kind)})`;if(!Array.isArray(e.command)||e.command.length===0)return`externalProviders["${r}"].command must be a non-empty string array`;if(!e.command.every(t=>typeof t=="string"&&t.length>0))return`externalProviders["${r}"].command must contain only non-empty strings`;if(e.billingMode!==void 0&&!["subscription","metered-api","metered-capped","local"].includes(e.billingMode))return`externalProviders["${r}"].billingMode "${String(e.billingMode)}" is not a valid billing mode`;if(e.models!==void 0&&(!Array.isArray(e.models)||e.models.some(t=>typeof t!="string")))return`externalProviders["${r}"].models must be a string array`;if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||e.timeoutMs<=0))return`externalProviders["${r}"].timeoutMs must be a positive number`;if(e.maxConcurrency!==void 0&&(typeof e.maxConcurrency!="number"||e.maxConcurrency<1))return`externalProviders["${r}"].maxConcurrency must be >= 1`;if(e.stripEnv!==void 0&&(!Array.isArray(e.stripEnv)||e.stripEnv.some(t=>typeof t!="string")))return`externalProviders["${r}"].stripEnv must be a string array`;if("apiKey"in e)return`externalProviders["${r}"] must not contain an apiKey \u2014 keys belong in the environment, not in llm-config.json`}var P=class r{type;name;billingMode;config;requestCounter=0;availabilityCache;active=0;queue=[];constructor(o,e){let t=R(o,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});this.type=o,this.config=e,this.name=e.displayName??o,this.billingMode=e.billingMode??"metered-api"}async isAvailable(){let o=Date.now();if(this.availabilityCache&&o-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=ge(this.config.command[0]);return this.availabilityCache={at:o,available:e},e}async healthCheck(){let o=Date.now(),e=await this.isAvailable(),t=Date.now()-o;return e?{healthy:!0,latencyMs:t,models:this.getSupportedModels(),details:{command:this.config.command[0],billing:this.billingMode,external:!0}}:{healthy:!1,latencyMs:t,error:`External provider "${this.type}" could not run "${this.config.command[0]}". Check that the host is installed and on PATH.`}}async generate(o,e){let t=e?.model??this.defaultModel(),i=`${this.type}-${++this.requestCounter}-${Date.now()}`,n=ye(o,e?.systemPrompt),s=e?.timeoutMs??this.config.timeoutMs??ce,l=[];this.config.modelFlag&&t&&t!==E&&l.push(this.config.modelFlag,t);let a=Date.now(),{code:d,stdout:u,stderr:f}=await this.withConcurrency(()=>this.spawnHost(l,n,s)),g=Date.now()-a,v=u.trim();if(d!==0&&!v)throw this.classifyError(f||`${this.type} exited with code ${d}`,t);let c=Math.ceil(n.length/4),S=Math.ceil(v.length/4),J={promptTokens:c,completionTokens:S,totalTokens:c+S};return{content:v,model:t,provider:this.type,usage:J,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"local-estimate"},latencyMs:g,finishReason:"stop",cached:!1,requestId:i}}async embed(o,e){throw p(`External provider "${this.type}" does not support embeddings. Use a provider with an embeddings endpoint (openai, ollama, cognitum).`,"EMBEDDING_UNSUPPORTED",{provider:this.type,retryable:!1})}async complete(o,e){let t=await this.generate(o,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});return{completion:t.content,model:t.model,provider:this.type,usage:t.usage,latencyMs:t.latencyMs,cached:t.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[...this.config.models??[E]]}getCostPerToken(){return{input:0,output:0}}async dispose(){}defaultModel(){return this.config.defaultModel??this.config.models?.[0]??E}static childEnv(o=[],e=process.env){let t={...e};for(let i of o)delete t[i];return t}classifyError(o,e){let t=o.toLowerCase();return t.includes("rate limit")||t.includes("usage limit")||t.includes("429")||t.includes("quota")?p(o,"RATE_LIMITED",{provider:this.type,model:e,retryable:!0,retryAfterMs:6e4}):p(o,"PROVIDER_UNAVAILABLE",{provider:this.type,model:e,retryable:!0})}spawnHost(o,e,t){let[i,...n]=this.config.command,s=[...n,...o];return new Promise((l,a)=>{let d=se(i,s,{env:r.childEnv(this.config.stripEnv),stdio:["pipe","pipe","pipe"]}),u="",f="",g=!1,v=setTimeout(()=>{g||(g=!0,d.kill("SIGKILL"),a(p(`${this.type} timed out after ${t}ms`,"TIMEOUT",{provider:this.type,retryable:!0})))},t);d.stdout.on("data",c=>u+=c.toString()),d.stderr.on("data",c=>f+=c.toString()),d.on("error",c=>{g||(g=!0,clearTimeout(v),a(p(`Failed to spawn "${i}" for provider "${this.type}": ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:this.type,retryable:!1,cause:c})))}),d.on("close",c=>{g||(g=!0,clearTimeout(v),l({code:c??0,stdout:u,stderr:f}))}),d.stdin.on("error",()=>{});try{d.stdin.write(e),d.stdin.end()}catch{}})}async withConcurrency(o){let e=this.config.maxConcurrency??me;this.active>=e&&await new Promise(t=>this.queue.push(t)),this.active++;try{return await o()}finally{this.active--;let t=this.queue.shift();t&&t()}}};function ge(r,o=process.env){let e=n=>{try{return ae(n,de.X_OK),le(n).isFile()}catch{return!1}};if(r.includes("/")||r.includes("\\"))return e(r);let t=(o.PATH??"").split(ue).filter(Boolean),i=process.platform==="win32"?["",...(o.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]:[""];return t.some(n=>i.some(s=>e(pe(n,r+s))))}function ye(r,o){if(typeof r=="string")return o?`${o}
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.15.12");process.exit(0)}
2
+ import{i as b,l as D,n as Q}from"./chunk-PGSJBXTD.js";import{v as X}from"./chunk-L7NGKANW.js";import{d as _,e as Y}from"./chunk-ADUAJIAU.js";import{c as w}from"./chunk-DZGPUGUG.js";var W=["claude","claude-code","codex","openai","ollama","openrouter","bedrock","azure-openai","gemini","cognitum"];function x(r){return W.includes(r)}function p(r,o,e){let t=new Error(r);return t.name="LLMError",t.code=o,t.provider=e?.provider,t.model=e?.model,t.retryable=e?.retryable??!1,t.retryAfterMs=e?.retryAfterMs,t.cause=e?.cause,t}function Te(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var y=new Map,Z=new Set(["anthropic"]),N=/^[a-z0-9][a-z0-9-]{0,62}$/;function M(r){if(typeof r!="string"||r.trim().length===0)return"provider type must be a non-empty string";if(r!==r.toLowerCase())return`provider type "${r}" must be lowercase (AQE_LLM_PROVIDER is matched case-insensitively)`;if(!N.test(r))return`provider type "${r}" must match ${N.source} (lowercase alphanumeric and dashes)`;if(x(r))return`provider type "${r}" is built in and cannot be overridden`;if(Z.has(r))return`provider type "${r}" is reserved`}function ee(r,o,e={}){let t=M(r);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});if(typeof o!="function")throw p(`provider "${r}" must be registered with a factory function`,"INVALID_REGISTRATION",{retryable:!1});y.set(r,{...e,type:r,factory:o,source:e.source??"api"})}function F(r,o,e={}){try{ee(r,o,e);return}catch(t){return t instanceof Error?t.message:String(t)}}function B(r){return y.delete(r)}function $(r){return y.has(r)}function ke(r){return y.get(r)}function h(){return[...y.keys()]}var re=["isAvailable","healthCheck","generate","complete","getConfig","getSupportedModels","getCostPerToken","dispose"];function te(r,o){if(!o||typeof o!="object")return`provider "${r}" factory returned ${o===null?"null":typeof o}, expected an LLMProvider`;let e=o,t=re.filter(i=>typeof e[i]!="function");if(t.length>0)return`provider "${r}" is missing required LLMProvider method(s): ${t.join(", ")}`;if(typeof e.type!="string"||e.type.length===0)return`provider "${r}" must expose a non-empty \`type\``;if(e.type!==r)return`provider "${r}" reports type "${e.type}" \u2014 a provider must not claim an identity other than the one it was registered under`}function Le(r){let o=y.get(r);if(!o)throw p(`Unknown provider type: ${r}`,"PROVIDER_UNAVAILABLE",{retryable:!1});let e=o.factory(o.config),t=te(r,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});return e}function Ae(r){let o=y.get(r);if(o)return{mode:o.billingMode??"metered-api",source:o.source,detail:o.sourceDetail}}Q();function q(r){return r==="onnx"||x(r)}var T=["claude","claude-code","codex","openai","ollama","openrouter","gemini","azure-openai","bedrock","cognitum","onnx"];var oe={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},ne=[{provider:"claude",models:[b,D[1]],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-6-sol","gpt-6-luna"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-5","openai/gpt-6-sol"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["qwen3-coder:30b","qwen3:30b-a3b"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],ie={id:"default-fallback-chain",entries:ne,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},U={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:b,fallbackChain:ie,fallbackBehavior:oe,providers:{claude:{enabled:!0,defaultModel:b},"claude-code":{enabled:!1,defaultModel:b},openai:{enabled:!0,defaultModel:"gpt-6-sol"},ollama:{enabled:!0,defaultModel:"qwen3-coder:30b"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-5"},gemini:{enabled:!1,defaultModel:"gemini-2.5-flash"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},cognitum:{enabled:!1,defaultModel:"cognitum-auto"},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},Ue=[{canonicalId:"claude-opus-5",canonicalName:"Claude Opus 5",providerIds:{claude:"claude-opus-5",openrouter:"anthropic/claude-opus-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-5",canonicalName:"Claude Sonnet 5",providerIds:{claude:"claude-sonnet-5",openrouter:"anthropic/claude-sonnet-5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:2,outputCostPer1M:10},{canonicalId:"claude-opus-5-5",canonicalName:"Claude Opus 5.5",providerIds:{claude:"claude-opus-5-5",openrouter:"anthropic/claude-opus-5.5"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:4,outputCostPer1M:20},{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];import{spawn as se}from"node:child_process";import{accessSync as ae,constants as de,statSync as le}from"node:fs";import{delimiter as ue,join as pe}from"node:path";var ce=18e4,me=2,E="default";function R(r,o){if(!o||typeof o!="object")return`externalProviders["${r}"] must be an object`;let e=o;if(e.kind!=="cli")return`externalProviders["${r}"].kind must be "cli" (got ${JSON.stringify(e.kind)})`;if(!Array.isArray(e.command)||e.command.length===0)return`externalProviders["${r}"].command must be a non-empty string array`;if(!e.command.every(t=>typeof t=="string"&&t.length>0))return`externalProviders["${r}"].command must contain only non-empty strings`;if(e.billingMode!==void 0&&!["subscription","metered-api","metered-capped","local"].includes(e.billingMode))return`externalProviders["${r}"].billingMode "${String(e.billingMode)}" is not a valid billing mode`;if(e.models!==void 0&&(!Array.isArray(e.models)||e.models.some(t=>typeof t!="string")))return`externalProviders["${r}"].models must be a string array`;if(e.timeoutMs!==void 0&&(typeof e.timeoutMs!="number"||e.timeoutMs<=0))return`externalProviders["${r}"].timeoutMs must be a positive number`;if(e.maxConcurrency!==void 0&&(typeof e.maxConcurrency!="number"||e.maxConcurrency<1))return`externalProviders["${r}"].maxConcurrency must be >= 1`;if(e.stripEnv!==void 0&&(!Array.isArray(e.stripEnv)||e.stripEnv.some(t=>typeof t!="string")))return`externalProviders["${r}"].stripEnv must be a string array`;if("apiKey"in e)return`externalProviders["${r}"] must not contain an apiKey \u2014 keys belong in the environment, not in llm-config.json`}var P=class r{type;name;billingMode;config;requestCounter=0;availabilityCache;active=0;queue=[];constructor(o,e){let t=R(o,e);if(t)throw p(t,"INVALID_REGISTRATION",{retryable:!1});this.type=o,this.config=e,this.name=e.displayName??o,this.billingMode=e.billingMode??"metered-api"}async isAvailable(){let o=Date.now();if(this.availabilityCache&&o-this.availabilityCache.at<6e4)return this.availabilityCache.available;let e=ge(this.config.command[0]);return this.availabilityCache={at:o,available:e},e}async healthCheck(){let o=Date.now(),e=await this.isAvailable(),t=Date.now()-o;return e?{healthy:!0,latencyMs:t,models:this.getSupportedModels(),details:{command:this.config.command[0],billing:this.billingMode,external:!0}}:{healthy:!1,latencyMs:t,error:`External provider "${this.type}" could not run "${this.config.command[0]}". Check that the host is installed and on PATH.`}}async generate(o,e){let t=e?.model??this.defaultModel(),i=`${this.type}-${++this.requestCounter}-${Date.now()}`,n=ye(o,e?.systemPrompt),s=e?.timeoutMs??this.config.timeoutMs??ce,l=[];this.config.modelFlag&&t&&t!==E&&l.push(this.config.modelFlag,t);let a=Date.now(),{code:d,stdout:u,stderr:f}=await this.withConcurrency(()=>this.spawnHost(l,n,s)),g=Date.now()-a,v=u.trim();if(d!==0&&!v)throw this.classifyError(f||`${this.type} exited with code ${d}`,t);let c=Math.ceil(n.length/4),S=Math.ceil(v.length/4),J={promptTokens:c,completionTokens:S,totalTokens:c+S};return{content:v,model:t,provider:this.type,usage:J,cost:{inputCost:0,outputCost:0,totalCost:0,currency:"USD",source:"local-estimate"},latencyMs:g,finishReason:"stop",cached:!1,requestId:i}}async embed(o,e){throw p(`External provider "${this.type}" does not support embeddings. Use a provider with an embeddings endpoint (openai, ollama, cognitum).`,"EMBEDDING_UNSUPPORTED",{provider:this.type,retryable:!1})}async complete(o,e){let t=await this.generate(o,{model:e?.model,temperature:e?.temperature,maxTokens:e?.maxTokens});return{completion:t.content,model:t.model,provider:this.type,usage:t.usage,latencyMs:t.latencyMs,cached:t.cached}}getConfig(){return{...this.config}}getSupportedModels(){return[...this.config.models??[E]]}getCostPerToken(){return{input:0,output:0}}async dispose(){}defaultModel(){return this.config.defaultModel??this.config.models?.[0]??E}static childEnv(o=[],e=process.env){let t={...e};for(let i of o)delete t[i];return t}classifyError(o,e){let t=o.toLowerCase();return t.includes("rate limit")||t.includes("usage limit")||t.includes("429")||t.includes("quota")?p(o,"RATE_LIMITED",{provider:this.type,model:e,retryable:!0,retryAfterMs:6e4}):p(o,"PROVIDER_UNAVAILABLE",{provider:this.type,model:e,retryable:!0})}spawnHost(o,e,t){let[i,...n]=this.config.command,s=[...n,...o];return new Promise((l,a)=>{let d=se(i,s,{env:r.childEnv(this.config.stripEnv),stdio:["pipe","pipe","pipe"]}),u="",f="",g=!1,v=setTimeout(()=>{g||(g=!0,d.kill("SIGKILL"),a(p(`${this.type} timed out after ${t}ms`,"TIMEOUT",{provider:this.type,retryable:!0})))},t);d.stdout.on("data",c=>u+=c.toString()),d.stderr.on("data",c=>f+=c.toString()),d.on("error",c=>{g||(g=!0,clearTimeout(v),a(p(`Failed to spawn "${i}" for provider "${this.type}": ${c.message}`,"PROVIDER_UNAVAILABLE",{provider:this.type,retryable:!1,cause:c})))}),d.on("close",c=>{g||(g=!0,clearTimeout(v),l({code:c??0,stdout:u,stderr:f}))}),d.stdin.on("error",()=>{});try{d.stdin.write(e),d.stdin.end()}catch{}})}async withConcurrency(o){let e=this.config.maxConcurrency??me;this.active>=e&&await new Promise(t=>this.queue.push(t)),this.active++;try{return await o()}finally{this.active--;let t=this.queue.shift();t&&t()}}};function ge(r,o=process.env){let e=n=>{try{return ae(n,de.X_OK),le(n).isFile()}catch{return!1}};if(r.includes("/")||r.includes("\\"))return e(r);let t=(o.PATH??"").split(ue).filter(Boolean),i=process.platform==="win32"?["",...(o.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]:[""];return t.some(n=>i.some(s=>e(pe(n,r+s))))}function ye(r,o){if(typeof r=="string")return o?`${o}
3
3
 
4
4
  ${r}`:r;let e=r.filter(n=>n.role==="system").map(n=>n.content);o&&e.unshift(o);let t=r.filter(n=>n.role!=="system").map(n=>`${n.role==="assistant"?"Assistant":"User"}: ${n.content}`).join(`
5
5
 
@@ -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.15.11");process.exit(0)}
2
- import{a as v,b as w,c as A,e as O,f as z}from"./chunk-XGPTZUKQ.js";import{b as S,d as $}from"./chunk-JFLU7L3W.js";import{i as D}from"./chunk-7R5HC56U.js";import{a as N,e as F}from"./chunk-DDEOZPWJ.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(v),e.exec(w),e.exec(A)})()}schemaExists(e){return O(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=D(),r={id:t,...e},s=C(r);return this.config.db.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.15.12");process.exit(0)}
2
+ import{a as v,b as w,c as A,e as O,f as z}from"./chunk-66PXR3NI.js";import{b as S,d as $}from"./chunk-WTAUF6O4.js";import{i as D}from"./chunk-7TA5MUPW.js";import{a as N,e as F}from"./chunk-W4II6SIH.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(v),e.exec(w),e.exec(A)})()}schemaExists(e){return O(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=D(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
@@ -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.15.11");process.exit(0)}
2
- import{e as z}from"./chunk-JGJXXAS6.js";import{a as P}from"./chunk-7HEMJHPP.js";import{a as w,b as S}from"./chunk-AFFN6E6Q.js";import{u as $,v as H}from"./chunk-LD5CFK53.js";import{a as T,e as I}from"./chunk-WM3SRRA6.js";import{c as C,d as M}from"./chunk-EH2S6AOR.js";import{a as k,e as F}from"./chunk-DDEOZPWJ.js";import{f as D}from"./chunk-CFWGGRE7.js";M();import{createHash as L}from"crypto";import*as x from"path";function Q(){let o="3.15.11",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var U={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function N(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function j(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...U,...e}}computeFingerprint(e,t,r,i){let n=N({action:t,build:Q(),domain:e,input:r,scope:j(i)});return L("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
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.15.12");process.exit(0)}
2
+ import{e as z}from"./chunk-BC4T6SCV.js";import{a as P}from"./chunk-ZGROHCOW.js";import{a as w,b as S}from"./chunk-ULCW6IVQ.js";import{u as $,v as H}from"./chunk-L7NGKANW.js";import{a as T,e as I}from"./chunk-SPC4RBLF.js";import{c as C,d as M}from"./chunk-DZGPUGUG.js";import{a as k,e as F}from"./chunk-W4II6SIH.js";import{f as D}from"./chunk-WDEXOLK2.js";M();import{createHash as L}from"crypto";import*as x from"path";function Q(){let o="3.15.12",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var U={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function N(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function j(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...U,...e}}computeFingerprint(e,t,r,i){let n=N({action:t,build:Q(),domain:e,input:r,scope:j(i)});return L("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{d()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=d();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
@@ -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.15.11");process.exit(0)}
2
- import{a as l,d as b}from"./chunk-M5XYIQYZ.js";import{a as d,b as g}from"./chunk-5N25I53C.js";import{a as f}from"./chunk-IO5537OM.js";import{c as p}from"./chunk-FZHSG75I.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
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.15.12");process.exit(0)}
2
+ import{a as l,d as b}from"./chunk-ZROAMFX2.js";import{a as d,b as g}from"./chunk-3IU4LDZR.js";import{a as f}from"./chunk-UJNGGFGX.js";import{c as p}from"./chunk-ADUAJIAU.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
@@ -0,0 +1,13 @@
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.15.12");process.exit(0)}
2
+ import{b as Q,d as q}from"./chunk-6QRI3JVE.js";import{c as z,d as me}from"./chunk-DZGPUGUG.js";import{a as F,e as pe}from"./chunk-W4II6SIH.js";q();pe();q();import*as _ from"node:http";import*as D from"node:https";import{createHash as ue}from"node:crypto";import{URL as X}from"node:url";var N={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},fe="AQE embedder endpoint identity canary v1",ge="/v1/embeddings";function J(t){if(t.startsWith("unix:"))return t;try{let e=new X(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function he(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new X(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var U=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}trip(){this.trippedAt=Date.now()}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??N.model,expectedDim:e.expectedDim??N.expectedDim,connectTimeoutMs:e.connectTimeoutMs??N.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??N.requestTimeoutMs,failureThreshold:e.failureThreshold??N.failureThreshold,failureWindowMs:e.failureWindowMs??N.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=he(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new D.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new _.Agent({keepAlive:!0});this.breaker=new U(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([fe]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=ue("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}async probeThroughOpenBreaker(){try{return await this.probe()}catch(e){throw this.breaker.trip(),e}}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return Q(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ge,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=_.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?D.request:_.request);let o=this.parsed.safeUrl,c=this.opts.connectTimeoutMs,S=this.opts.requestTimeoutMs;return new Promise((p,k)=>{let w=!1,M=d=>{w||(w=!0,p(d))},b=d=>{w||(w=!0,k(d))},I=s(i,d=>{let h=[];d.on("data",f=>h.push(Buffer.from(f))),d.on("end",()=>{let f=Buffer.concat(h).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){b(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${f.slice(0,200)}`));return}try{let y=JSON.parse(f);M(y)}catch(y){b(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${y.message}`))}}),d.on("error",f=>b(f))});I.on("socket",d=>{d.setTimeout(c);let h=()=>{d.setTimeout(S)};d.connecting?d.once("connect",h):h(),d.on("timeout",()=>{let f=d.connecting?"connect":"request",y=d.connecting?c:S,R=new Error(`[EmbedderEndpointClient] ${f} timeout after ${y}ms`);b(R),I.destroy(R)})}),I.on("error",d=>b(d)),I.write(n),I.end()})}};me();import{join as K,resolve as Ee}from"node:path";import{existsSync as be,mkdirSync as ye}from"node:fs";import{createRequire as we}from"node:module";var Ie=we(import.meta.url);function ve(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:Ee(z(),t):K(z(),".agentic-qe","memory.db")}var Y="_system",Z="embedder_identity:",C=null,B=!1;function ee(){if(C)return C;if(B)return null;try{let t=Ie("better-sqlite3"),e=ve(),n=K(e,"..");be(n)||ye(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
+ CREATE TABLE IF NOT EXISTS kv_store (
4
+ key TEXT NOT NULL,
5
+ namespace TEXT NOT NULL,
6
+ value TEXT NOT NULL,
7
+ expires_at INTEGER,
8
+ created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
9
+ PRIMARY KEY (namespace, key)
10
+ );
11
+ CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
+ `),C=r,r}catch{return B=!0,null}}function te(t){let e=ee();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(Y,Z+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function ne(t){let e=ee();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Z+t.endpoint,Y,JSON.stringify(n))}function re(){if(C)try{C.close()}catch{}C=null,B=!1}q();import{createHash as oe}from"node:crypto";import{existsSync as xe,readFileSync as Te,renameSync as Se,writeFileSync as Ne}from"node:fs";var se="aqe embedding-space compatibility canary v1";var v=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Ce(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function ae(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return oe("sha256").update(e).digest("hex").slice(0,16)}function V(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=oe("sha256").update("aqe:embedding-space:v1\0").update(Ce(t)).digest("hex");return{...t,spaceId:e}}function We(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}var Re="[VectorSearch] WARN: semantic vector search is not active: no embedding runtime was available when the ANN indexes were opened (set AQE_EMBEDDER_ENDPOINT, or install @huggingface/transformers). Any existing vectors in patterns.rvf and brain.rvf are kept and will be used once an embedder is available; until then pattern search uses SQLite text matching.",Ge="VECTOR_SPACE_UNVERIFIED: no embedding runtime was available when the RVF index was opened; index left unbound (existing vectors are kept)",ie=!1;function je(){ie||(ie=!0,console.warn(Re))}function _e(t){return`${t}.space.json`}function Qe(t,e,n){if(!e)throw new v("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=_e(t);if(xe(r)){let s;try{s=JSON.parse(Te(r,"utf8"))}catch{throw new v("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new v("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new v("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new v("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;Ne(i,`${JSON.stringify(a)}
13
+ `,{encoding:"utf8",mode:384}),Se(i,r)}var H=null,g=null,x=null,E=!1,A="",L=null,m=null,l=null,T=null,G={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},u=new Map,de=36e5;function W(t){return l?`endpoint:${l.fingerprint}:${t}`:`inproc:${t}`}function le(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function O(t={},e=!1){if(E&&!e)throw new Error(`Transformer initialization previously failed: ${A}`);if(x)return x;let n={...G,...t};return x=(async()=>{try{if(n.endpoint){let S=J(n.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${S}`),m=new P({endpoint:n.endpoint,token:n.endpointToken,model:n.modelName,expectedDim:$()}),l=await m.probe(),T=V({provider:"openai-compatible-endpoint",model:n.modelName,dimensions:l.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:l.endpoint,runtimeFingerprint:l.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${l.dim} fingerprint=${l.fingerprint}`);try{let p=te(l.endpoint);p&&p.fingerprint!==l.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${p.fingerprint} dim=${p.dim}, current fingerprint=${l.fingerprint} dim=${l.dim}. Vectors written before this change may no longer be comparable.`),ne(l)}catch(p){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(p)}`)}g=Me(m),E=!1,A="";return}let r;try{r=await import("./transformers-U2ML3OHE.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}H=r.pipeline,console.log(`[RealEmbeddings] Loading model: ${n.modelName}`);let a=performance.now();g=await H("feature-extraction",n.modelName,{quantized:n.quantized});let i=g;if(!i)throw new Error("Transformer pipeline returned no embedding model");let s=await i(se,{pooling:"mean",normalize:!0}),o=Array.from(s.data);T=V({provider:"huggingface-transformers",model:n.modelName,dimensions:o.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${n.quantized?"quantized":"full"}`,runtimeFingerprint:ae(o)}),E=!1,A="";let c=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${c.toFixed(0)}ms`)}catch(r){throw E=!0,A=F(r),new Error(`Failed to initialize transformer model: ${A}`)}})(),x}function Me(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??$(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function et(t,e={}){let n={...G,...e};if(le(t))return new Array($()).fill(0);if(g||await O(e),!g)throw new Error("Embedding model failed to initialize");let r=W(t);if(n.enableCache){let c=u.get(r);if(c&&Date.now()-c.timestamp<de)return c.embedding}let a=performance.now(),i=await g(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(u.size>=n.maxCacheSize){let c=u.keys().next().value;c&&u.delete(c)}u.set(r,{embedding:s,timestamp:Date.now()})}return s}async function tt(t,e={}){let n={...G,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)le(t[o])?i[o]=new Array($()).fill(0):s.push(o);if(s.length===0)return i;if(g||await O(e),!g)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let c=u.get(W(t[o]));c&&Date.now()-c.timestamp<de?i[o]=c.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),c=32;for(let p=0;p<r.length;p+=c){let k=Math.min(p+c,r.length),w=r.slice(p,k),M=await g(w,{pooling:"mean",normalize:!0}),b=M.dims||[w.length,384],I=b[0],d=b[1];for(let h=0;h<I;h++){let f=h*d,y=Array.from(M.data.slice(f,f+d)),R=p+h,ce=a[R];if(i[ce]=y,n.enableCache){if(u.size>=n.maxCacheSize){let j=u.keys().next().value;j&&u.delete(j)}u.set(W(r[R]),{embedding:y,timestamp:Date.now()})}}}let S=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${S.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function nt(){u.clear(),console.log("[RealEmbeddings] Cache cleared")}function rt(){return{size:u.size,hitRate:0}}function it(){return!E&&g!==null}function $(){return 384}function ot(){H=null,g=null,x=null,E=!1,A="",u.clear(),m&&m.close(),m=null,l=null,T=null,re()}function st(){E&&(E=!1,A="",x=null,m&&m.close(),m=null,l=null)}async function at(t={}){if(E)return L??=Pe(t).finally(()=>{L=null}),L;let e=m;if(!e||!e.getBreakerState().open)return;let n=await e.probeThroughOpenBreaker();if(l&&n.fingerprint!==l.fingerprint)throw new Error(`[RealEmbeddings] endpoint identity changed since this process bound to it (fingerprint ${l.fingerprint} -> ${n.fingerprint}); restart to use the new embedding space`)}async function Pe(t){m&&m.close(),m=null,l=null,x=null,await O(t,!0)}function dt(){return m!==null}function lt(){return l}function ct(){return T}async function pt(){if(T)return T;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await O({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),T):null}export{J as a,se as b,We as c,Ge as d,je as e,Qe as f,G as g,et as h,tt as i,nt as j,rt as k,it as l,$ as m,ot as n,st as o,at as p,dt as q,lt as r,ct as s,pt as t};
@@ -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.15.11");process.exit(0)}
2
- import{a as _}from"./chunk-G4CKPWF6.js";import{a as w}from"./chunk-E44NNCEU.js";import{d as k,f as q}from"./chunk-5HQP4SLM.js";import{r as M,v as U}from"./chunk-LD5CFK53.js";import{b as f,d as P}from"./chunk-JFLU7L3W.js";import{a as g,e as F}from"./chunk-DDEOZPWJ.js";import{a as R}from"./chunk-CFWGGRE7.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e=Object.create(null);for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.12");process.exit(0)}
2
+ import{a as _}from"./chunk-DAUEK66C.js";import{a as w}from"./chunk-RYHG3I7J.js";import{d as k,f as q}from"./chunk-TGMXUZZC.js";import{r as M,v as U}from"./chunk-L7NGKANW.js";import{b as f,d as P}from"./chunk-WTAUF6O4.js";import{a as g,e as F}from"./chunk-W4II6SIH.js";import{a as R}from"./chunk-WDEXOLK2.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e=Object.create(null);for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
3
  SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
4
  `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
5
5
  INSERT OR REPLACE INTO routing_outcomes (
@@ -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.15.11");process.exit(0)}
2
- import{b as t,d as o}from"./chunk-CFWGGRE7.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
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.15.12");process.exit(0)}
2
+ import{b as t,d as o}from"./chunk-WDEXOLK2.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};