agentic-qe 3.13.12 → 3.14.0

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 (415) hide show
  1. package/.claude/skills/qe-court/SKILL.md +4 -4
  2. package/.claude/skills/qe-court/config-schema.json +38 -0
  3. package/.claude/skills/qe-court/evals/qe-court.yaml +8 -8
  4. package/.claude/skills/skills-manifest.json +1 -1
  5. package/CHANGELOG.md +53 -0
  6. package/assets/skills/qe-court/SKILL.md +4 -4
  7. package/assets/skills/qe-court/config-schema.json +38 -0
  8. package/assets/skills/qe-court/evals/qe-court.yaml +8 -8
  9. package/assets/skills/skills-manifest.json +1 -1
  10. package/dist/cli/brain-commands.d.ts +1 -0
  11. package/dist/cli/brain-commands.js +1 -0
  12. package/dist/cli/bundle.js +5 -5
  13. package/dist/cli/chunks/adapter-3VBXL7DO.js +2 -0
  14. package/dist/cli/chunks/{agent-booster-wasm-7I7LZFNC.js → agent-booster-wasm-JZO6VUW4.js} +2 -2
  15. package/dist/cli/chunks/{agent-handler-QZZT52BH.js → agent-handler-534KFGEJ.js} +2 -2
  16. package/dist/cli/chunks/{agent-memory-branch-MLQS5Y26.js → agent-memory-branch-B7KWLWY4.js} +2 -2
  17. package/dist/cli/chunks/aqe-learning-engine-NXRNKJNA.js +2 -0
  18. package/dist/cli/chunks/{arena-IM4CP6LP.js → arena-7CCD3S3I.js} +2 -2
  19. package/dist/cli/chunks/{arena-WRIY37EJ.js → arena-OW5MELJX.js} +4 -4
  20. package/dist/cli/chunks/{audit-BSAQ4EFN.js → audit-BHVKN4E2.js} +3 -3
  21. package/dist/cli/chunks/base-F6GMOKU2.js +2 -0
  22. package/dist/cli/chunks/{better-sqlite3-X2XZUXWZ.js → better-sqlite3-P5FA6WFK.js} +2 -2
  23. package/dist/cli/chunks/brain-handler-WNW5LOV7.js +90 -0
  24. package/dist/cli/chunks/{branch-enumerator-NI4Q7DSJ.js → branch-enumerator-TVZ2ODKH.js} +2 -2
  25. package/dist/cli/chunks/{browser-PXBLORUZ.js → browser-TCEB2W2F.js} +2 -2
  26. package/dist/cli/chunks/browser-workflow-QRDC46LR.js +2 -0
  27. package/dist/cli/chunks/{chunk-4FVOJBEU.js → chunk-2D7UBX5S.js} +1 -1
  28. package/dist/cli/chunks/{chunk-NG6A7LCG.js → chunk-2HYVOX6N.js} +1 -1
  29. package/dist/cli/chunks/{chunk-MGKH4LCM.js → chunk-2NO4H35K.js} +1 -1
  30. package/dist/cli/chunks/{chunk-UC4EIULB.js → chunk-2O4DDPEA.js} +19 -19
  31. package/dist/cli/chunks/{chunk-IT5QIUUA.js → chunk-3EM2MK3Z.js} +2 -2
  32. package/dist/cli/chunks/chunk-3GUO4ERR.js +24 -0
  33. package/dist/cli/chunks/{chunk-XIKYUBIV.js → chunk-3JIJBR4V.js} +2 -2
  34. package/dist/cli/chunks/{chunk-NL2SCAGJ.js → chunk-3QT6S3A3.js} +3 -3
  35. package/dist/cli/chunks/{chunk-SOS37ECY.js → chunk-3RYTAYR6.js} +1 -1
  36. package/dist/cli/chunks/chunk-43GPSYAL.js +14 -0
  37. package/dist/cli/chunks/{chunk-IPDM3CAK.js → chunk-4FEJEVG7.js} +1 -1
  38. package/dist/cli/chunks/{chunk-M3354CE4.js → chunk-4MK2G6TK.js} +2 -2
  39. package/dist/cli/chunks/{chunk-AM42ROKZ.js → chunk-4XTHRAUV.js} +1 -1
  40. package/dist/cli/chunks/{chunk-LRO74LPA.js → chunk-4ZVGSVHV.js} +4 -4
  41. package/dist/cli/chunks/{chunk-I5SXLV7D.js → chunk-52DFCV57.js} +2 -2
  42. package/dist/cli/chunks/{chunk-WYFAPA2G.js → chunk-5LEAGKX5.js} +2 -2
  43. package/dist/cli/chunks/{chunk-OZ53BIY5.js → chunk-5MZF4N4Q.js} +1 -1
  44. package/dist/cli/chunks/{chunk-NDRZZSD5.js → chunk-5VDVYTO5.js} +2 -2
  45. package/dist/cli/chunks/chunk-5XGVSQS2.js +11 -0
  46. package/dist/cli/chunks/{chunk-SXFSJJZF.js → chunk-6AOZU3UN.js} +2 -2
  47. package/dist/cli/chunks/{chunk-2VTX4SYW.js → chunk-6AYO3IR2.js} +2 -2
  48. package/dist/cli/chunks/{chunk-4AITMWFZ.js → chunk-6DPAMYLU.js} +2 -2
  49. package/dist/cli/chunks/{chunk-WE3VKDMK.js → chunk-6IJMD2ZL.js} +3 -3
  50. package/dist/cli/chunks/{chunk-5E76HULA.js → chunk-6IZQSLYZ.js} +2 -2
  51. package/dist/cli/chunks/{chunk-VBHA4SDU.js → chunk-6W42XWLL.js} +2 -2
  52. package/dist/cli/chunks/{chunk-ASWWBNX2.js → chunk-7BOPFN3Y.js} +2 -2
  53. package/dist/cli/chunks/{chunk-SCQNISGS.js → chunk-7OUMJCJT.js} +1 -1
  54. package/dist/cli/chunks/{chunk-M73KM3AZ.js → chunk-7RAB2BZY.js} +160 -26
  55. package/dist/cli/chunks/{chunk-4ANJV6I4.js → chunk-7RVAHJQZ.js} +3 -3
  56. package/dist/cli/chunks/{chunk-VQCLSX7T.js → chunk-A2WZEMWT.js} +1 -1
  57. package/dist/cli/chunks/{chunk-YQOQVSYU.js → chunk-A7SKM6JL.js} +1 -1
  58. package/dist/cli/chunks/chunk-AFGT26NR.js +2 -0
  59. package/dist/cli/chunks/{chunk-JVFZAJ5N.js → chunk-AR6SATU3.js} +2 -2
  60. package/dist/cli/chunks/{chunk-YL2GOJF6.js → chunk-AVLA5PBJ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-R7LGVJMZ.js → chunk-B3H4K7CY.js} +2 -2
  62. package/dist/cli/chunks/{chunk-UWZYXI3R.js → chunk-BQCTO7UB.js} +2 -2
  63. package/dist/cli/chunks/{chunk-HAJG44BD.js → chunk-BZ4QVFP2.js} +2 -2
  64. package/dist/cli/chunks/{chunk-NNLZAVFH.js → chunk-CIUOC5F3.js} +1 -1
  65. package/dist/cli/chunks/{chunk-KRZYWVS3.js → chunk-CIZ6LSNV.js} +2 -2
  66. package/dist/cli/chunks/{chunk-HQWFZQMJ.js → chunk-DDPJUAXQ.js} +2 -2
  67. package/dist/cli/chunks/{chunk-X3JNFQW2.js → chunk-DJITEQYS.js} +2 -2
  68. package/dist/cli/chunks/{chunk-TB2N3CAK.js → chunk-DOWCOZDO.js} +2 -2
  69. package/dist/cli/chunks/{chunk-GJJWXRAD.js → chunk-E4NU4BJA.js} +2 -2
  70. package/dist/cli/chunks/{chunk-H3GAR4SV.js → chunk-E722WNWC.js} +2 -2
  71. package/dist/cli/chunks/chunk-ECTPFCON.js +2 -0
  72. package/dist/cli/chunks/{chunk-4YFXF5AQ.js → chunk-EJ6IP7DE.js} +5 -5
  73. package/dist/cli/chunks/{chunk-AN5CGTTJ.js → chunk-ENGKLFLY.js} +2 -2
  74. package/dist/cli/chunks/{chunk-7A4WTRWI.js → chunk-FF43SRP6.js} +1 -1
  75. package/dist/cli/chunks/{chunk-52VGZJSD.js → chunk-FOHYBR3O.js} +1 -1
  76. package/dist/cli/chunks/{chunk-6KI6LAAZ.js → chunk-FRL3X2QA.js} +2 -2
  77. package/dist/cli/chunks/{chunk-3ASVQILY.js → chunk-GKNDP5VK.js} +2 -2
  78. package/dist/cli/chunks/{chunk-2VY7FL6A.js → chunk-GVEJP5T7.js} +2 -2
  79. package/dist/cli/chunks/{chunk-VD53LBF7.js → chunk-H3YDDKBW.js} +3 -3
  80. package/dist/cli/chunks/{chunk-Z6DSYLAG.js → chunk-H6NFDOMK.js} +1 -1
  81. package/dist/cli/chunks/{chunk-BZIPYXSW.js → chunk-H76TV4UU.js} +3 -3
  82. package/dist/cli/chunks/{chunk-XT473WPO.js → chunk-HJIAVR6P.js} +2 -2
  83. package/dist/cli/chunks/{chunk-MLXLGBQZ.js → chunk-HLNQDRHA.js} +1 -1
  84. package/dist/cli/chunks/{chunk-DGFINXUE.js → chunk-HNKPLVYS.js} +1 -1
  85. package/dist/cli/chunks/{chunk-WXU7FAEB.js → chunk-HQ7243G3.js} +2 -2
  86. package/dist/cli/chunks/{chunk-VA2ORJB5.js → chunk-HQHLHSJO.js} +2 -2
  87. package/dist/cli/chunks/{chunk-2W3D5A4R.js → chunk-I3VHXA2W.js} +2 -2
  88. package/dist/cli/chunks/{chunk-EG73WYAW.js → chunk-IE5LC7MB.js} +2 -2
  89. package/dist/cli/chunks/{chunk-S6WHYOWV.js → chunk-IL4AEB3J.js} +27 -25
  90. package/dist/cli/chunks/{chunk-TWUWLSGQ.js → chunk-IL6QRXRP.js} +6 -6
  91. package/dist/cli/chunks/{chunk-5PNQNBDZ.js → chunk-IQ3JFHZN.js} +1 -1
  92. package/dist/cli/chunks/{chunk-MB2KLJ6Q.js → chunk-IQLRA4FV.js} +1 -1
  93. package/dist/cli/chunks/{chunk-A5RWLPVT.js → chunk-J3XSHJGK.js} +2 -2
  94. package/dist/cli/chunks/{chunk-U5G6OC2C.js → chunk-JAK5UUWH.js} +2 -2
  95. package/dist/cli/chunks/{chunk-E67ZXRG6.js → chunk-JGROLJ33.js} +1 -1
  96. package/dist/cli/chunks/{chunk-VNODKACB.js → chunk-JMKMDSXG.js} +2 -2
  97. package/dist/cli/chunks/{chunk-LXVT6JXO.js → chunk-JRKEBESE.js} +2 -2
  98. package/dist/cli/chunks/{chunk-AKUDUB3O.js → chunk-JTWJR2KY.js} +2 -2
  99. package/dist/cli/chunks/{chunk-IOJ34SXJ.js → chunk-JY4VZ6BN.js} +2 -2
  100. package/dist/cli/chunks/{chunk-AYH3DMW2.js → chunk-K6CGQR5R.js} +1 -1
  101. package/dist/cli/chunks/{chunk-QXO35J6F.js → chunk-KDIZQHG5.js} +2 -2
  102. package/dist/cli/chunks/{chunk-7LATB5IR.js → chunk-KTSCZ7AW.js} +2 -2
  103. package/dist/cli/chunks/{chunk-M7CPJW53.js → chunk-L4C42WYI.js} +2 -2
  104. package/dist/cli/chunks/{chunk-QG5L2JM5.js → chunk-LCSVROU7.js} +10 -10
  105. package/dist/cli/chunks/{chunk-6BSZHNOC.js → chunk-LKR7T3OZ.js} +1 -1
  106. package/dist/cli/chunks/{chunk-GJUGG6UR.js → chunk-LZHTCUCO.js} +2 -2
  107. package/dist/cli/chunks/{chunk-7RVLVIAI.js → chunk-M3HUZD2I.js} +1 -1
  108. package/dist/cli/chunks/{chunk-RP5VFZJO.js → chunk-MO7EITJK.js} +2 -2
  109. package/dist/cli/chunks/{chunk-44NPKZGI.js → chunk-N2YAUDAV.js} +2 -2
  110. package/dist/cli/chunks/{chunk-G6FJHDUG.js → chunk-NDPQ2WPU.js} +1 -1
  111. package/dist/cli/chunks/{chunk-UBOGJHWC.js → chunk-NKWO2X3T.js} +1 -1
  112. package/dist/cli/chunks/{chunk-NJ3QXJ54.js → chunk-NOPVFBQM.js} +2 -2
  113. package/dist/cli/chunks/{chunk-AOOCV56W.js → chunk-NYARYONH.js} +1 -1
  114. package/dist/cli/chunks/{chunk-6KKVMPPR.js → chunk-O2MZZL54.js} +2 -2
  115. package/dist/cli/chunks/{chunk-2JAC57JE.js → chunk-OIYUSWHX.js} +1 -1
  116. package/dist/cli/chunks/{chunk-BODFJ3DC.js → chunk-OONCRNFA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-ZMYV4R32.js → chunk-PEW6FZ47.js} +1 -1
  118. package/dist/cli/chunks/{chunk-42AS3HPO.js → chunk-Q73RRTLE.js} +2 -2
  119. package/dist/cli/chunks/{chunk-IQH2RDN3.js → chunk-QKQZ4IJF.js} +5 -5
  120. package/dist/cli/chunks/{chunk-MYVKTG55.js → chunk-QMMDN4WX.js} +3 -3
  121. package/dist/cli/chunks/chunk-QQCENKCX.js +2 -0
  122. package/dist/cli/chunks/{chunk-7PCIN7UN.js → chunk-QSPRQPEL.js} +2 -2
  123. package/dist/cli/chunks/{chunk-ZSAGRDXA.js → chunk-QZPFUFZG.js} +2 -2
  124. package/dist/cli/chunks/chunk-R2B6EE45.js +2 -0
  125. package/dist/cli/chunks/{chunk-33YZGOT6.js → chunk-R6WJF4D5.js} +2 -2
  126. package/dist/cli/chunks/{chunk-QM4Z7TQH.js → chunk-RGVD6ZUX.js} +1 -1
  127. package/dist/cli/chunks/{chunk-VQD2ELNL.js → chunk-RKUYVVGJ.js} +2 -2
  128. package/dist/cli/chunks/{chunk-5VSS2RBD.js → chunk-S5YVLPXU.js} +2 -2
  129. package/dist/cli/chunks/{chunk-IPZEBALY.js → chunk-SROZXIMT.js} +37 -37
  130. package/dist/cli/chunks/{chunk-GMLRIZ4E.js → chunk-SSV6KSFT.js} +1 -1
  131. package/dist/cli/chunks/{chunk-PVINNJ4P.js → chunk-SUSMHSXT.js} +2 -2
  132. package/dist/cli/chunks/{chunk-KXSUDN46.js → chunk-T3BZAFLP.js} +1 -1
  133. package/dist/cli/chunks/{chunk-MLFELTJX.js → chunk-TGOGCA74.js} +2 -2
  134. package/dist/cli/chunks/{chunk-G45AOQDZ.js → chunk-TKYEP7OR.js} +1 -1
  135. package/dist/cli/chunks/{chunk-KYJBJ56M.js → chunk-TQJE7DNL.js} +2 -2
  136. package/dist/cli/chunks/{chunk-5PI75QYP.js → chunk-TRDEULS7.js} +2 -2
  137. package/dist/cli/chunks/{chunk-OG3DBHIV.js → chunk-U4GZWPKM.js} +2 -2
  138. package/dist/cli/chunks/{chunk-NJ4YVAG7.js → chunk-UI6WSPEK.js} +3 -3
  139. package/dist/cli/chunks/{chunk-4M7YZ2X7.js → chunk-UUJ5VQJM.js} +1 -1
  140. package/dist/cli/chunks/{chunk-UJUK6T4V.js → chunk-VESOYP6A.js} +2 -2
  141. package/dist/cli/chunks/{chunk-7ZVO7I4Q.js → chunk-VOSISOFD.js} +1 -1
  142. package/dist/cli/chunks/{chunk-HRTSYT4N.js → chunk-VPVZHJSU.js} +2 -2
  143. package/dist/cli/chunks/{chunk-66OQ7AB3.js → chunk-VRRG66XB.js} +1 -1
  144. package/dist/cli/chunks/{chunk-4Z4X2ND4.js → chunk-VXU53F7Z.js} +2 -2
  145. package/dist/cli/chunks/{chunk-XM5I7J5S.js → chunk-VYENTZ45.js} +2 -2
  146. package/dist/cli/chunks/chunk-WJXHE52V.js +65 -0
  147. package/dist/cli/chunks/{chunk-3XVZHJQT.js → chunk-WKNWRDA5.js} +1 -1
  148. package/dist/cli/chunks/{chunk-DFLASG3B.js → chunk-WTHAVFIC.js} +1 -1
  149. package/dist/cli/chunks/{chunk-NTALX2YC.js → chunk-WWWX76QB.js} +2 -2
  150. package/dist/cli/chunks/{chunk-L3GBNX7B.js → chunk-XITTURP2.js} +2 -2
  151. package/dist/cli/chunks/{chunk-FI6J3UHJ.js → chunk-XXFKN7LB.js} +1 -1
  152. package/dist/cli/chunks/{chunk-RP2BRRLX.js → chunk-YEAC3DC6.js} +2 -2
  153. package/dist/cli/chunks/{chunk-JTYCOFTD.js → chunk-YKWMKRYB.js} +1 -1
  154. package/dist/cli/chunks/chunk-YKZV7O65.js +2 -0
  155. package/dist/cli/chunks/{chunk-N4OQ4D4V.js → chunk-YW4RNZWT.js} +2 -2
  156. package/dist/cli/chunks/{chunk-P6EFKHNI.js → chunk-ZAAYOENS.js} +2 -2
  157. package/dist/cli/chunks/chunk-ZBKGX72B.js +13 -0
  158. package/dist/cli/chunks/{chunk-TJVTV3HP.js → chunk-ZBOWR4XT.js} +2 -2
  159. package/dist/cli/chunks/{chunk-4THFPRFM.js → chunk-ZCVJCCQQ.js} +2 -2
  160. package/dist/cli/chunks/{chunk-X2SZCVDA.js → chunk-ZI3UO7QR.js} +8 -7
  161. package/dist/cli/chunks/{chunk-DCVFHVPR.js → chunk-ZNSMVQCG.js} +2 -2
  162. package/dist/cli/chunks/{chunk-Z56BBX77.js → chunk-ZQSXG7FA.js} +2 -2
  163. package/dist/cli/chunks/{ci-QAUD62WH.js → ci-B432UH6N.js} +2 -2
  164. package/dist/cli/chunks/{ci-output-TZDVTNE7.js → ci-output-GTHH7WYG.js} +2 -2
  165. package/dist/cli/chunks/{circuit-breaker-ZWPHJ7YJ.js → circuit-breaker-VW75DLME.js} +2 -2
  166. package/dist/cli/chunks/{claude-flow-setup-SCB4EURN.js → claude-flow-setup-RE3IVT7U.js} +2 -2
  167. package/dist/cli/chunks/client-HNBZUEVV.js +2 -0
  168. package/dist/cli/chunks/{cline-installer-EHZLMLXF.js → cline-installer-NUBZZ55N.js} +2 -2
  169. package/dist/cli/chunks/{code-3N6PBJMK.js → code-K6JCWKNW.js} +2 -2
  170. package/dist/cli/chunks/{code-index-extractor-6DIKHNRI.js → code-index-extractor-I4ILB5JN.js} +2 -2
  171. package/dist/cli/chunks/{codex-installer-P7DPQMYL.js → codex-installer-AKQ5BCHU.js} +2 -2
  172. package/dist/cli/chunks/{completions-5MKWWCCE.js → completions-V3KJVJF4.js} +2 -2
  173. package/dist/cli/chunks/{complexity-analyzer-TPM4IPEK.js → complexity-analyzer-HRG7OOY3.js} +2 -2
  174. package/dist/cli/chunks/{continuedev-installer-VXODKGVX.js → continuedev-installer-CNTDONWG.js} +2 -2
  175. package/dist/cli/chunks/{copilot-installer-PVD5O56P.js → copilot-installer-XPWWIWYA.js} +2 -2
  176. package/dist/cli/chunks/core-handlers-TB7NLYXL.js +2 -0
  177. package/dist/cli/chunks/{cost-tracker-JOMZEQF3.js → cost-tracker-MFNLQ56K.js} +2 -2
  178. package/dist/cli/chunks/{coverage-HTXLEV3B.js → coverage-KOIK654V.js} +3 -3
  179. package/dist/cli/chunks/cross-domain-router-MDSI553U.js +2 -0
  180. package/dist/cli/chunks/{cursor-installer-SHKDTDDZ.js → cursor-installer-S5MKLRQQ.js} +2 -2
  181. package/dist/cli/chunks/{daemon-FCFEWVVJ.js → daemon-DUS6JYW6.js} +3 -3
  182. package/dist/cli/chunks/{daemon-PN4FEPLE.js → daemon-Z7VPGWHY.js} +4 -4
  183. package/dist/cli/chunks/{dag-attention-scheduler-PLOHU5SR.js → dag-attention-scheduler-7CQ3ARNI.js} +2 -2
  184. package/dist/cli/chunks/{detect-F3H4ZEZY.js → detect-WORBCAYF.js} +2 -2
  185. package/dist/cli/chunks/{dist-node-5TC665N6.js → dist-node-KRNI6OYW.js} +2 -2
  186. package/dist/cli/chunks/{domain-handler-ZIWVFXCU.js → domain-handler-KRUR2VQG.js} +2 -2
  187. package/dist/cli/chunks/{domain-transfer-7Q5JYMYR.js → domain-transfer-VEOVLV54.js} +2 -2
  188. package/dist/cli/chunks/dream-X7ISHFEE.js +2 -0
  189. package/dist/cli/chunks/embed-and-insert-pattern-QU3NQVA5.js +3 -0
  190. package/dist/cli/chunks/{eval-E2K2T75A.js → eval-AYQ7BSUP.js} +2 -2
  191. package/dist/cli/chunks/{experience-capture-middleware-Z5SE2O53.js → experience-capture-middleware-AWQBL6LT.js} +3 -3
  192. package/dist/cli/chunks/{fast-paths-3H52RSUK.js → fast-paths-V5EL4BYJ.js} +2 -2
  193. package/dist/cli/chunks/{feature-flags-LUHSMHPS.js → feature-flags-BXX7BP22.js} +2 -2
  194. package/dist/cli/chunks/{feature-flags-ONIKUZVK.js → feature-flags-P34BPRWU.js} +2 -2
  195. package/dist/cli/chunks/{file-discovery-FLYSYSS4.js → file-discovery-MS6BKQ2U.js} +2 -2
  196. package/dist/cli/chunks/{fleet-6OJUAAKV.js → fleet-7WVVPA4W.js} +3 -3
  197. package/dist/cli/chunks/{gnn-wrapper-PUL6B7KZ.js → gnn-wrapper-7WQ3LEPG.js} +2 -2
  198. package/dist/cli/chunks/{heartbeat-handler-HGHHDUDY.js → heartbeat-handler-P7QD3BZH.js} +4 -4
  199. package/dist/cli/chunks/heartbeat-scheduler-2C5XGFQT.js +2 -0
  200. package/dist/cli/chunks/hnsw-adapter-KCVMXLUL.js +2 -0
  201. package/dist/cli/chunks/hnsw-index-OGWZS6MP.js +2 -0
  202. package/dist/cli/chunks/{hnsw-legacy-bridge-NDZSNMYX.js → hnsw-legacy-bridge-Y3GAR3UP.js} +2 -2
  203. package/dist/cli/chunks/{hnswlib-node-PISLKSO2.js → hnswlib-node-5QUXZQWQ.js} +2 -2
  204. package/dist/cli/chunks/{hooks-WYG54MRI.js → hooks-2D64KPRY.js} +10 -10
  205. package/dist/cli/chunks/{hypergraph-engine-EDHKHZZ2.js → hypergraph-engine-5INXEZDP.js} +2 -2
  206. package/dist/cli/chunks/{hypergraph-handler-OCHZAPPL.js → hypergraph-handler-YJJJ3ESZ.js} +3 -3
  207. package/dist/cli/chunks/impact-analyzer-IBJ43GQL.js +2 -0
  208. package/dist/cli/chunks/{init-handler-5TCJ672H.js → init-handler-QSFYJN5Q.js} +6 -6
  209. package/dist/cli/chunks/init-wizard-6XMFD5LP.js +2 -0
  210. package/dist/cli/chunks/kernel-UDUMUPB3.js +2 -0
  211. package/dist/cli/chunks/{kilocode-installer-SWUQRCTZ.js → kilocode-installer-3N3QGTJU.js} +2 -2
  212. package/dist/cli/chunks/{kiro-installer-L22EBAM5.js → kiro-installer-GIWVTFZQ.js} +2 -2
  213. package/dist/cli/chunks/knowledge-graph-JRYTUG3W.js +2 -0
  214. package/dist/cli/chunks/learning-SGO2DQ5Q.js +122 -0
  215. package/dist/cli/chunks/{llm-router-F2L4LFT2.js → llm-router-HBBULO65.js} +14 -14
  216. package/dist/cli/chunks/llm-router-service-KF5ZALUQ.js +2 -0
  217. package/dist/cli/chunks/{load-A4ZF2KHC.js → load-B5OFYB4H.js} +2 -2
  218. package/dist/cli/chunks/load-test-LHMBCNCH.js +2 -0
  219. package/dist/cli/chunks/{mcp-T2Z46NNK.js → mcp-FG3LNQR4.js} +2 -2
  220. package/dist/cli/chunks/{memory-PUC3J6XC.js → memory-SPS7ZWLC.js} +5 -5
  221. package/dist/cli/chunks/memory-backend-WZHKHBZK.js +2 -0
  222. package/dist/cli/chunks/memory-handlers-P7FTPWP3.js +2 -0
  223. package/dist/cli/chunks/{multi-model-executor-U5L4FI4O.js → multi-model-executor-PUB7E6KH.js} +2 -2
  224. package/dist/cli/chunks/{opencode-installer-UWI6KHYH.js → opencode-installer-TGCSGVG2.js} +2 -2
  225. package/dist/cli/chunks/{orchestrator-3BEI7R5D.js → orchestrator-S5FTJFGB.js} +10 -13
  226. package/dist/cli/chunks/pattern-null-store-UZSHCRL2.js +2 -0
  227. package/dist/cli/chunks/{pattern-usage-recorder-EGWUI5LU.js → pattern-usage-recorder-LCXXGRAB.js} +2 -2
  228. package/dist/cli/chunks/{pipeline-JG6M4RHD.js → pipeline-ENOSRHKW.js} +2 -2
  229. package/dist/cli/chunks/{platform-F76G6RUI.js → platform-WCRBO3Z7.js} +2 -2
  230. package/dist/cli/chunks/{plugin-EEGN3PMK.js → plugin-JZ5ODJSU.js} +2 -2
  231. package/dist/cli/chunks/{prime-radiant-advanced-wasm-7KZAINFT.js → prime-radiant-advanced-wasm-DPJUPNCG.js} +2 -2
  232. package/dist/cli/chunks/protocol-executor-42NLVDTC.js +2 -0
  233. package/dist/cli/chunks/{protocol-handler-UCEHYK2R.js → protocol-handler-IP4NLVY3.js} +2 -2
  234. package/dist/cli/chunks/{prove-JSNG75VD.js → prove-P6FM4RU7.js} +2 -2
  235. package/dist/cli/chunks/qe-reasoning-bank-W74RSMMU.js +2 -0
  236. package/dist/cli/chunks/{quality-7SRM2HBM.js → quality-UHP4XO26.js} +2 -2
  237. package/dist/cli/chunks/{quality-gate-A5MPWHST.js → quality-gate-63DDBSGM.js} +3 -3
  238. package/dist/cli/chunks/queen-coordinator-XELKSRMS.js +2 -0
  239. package/dist/cli/chunks/real-embeddings-6SO5MFRQ.js +2 -0
  240. package/dist/cli/chunks/{roocode-installer-UYQK64BZ.js → roocode-installer-WTWUOFCH.js} +2 -2
  241. package/dist/cli/chunks/router-GTW2EQZV.js +2 -0
  242. package/dist/cli/chunks/routing-feedback-NVOBWEMK.js +2 -0
  243. package/dist/cli/chunks/{routing-handler-PY3KPDTH.js → routing-handler-IK7HYERQ.js} +2 -2
  244. package/dist/cli/chunks/{ruvector-commands-GCAOUTYS.js → ruvector-commands-THLB4NIM.js} +2 -2
  245. package/dist/cli/chunks/rvf-dual-writer-5OPVMXNL.js +2 -0
  246. package/dist/cli/chunks/rvf-migration-adapter-5S4YFTX4.js +2 -0
  247. package/dist/cli/chunks/rvf-migration-coordinator-BUKCSHBD.js +2 -0
  248. package/dist/cli/chunks/rvf-native-adapter-LYSJHEVX.js +2 -0
  249. package/dist/cli/chunks/{rvf-store-integrity-HNDKOM4L.js → rvf-store-integrity-ECTADZIN.js} +2 -2
  250. package/dist/cli/chunks/safe-db-AEB3JMLD.js +2 -0
  251. package/dist/cli/chunks/schedule-4QNPCQNT.js +2 -0
  252. package/dist/cli/chunks/scheduler-S3DFHX6A.js +2 -0
  253. package/dist/cli/chunks/{security-MQ2VB7PY.js → security-HN4UXFXX.js} +3 -3
  254. package/dist/cli/chunks/{shared-rvf-adapter-TAZEU6QK.js → shared-rvf-adapter-XJCPX5SN.js} +2 -2
  255. package/dist/cli/chunks/{shared-rvf-dual-writer-B7N6AOCY.js → shared-rvf-dual-writer-23X5PNY5.js} +2 -2
  256. package/dist/cli/chunks/sqlite-persistence-L2KISU2H.js +2 -0
  257. package/dist/cli/chunks/{status-handler-NZP7DFHE.js → status-handler-ZXANTHKT.js} +2 -2
  258. package/dist/cli/chunks/{structural-health-ALLUQ4X6.js → structural-health-LR6WI3AH.js} +2 -2
  259. package/dist/cli/chunks/{sync-WJJG5J6V.js → sync-4OEI3BC2.js} +2 -2
  260. package/dist/cli/chunks/{sync-MM7OCUYD.js → sync-I5IUJF33.js} +2 -2
  261. package/dist/cli/chunks/{task-handler-CAQUEEB4.js → task-handler-R3ATJKU5.js} +2 -2
  262. package/dist/cli/chunks/{task-handlers-25BJ7D3W.js → task-handlers-4X357AEW.js} +3 -3
  263. package/dist/cli/chunks/{test-HW7GVGVN.js → test-PR2B5H2F.js} +4 -4
  264. package/dist/cli/chunks/{test-scheduling-HTMFJMSP.js → test-scheduling-ZNOSQVLD.js} +3 -3
  265. package/dist/cli/chunks/token-bootstrap-LYXOI72S.js +2 -0
  266. package/dist/cli/chunks/{token-usage-RJZDMBDP.js → token-usage-R6EQZBX2.js} +2 -2
  267. package/dist/cli/chunks/{transformers-3YFW3EUO.js → transformers-COQWK27J.js} +2 -2
  268. package/dist/cli/chunks/{tree-sitter-wasm-parser-U3PQPIK7.js → tree-sitter-wasm-parser-LLIW2X3M.js} +2 -2
  269. package/dist/cli/chunks/{types-7Q762WDO.js → types-MEYTZITK.js} +2 -2
  270. package/dist/cli/chunks/unified-memory-5KQMA7FV.js +2 -0
  271. package/dist/cli/chunks/unified-memory-hnsw-PQRPTYOD.js +2 -0
  272. package/dist/cli/chunks/unified-persistence-YDONVPJB.js +2 -0
  273. package/dist/cli/chunks/{upgrade-F7MKJWBQ.js → upgrade-DVIJ456A.js} +2 -2
  274. package/dist/cli/chunks/{validate-B27AVRA6.js → validate-UYTSMJ5X.js} +2 -2
  275. package/dist/cli/chunks/{validate-swarm-GYZR3GNL.js → validate-swarm-P32WCJR6.js} +2 -2
  276. package/dist/cli/chunks/{vibium-W4XQMPJP.js → vibium-JGVOLM6X.js} +2 -2
  277. package/dist/cli/chunks/visual-security-RJ7RTNGJ.js +2 -0
  278. package/dist/cli/chunks/{web-tree-sitter-I7CDCFJU.js → web-tree-sitter-5ZGNCTPN.js} +2 -2
  279. package/dist/cli/chunks/{windsurf-installer-UYLHFDHU.js → windsurf-installer-IILSSQAE.js} +2 -2
  280. package/dist/cli/chunks/{witness-chain-B66SYZKU.js → witness-chain-JZMXCG3B.js} +2 -2
  281. package/dist/cli/chunks/witness-chain-YXXXNGAM.js +2 -0
  282. package/dist/cli/chunks/{witness-key-manager-U4JPAHVW.js → witness-key-manager-UUTLNUIH.js} +2 -2
  283. package/dist/cli/chunks/{workflow-DYMO47FF.js → workflow-NS7HXVHZ.js} +4 -4
  284. package/dist/cli/chunks/workflow-orchestrator-5KUAVSTH.js +2 -0
  285. package/dist/cli/chunks/{wrappers-7S6DQTEA.js → wrappers-XKEDSV5W.js} +2 -2
  286. package/dist/cli/commands/learning.js +44 -0
  287. package/dist/cli/commands/llm-router.js +27 -21
  288. package/dist/cli/handlers/brain-handler.js +2 -0
  289. package/dist/context/compaction/index.d.ts +1 -0
  290. package/dist/context/compaction/index.js +3 -0
  291. package/dist/context/compaction/instruction-provenance.d.ts +20 -0
  292. package/dist/context/compaction/instruction-provenance.js +18 -0
  293. package/dist/context/compaction/tier2-session-summary.d.ts +8 -0
  294. package/dist/context/compaction/tier2-session-summary.js +20 -0
  295. package/dist/context/compaction/tier3-llm-compact.d.ts +4 -0
  296. package/dist/context/compaction/tier3-llm-compact.js +32 -4
  297. package/dist/init/phases/07-hooks.js +0 -3
  298. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +4 -2
  299. package/dist/integrations/ruvector/brain-exporter.d.ts +1 -1
  300. package/dist/integrations/ruvector/brain-exporter.js +15 -3
  301. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +4 -0
  302. package/dist/integrations/ruvector/brain-rvf-exporter.js +118 -37
  303. package/dist/integrations/ruvector/brain-search.d.ts +1 -1
  304. package/dist/integrations/ruvector/brain-search.js +1 -1
  305. package/dist/integrations/ruvector/brain-shared.d.ts +4 -2
  306. package/dist/integrations/ruvector/brain-shared.js +11 -4
  307. package/dist/integrations/ruvector/brain-table-ddl.d.ts +2 -2
  308. package/dist/integrations/ruvector/brain-table-ddl.js +20 -8
  309. package/dist/integrations/ruvector/cognitive-container.js +1 -1
  310. package/dist/integrations/ruvector/rvf-dual-writer.d.ts +4 -0
  311. package/dist/integrations/ruvector/rvf-dual-writer.js +57 -9
  312. package/dist/integrations/ruvector/rvf-store-integrity.js +1 -1
  313. package/dist/kernel/unified-memory-schemas.d.ts +4 -3
  314. package/dist/kernel/unified-memory-schemas.js +19 -9
  315. package/dist/kernel/unified-memory.d.ts +2 -0
  316. package/dist/kernel/unified-memory.js +19 -0
  317. package/dist/learning/embed-and-insert-pattern.js +6 -3
  318. package/dist/learning/embedding-space.d.ts +50 -0
  319. package/dist/learning/embedding-space.js +128 -0
  320. package/dist/learning/evidence-admission-store.d.ts +15 -0
  321. package/dist/learning/evidence-admission-store.js +68 -0
  322. package/dist/learning/index.d.ts +4 -0
  323. package/dist/learning/index.js +2 -0
  324. package/dist/learning/learning-evidence-admission.d.ts +44 -0
  325. package/dist/learning/learning-evidence-admission.js +97 -0
  326. package/dist/learning/pattern-store.d.ts +5 -0
  327. package/dist/learning/pattern-store.js +36 -7
  328. package/dist/learning/qe-flywheel/coupled-anchor.d.ts +8 -0
  329. package/dist/learning/qe-flywheel/coupled-anchor.js +46 -3
  330. package/dist/learning/qe-reasoning-bank.js +4 -0
  331. package/dist/learning/real-embeddings.d.ts +3 -0
  332. package/dist/learning/real-embeddings.js +40 -3
  333. package/dist/learning/real-qe-reasoning-bank.js +7 -3
  334. package/dist/learning/rvf-pattern-migration.d.ts +2 -0
  335. package/dist/learning/rvf-pattern-migration.js +5 -3
  336. package/dist/learning/rvf-pattern-store.d.ts +3 -0
  337. package/dist/learning/rvf-pattern-store.js +21 -1
  338. package/dist/learning/sqlite-persistence.d.ts +7 -2
  339. package/dist/learning/sqlite-persistence.js +58 -21
  340. package/dist/mcp/bundle.js +603 -447
  341. package/dist/mcp/handlers/memory-handlers.js +6 -2
  342. package/dist/migrations/20260830_add_learning_evidence_tables.d.ts +7 -0
  343. package/dist/migrations/20260830_add_learning_evidence_tables.js +173 -0
  344. package/dist/persistence/rvf-migration-adapter.d.ts +2 -0
  345. package/dist/persistence/rvf-migration-adapter.js +56 -12
  346. package/dist/shared/llm/llm-router-service.d.ts +8 -0
  347. package/dist/shared/llm/llm-router-service.js +21 -3
  348. package/dist/shared/sql-safety.js +4 -0
  349. package/dist/skills/qe-court/cli.d.ts +3 -0
  350. package/dist/skills/qe-court/cli.js +54 -0
  351. package/dist/verification/adversarial-verify/calibrate.d.ts +46 -2
  352. package/dist/verification/adversarial-verify/calibrate.js +104 -2
  353. package/dist/verification/adversarial-verify/index.d.ts +1 -1
  354. package/dist/verification/adversarial-verify/index.js +1 -1
  355. package/package.json +8 -3
  356. package/dist/cli/chunks/adapter-FUV6LBJT.js +0 -2
  357. package/dist/cli/chunks/aqe-learning-engine-QNFNA3J4.js +0 -2
  358. package/dist/cli/chunks/base-37W2XIXC.js +0 -2
  359. package/dist/cli/chunks/brain-handler-TVTTWZGP.js +0 -89
  360. package/dist/cli/chunks/browser-workflow-PDIUEK7B.js +0 -2
  361. package/dist/cli/chunks/chunk-EDRPTLAX.js +0 -2
  362. package/dist/cli/chunks/chunk-GEQWCK4F.js +0 -2
  363. package/dist/cli/chunks/chunk-GQLJYTXN.js +0 -2
  364. package/dist/cli/chunks/chunk-NLZUGANH.js +0 -11
  365. package/dist/cli/chunks/chunk-O4BWESH5.js +0 -2
  366. package/dist/cli/chunks/chunk-PGFCKE4G.js +0 -12
  367. package/dist/cli/chunks/chunk-RACWX2ZX.js +0 -9
  368. package/dist/cli/chunks/chunk-SNC73DWF.js +0 -2
  369. package/dist/cli/chunks/chunk-TDVMILKO.js +0 -2
  370. package/dist/cli/chunks/chunk-TK5XLF3Z.js +0 -65
  371. package/dist/cli/chunks/chunk-UQ4UCHO7.js +0 -2
  372. package/dist/cli/chunks/chunk-VZGP77YU.js +0 -12
  373. package/dist/cli/chunks/chunk-WA6CSEOX.js +0 -2
  374. package/dist/cli/chunks/chunk-WYIXNHPF.js +0 -2
  375. package/dist/cli/chunks/client-4W3KWTAU.js +0 -2
  376. package/dist/cli/chunks/core-handlers-BDU2XBLO.js +0 -2
  377. package/dist/cli/chunks/cross-domain-router-BPB6IHN4.js +0 -2
  378. package/dist/cli/chunks/dream-WFCZGFDY.js +0 -2
  379. package/dist/cli/chunks/embed-and-insert-pattern-VESJQSYD.js +0 -3
  380. package/dist/cli/chunks/heartbeat-scheduler-HWS4SHRM.js +0 -2
  381. package/dist/cli/chunks/hnsw-adapter-7QOBHKRB.js +0 -2
  382. package/dist/cli/chunks/hnsw-index-6WUKYJH7.js +0 -2
  383. package/dist/cli/chunks/hybrid-router-525JTRA5.js +0 -2
  384. package/dist/cli/chunks/impact-analyzer-GG6CJEOK.js +0 -2
  385. package/dist/cli/chunks/init-wizard-4VFAOK4Y.js +0 -2
  386. package/dist/cli/chunks/kernel-N3FQGOST.js +0 -2
  387. package/dist/cli/chunks/knowledge-graph-I5QIHB4G.js +0 -2
  388. package/dist/cli/chunks/learning-TQOGG3CR.js +0 -119
  389. package/dist/cli/chunks/llm-router-service-NCJZYJLG.js +0 -2
  390. package/dist/cli/chunks/load-test-DCJEYIXD.js +0 -2
  391. package/dist/cli/chunks/memory-backend-O6KO2KTX.js +0 -2
  392. package/dist/cli/chunks/memory-handlers-4Z43WEKD.js +0 -2
  393. package/dist/cli/chunks/pattern-null-store-5WIJKX2K.js +0 -2
  394. package/dist/cli/chunks/protocol-executor-5TPNAZTB.js +0 -2
  395. package/dist/cli/chunks/provider-manager-3VMOZ6HV.js +0 -2
  396. package/dist/cli/chunks/qe-reasoning-bank-BATV4NTT.js +0 -2
  397. package/dist/cli/chunks/queen-coordinator-EIHGYBUO.js +0 -2
  398. package/dist/cli/chunks/real-embeddings-ZBF5EQOG.js +0 -2
  399. package/dist/cli/chunks/router-EMVGY4HU.js +0 -2
  400. package/dist/cli/chunks/routing-feedback-JUP4OFB2.js +0 -2
  401. package/dist/cli/chunks/rvf-dual-writer-BUNP4SKD.js +0 -2
  402. package/dist/cli/chunks/rvf-migration-adapter-VSOAPLMB.js +0 -2
  403. package/dist/cli/chunks/rvf-migration-coordinator-LSWEHAWX.js +0 -2
  404. package/dist/cli/chunks/rvf-native-adapter-LOC42TQ6.js +0 -2
  405. package/dist/cli/chunks/safe-db-WQ62IQKV.js +0 -2
  406. package/dist/cli/chunks/schedule-XJRP57TE.js +0 -2
  407. package/dist/cli/chunks/scheduler-EZH5SDIM.js +0 -2
  408. package/dist/cli/chunks/sqlite-persistence-HPEVCTIB.js +0 -2
  409. package/dist/cli/chunks/token-bootstrap-F2DCLWGW.js +0 -2
  410. package/dist/cli/chunks/unified-memory-ATILROKR.js +0 -2
  411. package/dist/cli/chunks/unified-memory-hnsw-XJXAX7DW.js +0 -2
  412. package/dist/cli/chunks/unified-persistence-3TN5PBWE.js +0 -2
  413. package/dist/cli/chunks/visual-security-VFWRBCNA.js +0 -2
  414. package/dist/cli/chunks/witness-chain-JC5LEXRV.js +0 -2
  415. package/dist/cli/chunks/workflow-orchestrator-TKQUF2KN.js +0 -2
