agentic-qe 3.10.7 → 3.10.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +84 -0
  3. package/dist/cli/bundle.js +5 -5
  4. package/dist/cli/chunks/adapter-TRSV37EA.js +2 -0
  5. package/dist/cli/chunks/{agent-booster-wasm-6I3JMU2M.js → agent-booster-wasm-RPAOJXZ3.js} +2 -2
  6. package/dist/cli/chunks/{agent-handler-XWI7YM6R.js → agent-handler-SMD5CAS6.js} +2 -2
  7. package/dist/cli/chunks/{agent-memory-branch-QFZKQN2L.js → agent-memory-branch-3IOQIQ7Y.js} +2 -2
  8. package/dist/cli/chunks/aqe-learning-engine-CVJRJOSO.js +2 -0
  9. package/dist/cli/chunks/{arena-5HNPVTBZ.js → arena-AP2J62WO.js} +4 -4
  10. package/dist/cli/chunks/{arena-P4IUBKZP.js → arena-GT3D6EAO.js} +2 -2
  11. package/dist/cli/chunks/{audit-PBSH25VZ.js → audit-Q3GJ5354.js} +2 -2
  12. package/dist/cli/chunks/base-BX4A2D4V.js +2 -0
  13. package/dist/cli/chunks/{hnswlib-node-ILDTCGLZ.js → better-sqlite3-6A6EAXAT.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-EVYRCKXI.js → brain-handler-2Z4ILQF3.js} +3 -3
  15. package/dist/cli/chunks/{branch-enumerator-SUDGYJQJ.js → branch-enumerator-EZWGL4UM.js} +2 -2
  16. package/dist/cli/chunks/{browser-4UKMW2RE.js → browser-YZELFPLJ.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-O3RL7EYT.js +2 -0
  18. package/dist/cli/chunks/{chunk-QBVFONWU.js → chunk-246Z3PH6.js} +2 -2
  19. package/dist/cli/chunks/{chunk-B5ZJV7GZ.js → chunk-2I5QLMQF.js} +2 -2
  20. package/dist/cli/chunks/{chunk-AW3LGLC3.js → chunk-2K2X75UF.js} +2 -2
  21. package/dist/cli/chunks/{chunk-OW4LJ5HE.js → chunk-2WRVNEIR.js} +2 -2
  22. package/dist/cli/chunks/{chunk-EWNJK2BU.js → chunk-2WSEJHFQ.js} +1 -1
  23. package/dist/cli/chunks/{chunk-6RG7ZJ2H.js → chunk-352W5G4G.js} +2 -2
  24. package/dist/cli/chunks/{chunk-7NK2H7H5.js → chunk-3HT4CT6F.js} +2 -2
  25. package/dist/cli/chunks/{chunk-MDVJVY4C.js → chunk-3YKJGKOY.js} +4 -4
  26. package/dist/cli/chunks/{chunk-OPLLH67G.js → chunk-42FBJF73.js} +1 -1
  27. package/dist/cli/chunks/{chunk-IXAABYGS.js → chunk-4BB75U6N.js} +2 -2
  28. package/dist/cli/chunks/{chunk-LJHCPN4E.js → chunk-4D3LVXUD.js} +2 -2
  29. package/dist/cli/chunks/{chunk-VPBXVZWE.js → chunk-4EJTE5TL.js} +1 -1
  30. package/dist/cli/chunks/{chunk-I7M574IO.js → chunk-4MUZGQPE.js} +2 -2
  31. package/dist/cli/chunks/{chunk-M7SO5KNJ.js → chunk-57XCLC55.js} +2 -2
  32. package/dist/cli/chunks/{chunk-QBVS4CXM.js → chunk-5HLOQEKL.js} +1 -1
  33. package/dist/cli/chunks/{chunk-XWPUCPYW.js → chunk-5U5SEO7C.js} +2 -2
  34. package/dist/cli/chunks/{chunk-YB4GXJJG.js → chunk-5X73HV2P.js} +1 -1
  35. package/dist/cli/chunks/{chunk-OSETFZVE.js → chunk-62MH7QAQ.js} +2 -2
  36. package/dist/cli/chunks/{chunk-64BSODHA.js → chunk-6HPI6YX3.js} +2 -2
  37. package/dist/cli/chunks/{chunk-SG6O3PXZ.js → chunk-6TR3OM7C.js} +2 -2
  38. package/dist/cli/chunks/{chunk-FQBNPSV2.js → chunk-757YHKIJ.js} +2 -2
  39. package/dist/cli/chunks/{chunk-JJELOEIY.js → chunk-7C5HI4ZA.js} +4 -4
  40. package/dist/cli/chunks/chunk-7D5JE46U.js +2 -0
  41. package/dist/cli/chunks/{chunk-L2ZSYIDA.js → chunk-7NT34MLU.js} +1 -1
  42. package/dist/cli/chunks/{chunk-6QBD64W3.js → chunk-7PYEJ4NV.js} +2 -2
  43. package/dist/cli/chunks/{chunk-ISLI6D4K.js → chunk-7S6D5K4X.js} +2 -2
  44. package/dist/cli/chunks/chunk-ABJPFKHE.js +2 -0
  45. package/dist/cli/chunks/{chunk-LEZ2MGHM.js → chunk-ABVBHH7P.js} +3 -3
  46. package/dist/cli/chunks/{chunk-V7WBNB2S.js → chunk-AHUX7QSE.js} +2 -2
  47. package/dist/cli/chunks/{chunk-DPT37UHR.js → chunk-AU4DQMLJ.js} +4 -4
  48. package/dist/cli/chunks/{chunk-MOI74MMX.js → chunk-BG2FN5K2.js} +2 -2
  49. package/dist/cli/chunks/{chunk-JNQVPTOM.js → chunk-BM52ZEAD.js} +2 -2
  50. package/dist/cli/chunks/{chunk-BLFZFKT6.js → chunk-BSMUT672.js} +2 -2
  51. package/dist/cli/chunks/{chunk-34NT5NBZ.js → chunk-BVEQPMOF.js} +2 -2
  52. package/dist/cli/chunks/{chunk-QLVZEEPR.js → chunk-BYVARYGB.js} +2 -2
  53. package/dist/cli/chunks/{chunk-QDBFB4XD.js → chunk-C6GQIUKW.js} +2 -2
  54. package/dist/cli/chunks/{chunk-X6OJFP7G.js → chunk-C6JULAWA.js} +2 -2
  55. package/dist/cli/chunks/{chunk-76SUEI7S.js → chunk-CDJIYJIA.js} +1 -1
  56. package/dist/cli/chunks/{chunk-2J4ZUUU5.js → chunk-CLJNAQXB.js} +2 -2
  57. package/dist/cli/chunks/{chunk-DU7Y54JI.js → chunk-CLSHSVMY.js} +1 -1
  58. package/dist/cli/chunks/{chunk-O4B6FFC5.js → chunk-CREORFJV.js} +1 -1
  59. package/dist/cli/chunks/{chunk-S4NNQE4L.js → chunk-CVRTXIYP.js} +1 -1
  60. package/dist/cli/chunks/{chunk-TTLAWPEN.js → chunk-CWRSQQHV.js} +2 -2
  61. package/dist/cli/chunks/{chunk-R2B6EQQF.js → chunk-D2JCSWYM.js} +2 -2
  62. package/dist/cli/chunks/{chunk-Z44VJC5U.js → chunk-D7NWDUY3.js} +2 -2
  63. package/dist/cli/chunks/chunk-DK6WWNCL.js +2 -0
  64. package/dist/cli/chunks/{chunk-X3HRJV65.js → chunk-DNE6MVNA.js} +1 -1
  65. package/dist/cli/chunks/{chunk-UURGDFGU.js → chunk-DZWZASDV.js} +1 -1
  66. package/dist/cli/chunks/{chunk-L6NB4UHR.js → chunk-EL6F72JN.js} +2 -2
  67. package/dist/cli/chunks/{chunk-G7ISGLKP.js → chunk-EYGRNXQT.js} +1 -1
  68. package/dist/cli/chunks/{chunk-K6A3AWUI.js → chunk-FALB6Z2Y.js} +1 -1
  69. package/dist/cli/chunks/{chunk-TXXRBNOB.js → chunk-FD37QFXW.js} +1 -1
  70. package/dist/cli/chunks/{chunk-MWRKNBSY.js → chunk-G4KVGUQN.js} +2 -2
  71. package/dist/cli/chunks/{chunk-32E2OPIE.js → chunk-G7V2HDTH.js} +3 -3
  72. package/dist/cli/chunks/{chunk-YMBPKBKG.js → chunk-GPALZJD3.js} +1 -1
  73. package/dist/cli/chunks/{chunk-3IJS52OS.js → chunk-H4SHHYRD.js} +2 -2
  74. package/dist/cli/chunks/{chunk-3XEL7XCA.js → chunk-H7AQ7M3J.js} +1 -1
  75. package/dist/cli/chunks/{chunk-CW7JQVXV.js → chunk-HAC7NB6R.js} +2 -2
  76. package/dist/cli/chunks/{chunk-KXENXRZE.js → chunk-HGKZOSAI.js} +1 -1
  77. package/dist/cli/chunks/{chunk-L3EQQMFI.js → chunk-HQZX4XYH.js} +2 -2
  78. package/dist/cli/chunks/{chunk-LFSQSLNP.js → chunk-HZSYCVLC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-2JWFS2K2.js → chunk-I5C7O5IQ.js} +2 -2
  80. package/dist/cli/chunks/{chunk-LSHUPEQQ.js → chunk-I7RTTJH5.js} +2 -2
  81. package/dist/cli/chunks/{chunk-R7KIC6TL.js → chunk-ILPIH4Z6.js} +1 -1
  82. package/dist/cli/chunks/{chunk-262F3EMN.js → chunk-IR7PJUO7.js} +2 -2
  83. package/dist/cli/chunks/{chunk-MMR23KAO.js → chunk-J6GKKXCP.js} +2 -2
  84. package/dist/cli/chunks/{chunk-INI3AGF5.js → chunk-JZNMU63B.js} +2 -2
  85. package/dist/cli/chunks/{chunk-J5ETX2DG.js → chunk-K23XK33X.js} +2 -2
  86. package/dist/cli/chunks/{chunk-S423UHYM.js → chunk-KAMFT25W.js} +2 -2
  87. package/dist/cli/chunks/{chunk-AKSCYNFH.js → chunk-KJA5A3TV.js} +2 -2
  88. package/dist/cli/chunks/{chunk-76JYG426.js → chunk-KRAWWBX5.js} +2 -2
  89. package/dist/cli/chunks/{chunk-4RGV6Z2H.js → chunk-L5IO7QNO.js} +2 -2
  90. package/dist/cli/chunks/{chunk-HBWAMCVB.js → chunk-L5NEEGKO.js} +14 -14
  91. package/dist/cli/chunks/{chunk-BRYYQQUV.js → chunk-LHKQW72O.js} +1 -1
  92. package/dist/cli/chunks/{chunk-BPC6X6VR.js → chunk-LT6QHDPK.js} +2 -2
  93. package/dist/cli/chunks/{chunk-HARYQMWN.js → chunk-MDED3HJI.js} +2 -2
  94. package/dist/cli/chunks/{chunk-HDLF6LGO.js → chunk-NLUWPS2H.js} +3 -3
  95. package/dist/cli/chunks/{chunk-CGBEI7UH.js → chunk-NMQEU4BG.js} +2 -2
  96. package/dist/cli/chunks/{chunk-K6IU2MV4.js → chunk-NOWGQ6YZ.js} +1 -1
  97. package/dist/cli/chunks/{chunk-YLXUF5KW.js → chunk-NYBAH76S.js} +3 -3
  98. package/dist/cli/chunks/{chunk-TIUC5LRA.js → chunk-O36VC7B7.js} +2 -2
  99. package/dist/cli/chunks/{chunk-3O4Q4GAX.js → chunk-OD4OIPXO.js} +15 -13
  100. package/dist/cli/chunks/{chunk-LUZH2IZY.js → chunk-OF3EMOWN.js} +2 -2
  101. package/dist/cli/chunks/{chunk-AKL5A3IZ.js → chunk-OIN3Y4BY.js} +1 -1
  102. package/dist/cli/chunks/chunk-OPKEQYAC.js +2 -0
  103. package/dist/cli/chunks/{chunk-TY7XPI6R.js → chunk-OQUH7657.js} +2 -2
  104. package/dist/cli/chunks/{chunk-F5RZSNHI.js → chunk-OSP5AJAB.js} +2 -2
  105. package/dist/cli/chunks/{chunk-6A2HRMTD.js → chunk-PFGH7TWL.js} +2 -2
  106. package/dist/cli/chunks/{chunk-MK73CCKO.js → chunk-PYQZ4OA3.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BU2I77YW.js → chunk-QAP5S7YC.js} +3 -3
  108. package/dist/cli/chunks/{chunk-JNXPRDNV.js → chunk-QE3CZGAC.js} +3 -3
  109. package/dist/cli/chunks/{chunk-5QMIVHFT.js → chunk-QFIKEZB5.js} +2 -2
  110. package/dist/cli/chunks/{chunk-AY4IEMRI.js → chunk-QHICG2NI.js} +2 -2
  111. package/dist/cli/chunks/{chunk-4I6FK67T.js → chunk-QHPLU5BU.js} +3 -3
  112. package/dist/cli/chunks/{chunk-HI4DA7Z3.js → chunk-QL6ZJ7RV.js} +2 -2
  113. package/dist/cli/chunks/{chunk-FK4JHBG4.js → chunk-QL7OOCPO.js} +2 -2
  114. package/dist/cli/chunks/{chunk-6OLPKIYU.js → chunk-QWXJRZEH.js} +1 -1
  115. package/dist/cli/chunks/{chunk-S7FNTWFM.js → chunk-R2M3RMCN.js} +2 -2
  116. package/dist/cli/chunks/{chunk-NKYMHEHY.js → chunk-RHOBDQXA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-6F5KPT6U.js → chunk-RRSJ7BMF.js} +1 -1
  118. package/dist/cli/chunks/{chunk-RLXCFURS.js → chunk-RSWQY4NZ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-UPDPD43T.js → chunk-S73EBPI5.js} +2 -2
  120. package/dist/cli/chunks/{chunk-OMDV6GFP.js → chunk-TIR3Z6TE.js} +1 -1
  121. package/dist/cli/chunks/{chunk-UVUVWA4B.js → chunk-TKZABUHO.js} +1 -1
  122. package/dist/cli/chunks/{chunk-4MJQJQLY.js → chunk-TOGD2JH2.js} +2 -2
  123. package/dist/cli/chunks/{chunk-QMGNYRR5.js → chunk-TVU6NMO3.js} +3 -3
  124. package/dist/cli/chunks/{chunk-C5CY5NSW.js → chunk-TXWUV3S5.js} +2 -2
  125. package/dist/cli/chunks/{chunk-3W6QASVB.js → chunk-U6TZVACK.js} +2 -2
  126. package/dist/cli/chunks/{chunk-L5UUUSSB.js → chunk-UJBIHPU5.js} +1 -1
  127. package/dist/cli/chunks/{chunk-FWLXK6AH.js → chunk-UPGKS6Z3.js} +2 -2
  128. package/dist/cli/chunks/{chunk-SLASYVNX.js → chunk-UU7OCRZM.js} +2 -2
  129. package/dist/cli/chunks/{chunk-WCXQA24H.js → chunk-UUA2NVUN.js} +8 -8
  130. package/dist/cli/chunks/{chunk-IYZWEYWJ.js → chunk-UX4UHYLE.js} +1 -1
  131. package/dist/cli/chunks/{chunk-V3KNHI5B.js → chunk-VDL277DX.js} +2 -2
  132. package/dist/cli/chunks/{chunk-RJBCIN2G.js → chunk-VHCHBMZC.js} +2 -2
  133. package/dist/cli/chunks/{chunk-222ZQTL5.js → chunk-VHYNRISI.js} +2 -2
  134. package/dist/cli/chunks/{chunk-4W5QWFU4.js → chunk-VIHFC67B.js} +1 -1
  135. package/dist/cli/chunks/{chunk-DYNO72WD.js → chunk-WOGWIMQK.js} +2 -2
  136. package/dist/cli/chunks/{chunk-SFW6IDMR.js → chunk-WPBVLIWQ.js} +10 -10
  137. package/dist/cli/chunks/{chunk-CJTDQJ7E.js → chunk-WWGGL3TR.js} +1 -1
  138. package/dist/cli/chunks/{chunk-2MLISLRR.js → chunk-X6YUGKMM.js} +1 -1
  139. package/dist/cli/chunks/{chunk-PY3HWJRJ.js → chunk-X7677BX3.js} +2 -2
  140. package/dist/cli/chunks/{chunk-MRLGQX7Y.js → chunk-XEMP2PNW.js} +2 -2
  141. package/dist/cli/chunks/{chunk-YBM4LUSF.js → chunk-XLK4GP3I.js} +2 -2
  142. package/dist/cli/chunks/chunk-XYRJL7YN.js +2 -0
  143. package/dist/cli/chunks/{chunk-OAXDI4XM.js → chunk-YB3PQ3UV.js} +1 -1
  144. package/dist/cli/chunks/{chunk-GUDOOOO6.js → chunk-YHFCLJMY.js} +1 -1
  145. package/dist/cli/chunks/{chunk-HELQ7CXL.js → chunk-YQBL5XTM.js} +1 -1
  146. package/dist/cli/chunks/chunk-Z6FRNWQA.js +6 -0
  147. package/dist/cli/chunks/{chunk-U7EGKKN3.js → chunk-ZT2DGSIO.js} +2 -2
  148. package/dist/cli/chunks/{chunk-DYSRMAZP.js → chunk-ZVF7QY4R.js} +1 -1
  149. package/dist/cli/chunks/{ci-OO42YBET.js → ci-KDEFR2X3.js} +2 -2
  150. package/dist/cli/chunks/{ci-output-YXMTEX7Q.js → ci-output-Z3WXRRFI.js} +2 -2
  151. package/dist/cli/chunks/{circuit-breaker-EHA4N643.js → circuit-breaker-GS44DEW2.js} +2 -2
  152. package/dist/cli/chunks/{claude-flow-setup-E6G6SLYI.js → claude-flow-setup-OHVMHAAH.js} +2 -2
  153. package/dist/cli/chunks/client-T263ZXVV.js +2 -0
  154. package/dist/cli/chunks/cline-installer-5TCF4MZD.js +4 -0
  155. package/dist/cli/chunks/{code-Q3U6XDOO.js → code-3KCGTG7Z.js} +2 -2
  156. package/dist/cli/chunks/{code-index-extractor-BK2DC4MO.js → code-index-extractor-LJBI54MZ.js} +2 -2
  157. package/dist/cli/chunks/codex-installer-IB62Z6LA.js +8 -0
  158. package/dist/cli/chunks/{completions-TZ5F33TA.js → completions-JDXX7KKB.js} +2 -2
  159. package/dist/cli/chunks/{complexity-analyzer-N7U4V7ID.js → complexity-analyzer-6JVDXXXP.js} +2 -2
  160. package/dist/cli/chunks/continuedev-installer-PUB45QVR.js +15 -0
  161. package/dist/cli/chunks/copilot-installer-QWJ36P22.js +3 -0
  162. package/dist/cli/chunks/core-handlers-ODKKGCFK.js +2 -0
  163. package/dist/cli/chunks/{cost-tracker-ZTIDLUFW.js → cost-tracker-J3KEJDL5.js} +2 -2
  164. package/dist/cli/chunks/{coverage-6G7T7TRQ.js → coverage-FWKRI2EY.js} +3 -3
  165. package/dist/cli/chunks/cross-domain-router-APU725GC.js +2 -0
  166. package/dist/cli/chunks/cursor-installer-2HYCUCTH.js +3 -0
  167. package/dist/cli/chunks/{daemon-KTXGJJRI.js → daemon-BVP66DIZ.js} +4 -4
  168. package/dist/cli/chunks/{daemon-5A4GD6XA.js → daemon-G3DBRWDQ.js} +3 -3
  169. package/dist/cli/chunks/{dag-attention-scheduler-4CUEQZD6.js → dag-attention-scheduler-2AQLNB4B.js} +2 -2
  170. package/dist/cli/chunks/{detect-I32JUSUE.js → detect-RUM5SHNE.js} +2 -2
  171. package/dist/cli/chunks/{dist-node-7ITNV6QS.js → dist-node-GX7MJHFT.js} +2 -2
  172. package/dist/cli/chunks/{domain-handler-LIFCXSZ4.js → domain-handler-OFBGZ2U5.js} +2 -2
  173. package/dist/cli/chunks/{domain-transfer-67UWLHSK.js → domain-transfer-6CGRPRGR.js} +2 -2
  174. package/dist/cli/chunks/dream-PJ5GKY3J.js +2 -0
  175. package/dist/cli/chunks/{embed-and-insert-pattern-4WC5RUD6.js → embed-and-insert-pattern-MUOEVQX2.js} +2 -2
  176. package/dist/cli/chunks/{eval-DLS2UAQ2.js → eval-SJMG67DE.js} +2 -2
  177. package/dist/cli/chunks/{experience-capture-middleware-VG5E6OJA.js → experience-capture-middleware-ICKN6IXX.js} +3 -3
  178. package/dist/cli/chunks/{fast-paths-262IVHDN.js → fast-paths-HXLBG3J4.js} +2 -2
  179. package/dist/cli/chunks/{feature-flags-L3K7DBN3.js → feature-flags-CRUB2ASU.js} +2 -2
  180. package/dist/cli/chunks/{feature-flags-JJ3FHZGD.js → feature-flags-JYZSSQJC.js} +2 -2
  181. package/dist/cli/chunks/{file-discovery-Q3PBKVUW.js → file-discovery-YHHC7NTJ.js} +2 -2
  182. package/dist/cli/chunks/{fleet-LQ5S2YHG.js → fleet-2VGDL4YL.js} +3 -3
  183. package/dist/cli/chunks/{gnn-wrapper-I33Z537H.js → gnn-wrapper-7ZAGD4S4.js} +2 -2
  184. package/dist/cli/chunks/{heartbeat-handler-RYIRAGZ7.js → heartbeat-handler-HAW3JRHN.js} +4 -4
  185. package/dist/cli/chunks/heartbeat-scheduler-4ZHUIW3Q.js +2 -0
  186. package/dist/cli/chunks/hnsw-adapter-UVJJ6TTP.js +2 -0
  187. package/dist/cli/chunks/hnsw-index-K6HS34JZ.js +2 -0
  188. package/dist/cli/chunks/{hnsw-legacy-bridge-SSENBBPR.js → hnsw-legacy-bridge-BO325POX.js} +2 -2
  189. package/dist/cli/chunks/{better-sqlite3-F262IAGH.js → hnswlib-node-YTK7S7GL.js} +2 -2
  190. package/dist/cli/chunks/{hooks-LR5KQMN5.js → hooks-HKM3JTFQ.js} +10 -10
  191. package/dist/cli/chunks/hybrid-router-25S7OH2Y.js +2 -0
  192. package/dist/cli/chunks/{hypergraph-engine-NDZA2DKP.js → hypergraph-engine-LGLGHK6B.js} +2 -2
  193. package/dist/cli/chunks/{hypergraph-handler-ADMWVHBT.js → hypergraph-handler-6QDVREZA.js} +3 -3
  194. package/dist/cli/chunks/impact-analyzer-UP4RDMJH.js +2 -0
  195. package/dist/cli/chunks/init-handler-XUQ7XHIE.js +74 -0
  196. package/dist/cli/chunks/init-wizard-2PAJ3GEC.js +2 -0
  197. package/dist/cli/chunks/kernel-7WOQGMMT.js +2 -0
  198. package/dist/cli/chunks/kilocode-installer-6CEZLVIX.js +4 -0
  199. package/dist/cli/chunks/{kiro-installer-TINLYZ22.js → kiro-installer-6CJGATOS.js} +4 -4
  200. package/dist/cli/chunks/knowledge-graph-FN2AWHGR.js +2 -0
  201. package/dist/cli/chunks/{learning-KBT3S5WW.js → learning-EIYTYZJY.js} +3 -3
  202. package/dist/cli/chunks/{llm-router-2MX5LUAB.js → llm-router-J4CI7VHU.js} +4 -4
  203. package/dist/cli/chunks/llm-router-service-C3UPBAS3.js +2 -0
  204. package/dist/cli/chunks/{load-IQWTGMLZ.js → load-CQPWGLQQ.js} +2 -2
  205. package/dist/cli/chunks/load-test-PQSGLDXJ.js +2 -0
  206. package/dist/cli/chunks/mcp-THOATWCO.js +2 -0
  207. package/dist/cli/chunks/{memory-XQVPI4UT.js → memory-NZHMHMRK.js} +5 -5
  208. package/dist/cli/chunks/memory-backend-6FR4RT5O.js +2 -0
  209. package/dist/cli/chunks/{memory-handlers-XD7MSFUN.js → memory-handlers-L2J54AQE.js} +2 -2
  210. package/dist/cli/chunks/{multi-model-executor-JC63UCWG.js → multi-model-executor-3P5E773H.js} +2 -2
  211. package/dist/cli/chunks/opencode-installer-IRZMKSNG.js +15 -0
  212. package/dist/cli/chunks/{orchestrator-B75QWJUF.js → orchestrator-UADLXTKP.js} +18 -18
  213. package/dist/cli/chunks/pattern-null-store-B2UX4NZY.js +2 -0
  214. package/dist/cli/chunks/{pipeline-TCBQ2UTZ.js → pipeline-QEH3XHXJ.js} +2 -2
  215. package/dist/cli/chunks/{platform-T43AYI3Z.js → platform-NEZ3NXLT.js} +2 -2
  216. package/dist/cli/chunks/{plugin-MSI3ZU3Z.js → plugin-O33HR2VO.js} +2 -2
  217. package/dist/cli/chunks/{prime-radiant-advanced-wasm-V62CWI6M.js → prime-radiant-advanced-wasm-MBUMFEX7.js} +2 -2
  218. package/dist/cli/chunks/protocol-executor-OQ6SL7SR.js +2 -0
  219. package/dist/cli/chunks/{protocol-handler-OH2INET2.js → protocol-handler-L455UOUT.js} +2 -2
  220. package/dist/cli/chunks/{prove-6PTMXMUL.js → prove-3XA3SMAA.js} +2 -2
  221. package/dist/cli/chunks/provider-manager-DQWHW2RG.js +2 -0
  222. package/dist/cli/chunks/qe-reasoning-bank-3JS2CZAE.js +2 -0
  223. package/dist/cli/chunks/{quality-PLNQN5GU.js → quality-H6Z5JH5B.js} +2 -2
  224. package/dist/cli/chunks/queen-coordinator-KXCWEM3Y.js +2 -0
  225. package/dist/cli/chunks/{real-embeddings-OW4OKR77.js → real-embeddings-5DNJ4KEM.js} +2 -2
  226. package/dist/cli/chunks/roocode-installer-KHXKR2FK.js +4 -0
  227. package/dist/cli/chunks/router-OVLIKT55.js +2 -0
  228. package/dist/cli/chunks/routing-feedback-2BYCXNXX.js +2 -0
  229. package/dist/cli/chunks/{routing-handler-CKFXXPMI.js → routing-handler-WAMGESEM.js} +2 -2
  230. package/dist/cli/chunks/{ruvector-commands-GERRPTJL.js → ruvector-commands-4J7XC6XY.js} +2 -2
  231. package/dist/cli/chunks/{rvf-dual-writer-5FAB2QPA.js → rvf-dual-writer-3PZEN6XN.js} +2 -2
  232. package/dist/cli/chunks/{rvf-migration-adapter-46COKWYB.js → rvf-migration-adapter-OIUNRQSU.js} +2 -2
  233. package/dist/cli/chunks/{rvf-migration-coordinator-AJVRWSNC.js → rvf-migration-coordinator-QZXDI4I5.js} +2 -2
  234. package/dist/cli/chunks/rvf-native-adapter-YNUYOQ5C.js +2 -0
  235. package/dist/cli/chunks/safe-db-6TYYEU7C.js +2 -0
  236. package/dist/cli/chunks/schedule-XVH7RTVY.js +2 -0
  237. package/dist/cli/chunks/scheduler-DHZBN5HA.js +2 -0
  238. package/dist/cli/chunks/{security-Q622IVRB.js → security-5NY77AMD.js} +3 -3
  239. package/dist/cli/chunks/{shared-rvf-adapter-EST24R3R.js → shared-rvf-adapter-MHPUZIMW.js} +2 -2
  240. package/dist/cli/chunks/{shared-rvf-dual-writer-CP6EXKBT.js → shared-rvf-dual-writer-ITLDYHCX.js} +2 -2
  241. package/dist/cli/chunks/sqlite-persistence-NR5WXTPN.js +2 -0
  242. package/dist/cli/chunks/{status-handler-LLRQB4E2.js → status-handler-7RBRIXZD.js} +2 -2
  243. package/dist/cli/chunks/{structural-health-BUFWTNN2.js → structural-health-MQPY6GA6.js} +2 -2
  244. package/dist/cli/chunks/{sync-JDG4SNT5.js → sync-66KCEANE.js} +2 -2
  245. package/dist/cli/chunks/{sync-RDL2RUOV.js → sync-USVQTHKN.js} +2 -2
  246. package/dist/cli/chunks/{task-handler-KPP6ZXA6.js → task-handler-4UI4FPPW.js} +2 -2
  247. package/dist/cli/chunks/{task-handlers-MRK2BQWI.js → task-handlers-KRII3GVV.js} +3 -3
  248. package/dist/cli/chunks/{test-7NYFTHRY.js → test-JHN2MVEG.js} +4 -4
  249. package/dist/cli/chunks/{test-scheduling-LGPKDMWD.js → test-scheduling-ZWTEGS3S.js} +3 -3
  250. package/dist/cli/chunks/{token-bootstrap-H5JHB7TD.js → token-bootstrap-YWXL6AS5.js} +2 -2
  251. package/dist/cli/chunks/{token-usage-TWPDS5U3.js → token-usage-INII2XM3.js} +2 -2
  252. package/dist/cli/chunks/{transformers-GRNPPUHM.js → transformers-DVFGDNZC.js} +2 -2
  253. package/dist/cli/chunks/{tree-sitter-wasm-parser-DOH5F6TO.js → tree-sitter-wasm-parser-W2XJT3XF.js} +2 -2
  254. package/dist/cli/chunks/{types-NYV3YKE3.js → types-GBZ5Q2GP.js} +2 -2
  255. package/dist/cli/chunks/unified-memory-WJEZ5YAK.js +2 -0
  256. package/dist/cli/chunks/unified-memory-hnsw-6ZA2PMYO.js +2 -0
  257. package/dist/cli/chunks/unified-persistence-SWH6R7MA.js +2 -0
  258. package/dist/cli/chunks/{upgrade-GDJMRYAT.js → upgrade-2JEXEGQX.js} +2 -2
  259. package/dist/cli/chunks/{validate-SIRFOPPM.js → validate-GDCM5YTS.js} +2 -2
  260. package/dist/cli/chunks/{validate-swarm-XGMJYR6X.js → validate-swarm-QZ5RSJEU.js} +2 -2
  261. package/dist/cli/chunks/{vibium-NP6ENRKV.js → vibium-I5BMT734.js} +2 -2
  262. package/dist/cli/chunks/visual-security-PH5JQZCZ.js +2 -0
  263. package/dist/cli/chunks/{web-tree-sitter-YDBWPYZD.js → web-tree-sitter-3QY2LMLP.js} +2 -2
  264. package/dist/cli/chunks/windsurf-installer-V7OBPLOB.js +7 -0
  265. package/dist/cli/chunks/{witness-chain-YHLBWQQ3.js → witness-chain-BNJ4VSZX.js} +2 -2
  266. package/dist/cli/chunks/witness-chain-WYMBNGSL.js +2 -0
  267. package/dist/cli/chunks/{workflow-TA6RY7R5.js → workflow-3FJSNLPI.js} +4 -4
  268. package/dist/cli/chunks/workflow-orchestrator-56JIXCI4.js +2 -0
  269. package/dist/cli/chunks/{wrappers-DS77IK4H.js → wrappers-ERTQNIPK.js} +2 -2
  270. package/dist/cli/commands/mcp.js +28 -28
  271. package/dist/cli/handlers/init-handler.d.ts +4 -0
  272. package/dist/cli/handlers/init-handler.js +50 -1
  273. package/dist/coordination/result-saver.js +4 -0
  274. package/dist/domains/code-intelligence/coordinator-hypergraph.js +9 -4
  275. package/dist/domains/code-intelligence/coordinator.js +9 -4
  276. package/dist/init/cline-installer.d.ts +6 -0
  277. package/dist/init/cline-installer.js +3 -1
  278. package/dist/init/codex-installer.d.ts +6 -0
  279. package/dist/init/codex-installer.js +3 -1
  280. package/dist/init/continuedev-installer.d.ts +6 -0
  281. package/dist/init/continuedev-installer.js +10 -3
  282. package/dist/init/copilot-installer.d.ts +6 -0
  283. package/dist/init/copilot-installer.js +3 -1
  284. package/dist/init/cursor-installer.d.ts +6 -0
  285. package/dist/init/cursor-installer.js +3 -1
  286. package/dist/init/kilocode-installer.d.ts +6 -0
  287. package/dist/init/kilocode-installer.js +3 -1
  288. package/dist/init/kiro-installer.d.ts +5 -0
  289. package/dist/init/kiro-installer.js +4 -4
  290. package/dist/init/opencode-installer.d.ts +39 -17
  291. package/dist/init/opencode-installer.js +166 -114
  292. package/dist/init/orchestrator.js +2 -0
  293. package/dist/init/phases/04-database.d.ts +5 -0
  294. package/dist/init/phases/04-database.js +7 -0
  295. package/dist/init/phases/05-learning.js +3 -0
  296. package/dist/init/phases/06-code-intelligence.js +6 -0
  297. package/dist/init/phases/07-hooks.js +5 -0
  298. package/dist/init/phases/08-mcp.js +34 -7
  299. package/dist/init/phases/09-assets.js +35 -28
  300. package/dist/init/phases/10-workers.js +4 -0
  301. package/dist/init/phases/11-claude-md.d.ts +1 -0
  302. package/dist/init/phases/11-claude-md.js +8 -0
  303. package/dist/init/phases/12-verification.js +10 -5
  304. package/dist/init/phases/13-governance.js +5 -0
  305. package/dist/init/phases/phase-interface.d.ts +14 -0
  306. package/dist/init/platform-config-generator.d.ts +3 -1
  307. package/dist/init/platform-config-generator.js +31 -17
  308. package/dist/init/roocode-installer.d.ts +6 -0
  309. package/dist/init/roocode-installer.js +3 -1
  310. package/dist/init/windsurf-installer.d.ts +6 -0
  311. package/dist/init/windsurf-installer.js +3 -1
  312. package/dist/integrations/ruvector/rvf-native-adapter.js +8 -0
  313. package/dist/integrations/ruvector/shared-rvf-dual-writer.js +5 -0
  314. package/dist/kernel/kernel.js +4 -2
  315. package/dist/kernel/unified-memory.js +66 -48
  316. package/dist/learning/rvf-pattern-store.js +8 -0
  317. package/dist/mcp/bundle.js +361 -358
  318. package/dist/mcp/entry.js +52 -6
  319. package/dist/mcp/handlers/core-handlers.js +7 -2
  320. package/dist/mcp/protocol-server.js +27 -1
  321. package/dist/mcp/services/session-store.d.ts +1 -0
  322. package/dist/mcp/services/session-store.js +7 -0
  323. package/dist/mcp/tools/base.d.ts +6 -0
  324. package/dist/mcp/tools/base.js +16 -0
  325. package/dist/optimization/session-cache.d.ts +11 -0
  326. package/dist/optimization/session-cache.js +31 -0
  327. package/package.json +7 -5
  328. package/dist/cli/chunks/adapter-TTIBYXH2.js +0 -2
  329. package/dist/cli/chunks/aqe-learning-engine-CTV5OLSN.js +0 -2
  330. package/dist/cli/chunks/base-ISNCJZ7A.js +0 -2
  331. package/dist/cli/chunks/browser-workflow-OD32QTTI.js +0 -2
  332. package/dist/cli/chunks/chunk-DF7V6X3N.js +0 -2
  333. package/dist/cli/chunks/chunk-I64BLAFS.js +0 -2
  334. package/dist/cli/chunks/chunk-LHZYTNOQ.js +0 -6
  335. package/dist/cli/chunks/chunk-LRRQEAP5.js +0 -2
  336. package/dist/cli/chunks/chunk-XCYPVJ34.js +0 -2
  337. package/dist/cli/chunks/chunk-XK7P7OXO.js +0 -2
  338. package/dist/cli/chunks/client-N4FQ6SMD.js +0 -2
  339. package/dist/cli/chunks/cline-installer-6JPWD64G.js +0 -4
  340. package/dist/cli/chunks/codex-installer-DA3GBMLN.js +0 -8
  341. package/dist/cli/chunks/continuedev-installer-DDDJGW26.js +0 -14
  342. package/dist/cli/chunks/copilot-installer-JVFCE6GT.js +0 -3
  343. package/dist/cli/chunks/core-handlers-SFD5HCA3.js +0 -2
  344. package/dist/cli/chunks/cross-domain-router-7HGRUNLT.js +0 -2
  345. package/dist/cli/chunks/cursor-installer-JFNYGSDD.js +0 -3
  346. package/dist/cli/chunks/dream-HPGD5TLD.js +0 -2
  347. package/dist/cli/chunks/heartbeat-scheduler-O6TI5E4P.js +0 -2
  348. package/dist/cli/chunks/hnsw-adapter-TOVTN23J.js +0 -2
  349. package/dist/cli/chunks/hnsw-index-KCZ75V7K.js +0 -2
  350. package/dist/cli/chunks/hybrid-router-4JEPC4JZ.js +0 -2
  351. package/dist/cli/chunks/impact-analyzer-3MHIU3SE.js +0 -2
  352. package/dist/cli/chunks/init-handler-MGCYDX62.js +0 -70
  353. package/dist/cli/chunks/init-wizard-ERBO5JNA.js +0 -2
  354. package/dist/cli/chunks/kernel-XJPIIWET.js +0 -2
  355. package/dist/cli/chunks/kilocode-installer-DQVWZUKP.js +0 -4
  356. package/dist/cli/chunks/knowledge-graph-NTJEG6ZE.js +0 -2
  357. package/dist/cli/chunks/llm-router-service-4T66BGB5.js +0 -2
  358. package/dist/cli/chunks/load-test-PM674TSK.js +0 -2
  359. package/dist/cli/chunks/mcp-GCTTJUBZ.js +0 -2
  360. package/dist/cli/chunks/memory-backend-53NQ5CG7.js +0 -2
  361. package/dist/cli/chunks/opencode-installer-6VJGEBIU.js +0 -3
  362. package/dist/cli/chunks/pattern-null-store-IF2RG2ON.js +0 -2
  363. package/dist/cli/chunks/protocol-executor-7AS75ZWT.js +0 -2
  364. package/dist/cli/chunks/provider-manager-AU2C4AET.js +0 -2
  365. package/dist/cli/chunks/qe-reasoning-bank-WATQRCFO.js +0 -2
  366. package/dist/cli/chunks/queen-coordinator-IOCC4VQH.js +0 -2
  367. package/dist/cli/chunks/roocode-installer-C32LCYAJ.js +0 -4
  368. package/dist/cli/chunks/router-SCJMX6WA.js +0 -2
  369. package/dist/cli/chunks/routing-feedback-RWC7F553.js +0 -2
  370. package/dist/cli/chunks/rvf-native-adapter-W2RT6PTO.js +0 -2
  371. package/dist/cli/chunks/safe-db-HO2LCAO3.js +0 -2
  372. package/dist/cli/chunks/schedule-XENCR4MR.js +0 -2
  373. package/dist/cli/chunks/scheduler-WKZ3O2SS.js +0 -2
  374. package/dist/cli/chunks/sqlite-persistence-IN6BOSCX.js +0 -2
  375. package/dist/cli/chunks/unified-memory-6MXOYRXZ.js +0 -2
  376. package/dist/cli/chunks/unified-memory-hnsw-HY3JJD5Z.js +0 -2
  377. package/dist/cli/chunks/unified-persistence-LKQNQYRY.js +0 -2
  378. package/dist/cli/chunks/visual-security-7TBWICHP.js +0 -2
  379. package/dist/cli/chunks/windsurf-installer-MFI6EAPH.js +0 -7
  380. package/dist/cli/chunks/witness-chain-24SVOWQL.js +0 -2
  381. package/dist/cli/chunks/workflow-orchestrator-XBDXCTLY.js +0 -2
@@ -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.10.7");process.exit(0)}
2
- import{i as f,m as P}from"./chunk-HBWAMCVB.js";import{d as p,e as y}from"./chunk-222ZQTL5.js";import{b as h,d as U}from"./chunk-QBVFONWU.js";import{a as T,c as C}from"./chunk-XWPUCPYW.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{i as f,m as P}from"./chunk-L5NEEGKO.js";import{d as p,e as y}from"./chunk-VHYNRISI.js";import{b as h,d as U}from"./chunk-246Z3PH6.js";import{a as T,c as C}from"./chunk-5U5SEO7C.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
3
3
  ${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  import*as o from"fs";import*as l from"path";var m=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??l.join(process.cwd(),".agentic-qe","plugins"),this.keepVersions=e.keepVersions??2}has(e,t){let s=this.versionDir(e,t);return o.existsSync(s)&&o.existsSync(l.join(s,"qe-plugin.json"))}get(e,t){if(!this.has(e,t))return;let s=this.versionDir(e,t),i=o.readFileSync(l.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),c=o.statSync(s);return{manifest:r,path:s,cachedAt:c.birthtime.toISOString()}}store(e,t){let s=this.versionDir(e.name,e.version);return o.existsSync(s)||(o.mkdirSync(s,{recursive:!0}),this.copyDir(t,s),o.writeFileSync(l.join(s,"qe-plugin.json"),JSON.stringify(e,null,2)),this.pruneOldVersions(e.name)),s}remove(e,t){let s=this.versionDir(e,t);return o.existsSync(s)?(o.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let t=l.join(this.cacheDir,e);if(!o.existsSync(t))return[];let s=[],i=o.readdirSync(t);for(let r of i){let c=l.join(t,r),h=l.join(c,"qe-plugin.json");if(o.existsSync(h))try{let a=o.readFileSync(h,"utf-8"),f=JSON.parse(a),u=o.statSync(c);s.push({manifest:f,path:c,cachedAt:u.birthtime.toISOString()})}catch{}}return s}listAll(){if(!o.existsSync(this.cacheDir))return[];let e=[],t=o.readdirSync(this.cacheDir);for(let s of t){let i=this.listVersions(s);i.length>0&&(i.sort((r,c)=>c.manifest.version.localeCompare(r.manifest.version)),e.push(i[0]))}return e}versionDir(e,t){return l.join(this.cacheDir,e,t)}pruneOldVersions(e){let t=this.listVersions(e);if(t.length<=this.keepVersions)return;t.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=t.slice(0,t.length-this.keepVersions);for(let i of s)o.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,t){if(!o.existsSync(e))return;let s=o.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=l.join(e,i.name),c=l.join(t,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;o.mkdirSync(c,{recursive:!0}),this.copyDir(r,c)}else o.copyFileSync(r,c)}}};var R=/^[a-z][a-z0-9-]*$/,S=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/,j=["aqe-core-","agentic-qe-core-"];function E(n){let e=[],t=[];if(!n||typeof n!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=n;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):D(s.name,e,t),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):S.test(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>500&&t.push("description exceeds 500 characters"),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):V(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"&&e.push(`Dependency "${i}" must have a string version range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!S.test(s.minAqeVersion))&&t.push("minAqeVersion should be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:t}}function b(n){let e=typeof n=="string"?JSON.parse(n):n,t=E(e);if(!t.valid)throw new Error(`Invalid plugin manifest:
3
3
  - ${t.errors.join(`
4
4
  - `)}`);return e}function D(n,e,t){n.length>64&&e.push("name must be 64 characters or fewer"),R.test(n)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(n)&&e.push("name must contain only ASCII characters");for(let s of j)n.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(n)&&t.push(`name "${n}" is very generic \u2014 consider a more descriptive name`)}function V(n,e){n.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!n.endsWith(".js")&&!n.endsWith(".ts")&&!n.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var y=class{resolve(e){let t=new Map;for(let a of e)t.set(a.name,a);let s=[],i=new Set,r=new Set,c=new Map,h=(a,f)=>{if(i.has(a))return;if(r.has(a)){let g=[...f.slice(f.indexOf(a)),a];throw new Error(`Dependency cycle detected: ${g.join(" -> ")}`)}let u=t.get(a);if(!u)return;r.add(a);let k=Object.keys(u.dependencies??{}),P=[];for(let g of k)t.has(g)?h(g,[...f,a]):P.push(g);P.length>0&&c.set(a,P),r.delete(a),i.add(a),s.push(u)};for(let a of e)h(a.name,[]);return{ordered:s.map((a,f)=>({manifest:a,order:f})),missing:c}}canLoad(e,t){let i=Object.keys(e.dependencies??{}).filter(r=>!t.has(r));return{canLoad:i.length===0,missingDeps:i}}};var N=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],M=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),_=["..","~","/etc/","/proc/","/dev/","node_modules/"];function A(n){let e=[];return $(n.name,e),q(n.entryPoint,e),C(n.hooks,e),I(n.permissions,e),{safe:e.length===0,violations:e}}function $(n,e){/[^\x20-\x7E]/.test(n)&&e.push(`Plugin name "${n}" contains non-ASCII characters`),M.has(n.toLowerCase())&&e.push(`Plugin name "${n}" is a reserved name`);for(let s of N)n.toLowerCase().startsWith(s)&&e.push(`Plugin name "${n}" uses reserved prefix "${s}"`);let t=n.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");M.has(t)&&e.push(`Plugin name "${n}" is visually similar to a reserved name`)}function q(n,e){w(n,"entryPoint",e),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function C(n,e){if(n)for(let[t,s]of Object.entries(n))w(s,`hook[${t}]`,e)}function w(n,e,t){for(let s of _)n.includes(s)&&t.push(`${e} contains dangerous path pattern "${s}"`);n.includes("\0")&&t.push(`${e} contains null byte (path injection attempt)`)}function I(n,e){if(!n)return;let t=["fs:write-root","net:arbitrary","exec:shell"];for(let s of n)t.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as p from"fs";import*as d from"path";var v=class{type="local";async resolve(e){let t=d.resolve(e),s=d.join(t,"qe-plugin.json");if(!p.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=p.readFileSync(s,"utf-8");return b(i)}async getPluginPath(e){let t=d.resolve(e);if(!p.existsSync(t))throw new Error(`Plugin directory does not exist: ${t}`);return t}};var x=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new m,this.resolver=new y;let t=new v;if(this.sources.set("local",t),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,t="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(t);if(!i)return{success:!1,errors:[`Unknown source type: ${t}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(u){return{success:!1,errors:[`Failed to resolve plugin: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let c=E(r);if(!c.valid)return{success:!1,manifest:r,errors:c.errors,securityViolations:[]};let h=A(r);if(!h.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:h.violations};if(this.cache.has(r.name,r.version)){let u=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:u.path,errors:[],securityViolations:[]}}let a;try{a=await i.getPluginPath(e)}catch(u){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let f=this.cache.store(r,a);return{success:!0,manifest:r,cachePath:f,errors:s,securityViolations:[]}}remove(e,t){if(t)return this.cache.remove(e,t);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(t=>({name:t.manifest.name,version:t.manifest.version,description:t.manifest.description,domains:t.manifest.domains,source:"cached",cachePath:t.path}))}resolveLoadOrder(){let e=this.cache.listAll();return this.resolver.resolve(e.map(t=>t.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{b as a,m as b,x as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  function r(e,f){if(e==null)return e;let n={...e};for(let t of f){let o=n[t];typeof o=="string"&&(n[t]=new Date(o))}return n}export{r as a};
@@ -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.10.7");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.10.9");process.exit(0)}
2
2
  var p={"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},l=new Set(Object.keys(p)),w=new Set(["!","-","+"]);function h(r){let n=[],e=0;for(;e<r.length;){let t=r[e];if(/\s/.test(t)){e++;continue}if(/\d/.test(t)||t==="."&&/\d/.test(r[e+1])){let s="";for(;e<r.length&&/[\d.]/.test(r[e]);)s+=r[e++];n.push({type:"NUMBER",value:parseFloat(s),raw:s});continue}if(t==='"'||t==="'"){let s=t,u="";for(e++;e<r.length&&r[e]!==s;){if(r[e]==="\\"&&e+1<r.length){e++;let c=r[e];switch(c){case"n":u+=`
3
3
  `;break;case"t":u+=" ";break;case"r":u+="\r";break;default:u+=c}}else u+=r[e];e++}e++,n.push({type:"STRING",value:u,raw:`${s}${u}${s}`});continue}if(/[a-zA-Z_$]/.test(t)){let s="";for(;e<r.length&&/[a-zA-Z0-9_$]/.test(r[e]);)s+=r[e++];s==="true"?n.push({type:"BOOLEAN",value:!0,raw:s}):s==="false"?n.push({type:"BOOLEAN",value:!1,raw:s}):s==="null"?n.push({type:"NULL",value:null,raw:s}):s==="undefined"?n.push({type:"UNDEFINED",value:void 0,raw:s}):n.push({type:"IDENTIFIER",value:s,raw:s});continue}let a=r.slice(e,e+2),o=r.slice(e,e+3);if(o==="==="||o==="!=="){n.push({type:"OPERATOR",value:o,raw:o}),e+=3;continue}if(a==="=="||a==="!="||a==="<="||a===">="||a==="&&"||a==="||"){n.push({type:"OPERATOR",value:a,raw:a}),e+=2;continue}if(t==="("){n.push({type:"LPAREN",value:"(",raw:"("}),e++;continue}if(t===")"){n.push({type:"RPAREN",value:")",raw:")"}),e++;continue}if(t==="."){n.push({type:"DOT",value:".",raw:"."}),e++;continue}if("+-*/%<>!".includes(t)){n.push({type:"OPERATOR",value:t,raw:t}),e++;continue}throw new Error(`Unexpected character at position ${e}: ${t}`)}return n.push({type:"EOF",value:"",raw:""}),n}var i=class{tokens;pos=0;context;constructor(n,e){this.tokens=n,this.context=e}current(){return this.tokens[this.pos]}advance(){return this.tokens[this.pos++]}expect(n){let e=this.current();if(e.type!==n)throw new Error(`Expected ${n}, got ${e.type}`);return this.advance()}parse(){let n=this.parseExpression(0);if(this.current().type!=="EOF")throw new Error(`Unexpected token: ${this.current().raw}`);return n}parseExpression(n){let e=this.parseUnary();for(;;){let t=this.current();if(t.type!=="OPERATOR"||!l.has(t.value))break;let a=p[t.value];if(a<n)break;let o=this.advance().value,s=this.parseExpression(a+1);e=this.applyBinaryOperator(o,e,s)}return e}parseUnary(){let n=this.current();if(n.type==="OPERATOR"&&w.has(n.value)){let e=this.advance().value,t=this.parseUnary();return this.applyUnaryOperator(e,t)}return this.parsePrimary()}parsePrimary(){let n=this.current();switch(n.type){case"NUMBER":case"STRING":case"BOOLEAN":case"NULL":case"UNDEFINED":return this.advance(),n.value;case"IDENTIFIER":return this.parseIdentifier();case"LPAREN":{this.advance();let e=this.parseExpression(0);return this.expect("RPAREN"),e}default:throw new Error(`Unexpected token: ${n.raw}`)}}parseIdentifier(){let n=this.context,e=this.advance().value;for(typeof n=="object"&&n!==null&&(e in n)?n=n[e]:n=void 0;this.current().type==="DOT";){this.advance();let t=this.expect("IDENTIFIER").value;n!=null&&typeof n=="object"?n=n[t]:n=void 0}return n}applyBinaryOperator(n,e,t){switch(n){case"===":return e===t;case"!==":return e!==t;case"==":return e==t;case"!=":return e!=t;case"<":return e<t;case">":return e>t;case"<=":return e<=t;case">=":return e>=t;case"&&":return e&&t;case"||":return e||t;case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":return e/t;case"%":return e%t;default:throw new Error(`Unknown operator: ${n}`)}}applyUnaryOperator(n,e){switch(n){case"!":return!e;case"-":return-e;case"+":return+e;default:throw new Error(`Unknown unary operator: ${n}`)}}};function E(r,n={}){if(!r||typeof r!="string")throw new Error("Expression must be a non-empty string");let e=[/\beval\b/i,/\bFunction\b/,/\bconstructor\b/,/\b__proto__\b/,/\bprototype\b/,/\bimport\b/,/\brequire\b/,/\bprocess\b/,/\bglobal\b/,/\bwindow\b/,/\bdocument\b/,/\[\s*['"`]/,/\[.*\]/];for(let o of e)if(o.test(r))throw new Error(`Expression contains potentially dangerous pattern: ${r}`);let t=h(r.trim());return new i(t,n).parse()}function b(r,n={},e=!1){try{return!!E(r,n)}catch(t){return console.warn(`[SafeEvaluator] Failed to evaluate expression: ${r}`,t),e}}export{b as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
- import{a as ie,b as ae}from"./chunk-7NK2H7H5.js";import{S as oe,i as j,p as q}from"./chunk-76JYG426.js";import{c as g,e as D,g as $}from"./chunk-LRRQEAP5.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,w,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,w=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as ie,b as ae}from"./chunk-3HT4CT6F.js";import{S as oe,i as j,p as q}from"./chunk-KRAWWBX5.js";import{c as g,e as D,g as $}from"./chunk-ABJPFKHE.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),$(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function B(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function U(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,O=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=B(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=B(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-U(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-U(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(K){if(k)return k;throw new b(J??"Unknown load error")}K=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw J=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function Q(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,K,J,X,w,Y=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,K=!1,J=null;X=1e4,w=class{config;nativeIndex=null;currentMaxElements=X;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(Q(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(a*2,this.liveIds.size),c=this.nativeIndex.searchKnn(Q(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,W=d.get(m);(W===void 0||f>W.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=X,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function Z(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var re={};D(re,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>ee,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>te,buildLaplacian:()=>Z,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function te(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var ee,fe,T,V,L,ne=g(()=>{"use strict";_();_();ee={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...ee,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=te(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ye={};D(ye,{HnswAdapter:()=>G});var ve,p,G,xe=g(()=>{O();Y();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,G=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if(q()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(ne(),$(re));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(j())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{G as a,ye as b,xe as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
- import{a as b}from"./chunk-DF7V6X3N.js";import{c as k}from"./chunk-222ZQTL5.js";import{b as p,d as C}from"./chunk-QBVFONWU.js";C();b();var m=k.create("skill-validation-learner"),v=class{constructor(e){this.reasoningBank=e}reasoningBank;memoryNamespace="skill-validation";feedbackLoop=null;connectFeedbackLoop(e){this.feedbackLoop=e}async recordValidationOutcome(e){await this.reasoningBank.storeQEPattern({patternType:"test-template",name:`${e.skillName}-validation-${e.validationLevel}`,description:`Validation outcome for ${e.skillName} at level ${e.validationLevel}`,context:{tags:["skill-validation",e.skillName,e.model,e.validationLevel],testType:"integration"},template:{type:"config",content:JSON.stringify({outcome:{skillName:e.skillName,trustTier:e.trustTier,validationLevel:e.validationLevel,model:e.model,passed:e.passed,score:e.score,testCaseCount:e.testCaseResults.length,passedTests:e.testCaseResults.filter(s=>s.passed).length,avgReasoningQuality:this.calculateAvgReasoningQuality(e.testCaseResults),timestamp:e.timestamp.toISOString(),runId:e.runId,metadata:e.metadata}}),variables:[]}}),await this.updateSkillConfidence(e),e.validationLevel==="eval"&&await this.trackCrossModelBehavior(e),this.feedbackLoop&&e.runId&&await this.recordToFeedbackLoop(e)}async updateSkillConfidence(e){let s=`skill-confidence-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let r=n.value[0].pattern.template?.content;if(r){let i=p(r);i&&typeof i=="object"&&Array.isArray(i.outcomes)?t=i:t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName)}catch(a){m.debug("Confidence history parse failed",{skill:e.skillName,error:a instanceof Error?a.message:String(a)}),t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName);t.outcomes.push({score:e.score,timestamp:e.timestamp,model:e.model,validationLevel:e.validationLevel,passed:e.passed}),t.outcomes.length>100&&(t.outcomes=t.outcomes.slice(-100)),t.avgScore=t.outcomes.reduce((a,r)=>a+r.score,0)/t.outcomes.length,t.lastUpdated=new Date,t.trend=this.calculateTrend(t.outcomes),t.byLevel=this.calculateConfidenceByLevel(t.outcomes),await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Skill confidence tracking for ${e.skillName}`,context:{tags:["skill-confidence",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async trackCrossModelBehavior(e){let s=`cross-model-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let c=n.value[0].pattern.template?.content;if(c){let l=p(c);l&&typeof l=="object"&&typeof l.models=="object"?t=l:t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis()}catch(o){m.debug("Cross-model analysis parse failed",{error:o instanceof Error?o.message:String(o)}),t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis();t.models||(t.models={}),t.models[e.model]||(t.models[e.model]={scores:[],passRate:0,avgReasoningQuality:0,sampleCount:0});let a=t.models[e.model];a.scores.push(e.score),a.sampleCount++,a.scores.length>50&&(a.scores=a.scores.slice(-50));let r=this.calculateAvgReasoningQuality(e.testCaseResults);a.passRate=a.scores.filter(o=>o>=.9).length/a.scores.length,a.avgReasoningQuality=(a.avgReasoningQuality*(a.sampleCount-1)+r)/a.sampleCount;let i=Object.values(t.models).map(o=>o.passRate);if(i.length>1){let o=i.reduce((l,d)=>l+d,0)/i.length,c=i.reduce((l,d)=>l+Math.pow(d-o,2),0)/i.length;t.variance=c,t.hasAnomalies=c>.04,t.anomalies=[];for(let[l,d]of Object.entries(t.models))Math.abs(d.passRate-o)>.2&&t.anomalies.push({model:l,type:d.passRate<o?"low_performance":"high_variance",description:`Model ${l} has ${((d.passRate-o)*100).toFixed(1)}% difference from average`})}t.lastUpdated=new Date,await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Cross-model behavior tracking for ${e.skillName}`,context:{tags:["cross-model",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async recordToFeedbackLoop(e){if(!this.feedbackLoop)return;let s={taskId:e.runId,taskDescription:`Skill validation: ${e.skillName} (${e.validationLevel})`,recommendedAgent:"skill-validator",usedAgent:"skill-validator",followedRecommendation:!0,success:e.passed,qualityScore:e.score,durationMs:e.metadata?.duration||0,timestamp:e.timestamp};await this.feedbackLoop.recordRoutingOutcome(s)}async getSkillConfidence(e){let s=`skill-confidence-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Skill confidence pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async getCrossModelAnalysis(e){let s=`cross-model-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Cross-model pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async queryValidationPatterns(e,s=10){let n=await this.reasoningBank.searchQEPatterns(`${e} validation`,{limit:s});return n.success?n.value.filter(t=>t.pattern.context?.tags?.includes("skill-validation")).map(t=>t.pattern):[]}async getValidationTrends(e){let s=await this.getSkillConfidence(e),n=await this.getCrossModelAnalysis(e);if(!s)return null;let t={};if(n)for(let i of Object.keys(n.models)){let o=s.outcomes.filter(c=>c.model===i).map(c=>({score:c.score}));t[i]=this.calculateTrend(o)}let a=s.outcomes.slice(-20),r=a.filter(i=>i.passed).length/a.length;return{overall:s.trend||"stable",byModel:t,recentPassRate:r}}async extractLearnedPatterns(e){let s=await this.queryValidationPatterns(e,50),n=[],t=new Map;for(let a of s)try{let i=p(a.template?.content||"{}").outcome?.metadata?.category||"general";t.has(i)||t.set(i,[]),t.get(i).push(a)}catch(r){m.debug("Invalid pattern during category grouping",{error:r instanceof Error?r.message:String(r)})}for(let[a,r]of Array.from(t.entries())){let i=new Set,o=new Set,c=new Set,l=0;for(let d of r)try{let f=p(d.template?.content||"{}").outcome;if(!f)continue;c.add(f.model),l+=f.score;let h=d.context?.tags||[];f.passed?h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>i.add(g)):h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>o.add(g))}catch(u){m.debug("Invalid pattern during category extraction",{error:u instanceof Error?u.message:String(u)})}r.length>0&&n.push({id:`${e}-${a}`,skillName:e,category:a,successIndicators:Array.from(i),failureIndicators:Array.from(o),models:Array.from(c),confidence:l/r.length,observationCount:r.length})}return n}createEmptyConfidence(e){return{skillName:e,avgScore:0,outcomes:[],lastUpdated:new Date}}createEmptyCrossModelAnalysis(){return{models:{},variance:0,hasAnomalies:!1,lastUpdated:new Date}}calculateAvgReasoningQuality(e){return e.length===0?0:e.reduce((s,n)=>s+n.reasoningQuality,0)/e.length}calculateTrend(e){if(e.length<5)return"stable";let s=e.slice(-10),n=e.slice(-20,-10);if(n.length===0)return"stable";let t=s.reduce((i,o)=>i+o.score,0)/s.length,a=n.reduce((i,o)=>i+o.score,0)/n.length,r=t-a;return r>.05?"improving":r<-.05?"declining":"stable"}calculateConfidenceByLevel(e){let s={schema:[],validator:[],eval:[]};for(let t of e)t.validationLevel&&s[t.validationLevel].push(t.score);let n={};for(let[t,a]of Object.entries(s))a.length>0&&(n[t]=a.reduce((r,i)=>r+i,0)/a.length);return n}};function L(y){return new v(y)}export{L as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as b}from"./chunk-OPKEQYAC.js";import{c as k}from"./chunk-VHYNRISI.js";import{b as p,d as C}from"./chunk-246Z3PH6.js";C();b();var m=k.create("skill-validation-learner"),v=class{constructor(e){this.reasoningBank=e}reasoningBank;memoryNamespace="skill-validation";feedbackLoop=null;connectFeedbackLoop(e){this.feedbackLoop=e}async recordValidationOutcome(e){await this.reasoningBank.storeQEPattern({patternType:"test-template",name:`${e.skillName}-validation-${e.validationLevel}`,description:`Validation outcome for ${e.skillName} at level ${e.validationLevel}`,context:{tags:["skill-validation",e.skillName,e.model,e.validationLevel],testType:"integration"},template:{type:"config",content:JSON.stringify({outcome:{skillName:e.skillName,trustTier:e.trustTier,validationLevel:e.validationLevel,model:e.model,passed:e.passed,score:e.score,testCaseCount:e.testCaseResults.length,passedTests:e.testCaseResults.filter(s=>s.passed).length,avgReasoningQuality:this.calculateAvgReasoningQuality(e.testCaseResults),timestamp:e.timestamp.toISOString(),runId:e.runId,metadata:e.metadata}}),variables:[]}}),await this.updateSkillConfidence(e),e.validationLevel==="eval"&&await this.trackCrossModelBehavior(e),this.feedbackLoop&&e.runId&&await this.recordToFeedbackLoop(e)}async updateSkillConfidence(e){let s=`skill-confidence-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let r=n.value[0].pattern.template?.content;if(r){let i=p(r);i&&typeof i=="object"&&Array.isArray(i.outcomes)?t=i:t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName)}catch(a){m.debug("Confidence history parse failed",{skill:e.skillName,error:a instanceof Error?a.message:String(a)}),t=this.createEmptyConfidence(e.skillName)}else t=this.createEmptyConfidence(e.skillName);t.outcomes.push({score:e.score,timestamp:e.timestamp,model:e.model,validationLevel:e.validationLevel,passed:e.passed}),t.outcomes.length>100&&(t.outcomes=t.outcomes.slice(-100)),t.avgScore=t.outcomes.reduce((a,r)=>a+r.score,0)/t.outcomes.length,t.lastUpdated=new Date,t.trend=this.calculateTrend(t.outcomes),t.byLevel=this.calculateConfidenceByLevel(t.outcomes),await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Skill confidence tracking for ${e.skillName}`,context:{tags:["skill-confidence",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async trackCrossModelBehavior(e){let s=`cross-model-${e.skillName}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1}),t;if(n.success&&n.value.length>0)try{let c=n.value[0].pattern.template?.content;if(c){let l=p(c);l&&typeof l=="object"&&typeof l.models=="object"?t=l:t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis()}catch(o){m.debug("Cross-model analysis parse failed",{error:o instanceof Error?o.message:String(o)}),t=this.createEmptyCrossModelAnalysis()}else t=this.createEmptyCrossModelAnalysis();t.models||(t.models={}),t.models[e.model]||(t.models[e.model]={scores:[],passRate:0,avgReasoningQuality:0,sampleCount:0});let a=t.models[e.model];a.scores.push(e.score),a.sampleCount++,a.scores.length>50&&(a.scores=a.scores.slice(-50));let r=this.calculateAvgReasoningQuality(e.testCaseResults);a.passRate=a.scores.filter(o=>o>=.9).length/a.scores.length,a.avgReasoningQuality=(a.avgReasoningQuality*(a.sampleCount-1)+r)/a.sampleCount;let i=Object.values(t.models).map(o=>o.passRate);if(i.length>1){let o=i.reduce((l,d)=>l+d,0)/i.length,c=i.reduce((l,d)=>l+Math.pow(d-o,2),0)/i.length;t.variance=c,t.hasAnomalies=c>.04,t.anomalies=[];for(let[l,d]of Object.entries(t.models))Math.abs(d.passRate-o)>.2&&t.anomalies.push({model:l,type:d.passRate<o?"low_performance":"high_variance",description:`Model ${l} has ${((d.passRate-o)*100).toFixed(1)}% difference from average`})}t.lastUpdated=new Date,await this.reasoningBank.storeQEPattern({patternType:"test-template",name:s,description:`Cross-model behavior tracking for ${e.skillName}`,context:{tags:["cross-model",e.skillName]},template:{type:"config",content:JSON.stringify(t),variables:[]}})}async recordToFeedbackLoop(e){if(!this.feedbackLoop)return;let s={taskId:e.runId,taskDescription:`Skill validation: ${e.skillName} (${e.validationLevel})`,recommendedAgent:"skill-validator",usedAgent:"skill-validator",followedRecommendation:!0,success:e.passed,qualityScore:e.score,durationMs:e.metadata?.duration||0,timestamp:e.timestamp};await this.feedbackLoop.recordRoutingOutcome(s)}async getSkillConfidence(e){let s=`skill-confidence-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Skill confidence pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async getCrossModelAnalysis(e){let s=`cross-model-${e}`,n=await this.reasoningBank.searchQEPatterns(s,{limit:1});if(n.success&&n.value.length>0)try{let t=n.value[0].pattern.template?.content;if(t)return p(t)}catch(t){m.debug("Cross-model pattern content invalid",{skill:e,error:t instanceof Error?t.message:String(t)})}return null}async queryValidationPatterns(e,s=10){let n=await this.reasoningBank.searchQEPatterns(`${e} validation`,{limit:s});return n.success?n.value.filter(t=>t.pattern.context?.tags?.includes("skill-validation")).map(t=>t.pattern):[]}async getValidationTrends(e){let s=await this.getSkillConfidence(e),n=await this.getCrossModelAnalysis(e);if(!s)return null;let t={};if(n)for(let i of Object.keys(n.models)){let o=s.outcomes.filter(c=>c.model===i).map(c=>({score:c.score}));t[i]=this.calculateTrend(o)}let a=s.outcomes.slice(-20),r=a.filter(i=>i.passed).length/a.length;return{overall:s.trend||"stable",byModel:t,recentPassRate:r}}async extractLearnedPatterns(e){let s=await this.queryValidationPatterns(e,50),n=[],t=new Map;for(let a of s)try{let i=p(a.template?.content||"{}").outcome?.metadata?.category||"general";t.has(i)||t.set(i,[]),t.get(i).push(a)}catch(r){m.debug("Invalid pattern during category grouping",{error:r instanceof Error?r.message:String(r)})}for(let[a,r]of Array.from(t.entries())){let i=new Set,o=new Set,c=new Set,l=0;for(let d of r)try{let f=p(d.template?.content||"{}").outcome;if(!f)continue;c.add(f.model),l+=f.score;let h=d.context?.tags||[];f.passed?h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>i.add(g)):h.filter(g=>!["skill-validation",e].includes(g)).forEach(g=>o.add(g))}catch(u){m.debug("Invalid pattern during category extraction",{error:u instanceof Error?u.message:String(u)})}r.length>0&&n.push({id:`${e}-${a}`,skillName:e,category:a,successIndicators:Array.from(i),failureIndicators:Array.from(o),models:Array.from(c),confidence:l/r.length,observationCount:r.length})}return n}createEmptyConfidence(e){return{skillName:e,avgScore:0,outcomes:[],lastUpdated:new Date}}createEmptyCrossModelAnalysis(){return{models:{},variance:0,hasAnomalies:!1,lastUpdated:new Date}}calculateAvgReasoningQuality(e){return e.length===0?0:e.reduce((s,n)=>s+n.reasoningQuality,0)/e.length}calculateTrend(e){if(e.length<5)return"stable";let s=e.slice(-10),n=e.slice(-20,-10);if(n.length===0)return"stable";let t=s.reduce((i,o)=>i+o.score,0)/s.length,a=n.reduce((i,o)=>i+o.score,0)/n.length,r=t-a;return r>.05?"improving":r<-.05?"declining":"stable"}calculateConfidenceByLevel(e){let s={schema:[],validator:[],eval:[]};for(let t of e)t.validationLevel&&s[t.validationLevel].push(t.score);let n={};for(let[t,a]of Object.entries(s))a.length>0&&(n[t]=a.reduce((r,i)=>r+i,0)/a.length);return n}};function L(y){return new v(y)}export{L as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
- import{a as t,q as r}from"./chunk-4RGV6Z2H.js";import{c as l}from"./chunk-LRRQEAP5.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a as t,q as r}from"./chunk-L5IO7QNO.js";import{c as l}from"./chunk-ABJPFKHE.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
@@ -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.10.9");process.exit(0)}
2
+ var e=null,f=null,t=null,u=!1;async function W(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only"||process.env.AQE_MEMORY_BACKEND==="memory")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-YNUYOQ5C.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-WJEZ5YAK.js"),o=v().getDatabase();if(!o)return null;let{join:m}=await import("node:path"),g=m(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-3PZEN6XN.js"),l=new R(o,{rvfPath:g,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-JYZSSQJC.js"),a=y();if(a>=2){let{RvfMigrationAdapter:A}=await import("./rvf-migration-adapter-OIUNRQSU.js"),s=new A({stage:a});s.setSqliteDb(o);let{getSharedRvfAdapter:D}=await import("./shared-rvf-adapter-MHPUZIMW.js"),i=D();if(i){let h={ingest:n=>i.ingest(n),search:(n,M)=>i.search(n,M).map(c=>({id:c.id,score:c.score})),delete:n=>i.delete(n),status:()=>i.status(),close:()=>{}};s.setRvfStore(h)}f=s,console.log(`[RVF] Migration adapter active at stage ${a} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][a]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-BX4A2D4V.js").then(({registerRvfResetFn:r})=>r(w)).catch(()=>{})}})(),t)}function S(){return e}function b(){return f}function w(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{W as a,S as b,b as c,w as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  var t=["claude","openai","ollama","openrouter","gemini","azure-openai","bedrock","onnx"];var e={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},r=[{provider:"claude",models:["claude-sonnet-4-6","claude-haiku-4-5-20251001"],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-4o","gpt-4o-mini"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-4","openai/gpt-4o"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["llama3.1","mistral"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],o={id:"default-fallback-chain",entries:r,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},n={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",fallbackChain:o,fallbackBehavior:e,providers:{claude:{enabled:!0,defaultModel:"claude-sonnet-4-6"},openai:{enabled:!0,defaultModel:"gpt-4o"},ollama:{enabled:!0,defaultModel:"llama3.1"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-4"},gemini:{enabled:!1,defaultModel:"gemini-pro"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},a=[{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:64e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];export{t as a,n as b,a as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  import{createRequire as t}from"module";var o=t(import.meta.url),e=o("@huggingface/transformers"),n=e,{RuvectorLayer:i,TensorCompress:a,differentiableSearch:c,hierarchicalForward:s,getCompressionLevel:l,init:p,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:d,HyperbolicAttention:f,LinearAttention:A,MoEAttention:g,SonaEngine:h,pipeline:_}=e||{};export{n as a,i as b,a as c,c as d,s as e,l as f,p as g,m as h,u as i,d as j,f as k,A as l,g as m,h as n,_ as o};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-LRRQEAP5.js";var g={};o(g,{DotProductAttention:()=>u,FlashAttention:()=>m,HyperbolicAttention:()=>h,LinearAttention:()=>f,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>r,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>d,pipeline:()=>L});import{createRequire as n}from"module";var i,e,r,a,c,l,s,p,d,m,u,A,h,f,_,b,L,q=t(()=>{i=n(import.meta.url),e=i("hnswlib-node"),r=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:d,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:A,HyperbolicAttention:h,LinearAttention:f,MoEAttention:_,SonaEngine:b,pipeline:L}=e||{}});export{r as a,a as b,c,l as d,s as e,p as f,d as g,m as h,u as i,A as j,h as k,f as l,_ as m,b as n,L as o,g as p,q};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-ABJPFKHE.js";var g={};o(g,{DotProductAttention:()=>u,FlashAttention:()=>m,HyperbolicAttention:()=>h,LinearAttention:()=>f,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>r,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>d,pipeline:()=>L});import{createRequire as n}from"module";var i,e,r,a,c,l,s,p,d,m,u,A,h,f,_,b,L,q=t(()=>{i=n(import.meta.url),e=i("hnswlib-node"),r=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:d,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:A,HyperbolicAttention:h,LinearAttention:f,MoEAttention:_,SonaEngine:b,pipeline:L}=e||{}});export{r as a,a as b,c,l as d,s as e,p as f,d as g,m as h,u as i,A as j,h as k,f as l,_ as m,b as n,L as o,g as p,q};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  var i=class r{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new r(e)}};var s=class r{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new r(e)}static fromPercentage(e){return new r(e/100)}},u=class r{constructor(e,t){this._start=e;this._end=t;if(e>t)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,t){return new r(e,t)}static lastNDays(e){let t=new Date,n=new Date(t.getTime()-e*24*60*60*1e3);return new r(n,t)}},o=class r{constructor(e,t,n,a){this._major=e;this._minor=t;this._patch=n;this._prerelease=a}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,t,n,a){return new r(e,t,n,a)}static parse(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw new Error(`Invalid version format: ${e}`);return new r(parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4])}};export{i as a,s as b,u as c,o 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.10.7");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.10.9");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var g=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as q,join as H}from"path";import{existsSync as L,readFileSync as U}from"fs";var _=$(Q),z={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},p=class{constructor(e,t){this.queue=e;this.options={...z,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=q(this.options.repoRoot,".git","refs","heads");if(!L(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
3
  `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=q(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=U(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
- import{g}from"./chunk-YLXUF5KW.js";import{b as p,c as d}from"./chunk-2MLISLRR.js";import{b as m,c as f}from"./chunk-XWPUCPYW.js";import{i as h}from"./chunk-6OLPKIYU.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}memory;config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:r=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let n=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,n,i),s=[];if(r){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:n,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(r.success)for(let s of r.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let n=this.getBaseName(i),l=[`${n}.test`,`${n}.spec`,`test_${n}`,`${n}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10,{namespace:"code-intelligence:kg"});for(let a of c){let o=await this.memory.get(a,{namespace:"code-intelligence:kg"});o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,r=Math.min(1,e.directImpact.length/10);i+=r*t.directImpact;let n=Math.min(1,e.transitiveImpact.length/20);i+=n*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(n=>this.isCriticalPath(n.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let r=[...e.directImpact,...e.transitiveImpact].filter(n=>n.riskScore>=.7);return r.length>0&&t.push(`${r.length} high-risk files impacted: ${r.slice(0,2).map(n=>this.getFileName(n.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(r.success){let{nodes:n,edges:l}=r.value;for(let s of n){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let r=[],n=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(n.has(a.path)||a.path===s.file)continue;n.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);r.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(r)}calculateFileRiskScore(e,t,i,r=1){let n=0;return n+=Math.min(.3,t/20),n+=Math.min(.2,i/30),this.isCriticalPath(e)&&(n+=.3),this.isEntryPoint(e)&&(n+=.2),n=n*Math.pow(.8,r-1),Math.min(1,Math.max(0,n))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,r)=>i+r.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let r=t.get(i.file);(!r||i.distance<r.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,r)=>r.riskScore!==i.riskScore?r.riskScore-i.riskScore:i.distance-r.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{g}from"./chunk-NYBAH76S.js";import{b as p,c as d}from"./chunk-X6YUGKMM.js";import{b as m,c as f}from"./chunk-5U5SEO7C.js";import{i as h}from"./chunk-QWXJRZEH.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}memory;config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:r=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let n=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,n,i),s=[];if(r){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:n,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(r.success)for(let s of r.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let n=this.getBaseName(i),l=[`${n}.test`,`${n}.spec`,`test_${n}`,`${n}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10,{namespace:"code-intelligence:kg"});for(let a of c){let o=await this.memory.get(a,{namespace:"code-intelligence:kg"});o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,r=Math.min(1,e.directImpact.length/10);i+=r*t.directImpact;let n=Math.min(1,e.transitiveImpact.length/20);i+=n*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(n=>this.isCriticalPath(n.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let r=[...e.directImpact,...e.transitiveImpact].filter(n=>n.riskScore>=.7);return r.length>0&&t.push(`${r.length} high-risk files impacted: ${r.slice(0,2).map(n=>this.getFileName(n.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(r.success){let{nodes:n,edges:l}=r.value;for(let s of n){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let r=[],n=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(n.has(a.path)||a.path===s.file)continue;n.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);r.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(r)}calculateFileRiskScore(e,t,i,r=1){let n=0;return n+=Math.min(.3,t/20),n+=Math.min(.2,i/30),this.isCriticalPath(e)&&(n+=.3),this.isEntryPoint(e)&&(n+=.2),n=n*Math.pow(.8,r-1),Math.min(1,Math.max(0,n))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,r)=>i+r.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let r=t.get(i.file);(!r||i.distance<r.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,r)=>r.riskScore!==i.riskScore?r.riskScore-i.riskScore:i.distance-r.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u 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.10.7");process.exit(0)}
2
- import{a as N,c as ee}from"./chunk-XWPUCPYW.js";import{b as L,d as B}from"./chunk-QDBFB4XD.js";B();ee();B();import*as x from"node:http";import*as R from"node:https";import{createHash as te}from"node:crypto";import{URL as W}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ne="AQE embedder endpoint identity canary v1",re="/v1/embeddings";function X(n){if(n.startsWith("unix:"))return n;try{let e=new W(n);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):n}catch{return n}}function ie(n){if(n.startsWith("unix:")){let r=n.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${n}`);return{transport:"unix",socketPath:r,safeUrl:n}}let e=new W(n);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 D=class{constructor(e,t,r=()=>{}){this.threshold=e;this.windowMs=t;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(t=>e-t<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}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ie(e.endpoint),this.parsed.transport==="https"){let t=e.tlsOptions??{};this.agent=new R.Agent({keepAlive:!0,ca:t.ca,cert:t.cert,key:t.key,rejectUnauthorized:t.rejectUnauthorized!==!1,servername:t.servername})}else this.agent=new x.Agent({keepAlive:!0});this.breaker=new D(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 t=await this.postEmbeddings(e),r=this.decodeAndNormalize(t,e.length);return this.breaker.recordSuccess(),r}catch(t){throw this.breaker.recordFailure(),t}}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 s=await this.postEmbeddings([ne]);e=this.decodeAndNormalize(s,1)[0],this.breaker.recordSuccess()}catch(s){throw this.breaker.recordFailure(),s}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 t=Buffer.alloc(e.length*2);for(let s=0;s<e.length;s++){let o=Math.max(-32768,Math.min(32767,Math.round(e[s]*32767)));t.writeInt16LE(o,s*2)}let r=te("sha256").update(t).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,t){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==t)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${t}, got ${r.length}`);let s=r.map((o,i)=>({idx:typeof o.index=="number"?o.index:i,embedding:o.embedding}));return s.sort((o,i)=>o.idx-i.idx),s.map(({embedding:o},i)=>{if(typeof o=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${i} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(o))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${i}`);if(o.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${i}: expected ${this.opts.expectedDim}, got ${o.length}`);return L(o)})}postEmbeddings(e){let t=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(re,t)}request(e,t){let r={"content-type":"application/json","content-length":Buffer.byteLength(t),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let s={method:"POST",path:e,headers:r,agent:this.agent},o,i;this.parsed.transport==="unix"?(o={...s,socketPath:this.parsed.socketPath},i=x.request):(o={...s,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},i=this.parsed.transport==="https"?R.request:x.request);let l=this.parsed.safeUrl,c=this.opts.connectTimeoutMs,h=this.opts.requestTimeoutMs;return new Promise((S,I)=>{let E=!1,C=a=>{E||(E=!0,S(a))},y=a=>{E||(E=!0,I(a))},f=i(o,a=>{let g=[];a.on("data",u=>g.push(Buffer.from(u))),a.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!a.statusCode||a.statusCode<200||a.statusCode>=300){y(new Error(`[EmbedderEndpointClient] HTTP ${a.statusCode} from ${l}: ${u.slice(0,200)}`));return}try{let b=JSON.parse(u);C(b)}catch(b){y(new Error(`[EmbedderEndpointClient] invalid JSON from ${l}: ${b.message}`))}}),a.on("error",u=>y(u))});f.on("socket",a=>{a.setTimeout(c);let g=()=>{a.setTimeout(h)};a.connecting?a.once("connect",g):g(),a.on("timeout",()=>{let u=a.connecting?"connect":"request",b=a.connecting?c:h,M=new Error(`[EmbedderEndpointClient] ${u} timeout after ${b}ms`);y(M),f.destroy(M)})}),f.on("error",a=>y(a)),f.write(t),f.end()})}};import{join as H}from"node:path";import{existsSync as oe,mkdirSync as se}from"node:fs";import{createRequire as ae}from"node:module";var de=ae(import.meta.url);function le(){let n=process.env.AQE_MEMORY_PATH;return n&&n.length>0?n:H(process.cwd(),".agentic-qe","memory.db")}var j="_system",K="embedder_identity:",v=null,$=!1;function G(){if(v)return v;if($)return null;try{let n=de("better-sqlite3"),e=le(),t=H(e,"..");oe(t)||se(t,{recursive:!0});let r=new n(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),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.10.9");process.exit(0)}
2
+ import{a as N,c as ee}from"./chunk-5U5SEO7C.js";import{b as L,d as B}from"./chunk-C6GQIUKW.js";B();ee();B();import*as x from"node:http";import*as R from"node:https";import{createHash as te}from"node:crypto";import{URL as W}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ne="AQE embedder endpoint identity canary v1",re="/v1/embeddings";function X(n){if(n.startsWith("unix:"))return n;try{let e=new W(n);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):n}catch{return n}}function ie(n){if(n.startsWith("unix:")){let r=n.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${n}`);return{transport:"unix",socketPath:r,safeUrl:n}}let e=new W(n);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 D=class{constructor(e,t,r=()=>{}){this.threshold=e;this.windowMs=t;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(t=>e-t<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}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ie(e.endpoint),this.parsed.transport==="https"){let t=e.tlsOptions??{};this.agent=new R.Agent({keepAlive:!0,ca:t.ca,cert:t.cert,key:t.key,rejectUnauthorized:t.rejectUnauthorized!==!1,servername:t.servername})}else this.agent=new x.Agent({keepAlive:!0});this.breaker=new D(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 t=await this.postEmbeddings(e),r=this.decodeAndNormalize(t,e.length);return this.breaker.recordSuccess(),r}catch(t){throw this.breaker.recordFailure(),t}}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 s=await this.postEmbeddings([ne]);e=this.decodeAndNormalize(s,1)[0],this.breaker.recordSuccess()}catch(s){throw this.breaker.recordFailure(),s}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 t=Buffer.alloc(e.length*2);for(let s=0;s<e.length;s++){let o=Math.max(-32768,Math.min(32767,Math.round(e[s]*32767)));t.writeInt16LE(o,s*2)}let r=te("sha256").update(t).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,t){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==t)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${t}, got ${r.length}`);let s=r.map((o,i)=>({idx:typeof o.index=="number"?o.index:i,embedding:o.embedding}));return s.sort((o,i)=>o.idx-i.idx),s.map(({embedding:o},i)=>{if(typeof o=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${i} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(o))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${i}`);if(o.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${i}: expected ${this.opts.expectedDim}, got ${o.length}`);return L(o)})}postEmbeddings(e){let t=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(re,t)}request(e,t){let r={"content-type":"application/json","content-length":Buffer.byteLength(t),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let s={method:"POST",path:e,headers:r,agent:this.agent},o,i;this.parsed.transport==="unix"?(o={...s,socketPath:this.parsed.socketPath},i=x.request):(o={...s,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},i=this.parsed.transport==="https"?R.request:x.request);let l=this.parsed.safeUrl,c=this.opts.connectTimeoutMs,h=this.opts.requestTimeoutMs;return new Promise((S,I)=>{let E=!1,C=a=>{E||(E=!0,S(a))},y=a=>{E||(E=!0,I(a))},f=i(o,a=>{let g=[];a.on("data",u=>g.push(Buffer.from(u))),a.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!a.statusCode||a.statusCode<200||a.statusCode>=300){y(new Error(`[EmbedderEndpointClient] HTTP ${a.statusCode} from ${l}: ${u.slice(0,200)}`));return}try{let b=JSON.parse(u);C(b)}catch(b){y(new Error(`[EmbedderEndpointClient] invalid JSON from ${l}: ${b.message}`))}}),a.on("error",u=>y(u))});f.on("socket",a=>{a.setTimeout(c);let g=()=>{a.setTimeout(h)};a.connecting?a.once("connect",g):g(),a.on("timeout",()=>{let u=a.connecting?"connect":"request",b=a.connecting?c:h,M=new Error(`[EmbedderEndpointClient] ${u} timeout after ${b}ms`);y(M),f.destroy(M)})}),f.on("error",a=>y(a)),f.write(t),f.end()})}};import{join as H}from"node:path";import{existsSync as oe,mkdirSync as se}from"node:fs";import{createRequire as ae}from"node:module";var de=ae(import.meta.url);function le(){let n=process.env.AQE_MEMORY_PATH;return n&&n.length>0?n:H(process.cwd(),".agentic-qe","memory.db")}var j="_system",K="embedder_identity:",v=null,$=!1;function G(){if(v)return v;if($)return null;try{let n=de("better-sqlite3"),e=le(),t=H(e,"..");oe(t)||se(t,{recursive:!0});let r=new n(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS kv_store (
4
4
  key TEXT NOT NULL,
5
5
  namespace TEXT NOT NULL,
@@ -9,4 +9,4 @@ import{a as N,c as ee}from"./chunk-XWPUCPYW.js";import{b as L,d as B}from"./chun
9
9
  PRIMARY KEY (namespace, key)
10
10
  );
11
11
  CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
- `),v=r,r}catch{return $=!0,null}}function J(n){let e=G();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(j,K+n);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function Q(n){let e=G();if(!e)return;let t={fingerprint:n.fingerprint,dim:n.dim,endpoint:n.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(K+n.endpoint,j,JSON.stringify(t))}function Y(){if(v)try{v.close()}catch{}v=null,$=!1}var z=null,m=null,A=null,k=!1,O="",w=null,p=null,F={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},d=new Map,V=36e5;function _(n){return p?`endpoint:${p.fingerprint}:${n}`:`inproc:${n}`}function pe(n){let e=n.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 Z(n={}){if(k)throw new Error(`Transformer initialization previously failed: ${O}`);if(A)return A;let e={...F,...n};return A=(async()=>{try{if(e.endpoint){let o=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${o}`),w=new P({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:q()}),p=await w.probe(),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let i=J(p.endpoint);i&&i.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${i.fingerprint} dim=${i.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),Q(p)}catch(i){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${N(i)}`)}m=ce(w);return}z=(await import("./transformers-GRNPPUHM.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();m=await z("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(t){throw k=!0,O=N(t),new Error(`Failed to initialize transformer model: ${O}`)}})(),A}function ce(n){return async e=>{let t=Array.isArray(e)?e:[e],r=await n.embed(t),s=r[0]?.length??q(),o=new Float32Array(t.length*s);for(let i=0;i<r.length;i++)o.set(r[i],i*s);return{data:o,dims:[t.length,s]}}}async function Ae(n,e={}){let t={...F,...e};if(pe(n))return new Array(q()).fill(0);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");let r=_(n);if(t.enableCache){let c=d.get(r);if(c&&Date.now()-c.timestamp<V)return c.embedding}let s=performance.now(),o=await m(n,{pooling:"mean",normalize:!0}),i=Array.from(o.data),l=performance.now()-s;if(l>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${l.toFixed(1)}ms for "${n.slice(0,50)}..."`),t.enableCache){if(d.size>=t.maxCacheSize){let c=d.keys().next().value;c&&d.delete(c)}d.set(r,{embedding:i,timestamp:Date.now()})}return i}async function Ie(n,e={}){let t={...F,...e},r=[],s=[],o=new Array(n.length).fill(null);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let i=0;i<n.length;i++){let l=d.get(_(n[i]));l&&Date.now()-l.timestamp<V?o[i]=l.embedding:(r.push(n[i]),s.push(i))}else{r.push(...n);for(let i=0;i<n.length;i++)s.push(i)}if(r.length>0){let i=performance.now(),l=32;for(let h=0;h<r.length;h+=l){let S=Math.min(h+l,r.length),I=r.slice(h,S),E=await m(I,{pooling:"mean",normalize:!0}),C=E.dims||[I.length,384],y=C[0],f=C[1];for(let a=0;a<y;a++){let g=a*f,u=Array.from(E.data.slice(g,g+f)),b=h+a,M=s[b];if(o[M]=u,t.enableCache){if(d.size>=t.maxCacheSize){let U=d.keys().next().value;U&&d.delete(U)}d.set(_(r[b]),{embedding:u,timestamp:Date.now()})}}}let c=performance.now()-i;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${c.toFixed(0)}ms`)}return o.filter(i=>i!==null)}function Ce(){d.clear(),console.log("[RealEmbeddings] Cache cleared")}function Me(){return{size:d.size,hitRate:0}}function Pe(){return!k&&m!==null}function q(){return 384}function Re(){z=null,m=null,A=null,k=!1,O="",d.clear(),w&&w.close(),w=null,p=null,Y()}function Oe(){return w!==null}function ke(){return p}export{F as a,Ae as b,Ie as c,Ce as d,Me as e,Pe as f,q as g,Re as h,Oe as i,ke as j};
12
+ `),v=r,r}catch{return $=!0,null}}function J(n){let e=G();if(!e)return null;try{let t=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(j,K+n);if(!t)return null;let r=JSON.parse(t.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function Q(n){let e=G();if(!e)return;let t={fingerprint:n.fingerprint,dim:n.dim,endpoint:n.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(K+n.endpoint,j,JSON.stringify(t))}function Y(){if(v)try{v.close()}catch{}v=null,$=!1}var z=null,m=null,A=null,k=!1,O="",w=null,p=null,F={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},d=new Map,V=36e5;function _(n){return p?`endpoint:${p.fingerprint}:${n}`:`inproc:${n}`}function pe(n){let e=n.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 Z(n={}){if(k)throw new Error(`Transformer initialization previously failed: ${O}`);if(A)return A;let e={...F,...n};return A=(async()=>{try{if(e.endpoint){let o=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${o}`),w=new P({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:q()}),p=await w.probe(),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let i=J(p.endpoint);i&&i.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${i.fingerprint} dim=${i.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),Q(p)}catch(i){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${N(i)}`)}m=ce(w);return}z=(await import("./transformers-DVFGDNZC.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();m=await z("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(t){throw k=!0,O=N(t),new Error(`Failed to initialize transformer model: ${O}`)}})(),A}function ce(n){return async e=>{let t=Array.isArray(e)?e:[e],r=await n.embed(t),s=r[0]?.length??q(),o=new Float32Array(t.length*s);for(let i=0;i<r.length;i++)o.set(r[i],i*s);return{data:o,dims:[t.length,s]}}}async function Ae(n,e={}){let t={...F,...e};if(pe(n))return new Array(q()).fill(0);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");let r=_(n);if(t.enableCache){let c=d.get(r);if(c&&Date.now()-c.timestamp<V)return c.embedding}let s=performance.now(),o=await m(n,{pooling:"mean",normalize:!0}),i=Array.from(o.data),l=performance.now()-s;if(l>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${l.toFixed(1)}ms for "${n.slice(0,50)}..."`),t.enableCache){if(d.size>=t.maxCacheSize){let c=d.keys().next().value;c&&d.delete(c)}d.set(r,{embedding:i,timestamp:Date.now()})}return i}async function Ie(n,e={}){let t={...F,...e},r=[],s=[],o=new Array(n.length).fill(null);if(m||await Z(e),!m)throw new Error("Embedding model failed to initialize");if(t.enableCache)for(let i=0;i<n.length;i++){let l=d.get(_(n[i]));l&&Date.now()-l.timestamp<V?o[i]=l.embedding:(r.push(n[i]),s.push(i))}else{r.push(...n);for(let i=0;i<n.length;i++)s.push(i)}if(r.length>0){let i=performance.now(),l=32;for(let h=0;h<r.length;h+=l){let S=Math.min(h+l,r.length),I=r.slice(h,S),E=await m(I,{pooling:"mean",normalize:!0}),C=E.dims||[I.length,384],y=C[0],f=C[1];for(let a=0;a<y;a++){let g=a*f,u=Array.from(E.data.slice(g,g+f)),b=h+a,M=s[b];if(o[M]=u,t.enableCache){if(d.size>=t.maxCacheSize){let U=d.keys().next().value;U&&d.delete(U)}d.set(_(r[b]),{embedding:u,timestamp:Date.now()})}}}let c=performance.now()-i;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${c.toFixed(0)}ms`)}return o.filter(i=>i!==null)}function Ce(){d.clear(),console.log("[RealEmbeddings] Cache cleared")}function Me(){return{size:d.size,hitRate:0}}function Pe(){return!k&&m!==null}function q(){return 384}function Re(){z=null,m=null,A=null,k=!1,O="",d.clear(),w&&w.close(),w=null,p=null,Y()}function Oe(){return w!==null}function ke(){return p}export{F as a,Ae as b,Ie as c,Ce as d,Me as e,Pe as f,q as g,Re as h,Oe as i,ke as j};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  import{existsSync as _,readdirSync as d,statSync as w}from"fs";import{join as i,extname as E}from"path";var T=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,p={}){let{maxDepth:f=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:S=[]}=p;if(!_(s))return[];let o=w(s);if(o.isFile())return[s];if(!o.isDirectory())return[];let y=new Set(S.map(t=>t.startsWith(".")?t:`.${t}`)),n=[];function r(t,c){if(c>f)return;let a;try{a=d(t,{withFileTypes:!0})}catch{return}for(let e of a)if(e.isDirectory()){if(b.has(e.name))continue;r(i(t,e.name),c+1)}else if(e.isFile()){let u=E(e.name).toLowerCase();if(!(T.has(u)||y.has(u))||e.name.endsWith(".d.ts"))continue;let l=v.some(h=>e.name.includes(h))||e.name.startsWith("test_");x?l&&n.push(i(t,e.name)):(m||!l)&&n.push(i(t,e.name))}}return r(s,0),n}export{T as a,O as b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
- import{b as f,d as v}from"./chunk-QBVFONWU.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{b as f,d as v}from"./chunk-246Z3PH6.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
3
3
  ${this.options.title}
4
4
  `)),this.fleetBar=this.multiBar.create(100,0,{name:o.white("Fleet Progress".padEnd(30)),status:"",eta:""})}addAgent(e){if(!this.isActive)return;this.agentStates.set(e.id,e);let t=this.multiBar.create(100,e.progress,{name:o.gray(this.truncateName(e.name,30).padEnd(30)),status:this.getStatusIcon(e.status),eta:e.eta?this.formatEta(e.eta):""});this.agentBars.set(e.id,t),this.updateFleetProgress()}updateAgent(e,t,r){if(!this.isActive)return;let n=this.agentStates.get(e),i=this.agentBars.get(e);!n||!i||(n.progress=Math.min(100,Math.max(0,t)),r?.status&&(n.status=r.status),r?.message&&(n.message=r.message),r?.eta!==void 0&&(n.eta=r.eta),i.update(n.progress,{name:this.getAgentNameDisplay(n),status:this.getStatusIcon(n.status),eta:n.eta?this.formatEta(n.eta):""}),this.updateFleetProgress())}completeAgent(e,t=!0){if(!this.isActive)return;let r=this.agentStates.get(e),n=this.agentBars.get(e);!r||!n||(r.status=t?"completed":"failed",r.progress=t?100:r.progress,n.update(r.progress,{name:this.getAgentNameDisplay(r),status:this.getStatusIcon(r.status),eta:""}),this.updateFleetProgress())}stop(){if(!this.isActive)return;this.isActive=!1,this.multiBar.stop();let e=Array.from(this.agentStates.values()).filter(i=>i.status==="completed").length,t=Array.from(this.agentStates.values()).filter(i=>i.status==="failed").length,r=this.agentStates.size,n=Date.now()-this.startTime;console.log(""),console.log(t===0?o.green(`All ${e}/${r} agents completed successfully (${this.formatDuration(n)})`):o.yellow(`${e}/${r} agents completed, ${t} failed (${this.formatDuration(n)})`)),console.log("")}updateFleetProgress(){if(!this.fleetBar)return;let e=Array.from(this.agentStates.values()),t=e.reduce((a,l)=>a+l.progress,0),r=e.length>0?Math.round(t/e.length):0,n=e.filter(a=>a.status==="completed").length,i=e.filter(a=>a.status==="running").length;this.fleetBar.update(r,{status:o.gray(`${n}/${e.length} complete, ${i} running`),eta:this.options.showEta?this.estimateFleetEta(e):""})}getAgentNameDisplay(e){let t=this.truncateName(e.name,26);switch(e.status){case"completed":return o.green(t.padEnd(30));case"failed":return o.red(t.padEnd(30));case"running":return o.yellow(t.padEnd(30));default:return o.gray(t.padEnd(30))}}getStatusIcon(e){switch(e){case"completed":return o.green("\u2713");case"failed":return o.red("\u2717");case"running":return o.yellow("\u25B6");default:return o.gray("\u25CB")}}truncateName(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatEta(e){return e<=0?"":e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}estimateFleetEta(e){let t=e.filter(a=>a.status==="running"||a.status==="pending");if(t.length===0)return"";let r=t.map(a=>a.eta||0).filter(a=>a>0);if(r.length>0){let a=Math.max(...r);return o.gray(`ETA: ${this.formatEta(a)}`)}let n=Date.now()-this.startTime,i=t.reduce((a,l)=>a+l.progress,0)/t.length;if(i>0){let a=n/(i/100),l=Math.max(0,a-n);return o.gray(`ETA: ${this.formatEta(l)}`)}return""}};function X(s){let e=Date.now(),t=O({text:s,color:"cyan"}).start(),r=setInterval(()=>{let i=((Date.now()-e)/1e3).toFixed(1);t.text=`${s} (${i}s)`},100);r.unref?.();let n=()=>{clearInterval(r)};return{spinner:t,stop:()=>{n(),t.stop()},succeed:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.succeed(i||`${s} (${a}s)`)},fail:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.fail(i||`${s} failed (${a}s)`)}}}export{b as a,X as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");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.10.9");process.exit(0)}
2
2
  import{isIP as o}from"net";import{lookup as n}from"dns/promises";var f=[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^0\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/,/^fd[0-9a-f]{2}:/i];function t(r){return f.some(s=>s.test(r))}async function u(r){if(process.env.AQE_HOOKS_SSRF_DISABLED==="true")return{safe:!0};let s;try{s=new URL(r)}catch{return{safe:!1,reason:`Invalid URL: ${r}`}}let e=s.hostname.replace(/^\[|\]$/g,"");if(o(e))return t(e)?{safe:!1,reason:`Private IP blocked: ${e}`}:{safe:!0};try{let a=await n(e);if(t(a.address))return{safe:!1,reason:`DNS resolves to private IP: ${a.address}`}}catch(a){return{safe:!1,reason:`DNS lookup failed for ${e}: ${a.message}`}}return{safe:!0}}export{t as a,u as b};
@@ -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.10.7");process.exit(0)}
2
- import{a,b as u}from"./chunk-X3HRJV65.js";import{m as P}from"./chunk-HBWAMCVB.js";import{b as p}from"./chunk-U7EGKKN3.js";P();import*as i from"fs";import*as d from"path";var v="llm-config.json",f={claude:["ANTHROPIC_API_KEY","CLAUDE_API_KEY"],openai:["OPENAI_API_KEY"],ollama:[],openrouter:["OPENROUTER_API_KEY"],gemini:["GOOGLE_AI_API_KEY","GEMINI_API_KEY","GOOGLE_API_KEY"],"azure-openai":["AZURE_OPENAI_API_KEY"],bedrock:["AWS_ACCESS_KEY_ID"],onnx:[]},R=new Set(["claude","openai","ollama","openrouter","gemini","azure-openai","bedrock"]);function E(e){let r=e??p();return d.join(r,".agentic-qe",v)}function _(e=process.env){let r=new Set;for(let n of a){if(!R.has(n))continue;let o=f[n];if(o.length===0){r.add(n);continue}o.some(t=>(e[t]??"").trim().length>0)&&r.add(n)}return r}function g(e){let r=E(e);if(!i.existsSync(r))return{};let n=i.readFileSync(r,"utf8");if(!n.trim())return{};let o=JSON.parse(n);if(typeof o!="object"||o===null)throw new Error(`Invalid ${v}: expected object, got ${typeof o}`);return o}function C(e,r){let n=E(r),o=d.dirname(n);i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let t=y(e),s=JSON.stringify(t,null,2)+`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.9");process.exit(0)}
2
+ import{a,b as u}from"./chunk-DNE6MVNA.js";import{m as P}from"./chunk-L5NEEGKO.js";import{b as p}from"./chunk-ZT2DGSIO.js";P();import*as i from"fs";import*as d from"path";var v="llm-config.json",f={claude:["ANTHROPIC_API_KEY","CLAUDE_API_KEY"],openai:["OPENAI_API_KEY"],ollama:[],openrouter:["OPENROUTER_API_KEY"],gemini:["GOOGLE_AI_API_KEY","GEMINI_API_KEY","GOOGLE_API_KEY"],"azure-openai":["AZURE_OPENAI_API_KEY"],bedrock:["AWS_ACCESS_KEY_ID"],onnx:[]},R=new Set(["claude","openai","ollama","openrouter","gemini","azure-openai","bedrock"]);function E(e){let r=e??p();return d.join(r,".agentic-qe",v)}function _(e=process.env){let r=new Set;for(let n of a){if(!R.has(n))continue;let o=f[n];if(o.length===0){r.add(n);continue}o.some(t=>(e[t]??"").trim().length>0)&&r.add(n)}return r}function g(e){let r=E(e);if(!i.existsSync(r))return{};let n=i.readFileSync(r,"utf8");if(!n.trim())return{};let o=JSON.parse(n);if(typeof o!="object"||o===null)throw new Error(`Invalid ${v}: expected object, got ${typeof o}`);return o}function C(e,r){let n=E(r),o=d.dirname(n);i.existsSync(o)||i.mkdirSync(o,{recursive:!0});let t=y(e),s=JSON.stringify(t,null,2)+`
3
3
  `,c=n+".tmp-"+process.pid;i.writeFileSync(c,s,{encoding:"utf8",mode:384}),i.renameSync(c,n)}function y(e){if(!e.providers)return JSON.parse(JSON.stringify(e));let r=JSON.parse(JSON.stringify(e)),n=[];if(r.providers)for(let o of Object.keys(r.providers)){let t=r.providers[o];t&&"apiKey"in t&&t.apiKey&&(delete t.apiKey,n.push(o))}return n.length>0&&console.warn(`[router-config] Refused to persist apiKey for: ${n.join(", ")}. API keys belong in environment variables (e.g. ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY), NOT in .agentic-qe/llm-config.json which may be checked into source control.`),r}function l(e,r){let n={...e,...r,providers:{...e.providers??{}}};if(r.providers)for(let[o,t]of Object.entries(r.providers)){if(!t)continue;let s=o;n.providers[s]={...e.providers?.[s]??{},...t}}return n}function m(e,r=process.env){let n=_(r),o={...e,providers:{...e.providers??{}}};for(let t of n){if(f[t].length===0)continue;let c=o.providers[t]??{enabled:!1};c.enabled||(o.providers[t]={...c,enabled:!0})}return o}function A(e={}){let r=g(e.projectRoot),n=l(u,r),o=m(n,e.env);return e.override?l(o,e.override):o}function S(e={}){let r=e.env??process.env;for(let o of a){let t=f[o];if(t.length!==0&&t.some(s=>(r[s]??"").trim().length>0))return!0}let n=g(e.projectRoot);if(n.providers){for(let o of Object.values(n.providers))if(o?.enabled)return!0}return!1}export{_ as a,C as b,A as c,S 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.10.7");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.10.9");process.exit(0)}
2
2
  var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}timeoutMs};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};