@@ -0,0 +1,65 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{d as B,e as j,f as re,g as W}from"./chunk-A7SKM6JL.js";import{a as ie}from"./chunk-SSV6KSFT.js";import{b as Ne}from"./chunk-JMKMDSXG.js";import{a as se}from"./chunk-I3VHXA2W.js";import{c as De,n as A}from"./chunk-ZBKGX72B.js";import{b as Ie,c as st}from"./chunk-FRL3X2QA.js";import{a as ne,b as Fe,d as Oe,f as at}from"./chunk-DDPJUAXQ.js";import{c as _e}from"./chunk-QQCENKCX.js";import{b as P,c as w}from"./chunk-JGROLJ33.js";import{a as v,b as Ce,c as xe}from"./chunk-XITTURP2.js";import{i as I}from"./chunk-FOHYBR3O.js";import{B as Q,D as M,G as te,P as L,S as F,b as D}from"./chunk-ENGKLFLY.js";import{d as J,f as it}from"./chunk-PEW6FZ47.js";var G=J(E=>{var pt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var gt=Object.prototype.hasOwnProperty;function ue(n,e){return gt.call(n,e)}E.hasOwnProperty=ue;function $e(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)ue(n,i)&&r.push(i);return r}E._objectKeys=$e;function yt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=yt;function vt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=vt;function le(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=le;function St(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=St;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return le(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return le(r)+"/"+t}return""}E._getPathRecursive=he;function wt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=wt;function de(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(de(n[e]))return!0}else if(typeof n=="object"){for(var r=$e(n),i=r.length,s=0;s<i;s++)if(de(n[r[s]]))return!0}}return!1}E.hasUndefined=de;function ze(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var Pt=(function(n){pt(e,n);function e(t,r,i,s,a){var c=this.constructor,l=n.call(this,ze(t,{name:r,index:i,operation:s,tree:a}))||this;return l.name=r,l.index=i,l.operation=s,l.tree=a,Object.setPrototypeOf(l,c.prototype),l.message=ze(t,{name:r,index:i,operation:s,tree:a}),l}return e})(Error);E.PatchError=Pt});var fe=J(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var k={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=R._deepClone(r));var i=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:$(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},bt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:k.move,copy:k.copy,test:k.test,_get:k._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=Y;function O(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=$(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",l=c.split("/"),o=n,d=1,f=l.length,h=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=K;;){if(u=l[d],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&d>0&&l[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&h===void 0&&(o[u]===void 0?h=l.slice(0,d).join("/"):d==f-1&&(h=e.path),h!==void 0&&m(e,0,n,h)),d++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!R.isInteger(u))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);R.isInteger(u)&&(u=~~u)}if(d>=f){if(t&&e.op==="add"&&u>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=bt[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(d>=f){var a=k[e.op].call(e,o,u,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&d<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=O;function Je(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=O(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Je;function Et(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=Et;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(k[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Be([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=K;function Be(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Je(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=Be;function $(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!$(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!$(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=$});var je=J(U=>{Object.defineProperty(U,"__esModule",{value:!0});var b=G(),Rt=fe(),pe=new WeakMap,At=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Tt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Ct(n){return pe.get(n)}function xt(n,e){return n.observers.get(e)}function It(n,e){n.observers.delete(e.callback)}function Dt(n,e){e.unobserve()}U.unobserve=Dt;function Ft(n,e){var t=[],r,i=Ct(n);if(!i)i=new At(n),pe.set(n,i);else{var s=xt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){me(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){me(r),clearTimeout(r.next),It(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new Tt(e,r)),r}U.observe=Ft;function me(n,e){e===void 0&&(e=!1);var t=pe.get(n.object);ge(t.value,n.object,n.patches,"",e),n.patches.length&&Rt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}U.generate=me;function ge(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),a=b._objectKeys(n),c=!1,l=!1,o=a.length-1;o>=0;o--){var d=a[o],f=n[d];if(b.hasOwnProperty(e,d)&&!(e[d]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[d];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?ge(f,h,t,r+"/"+b.escapePathComponent(d),i):f!==h&&(c=!0,i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(d),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(d),value:b._deepClone(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(d),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(d)}),l=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!l&&s.length==a.length))for(var o=0;o<s.length;o++){var d=s[o];!b.hasOwnProperty(n,d)&&e[d]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(d),value:b._deepClone(e[d])})}}}function Ot(n,e,t){t===void 0&&(t=!1);var r=[];return ge(n,e,r,"",t),r}U.compare=Ot});var We=J(_=>{var _t=fe();Object.assign(_,_t);var Nt=je();Object.assign(_,Nt);var Z=G();_.JsonPatchError=Z.PatchError;_.deepClone=Z._deepClone;_.escapePathComponent=Z.escapePathComponent;_.unescapePathComponent=Z.unescapePathComponent});st();import{existsSync as Bt}from"node:fs";import{join as tt}from"node:path";xe();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??V,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=A()?.spaceId??this.embeddingSpaceId??null;De(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-L2KISU2H.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(d=>Array.isArray(d)?d[0]:void 0).filter(d=>typeof d=="string")),l=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(d=>d.id)),o=[...c].filter(d=>!l.has(d));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=A()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return w(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));if(this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding,r);i&&i!==e.id&&(e.id=i)}catch(i){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding&&this.adapter)try{let i=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:i}])}catch(i){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(i))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:I(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let c=A()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return w(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),l=this.adapter.search(c,i*2);for(let o of l){let d=await this.get(o.id);if(d&&this.matchesFilters(d,t)){let f=this.calculateReuseInfo(d,o.score);s.push({pattern:d,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),l=e,o=Math.sqrt(l.reduce((d,f)=>d+f*f,0));if(o>0)for(let d of c){if(!this.matchesFilters(d,t))continue;let f=this.sqliteStore.getPattern(d.id),h=f?.embedding;if(!h||h.length!==l.length)continue;let u=0,m=0;for(let S=0;S<l.length;S++)u+=l[S]*h[S],m+=h[S]*h[S];if(m=Math.sqrt(m),m===0)continue;let p=u/(o*m),y=this.calculateReuseInfo(f,p);s.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id)||!this.matchesFilters(o,t))continue;let d=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),l=new Set(s.map(o=>o.pattern.id));for(let o of c){if(l.has(o.id))continue;let d=await this.get(o.id);if(d&&this.matchesFilters(d,t)){let f=this.calculateReuseInfo(d,o.ftsScore);s.push({pattern:d,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}s.sort((c,l)=>l.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return w(new Error(`recordUsage failed: ${v(s)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};at();xe();F();function ct(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function lt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=ct(n,e.field);return lt(t,e.operator,e.value)}default:return!0}}function He(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Le=1e4,ke=2166136261;function Ue(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ce=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ce[n]=e}var Me="0123456789abcdef";function dt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Me[i>>4]+Me[i&15]}return t}function ut(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ht(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,l=1<<a;for(let o=0;o<n.length;o++)n[o][i]&l&&c++;c>=r&&(s|=l)}t[i]=s}return t}function ft(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ce[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function mt(n,e,t){return 1-ft(n,e,t)}var ae=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Le,this.baseSeed=e?.seed??ke,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ue(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=ut(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ht([r,i])}similarity(e,t){return mt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ie(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let l=0;l<c;l++)t[i++]=a>>>l*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},oe=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Le,this.baseSeed=e?.seed??ke,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ue(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:dt(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ce[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ie(e),s=0;for(;s<t;){let c=i.next(),l=t-s,o=l<4?l:4;for(let d=0;d<o;d++)r[s++]=c>>>d*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function qe(n){return new oe(n)}function Qe(n){return Q()?new ae(n):null}var ve=it(We(),1),ye=ve.default??ve,Ht=`
4
+ CREATE TABLE IF NOT EXISTS pattern_deltas (
5
+ id TEXT PRIMARY KEY,
6
+ pattern_id TEXT NOT NULL,
7
+ version INTEGER NOT NULL,
8
+ timestamp INTEGER NOT NULL,
9
+ type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
10
+ patch TEXT NOT NULL DEFAULT '[]',
11
+ reverse_patch TEXT NOT NULL DEFAULT '[]',
12
+ metadata TEXT
13
+ );
14
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
15
+ ON pattern_deltas (pattern_id, version);
16
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
17
+ ON pattern_deltas (timestamp);
18
+ `;function Ve(n,e){let t=ye.compare(n,e),r=ye.compare(e,n);return{forward:t,reverse:r}}function Mt(n,e){let t=JSON.parse(JSON.stringify(n));return ye.applyPatch(t,e).newDocument}function Xe(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var ee=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(Ht),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
+ INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
+ `)),this.prepared.set("getHistory",this.db.prepare(`
22
+ SELECT * FROM pattern_deltas
23
+ WHERE pattern_id = ?
24
+ ORDER BY version ASC
25
+ `)),this.prepared.set("currentVersion",this.db.prepare(`
26
+ SELECT MAX(version) as max_version FROM pattern_deltas
27
+ WHERE pattern_id = ?
28
+ `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
+ SELECT * FROM pattern_deltas
30
+ WHERE timestamp > ?
31
+ ORDER BY timestamp ASC
32
+ `)),this.prepared.set("countForPattern",this.db.prepare(`
33
+ SELECT COUNT(*) as cnt FROM pattern_deltas
34
+ WHERE pattern_id = ?
35
+ `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
+ DELETE FROM pattern_deltas
37
+ WHERE pattern_id = ? AND version IN (
38
+ SELECT version FROM pattern_deltas
39
+ WHERE pattern_id = ?
40
+ ORDER BY version ASC
41
+ LIMIT ?
42
+ )
43
+ `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:I(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}=Ve(t,r),l={id:I(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:c,metadata:i};return this.insertEvent(l),this.enforceRetention(e),l}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:c,reverse:l}=Ve(a,s),o={id:I(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:l,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Xe)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Xe)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=Mt(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
+ WHERE pattern_id = ? AND version != 0 AND id IN (
45
+ SELECT id FROM pattern_deltas
46
+ WHERE pattern_id = ? AND version != 0
47
+ ORDER BY version ASC
48
+ LIMIT ?
49
+ )`).run(e,e,s)}}};F();var Lt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Se=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Lt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),l={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(l),this.buffer.push(l),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:l.timestamp}),this.enforceRetention(e),l}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],l=a.version+1;for(let o of r)if(!(o.version<l)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),l=a.findIndex(f=>f.deltaType==="genesis");l>=0&&(c.unshift(a[l]),a.splice(l,1)),this.history.set(e,c);let o=c[0]?.version??0,d=this.snapshots.get(e);return d&&this.snapshots.set(e,d.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return M()?new Se(n):null}F();var kt=128,Ut=8,qt=1e4,we=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??kt,this.beta=e?.beta??Ut,this.maxPatterns=e?.maxPatterns??qt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let d=0;d<this.patterns.length;d++)r[d]=this.beta*this.dotProduct(this.patterns[d].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let d=1;d<i.length;d++)i[d]>a&&(a=i[d],s=d);let c=this.patterns[s],l=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:l,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),l=this.dotProduct(t,t);return-c+.5*l}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ye(n){return new we(n)}F();var Qt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},N=1e-5,Ke=1-N;function zt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function T(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function $t(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var C=class n{static poincareDistance(e,t){let r=T($t(e,t)),i=Math.max(N,1-T(e)),s=Math.max(N,1-T(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=zt(e,t),i=T(e),s=T(t),a=Math.max(N,1+2*r+i*s),c=1+2*r+s,l=1-i,o=new Float32Array(e.length);for(let d=0;d<e.length;d++)o[d]=(c*e[d]+l*t[d])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(N,1-T(e)),i=Math.sqrt(T(t));if(i<N)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(T(e));if(t<=Ke)return new Float32Array(e);let r=Ke/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(T(e));if(t<N)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Pe=class{config;points=new Map;constructor(e){if(this.config={...Qt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:C.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=C.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:C.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let l of e)if(s.set(l.id,l),!l.parentId)a.push(l.id);else{let o=i.get(l.parentId);o||(o=[],i.set(l.parentId,o)),o.push(l.id)}let c=a.map((l,o)=>({id:l,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:l,depth:o,angOff:d,angSpan:f}=c.shift(),h=Math.tanh(.3*(o+.1)),u=d+f/2,m=new Float32Array(r);m[0]=h*Math.cos(u),m[1]=h*Math.sin(u);let p=s.get(l);if(p&&p.features.length>0){let H=h*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*H}let y=C.project(m);t.set(l,y),this.points.set(l,{id:l,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=i.get(l)??[];for(let H=0;H<S.length;H++){let x=f/Math.max(1,S.length);c.push({id:S[H],depth:o+1,angOff:d+H*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ze(n){return Jt()?new Pe(n):null}function Jt(){return D().useHyperbolicHnsw}F();var be=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!L())return!1;try{return this.index=Ze(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=C.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=C.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function et(n){return new be(n)}var Ee=null;function rt(){return Ee||(Ee=qe({dimensions:1e4})),Ee}var Re;function jt(){return Re===void 0&&(Re=Qe()),Re}var q=null,Ae=0;function nt(n){return(!q||Ae!==n)&&(q=Ye({dimension:n,maxPatterns:1e4}),Ae=n),q}var V={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:j,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Te=class{constructor(e,t={}){this.memory=e;this.config={...V,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,M()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=A()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(this.hnswSpaceId=A()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-Y3GAR3UP.js"),{HnswAdapter:c}=await import("./hnsw-adapter-KCVMXLUL.js"),l=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(l),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-OGWZS6MP.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=A()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:c,spaceId:l}of e){if(r>=t)break;if(!s||l!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,c,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=A()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!r)return w(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let a=this.sqliteStore.storePattern(e,e.embedding,r);a&&a!==e.id&&(this.unindexPattern(e),e.id=a,this.indexPattern(e))}catch(a){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(a))}if(e.embedding){let a=await this.ensureHNSW();if(a)try{await a.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(c){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,c)}}if(Q())try{let c=rt().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,c.vector)}catch(a){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(a))}try{let a=jt();if(a){let c=[e.patternType,e.qeDomain];e.context?.tags&&c.push(...e.context.tags),e.name&&c.push(e.name);let l=a.fingerprintPattern(c);this.hdcTokenCache.set(e.id,l)}}catch(a){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(a))}if(te()&&e.embedding)try{nt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(a){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(a))}if(M()&&this.deltaTracker)try{let a={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,a)}catch(a){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(a))}if(e.embedding)try{let a=this.getVectorDeltaTracker();a&&(s?.embedding?a.recordDelta(e.id,s.embedding,e.embedding):a.getVersion(e.id)<0&&a.recordGenesis(e.id,e.embedding))}catch(a){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(a))}try{L()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:I(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=nt(e.length);if(h.getPatternCount()>0){let u=h.recall(new Float32Array(e));if(u&&u.similarity>.98){let m=u.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,u.similarity);s.push({pattern:p,score:u.similarity,matchType:"vector",similarity:u.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",v(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=A()?.spaceId??this.config.embeddingSpaceId;if(!h||t.embeddingSpaceId!==h)throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");let u=await this.ensureHNSW();if(u){let m=await u.search(e,i*2);for(let p of m){let y=await this.get(p.key);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.score);s.push({pattern:y,score:p.score,matchType:"vector",similarity:p.score,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let u=new Map(h.map(p=>[p.id,p.ftsScore])),m=new Set(s.map(p=>p.pattern.id));for(let p of s){let y=u.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of h){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);s.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of h)u.has(m.pattern.id)||s.push(m)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let u=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/a),y=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*y)}let l=this.sqliteStore?.getDatabase();if(l&&s.length>0)try{this.nullStore||(this.nullStore=new se(l));let h=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=h.get(u.pattern.id);m&&(u.nullSummary=m,u.score=se.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",v(h))}s.sort((h,u)=>u.score-h.score);let o=s;t.filter&&(o=He(s,t.filter));let d=o.slice(0,i),f=performance.now()-r;return this.recordSearchLatency(f),P(d)}catch(a){return w(Ce(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&s&&this.hdcCache.size>0)try{let l=rt(),o=l.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),d=c.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:l.similarity(o.vector,this.hdcCache.get(u))}));d.sort((u,m)=>m.similarity-u.similarity);let f=d.map(u=>u.id),h=c.filter(u=>!this.hdcCache.has(u));c=[...f,...h]}catch{}for(let l of c){if(i.length>=r)break;let o=this.patternCache.get(l);if(!o||!this.matchesFilters(o,t))continue;let d=0;if(s){let f=o.name.toLowerCase(),h=o.description.toLowerCase();f.includes(s)&&(d+=.5),h.includes(s)&&(s.length/h.length>.3?d+=.5:d+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){d+=.2;break}d=Math.min(d,1)}else d=o.qualityScore;if(d>0||!s){let f=this.calculateReuseInfo(o,d);i.push({pattern:o,score:d||o.qualityScore,matchType:s?"exact":"context",similarity:d||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),l=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&l,d=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,h=e.successRate,u=Math.min(e.reuseCount/10,1),m=o?f*.4+h*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:d,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=s.usageCount+1,l=s.successfulUses+(t?1:0),o=l/c,d=t?.02:-.01,f=Math.max(.1,Math.min(1,s.confidence+d)),h=B({confidence:f,usageCount:c,successRate:o}),u={...s,usageCount:c,successfulUses:l,successRate:o,confidence:f,qualityScore:h,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(M()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},S={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=re(u);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,d]of this.domainIndex)e[o]=d.size;for(let[o,d]of this.typeIndex)t[o]=d.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),l=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:l.nativeHNSW,vectorCount:l.vectorCount,indexSizeBytes:l.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let l=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-l,d=o>10080*60*1e3,f=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(d&&f||h)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),q&&(q.clear(),q=null,Ae=0),this.initialized=!1}indexHyperbolic(e,t,r){if(L())try{this.hyperbolicIndex||(this.hyperbolicIndex=et({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!L()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),l=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Kr(n,e){try{if(D().useRVFPatternStore&&Oe()){let r=process.env.AQE_PROJECT_ROOT??Ie(),i=tt(r,".agentic-qe"),s=tt(i,"patterns.rvf");if(Bt(i)){let a={...V,...e},c=!1;try{let l=Ne(i,a.embeddingDimension);if(l){c=!0;let o=new z(()=>l,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!c){let l=new z((o,d)=>{let f=()=>{try{return Fe(o)}catch{return null}},h=f();if(h){if(h.dimension()!==d){try{h.close()}catch{}throw new Error(`RVF dimension mismatch (file=${h.dimension()}, requested=${d})`)}return h}try{return ne(o,d)}catch(u){if(h=f(),h&&h.dimension()===d)return h;if(_e(o,u instanceof Error?u.message:String(u)))return ne(o,d);throw u}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Te(n,e)}export{Kr as a};
50
+ /*! Bundled license information:
51
+
52
+ fast-json-patch/commonjs/helpers.js:
53
+ (*!
54
+ * https://github.com/Starcounter-Jack/JSON-Patch
55
+ * (c) 2017-2022 Joachim Wester
56
+ * MIT licensed
57
+ *)
58
+
59
+ fast-json-patch/commonjs/duplex.js:
60
+ (*!
61
+ * https://github.com/Starcounter-Jack/JSON-Patch
62
+ * (c) 2017-2021 Joachim Wester
63
+ * MIT license
64
+ *)
65
+ */
@@ -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.13.12");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.14.0");process.exit(0)}
2
2
  var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");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.14.0");process.exit(0)}
2
2
  var o=!1;function r(t){if(!o){for(let e of["ALTER TABLE routing_outcomes ADD COLUMN exploration INTEGER NOT NULL DEFAULT 0","ALTER TABLE routing_outcomes ADD COLUMN criticality REAL","ALTER TABLE routing_outcomes ADD COLUMN q_weight REAL"])try{t.prepare(e).run()}catch{}try{t.prepare("CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration)").run()}catch{}o=!0}}export{r as a};
@@ -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.13.12");process.exit(0)}
2
- import{a as _}from"./chunk-DFLASG3B.js";import{a as w}from"./chunk-BODFJ3DC.js";import{c as k}from"./chunk-Z6DSYLAG.js";import{i as M,m as U}from"./chunk-M73KM3AZ.js";import{b as f,d as P}from"./chunk-VA2ORJB5.js";import{a as g,c as F}from"./chunk-L3GBNX7B.js";import{a as R}from"./chunk-ZMYV4R32.js";import{randomUUID as N}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={};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"},q=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??q}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,I={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},L=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...I,...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:L,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."}};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.14.0");process.exit(0)}
2
+ import{a as _}from"./chunk-WTHAVFIC.js";import{a as w}from"./chunk-OONCRNFA.js";import{c as k}from"./chunk-H6NFDOMK.js";import{k as M,o as U}from"./chunk-7RAB2BZY.js";import{b as f,d as P}from"./chunk-HQHLHSJO.js";import{a as g,c as F}from"./chunk-XITTURP2.js";import{a as R}from"./chunk-PEW6FZ47.js";import{randomUUID as N}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={};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"},q=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??q}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,I={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},L=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...I,...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:L,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."}};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.13.12");process.exit(0)}
2
- import{c as r}from"./chunk-ZMYV4R32.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{c as r}from"./chunk-PEW6FZ47.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t as c};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");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.14.0");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");process.exit(0)}
2
- import{a as v}from"./chunk-GEQWCK4F.js";import{c as l}from"./chunk-IOJ34SXJ.js";import{S as R,b as g}from"./chunk-AN5CGTTJ.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{a as v}from"./chunk-R2B6EE45.js";import{c as l}from"./chunk-JY4VZ6BN.js";import{S as R,b as g}from"./chunk-ENGKLFLY.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain_receipts (
4
4
  id TEXT PRIMARY KEY,
5
5
  chain_index INTEGER NOT NULL,
@@ -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.13.12");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.14.0");process.exit(0)}
2
2
  var l=[{name:"aqe-plan-quality",default:!0},{name:"aqe-plan-work",default:!0},{name:"aqe-research",default:!0},{name:"aqe-review-quality",default:!0},{name:"aqe-test-change",default:!0},{name:"aqe-ruflo",default:!1,files:["SKILL.md"]}];function t(a={}){return l.filter(e=>e.default||e.name==="aqe-ruflo"&&a.includeRuflo===!0)}export{t as a};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{b as E,c as D,d as Y,e as q}from"./chunk-2NO4H35K.js";import{c as V}from"./chunk-2O4DDPEA.js";import{a as w,b as j,c as G,e as A}from"./chunk-NDPQ2WPU.js";import{b as k,c as H,j as v,k as N,o as W,q as S,r as J}from"./chunk-5XGVSQS2.js";import{a as x}from"./chunk-H6NFDOMK.js";import{d as $,e as oe}from"./chunk-JY4VZ6BN.js";import{b as _,c as ie}from"./chunk-XITTURP2.js";import{i as U}from"./chunk-FOHYBR3O.js";var K={security:{provider:"claude",model:"claude-opus-4-7",temperature:.1,maxTokens:16e3,priority:100},"test-generation":{provider:"claude",model:"claude-sonnet-4-6",temperature:.3,maxTokens:8e3,priority:90},"code-analysis":{provider:"claude",model:"claude-sonnet-4-6",temperature:.2,maxTokens:8e3,priority:85},performance:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.2,maxTokens:4e3,priority:70},documentation:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.4,maxTokens:4e3,priority:60},learning:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3,maxTokens:8e3,priority:80},coordination:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.2,maxTokens:2e3,priority:75},simple:{provider:"openai",model:"gpt-4o-mini",temperature:.3,maxTokens:2e3,priority:50},general:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3,maxTokens:4e3,priority:60}},L={"security-auditor":"security","security-architect":"security","security-scanner":"security","v3-qe-security-scanner":"security","security-manager":"security","vulnerability-scanner":"security","penetration-tester":"security","compliance-auditor":"security","threat-analyzer":"security","test-generator":"test-generation","v3-qe-test-generator":"test-generation",tester:"test-generation","tdd-specialist":"test-generation","tdd-london-swarm":"test-generation","unit-test-generator":"test-generation","integration-test-generator":"test-generation","e2e-test-generator":"test-generation","mutation-tester":"test-generation","property-based-tester":"test-generation","contract-tester":"test-generation","v3-qe-contract-tester":"test-generation","api-tester":"test-generation","visual-tester":"test-generation","v3-qe-visual-tester":"test-generation","accessibility-tester":"test-generation","code-reviewer":"code-analysis","code-analyzer":"code-analysis",reviewer:"code-analysis","v3-qe-code-intelligence":"code-analysis","v3-qe-code-analyzer":"code-analysis","coverage-analyzer":"code-analysis","v3-qe-coverage-analyzer":"code-analysis","defect-predictor":"code-analysis","v3-qe-defect-predictor":"code-analysis","static-analyzer":"code-analysis","complexity-analyzer":"code-analysis","dependency-analyzer":"code-analysis","refactoring-advisor":"code-analysis","quality-assessor":"code-analysis","v3-qe-quality-assessor":"code-analysis","test-executor":"code-analysis","v3-qe-test-executor":"code-analysis","parallel-executor":"code-analysis","flaky-test-detector":"code-analysis","test-orchestrator":"code-analysis","performance-tester":"performance","performance-engineer":"performance","perf-analyzer":"performance","performance-benchmarker":"performance","load-tester":"performance","stress-tester":"performance","v3-qe-chaos-engineer":"performance","chaos-engineer":"performance","resilience-tester":"performance","scalability-tester":"performance","api-docs":"documentation","doc-generator":"documentation","readme-generator":"documentation","changelog-generator":"documentation","specification-writer":"documentation","v3-qe-learning-optimizer":"learning","learning-optimizer":"learning","ml-developer":"learning","pattern-learner":"learning","optimization-agent":"learning","smart-agent":"learning","requirements-validator":"code-analysis","v3-qe-requirements-validator":"code-analysis","bdd-generator":"test-generation","acceptance-tester":"test-generation",coordinator:"coordination","hierarchical-coordinator":"coordination","mesh-coordinator":"coordination","adaptive-coordinator":"coordination","collective-intelligence-coordinator":"coordination","swarm-memory-manager":"coordination","byzantine-coordinator":"coordination","raft-manager":"coordination","gossip-coordinator":"coordination","consensus-builder":"coordination","crdt-synchronizer":"coordination","quorum-manager":"coordination","task-orchestrator":"coordination","memory-coordinator":"coordination",coder:"code-analysis",planner:"code-analysis",researcher:"code-analysis","backend-dev":"code-analysis","mobile-dev":"code-analysis","cicd-engineer":"code-analysis","system-architect":"code-analysis","base-template-generator":"test-generation","github-modes":"coordination","pr-manager":"coordination","code-review-swarm":"code-analysis","issue-tracker":"coordination","release-manager":"coordination","workflow-automation":"coordination","project-board-sync":"coordination","repo-architect":"code-analysis","multi-repo-swarm":"coordination","sparc-coord":"coordination","sparc-coder":"code-analysis",specification:"documentation",pseudocode:"code-analysis",architecture:"code-analysis",refinement:"code-analysis","memory-specialist":"learning","production-validator":"code-analysis"},y={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},ge={security:y.heavyweight,"test-generation":y.standard,"code-analysis":y.standard,learning:y.standard,performance:{...y.lightweight,costSensitivity:"high"},coordination:y.lightweight,general:{...y.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...y.minimal,minContextSize:16e3},simple:y.minimal};function Q(l){if(l in L)return L[l];let e=l.toLowerCase();return e.includes("security")||e.includes("audit")||e.includes("vulnerab")||e.includes("penetration")||e.includes("threat")||e.includes("compliance")?"security":e.includes("test-gen")||e.includes("tdd")||e.includes("unit-test")||e.includes("e2e-test")||e.includes("integration-test")||e.includes("mutation")?"test-generation":e.includes("code-")||e.includes("coverage")||e.includes("defect")||e.includes("review")||e.includes("analyzer")||e.includes("quality")?"code-analysis":e.includes("perf")||e.includes("load")||e.includes("stress")||e.includes("benchmark")||e.includes("chaos")||e.includes("resilience")?"performance":e.includes("doc")||e.includes("readme")||e.includes("changelog")||e.includes("spec")?"documentation":e.includes("learn")||e.includes("ml-")||e.includes("pattern")||e.includes("optim")?"learning":e.includes("coord")||e.includes("swarm")||e.includes("orchestrat")||e.includes("consensus")||e.includes("manager")?"coordination":"general"}var I={},X={};function Z(l,e){I={...l??{}},X={...e??{}}}function ee(l){let e=Q(l),t=K[e],r=I[l];if(!r)return t;let i=r.provider!==void 0&&r.provider!==t.provider,o=r.model??(i?X[r.provider]:void 0);return{...t,...r.provider!==void 0?{provider:r.provider}:{},...o!==void 0?{model:o}:{},...r.temperature!==void 0?{temperature:r.temperature}:{},...r.maxTokens!==void 0?{maxTokens:r.maxTokens}:{},priority:r.priority??t.priority+100}}function te(){return Object.keys(I).map(l=>{let e=ee(l);return{id:`agent-override-${l}`,name:`User override: ${l} -> ${e.provider}/${e.model}`,description:`Per-agent routing override from .agentic-qe/llm-config.json (agentOverrides["${l}"])`,condition:{agentType:[l]},action:{provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,priority:e.priority},enabled:!0,priority:e.priority}}).sort((l,e)=>e.priority-l.priority)}var C=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},R=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as ne}from"crypto";var T=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${ne().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),a=o.outputTokens??i-n,s={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:a,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(s),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),a=this.calculateAgentMetrics(r,i),s=r.map(m=>m.decisionTimeMs),c=r.length,d=this.countByMode(r),u=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:a,totalDecisions:c,decisionsByMode:d,avgDecisionTimeMs:this.average(s),p95DecisionTimeMs:this.percentile(s,95),p99DecisionTimeMs:this.percentile(s,99),fallbackRate:c>0?u/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,P)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(s=>s.provider===e),r=this.providerCalls.filter(s=>s.provider===e),i=r.map(s=>s.latencyMs),o=t.map(s=>s.decisionTimeMs),n=r.filter(s=>s.success),a=r.filter(s=>!s.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(s=>s.ruleId).length,fallbackCount:t.filter(s=>s.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((s,c)=>s+(c.cost??0),0),totalTokens:r.reduce((s,c)=>s+c.totalTokens,0),totalInputTokens:r.reduce((s,c)=>s+c.inputTokens,0),totalOutputTokens:r.reduce((s,c)=>s+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:a.length,lastError:a.length>0?a[a.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),a=t.filter(c=>c.wasFallback).length,s=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,d)=>c+(d.cost??0),0),totalTokens:r.reduce((c,d)=>c+d.totalTokens,0),fallbackRate:t.length>0?a/t.length:0,successRate:t.length>0?s/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(d=>d.provider===i),n=t.filter(d=>d.provider===i);if(o.length===0&&n.length===0)continue;let a=n.map(d=>d.latencyMs),s=o.map(d=>d.decisionTimeMs),c=n.filter(d=>d.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(d=>d.ruleId).length,fallbackCount:o.filter(d=>d.wasFallback).length,avgDecisionTimeMs:this.average(s),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(a),p95LatencyMs:this.percentile(a,95),p99LatencyMs:this.percentile(a,99),totalCost:n.reduce((d,u)=>d+(u.cost??0),0),totalTokens:n.reduce((d,u)=>d+u.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function O(l){return new T(l)}var b=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),a={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(a),this.trimRecords(),this.checkAlerts(),a}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let a=n.reduce((c,d)=>c+d.totalCost,0),s=n.reduce((c,d)=>c+d.inputTokens+d.outputTokens,0);i.set(o,{totalCost:a,totalTokens:s,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:s>0?a/s:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(a=>a.agentType&&i.add(a.agentType));let o=new Map;for(let a of i){let s=r.filter(u=>u.agentType===a),c=s.reduce((u,g)=>u+g.totalCost,0),d=s.reduce((u,g)=>u+g.inputTokens+g.outputTokens,0);o.set(a,{totalCost:c,totalTokens:d,totalRequests:s.length,avgCostPerRequest:s.length>0?c/s.length:0,avgCostPerToken:d>0?c/d:0})}let n=r.filter(a=>!a.agentType);if(n.length>0){let a=n.reduce((c,d)=>c+d.totalCost,0),s=n.reduce((c,d)=>c+d.inputTokens+d.outputTokens,0);o.set("unknown",{totalCost:a,totalTokens:s,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:s>0?a/s:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let a=r.filter(d=>d.model===n),s=a.reduce((d,u)=>d+u.totalCost,0),c=a.reduce((d,u)=>d+u.inputTokens+u.outputTokens,0);o.set(n,{totalCost:s,totalTokens:c,totalRequests:a.length,avgCostPerRequest:a.length>0?s/a.length:0,avgCostPerToken:c>0?s/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let a=new Date(t.getTime()-n*i),s=new Date(a.getTime()-i),c=this.records.filter(d=>d.timestamp>=s&&d.timestamp<a);r.push({timestamp:a,cost:c.reduce((d,u)=>d+u.totalCost,0),tokens:c.reduce((d,u)=>d+u.inputTokens+u.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,a]of t)x[n]&&a.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:a.totalCost*.5,currentCost:a.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:a.totalCost*.7,currentCost:a.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,a)=>n+a.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,a)=>n+a.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=x[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,a)=>n+a.inputTokens+a.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function z(l){return new b(l)}ie();var M=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},h=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={...N,...t};let r=this.config.rules.length>0?this.config.rules:R;this.ruleEngine=new C(r),this.decisionCache=new M(100,this.config.decisionCacheTtlMs),this.metrics=new B,this.routerMetrics=O(),this.costMetrics=z()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new M(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=U(),r=await this.selectProvider(e),i=e.agentType??"";if(Y(i)&&(D(r.model)||D(r.providerModelId))){let n=r.model,a=r.providerModelId;r.model=q(i,r.model,E),r.providerModelId=q(i,r.providerModelId,E),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${a}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,a=o.action.provider,s=this.providerManager.getProvider(a);if(s){let c=this.createDecision(s,a,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let a of t){let s=this.providerManager.getProvider(a);if(!s)continue;let{input:c,output:d}=s.getCostPerToken(),u=this.estimateCostValue(e,c,d);n.push({provider:a,model:s.getConfig().model,reason:`Estimated cost: $${u.toFixed(6)}`,estimatedCost:u,excluded:!1}),u<r&&(r=u,i=a,o=s)}if(o){let a=o.getConfig(),s=this.createDecision(o,i,a.model,"cost-optimization");return s.metadata.estimatedCost=this.createCostEstimate(e,o),s.metadata.alternativesConsidered=n,s}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,a=[];for(let s of t){let c=this.providerManager.getProvider(s);if(!c)continue;let u=r[s]?.avgLatencyMs??1/0;a.push({provider:s,model:c.getConfig().model,reason:`Avg latency: ${u}ms`,estimatedLatencyMs:u,excluded:!1}),u<i&&(i=u,o=s,n=c)}if(n){let s=n.getConfig(),c=this.createDecision(n,o,s.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=a,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,a=0,s=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&s.push({provider:c,model:this.config.defaultModel});for(let u of i.entries)if(u.enabled&&u.provider!==t.providerType)for(let g of u.models)s.push({provider:u.provider,model:g});let d=s;if(e.requiresTools){let u=s.filter(g=>A(g.model));if(u.length>0&&u.length<s.length){let g=s.filter(m=>!A(m.model)).map(m=>`${m.provider}:${m.model}`);console.warn(`[llm-router] requiresTools: skipping tool-less model(s) ${g.join(", ")}`),d=u}}this.providerManager.assertWithinBudget(e.messages,{model:d[0]?.model,maxTokens:e.maxTokens});for(let{provider:u,model:g}of d){if(a>=o.maxAttempts)break;let m=this.providerManager.getProvider(u);if(!m)continue;a++;let P=Date.now();try{let p=await m.generate(e.messages,{model:g,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata});this.providerManager.recordResponseSpend(p,e.agentType);let f=Date.now()-P;return this.metrics.recordSuccess(u),this.routerMetrics.recordRoutingDecision(t,f,{agentType:e.agentType,success:!0,tokenUsage:p.usage,cost:p.cost}),this.routerMetrics.recordProviderCall(u,g,f,p.usage.totalTokens,{inputTokens:p.usage.promptTokens,outputTokens:p.usage.completionTokens,success:!0,cost:p.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(u,g,p.usage,p.cost,{agentType:e.agentType,requestId:p.requestId}),{content:p.content,model:p.model,providerModelId:p.model,provider:p.provider,usage:p.usage,cost:p.cost,latencyMs:p.latencyMs,finishReason:p.finishReason,cached:p.cached,requestId:p.requestId,routingDecision:t}}catch(p){n=_(p);let f=Date.now()-P;if(this.metrics.recordFailure(u),this.routerMetrics.recordProviderCall(u,g,f,0,{success:!1,agentType:e.agentType}),a<s.length){let F=s[a];F&&this.routerMetrics.recordFallback(u,F.provider,n.message,e.agentType)}!(H(p)&&!p.retryable)&&a<o.maxAttempts&&await this.delay(o.delayMs)}}throw k(`All providers failed after ${a} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:a}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:a,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic","claude-code":"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=j(e),n=w(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(G(e)){let n=w(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw k(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let s of e.messages)o+=Math.ceil(s.content.length/4);let n=e.maxTokens??1e3,a=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:a,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},B=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};oe();var se=$("llm/router-service");function re(l){let e={};for(let[i,o]of Object.entries(l.providers??{}))o?.defaultModel&&(e[i]=o.defaultModel);Z(l.agentOverrides,e);let t=te();if(t.length===0)return l;let r=l.rules.length>0?l.rules:R;return{...l,rules:[...t,...r]}}var ae=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function bt(l={}){if(l.providerManager){let c=re(S({projectRoot:l.projectRoot,override:l.override,env:l.env})),d=new h(l.providerManager,c);return await d.initialize(),{router:d,resolvedConfig:c,enabledProviders:de(c)}}if(!J({projectRoot:l.projectRoot,env:l.env}))return null;let e=re(S({projectRoot:l.projectRoot,override:l.override,env:l.env})),t=ce(e,l.env??process.env);if(t.length===0)return null;let r=new Set(t);for(let[c,d]of Object.entries(e.agentOverrides??{}))d.provider&&!r.has(d.provider)&&se.warn(`[llm-config] agentOverrides["${c}"] routes to provider "${d.provider}", which is not enabled (no API key detected and not enabled in .agentic-qe/llm-config.json). This override will not take effect until that provider is available.`);let{primary:i,fallbacks:o}=le(e,t),n={primary:i,fallbacks:o,providers:ue(e,t,l.allowProjectProviderEndpoints??!0),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},a=new V(n),s=new h(a,e);return await s.initialize(),{router:s,resolvedConfig:e,enabledProviders:t}}function ce(l,e=process.env){let t=W(e),r=[],i=o=>{r.includes(o)||!l.providers?.[o]?.enabled||t.has(o)&&r.push(o)};i(l.defaultProvider);for(let o of l.fallbackChain?.entries??[])i(o.provider);for(let o of ae)i(o);for(let o of v)i(o);return r}function de(l){let e=new Set([l.defaultProvider]);for(let t of l.fallbackChain?.entries??[])e.add(t.provider);return Array.from(e)}function le(l,e){if(e.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let t=e.includes(l.defaultProvider)?l.defaultProvider:e[0],r=e.filter(i=>i!==t);return{primary:t,fallbacks:r}}function ue(l,e,t=!0){let r={};for(let i of e){let o=l.providers?.[i];if(o){let n={...o};(i==="codex"||i==="claude-code")&&delete n.binaryPath,t||delete n.baseUrl,r[i]=n}}return r}export{bt as a,ce as b,le as c,ue 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.13.12");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-ZMYV4R32.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-PEW6FZ47.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");process.exit(0)}
2
- import{i as c}from"./chunk-YQOQVSYU.js";import{a as p}from"./chunk-GEQWCK4F.js";import{c as m}from"./chunk-IOJ34SXJ.js";import{b as g,d as E}from"./chunk-VA2ORJB5.js";import{a as l,b as _}from"./chunk-Z56BBX77.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.0");process.exit(0)}
2
+ import{i as c}from"./chunk-A7SKM6JL.js";import{a as p}from"./chunk-R2B6EE45.js";import{c as m}from"./chunk-JY4VZ6BN.js";import{b as g,d as E}from"./chunk-HQHLHSJO.js";import{a as l,b as _}from"./chunk-ZQSXG7FA.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -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.14.0");process.exit(0)}
2
+ import{a as F,c as de}from"./chunk-XITTURP2.js";import{b as W,d as k}from"./chunk-AR6SATU3.js";k();de();k();import*as S from"node:http";import*as R from"node:https";import{createHash as le}from"node:crypto";import{URL as G}from"node:url";var A={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},pe="AQE embedder endpoint identity canary v1",ce="/v1/embeddings";function j(t){if(t.startsWith("unix:"))return t;try{let e=new G(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function me(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 G(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 z=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},M=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??A.model,expectedDim:e.expectedDim??A.expectedDim,connectTimeoutMs:e.connectTimeoutMs??A.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??A.requestTimeoutMs,failureThreshold:e.failureThreshold??A.failureThreshold,failureWindowMs:e.failureWindowMs??A.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=me(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new R.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new S.Agent({keepAlive:!0});this.breaker=new z(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([pe]);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=le("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return W(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ce,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=S.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?R.request:S.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,N=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);N(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,T=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(T),w.destroy(T)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};import{join as X}from"node:path";import{existsSync as ue,mkdirSync as fe}from"node:fs";import{createRequire as ge}from"node:module";var he=ge(import.meta.url);function Ee(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t:X(process.cwd(),".agentic-qe","memory.db")}var J="_system",K="embedder_identity:",x=null,q=!1;function Y(){if(x)return x;if(q)return null;try{let t=he("better-sqlite3"),e=Ee(),n=X(e,"..");ue(n)||fe(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
+ `),x=r,r}catch{return q=!0,null}}function Q(t){let e=Y();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(J,K+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 Z(t){let e=Y();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(K+t.endpoint,J,JSON.stringify(n))}function ee(){if(x)try{x.close()}catch{}x=null,q=!1}k();import{createHash as te}from"node:crypto";import{existsSync as ye,readFileSync as we,renameSync as Ie,writeFileSync as ve}from"node:fs";var ne="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Ae(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 re(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 te("sha256").update(e).digest("hex").slice(0,16)}function U(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=te("sha256").update("aqe:embedding-space:v1\0").update(Ae(t)).digest("hex");return{...t,spaceId:e}}function ke(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}function xe(t){return`${t}.space.json`}function ze(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=xe(t);if(ye(r)){let s;try{s=JSON.parse(we(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;ve(i,`${JSON.stringify(a)}
13
+ `,{encoding:"utf8",mode:384}),Ie(i,r)}var V=null,f=null,C=null,P=!1,_="",v=null,p=null,O=null,L={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,ie=36e5;function B(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function oe(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 se(t={}){if(P)throw new Error(`Transformer initialization previously failed: ${_}`);if(C)return C;let e={...L,...t};return C=(async()=>{try{if(e.endpoint){let l=j(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new M({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),O=U({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=Q(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),Z(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Te(v);return}let n;try{n=await import("./transformers-COQWK27J.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}V=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await V("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(ne,{pooling:"mean",normalize:!0}),s=Array.from(i.data);O=U({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:re(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw P=!0,_=F(n),new Error(`Failed to initialize transformer model: ${_}`)}})(),C}function Te(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??D(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function He(t,e={}){let n={...L,...e};if(oe(t))return new Array(D()).fill(0);if(f||await se(e),!f)throw new Error("Embedding model failed to initialize");let r=B(t);if(n.enableCache){let l=c.get(r);if(l&&Date.now()-l.timestamp<ie)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(c.size>=n.maxCacheSize){let l=c.keys().next().value;l&&c.delete(l)}c.set(r,{embedding:s,timestamp:Date.now()})}return s}async function We(t,e={}){let n={...L,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)oe(t[o])?i[o]=new Array(D()).fill(0):s.push(o);if(s.length===0)return i;if(f||await se(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=c.get(B(t[o]));l&&Date.now()-l.timestamp<ie?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),N=await f(y,{pooling:"mean",normalize:!0}),h=N.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(N.data.slice(u,u+d)),T=b+g,ae=a[T];if(i[ae]=E,n.enableCache){if(c.size>=n.maxCacheSize){let H=c.keys().next().value;H&&c.delete(H)}c.set(B(r[T]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function Ge(){c.clear(),console.log("[RealEmbeddings] Cache cleared")}function je(){return{size:c.size,hitRate:0}}function Xe(){return!P&&f!==null}function D(){return 384}function Je(){V=null,f=null,C=null,P=!1,_="",c.clear(),v&&v.close(),v=null,p=null,O=null,ee()}function Ke(){return v!==null}function Ye(){return p}function Qe(){return O}export{ne as a,ke as b,ze as c,L as d,He as e,We as f,Ge as g,je as h,Xe as i,D as j,Je as k,Ke as l,Ye as m,Qe as n};
@@ -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.13.12");process.exit(0)}
2
- import{a as f}from"./chunk-GEQWCK4F.js";import{c as p}from"./chunk-IOJ34SXJ.js";import{a as l,d as b}from"./chunk-4Z4X2ND4.js";import{a as d,b as g}from"./chunk-2VTX4SYW.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.14.0");process.exit(0)}
2
+ import{a as f}from"./chunk-R2B6EE45.js";import{c as p}from"./chunk-JY4VZ6BN.js";import{a as l,d as b}from"./chunk-VXU53F7Z.js";import{a as d,b as g}from"./chunk-6AYO3IR2.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};