agentic-qe 3.13.10 → 3.13.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (746) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/auto-memory-hook.mjs +1 -1
  3. package/.claude/helpers/helpers.manifest.json +6 -6
  4. package/.claude/helpers/hook-handler.cjs +30 -0
  5. package/.claude/helpers/intelligence.cjs +121 -10
  6. package/.claude/helpers/statusline.cjs +786 -8
  7. package/.claude/skills/skills-manifest.json +1 -1
  8. package/CHANGELOG.md +78 -0
  9. package/README.md +1 -0
  10. package/assets/skills/skills-manifest.json +1 -1
  11. package/dist/agents/claim-verifier/claim-verifier-service.js +4 -4
  12. package/dist/agents/claim-verifier/index.js +6 -6
  13. package/dist/agents/claim-verifier/verifiers/file-verifier.js +1 -1
  14. package/dist/agents/claim-verifier/verifiers/index.js +3 -3
  15. package/dist/agents/claim-verifier/verifiers/output-verifier.js +1 -1
  16. package/dist/causal-discovery/causal-graph.js +2 -2
  17. package/dist/causal-discovery/discovery-engine.js +2 -2
  18. package/dist/causal-discovery/weight-matrix.js +2 -2
  19. package/dist/cli/bundle.js +5 -5
  20. package/dist/cli/chunks/adapter-FUV6LBJT.js +2 -0
  21. package/dist/cli/chunks/{agent-booster-wasm-AWNQ6KB3.js → agent-booster-wasm-7I7LZFNC.js} +2 -2
  22. package/dist/cli/chunks/{agent-handler-RSHQZHPS.js → agent-handler-QZZT52BH.js} +2 -2
  23. package/dist/cli/chunks/{agent-memory-branch-FU7Y3TQ3.js → agent-memory-branch-MLQS5Y26.js} +2 -2
  24. package/dist/cli/chunks/aqe-learning-engine-QNFNA3J4.js +2 -0
  25. package/dist/cli/chunks/{arena-LOK2WYHC.js → arena-IM4CP6LP.js} +2 -2
  26. package/dist/cli/chunks/{arena-XQOCNKB6.js → arena-WRIY37EJ.js} +4 -4
  27. package/dist/cli/chunks/{audit-6ZS4EAD2.js → audit-BSAQ4EFN.js} +3 -3
  28. package/dist/cli/chunks/base-37W2XIXC.js +2 -0
  29. package/dist/cli/chunks/{better-sqlite3-IMBCIZK3.js → better-sqlite3-X2XZUXWZ.js} +2 -2
  30. package/dist/cli/chunks/{brain-handler-3U6BH4EO.js → brain-handler-TVTTWZGP.js} +3 -3
  31. package/dist/cli/chunks/{branch-enumerator-CJBPVBXM.js → branch-enumerator-NI4Q7DSJ.js} +2 -2
  32. package/dist/cli/chunks/{browser-M4VW3KJY.js → browser-PXBLORUZ.js} +2 -2
  33. package/dist/cli/chunks/browser-workflow-PDIUEK7B.js +2 -0
  34. package/dist/cli/chunks/{chunk-PVGOOKBF.js → chunk-2JAC57JE.js} +1 -1
  35. package/dist/cli/chunks/{chunk-JWV5ZM2S.js → chunk-2VTX4SYW.js} +2 -2
  36. package/dist/cli/chunks/{chunk-IYLSML27.js → chunk-2VY7FL6A.js} +2 -2
  37. package/dist/cli/chunks/{chunk-7QNN4GQU.js → chunk-2W3D5A4R.js} +2 -2
  38. package/dist/cli/chunks/{chunk-OZLMIEJC.js → chunk-33YZGOT6.js} +2 -2
  39. package/dist/cli/chunks/{chunk-WSPEAYPG.js → chunk-3ASVQILY.js} +2 -2
  40. package/dist/cli/chunks/{chunk-YO63NTJV.js → chunk-3XVZHJQT.js} +1 -1
  41. package/dist/cli/chunks/{chunk-H7AACUYS.js → chunk-42AS3HPO.js} +2 -2
  42. package/dist/cli/chunks/{chunk-HEY2ZRL7.js → chunk-44NPKZGI.js} +2 -2
  43. package/dist/cli/chunks/{chunk-PIV3QHGJ.js → chunk-4AITMWFZ.js} +2 -2
  44. package/dist/cli/chunks/{chunk-2SS2SSNZ.js → chunk-4ANJV6I4.js} +3 -3
  45. package/dist/cli/chunks/{chunk-CCAY7Q56.js → chunk-4FVOJBEU.js} +1 -1
  46. package/dist/cli/chunks/{chunk-EZY3DAIX.js → chunk-4M7YZ2X7.js} +4 -4
  47. package/dist/cli/chunks/{chunk-HZIT42TM.js → chunk-4THFPRFM.js} +2 -2
  48. package/dist/cli/chunks/chunk-4YFXF5AQ.js +21 -0
  49. package/dist/cli/chunks/{chunk-PUN3KZ6N.js → chunk-4Z4X2ND4.js} +2 -2
  50. package/dist/cli/chunks/{chunk-4TSLLWE7.js → chunk-52VGZJSD.js} +1 -1
  51. package/dist/cli/chunks/{chunk-NRD76M7A.js → chunk-5E76HULA.js} +2 -2
  52. package/dist/cli/chunks/{chunk-RQTXQ6C7.js → chunk-5PI75QYP.js} +2 -2
  53. package/dist/cli/chunks/{chunk-7BZUNNWC.js → chunk-5PNQNBDZ.js} +1 -1
  54. package/dist/cli/chunks/{chunk-KBJYXZI7.js → chunk-5VSS2RBD.js} +2 -2
  55. package/dist/cli/chunks/{chunk-7QSGUJE2.js → chunk-66OQ7AB3.js} +1 -1
  56. package/dist/cli/chunks/{chunk-WFEHOEYP.js → chunk-6BSZHNOC.js} +1 -1
  57. package/dist/cli/chunks/{chunk-KQVTTP2S.js → chunk-6KI6LAAZ.js} +2 -2
  58. package/dist/cli/chunks/{chunk-NZRKWUBM.js → chunk-6KKVMPPR.js} +2 -2
  59. package/dist/cli/chunks/{chunk-KITVDY4T.js → chunk-7A4WTRWI.js} +1 -1
  60. package/dist/cli/chunks/{chunk-GRTU5QOT.js → chunk-7LATB5IR.js} +2 -2
  61. package/dist/cli/chunks/{chunk-J6H2LUBM.js → chunk-7PCIN7UN.js} +2 -2
  62. package/dist/cli/chunks/{chunk-FBJUNJ2A.js → chunk-7RVLVIAI.js} +1 -1
  63. package/dist/cli/chunks/{chunk-7NDJW2DU.js → chunk-7ZVO7I4Q.js} +1 -1
  64. package/dist/cli/chunks/{chunk-EE55ALFK.js → chunk-A5RWLPVT.js} +2 -2
  65. package/dist/cli/chunks/{chunk-U6YDS37V.js → chunk-AKUDUB3O.js} +2 -2
  66. package/dist/cli/chunks/{chunk-6SM74KJI.js → chunk-AM42ROKZ.js} +1 -1
  67. package/dist/cli/chunks/{chunk-VUCCPPQ6.js → chunk-AN5CGTTJ.js} +2 -2
  68. package/dist/cli/chunks/{chunk-QZOAU2N5.js → chunk-AOOCV56W.js} +1 -1
  69. package/dist/cli/chunks/{chunk-U562TIMO.js → chunk-ASWWBNX2.js} +2 -2
  70. package/dist/cli/chunks/{chunk-C5CP66K5.js → chunk-AYH3DMW2.js} +1 -1
  71. package/dist/cli/chunks/{chunk-U5NKLMF4.js → chunk-BODFJ3DC.js} +2 -2
  72. package/dist/cli/chunks/{chunk-YHAUBZ4H.js → chunk-BZIPYXSW.js} +3 -3
  73. package/dist/cli/chunks/{chunk-JMF3FMAO.js → chunk-DCVFHVPR.js} +2 -2
  74. package/dist/cli/chunks/{chunk-H633BGA7.js → chunk-DFLASG3B.js} +1 -1
  75. package/dist/cli/chunks/{chunk-CPXZC7LF.js → chunk-DGFINXUE.js} +1 -1
  76. package/dist/cli/chunks/{chunk-54RIPGMC.js → chunk-E67ZXRG6.js} +1 -1
  77. package/dist/cli/chunks/{chunk-A233TTUX.js → chunk-EDRPTLAX.js} +1 -1
  78. package/dist/cli/chunks/{chunk-UHSIP4DJ.js → chunk-EG73WYAW.js} +2 -2
  79. package/dist/cli/chunks/{chunk-EKZNA6HW.js → chunk-FI6J3UHJ.js} +1 -1
  80. package/dist/cli/chunks/{chunk-6FIWTBR5.js → chunk-G45AOQDZ.js} +1 -1
  81. package/dist/cli/chunks/{chunk-IR7FZYPO.js → chunk-G6FJHDUG.js} +1 -1
  82. package/dist/cli/chunks/chunk-GEQWCK4F.js +2 -0
  83. package/dist/cli/chunks/{chunk-6L36EHM2.js → chunk-GJJWXRAD.js} +2 -2
  84. package/dist/cli/chunks/{chunk-MMRORLMM.js → chunk-GJUGG6UR.js} +2 -2
  85. package/dist/cli/chunks/{chunk-YC5UJVV3.js → chunk-GMLRIZ4E.js} +1 -1
  86. package/dist/cli/chunks/{chunk-UNXPBIX5.js → chunk-GQLJYTXN.js} +2 -2
  87. package/dist/cli/chunks/{chunk-IJ3HHUSD.js → chunk-H3GAR4SV.js} +2 -2
  88. package/dist/cli/chunks/{chunk-OSWAQX4G.js → chunk-HAJG44BD.js} +2 -2
  89. package/dist/cli/chunks/{chunk-GSN4QIDI.js → chunk-HQWFZQMJ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-JUVW4DOU.js → chunk-HRTSYT4N.js} +2 -2
  91. package/dist/cli/chunks/{chunk-2HMBDTSI.js → chunk-I5SXLV7D.js} +2 -2
  92. package/dist/cli/chunks/{chunk-DR4V75BF.js → chunk-IOJ34SXJ.js} +2 -2
  93. package/dist/cli/chunks/{chunk-JALFKAAD.js → chunk-IPDM3CAK.js} +1 -1
  94. package/dist/cli/chunks/{chunk-NL3KX4NE.js → chunk-IPZEBALY.js} +34 -29
  95. package/dist/cli/chunks/{chunk-PSBQRTNF.js → chunk-IQH2RDN3.js} +5 -5
  96. package/dist/cli/chunks/{chunk-SWZUMHIQ.js → chunk-IT5QIUUA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-2LGQNT6Q.js → chunk-JTYCOFTD.js} +1 -1
  98. package/dist/cli/chunks/{chunk-Q7QKJY6Y.js → chunk-JVFZAJ5N.js} +2 -2
  99. package/dist/cli/chunks/{chunk-F3AHUNWH.js → chunk-KRZYWVS3.js} +2 -2
  100. package/dist/cli/chunks/{chunk-7JK57AI2.js → chunk-KXSUDN46.js} +1 -1
  101. package/dist/cli/chunks/{chunk-EP2HOAEB.js → chunk-KYJBJ56M.js} +2 -2
  102. package/dist/cli/chunks/{chunk-OLETDPH2.js → chunk-L3GBNX7B.js} +2 -2
  103. package/dist/cli/chunks/{chunk-VWZ743HH.js → chunk-LRO74LPA.js} +4 -4
  104. package/dist/cli/chunks/{chunk-FC47FRFI.js → chunk-LXVT6JXO.js} +4 -4
  105. package/dist/cli/chunks/{chunk-7XWFAPPI.js → chunk-M3354CE4.js} +2 -2
  106. package/dist/cli/chunks/{chunk-37GWETSW.js → chunk-M73KM3AZ.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BM5BSYPW.js → chunk-M7CPJW53.js} +2 -2
  108. package/dist/cli/chunks/{chunk-ZAEUW3Q4.js → chunk-MB2KLJ6Q.js} +1 -1
  109. package/dist/cli/chunks/{chunk-QHRMZP6J.js → chunk-MGKH4LCM.js} +1 -1
  110. package/dist/cli/chunks/{chunk-AJQGNQ3W.js → chunk-MLFELTJX.js} +2 -2
  111. package/dist/cli/chunks/{chunk-I3SBXWF2.js → chunk-MLXLGBQZ.js} +1 -1
  112. package/dist/cli/chunks/{chunk-6C5WRBGZ.js → chunk-MYVKTG55.js} +3 -3
  113. package/dist/cli/chunks/{chunk-EJRDL5W5.js → chunk-N4OQ4D4V.js} +2 -2
  114. package/dist/cli/chunks/{chunk-MMA6Q6NF.js → chunk-NDRZZSD5.js} +2 -2
  115. package/dist/cli/chunks/{chunk-HL5RC5YB.js → chunk-NG6A7LCG.js} +1 -1
  116. package/dist/cli/chunks/{chunk-JPDJARGR.js → chunk-NJ3QXJ54.js} +2 -2
  117. package/dist/cli/chunks/{chunk-DZNK4EM7.js → chunk-NJ4YVAG7.js} +3 -3
  118. package/dist/cli/chunks/chunk-NL2SCAGJ.js +12 -0
  119. package/dist/cli/chunks/chunk-NLZUGANH.js +11 -0
  120. package/dist/cli/chunks/{chunk-TIGBPVPZ.js → chunk-NNLZAVFH.js} +1 -1
  121. package/dist/cli/chunks/{chunk-7XCRPSSU.js → chunk-NTALX2YC.js} +2 -2
  122. package/dist/cli/chunks/{chunk-YALYPHSG.js → chunk-O4BWESH5.js} +2 -2
  123. package/dist/cli/chunks/{chunk-C656WHED.js → chunk-OG3DBHIV.js} +2 -2
  124. package/dist/cli/chunks/{chunk-BFX3N7KU.js → chunk-OZ53BIY5.js} +1 -1
  125. package/dist/cli/chunks/{chunk-BB4LWAAH.js → chunk-P6EFKHNI.js} +2 -2
  126. package/dist/cli/chunks/{chunk-2FFCL4BK.js → chunk-PGFCKE4G.js} +3 -3
  127. package/dist/cli/chunks/{chunk-66BUC3JG.js → chunk-PVINNJ4P.js} +2 -2
  128. package/dist/cli/chunks/{chunk-FOWBKCRK.js → chunk-QG5L2JM5.js} +10 -10
  129. package/dist/cli/chunks/{chunk-ATSVI6T4.js → chunk-QM4Z7TQH.js} +1 -1
  130. package/dist/cli/chunks/{chunk-Q26QKZYI.js → chunk-QXO35J6F.js} +2 -2
  131. package/dist/cli/chunks/{chunk-FOPLJRWL.js → chunk-R7LGVJMZ.js} +2 -2
  132. package/dist/cli/chunks/{chunk-PLJ72A3I.js → chunk-RACWX2ZX.js} +2 -2
  133. package/dist/cli/chunks/{chunk-ZH3MVVXO.js → chunk-RP2BRRLX.js} +2 -2
  134. package/dist/cli/chunks/{chunk-T7OS4CB4.js → chunk-RP5VFZJO.js} +2 -2
  135. package/dist/cli/chunks/{chunk-7GZJMPTD.js → chunk-S6WHYOWV.js} +2 -2
  136. package/dist/cli/chunks/{chunk-C5HYQTD7.js → chunk-SCQNISGS.js} +1 -1
  137. package/dist/cli/chunks/chunk-SNC73DWF.js +2 -0
  138. package/dist/cli/chunks/{chunk-WKE2FUCP.js → chunk-SOS37ECY.js} +1 -1
  139. package/dist/cli/chunks/{chunk-BTG5UFMA.js → chunk-SXFSJJZF.js} +2 -2
  140. package/dist/cli/chunks/{chunk-IHNPXNFG.js → chunk-TB2N3CAK.js} +2 -2
  141. package/dist/cli/chunks/chunk-TDVMILKO.js +2 -0
  142. package/dist/cli/chunks/{chunk-RYHOV4E3.js → chunk-TJVTV3HP.js} +2 -2
  143. package/dist/cli/chunks/{chunk-2E35LWYJ.js → chunk-TK5XLF3Z.js} +4 -4
  144. package/dist/cli/chunks/{chunk-NCX4W65B.js → chunk-TWUWLSGQ.js} +6 -6
  145. package/dist/cli/chunks/{chunk-WIB6KRFJ.js → chunk-U5G6OC2C.js} +2 -2
  146. package/dist/cli/chunks/{chunk-OZO2JUEK.js → chunk-UBOGJHWC.js} +1 -1
  147. package/dist/cli/chunks/{chunk-WK5MKY45.js → chunk-UC4EIULB.js} +13 -13
  148. package/dist/cli/chunks/{chunk-KBOGA4GA.js → chunk-UJUK6T4V.js} +2 -2
  149. package/dist/cli/chunks/chunk-UQ4UCHO7.js +2 -0
  150. package/dist/cli/chunks/{chunk-4PRQMFVO.js → chunk-UWZYXI3R.js} +2 -2
  151. package/dist/cli/chunks/{chunk-GQ6H37RN.js → chunk-VA2ORJB5.js} +2 -2
  152. package/dist/cli/chunks/{chunk-U5WFVIKL.js → chunk-VBHA4SDU.js} +2 -2
  153. package/dist/cli/chunks/{chunk-PGJHCCR6.js → chunk-VD53LBF7.js} +3 -3
  154. package/dist/cli/chunks/{chunk-UHHWEWDA.js → chunk-VNODKACB.js} +2 -2
  155. package/dist/cli/chunks/{chunk-3E3YLEHB.js → chunk-VQCLSX7T.js} +1 -1
  156. package/dist/cli/chunks/{chunk-G7YD3BR3.js → chunk-VQD2ELNL.js} +2 -2
  157. package/dist/cli/chunks/{chunk-RCXC4YGL.js → chunk-VZGP77YU.js} +1 -1
  158. package/dist/cli/chunks/chunk-WA6CSEOX.js +2 -0
  159. package/dist/cli/chunks/{chunk-JGXU5FUZ.js → chunk-WE3VKDMK.js} +3 -3
  160. package/dist/cli/chunks/{chunk-MGJPS2YV.js → chunk-WXU7FAEB.js} +2 -2
  161. package/dist/cli/chunks/{chunk-O5QZB2AP.js → chunk-WYFAPA2G.js} +2 -2
  162. package/dist/cli/chunks/{chunk-MFGKSD44.js → chunk-WYIXNHPF.js} +2 -2
  163. package/dist/cli/chunks/{chunk-2HEHM2KV.js → chunk-X2SZCVDA.js} +2 -2
  164. package/dist/cli/chunks/{chunk-2CLM53W2.js → chunk-X3JNFQW2.js} +2 -2
  165. package/dist/cli/chunks/{chunk-NBUBGYLE.js → chunk-XIKYUBIV.js} +2 -2
  166. package/dist/cli/chunks/{chunk-2FPHM356.js → chunk-XM5I7J5S.js} +2 -2
  167. package/dist/cli/chunks/{chunk-35CHBX6K.js → chunk-XT473WPO.js} +2 -2
  168. package/dist/cli/chunks/{chunk-74QKFILD.js → chunk-YL2GOJF6.js} +2 -2
  169. package/dist/cli/chunks/{chunk-K6SXDKWV.js → chunk-YQOQVSYU.js} +1 -1
  170. package/dist/cli/chunks/{chunk-G427QR5W.js → chunk-Z56BBX77.js} +2 -2
  171. package/dist/cli/chunks/{chunk-LPVHYZAE.js → chunk-Z6DSYLAG.js} +1 -1
  172. package/dist/cli/chunks/{chunk-W3DCBOLL.js → chunk-ZMYV4R32.js} +1 -1
  173. package/dist/cli/chunks/{chunk-UL6PT654.js → chunk-ZSAGRDXA.js} +2 -2
  174. package/dist/cli/chunks/{ci-7QW7234M.js → ci-QAUD62WH.js} +2 -2
  175. package/dist/cli/chunks/{ci-output-WGP4YKPQ.js → ci-output-TZDVTNE7.js} +2 -2
  176. package/dist/cli/chunks/{circuit-breaker-AOHSCJYO.js → circuit-breaker-ZWPHJ7YJ.js} +2 -2
  177. package/dist/cli/chunks/{claude-flow-setup-CIZ3TWR7.js → claude-flow-setup-SCB4EURN.js} +2 -2
  178. package/dist/cli/chunks/client-4W3KWTAU.js +2 -0
  179. package/dist/cli/chunks/{cline-installer-J2QVGPJY.js → cline-installer-EHZLMLXF.js} +2 -2
  180. package/dist/cli/chunks/{code-WH26MFMB.js → code-3N6PBJMK.js} +2 -2
  181. package/dist/cli/chunks/{code-index-extractor-DBOYEFZ4.js → code-index-extractor-6DIKHNRI.js} +2 -2
  182. package/dist/cli/chunks/{codex-installer-MWYVGZC4.js → codex-installer-P7DPQMYL.js} +2 -2
  183. package/dist/cli/chunks/{completions-LNBHGWUS.js → completions-5MKWWCCE.js} +2 -2
  184. package/dist/cli/chunks/{complexity-analyzer-AMYCTQG2.js → complexity-analyzer-TPM4IPEK.js} +2 -2
  185. package/dist/cli/chunks/{continuedev-installer-73EQPP37.js → continuedev-installer-VXODKGVX.js} +2 -2
  186. package/dist/cli/chunks/{copilot-installer-JWSY2272.js → copilot-installer-PVD5O56P.js} +2 -2
  187. package/dist/cli/chunks/core-handlers-BDU2XBLO.js +2 -0
  188. package/dist/cli/chunks/{cost-tracker-XQVIORRZ.js → cost-tracker-JOMZEQF3.js} +2 -2
  189. package/dist/cli/chunks/{coverage-HYGJIQ25.js → coverage-HTXLEV3B.js} +3 -3
  190. package/dist/cli/chunks/cross-domain-router-BPB6IHN4.js +2 -0
  191. package/dist/cli/chunks/{cursor-installer-DNPNJGZM.js → cursor-installer-SHKDTDDZ.js} +2 -2
  192. package/dist/cli/chunks/{daemon-GSOGO6L3.js → daemon-FCFEWVVJ.js} +3 -3
  193. package/dist/cli/chunks/{daemon-6JNNBU33.js → daemon-PN4FEPLE.js} +6 -6
  194. package/dist/cli/chunks/{dag-attention-scheduler-7SGPLKGI.js → dag-attention-scheduler-PLOHU5SR.js} +2 -2
  195. package/dist/cli/chunks/{detect-IXD77HG4.js → detect-F3H4ZEZY.js} +2 -2
  196. package/dist/cli/chunks/{dist-node-ARTYK2HL.js → dist-node-5TC665N6.js} +2 -2
  197. package/dist/cli/chunks/{domain-handler-X4BOFLMY.js → domain-handler-ZIWVFXCU.js} +2 -2
  198. package/dist/cli/chunks/{domain-transfer-7JBEXLFL.js → domain-transfer-7Q5JYMYR.js} +2 -2
  199. package/dist/cli/chunks/dream-WFCZGFDY.js +2 -0
  200. package/dist/cli/chunks/{embed-and-insert-pattern-VSOLKM3Y.js → embed-and-insert-pattern-VESJQSYD.js} +2 -2
  201. package/dist/cli/chunks/{eval-HS2QQW42.js → eval-E2K2T75A.js} +2 -2
  202. package/dist/cli/chunks/{experience-capture-middleware-MWEPZYBT.js → experience-capture-middleware-Z5SE2O53.js} +3 -3
  203. package/dist/cli/chunks/{fast-paths-RONNJ6AC.js → fast-paths-3H52RSUK.js} +2 -2
  204. package/dist/cli/chunks/{feature-flags-4YE5A6XG.js → feature-flags-LUHSMHPS.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-CLW4K2HN.js → feature-flags-ONIKUZVK.js} +2 -2
  206. package/dist/cli/chunks/{file-discovery-56C2FW4V.js → file-discovery-FLYSYSS4.js} +2 -2
  207. package/dist/cli/chunks/{fleet-KMB6RM3R.js → fleet-6OJUAAKV.js} +3 -3
  208. package/dist/cli/chunks/{gnn-wrapper-R2OMDND4.js → gnn-wrapper-PUL6B7KZ.js} +2 -2
  209. package/dist/cli/chunks/{heartbeat-handler-FP3CIA2V.js → heartbeat-handler-HGHHDUDY.js} +4 -4
  210. package/dist/cli/chunks/heartbeat-scheduler-HWS4SHRM.js +2 -0
  211. package/dist/cli/chunks/hnsw-adapter-7QOBHKRB.js +2 -0
  212. package/dist/cli/chunks/hnsw-index-6WUKYJH7.js +2 -0
  213. package/dist/cli/chunks/{hnsw-legacy-bridge-EQKXBLRX.js → hnsw-legacy-bridge-NDZSNMYX.js} +2 -2
  214. package/dist/cli/chunks/{hnswlib-node-JG3WOXKM.js → hnswlib-node-PISLKSO2.js} +2 -2
  215. package/dist/cli/chunks/{hooks-6QZYELUZ.js → hooks-WYG54MRI.js} +40 -40
  216. package/dist/cli/chunks/hybrid-router-525JTRA5.js +2 -0
  217. package/dist/cli/chunks/{hypergraph-engine-5HGNZFDH.js → hypergraph-engine-EDHKHZZ2.js} +2 -2
  218. package/dist/cli/chunks/{hypergraph-handler-LO2ODOYD.js → hypergraph-handler-OCHZAPPL.js} +3 -3
  219. package/dist/cli/chunks/impact-analyzer-GG6CJEOK.js +2 -0
  220. package/dist/cli/chunks/{init-handler-E346YK6H.js → init-handler-5TCJ672H.js} +6 -6
  221. package/dist/cli/chunks/init-wizard-4VFAOK4Y.js +2 -0
  222. package/dist/cli/chunks/kernel-N3FQGOST.js +2 -0
  223. package/dist/cli/chunks/{kilocode-installer-ZBJNB6N4.js → kilocode-installer-SWUQRCTZ.js} +2 -2
  224. package/dist/cli/chunks/{kiro-installer-3TWFO4QZ.js → kiro-installer-L22EBAM5.js} +2 -2
  225. package/dist/cli/chunks/knowledge-graph-I5QIHB4G.js +2 -0
  226. package/dist/cli/chunks/{learning-3MLFLTM2.js → learning-TQOGG3CR.js} +3 -3
  227. package/dist/cli/chunks/llm-router-F2L4LFT2.js +37 -0
  228. package/dist/cli/chunks/llm-router-service-NCJZYJLG.js +2 -0
  229. package/dist/cli/chunks/{load-P6XC2P74.js → load-A4ZF2KHC.js} +2 -2
  230. package/dist/cli/chunks/load-test-DCJEYIXD.js +2 -0
  231. package/dist/cli/chunks/{mcp-XEND7FPN.js → mcp-T2Z46NNK.js} +2 -2
  232. package/dist/cli/chunks/{memory-HZ2WSMWW.js → memory-PUC3J6XC.js} +5 -5
  233. package/dist/cli/chunks/memory-backend-O6KO2KTX.js +2 -0
  234. package/dist/cli/chunks/memory-handlers-4Z43WEKD.js +2 -0
  235. package/dist/cli/chunks/{multi-model-executor-IYEHZP73.js → multi-model-executor-U5L4FI4O.js} +2 -2
  236. package/dist/cli/chunks/{opencode-installer-GH3VVBM2.js → opencode-installer-UWI6KHYH.js} +2 -2
  237. package/dist/cli/chunks/{orchestrator-GOKIBTQG.js → orchestrator-3BEI7R5D.js} +5 -5
  238. package/dist/cli/chunks/pattern-null-store-5WIJKX2K.js +2 -0
  239. package/dist/cli/chunks/{pattern-usage-recorder-J2X4DD5S.js → pattern-usage-recorder-EGWUI5LU.js} +2 -2
  240. package/dist/cli/chunks/{pipeline-ELINTMVF.js → pipeline-JG6M4RHD.js} +2 -2
  241. package/dist/cli/chunks/{platform-PIPUB3LU.js → platform-F76G6RUI.js} +2 -2
  242. package/dist/cli/chunks/{plugin-DXDNI6ZV.js → plugin-EEGN3PMK.js} +2 -2
  243. package/dist/cli/chunks/{prime-radiant-advanced-wasm-K6WWURGX.js → prime-radiant-advanced-wasm-7KZAINFT.js} +2 -2
  244. package/dist/cli/chunks/protocol-executor-5TPNAZTB.js +2 -0
  245. package/dist/cli/chunks/{protocol-handler-NMO7VI64.js → protocol-handler-UCEHYK2R.js} +2 -2
  246. package/dist/cli/chunks/{prove-4BLOE4SC.js → prove-JSNG75VD.js} +2 -2
  247. package/dist/cli/chunks/provider-manager-3VMOZ6HV.js +2 -0
  248. package/dist/cli/chunks/qe-reasoning-bank-BATV4NTT.js +2 -0
  249. package/dist/cli/chunks/{quality-MYXBP3GX.js → quality-7SRM2HBM.js} +2 -2
  250. package/dist/cli/chunks/{quality-gate-AXPBK3MT.js → quality-gate-A5MPWHST.js} +3 -3
  251. package/dist/cli/chunks/queen-coordinator-EIHGYBUO.js +2 -0
  252. package/dist/cli/chunks/{real-embeddings-4AKAVZIY.js → real-embeddings-ZBF5EQOG.js} +2 -2
  253. package/dist/cli/chunks/{roocode-installer-JE36LP4T.js → roocode-installer-UYQK64BZ.js} +2 -2
  254. package/dist/cli/chunks/router-EMVGY4HU.js +2 -0
  255. package/dist/cli/chunks/routing-feedback-JUP4OFB2.js +2 -0
  256. package/dist/cli/chunks/{routing-handler-LOJUJCVV.js → routing-handler-PY3KPDTH.js} +2 -2
  257. package/dist/cli/chunks/{ruvector-commands-6PNDYF32.js → ruvector-commands-GCAOUTYS.js} +2 -2
  258. package/dist/cli/chunks/{rvf-dual-writer-GSTQPRNA.js → rvf-dual-writer-BUNP4SKD.js} +2 -2
  259. package/dist/cli/chunks/{rvf-migration-adapter-Z2DSEG3E.js → rvf-migration-adapter-VSOAPLMB.js} +2 -2
  260. package/dist/cli/chunks/{rvf-migration-coordinator-XRNODDH4.js → rvf-migration-coordinator-LSWEHAWX.js} +2 -2
  261. package/dist/cli/chunks/rvf-native-adapter-LOC42TQ6.js +2 -0
  262. package/dist/cli/chunks/{rvf-store-integrity-LVEFIUUW.js → rvf-store-integrity-HNDKOM4L.js} +2 -2
  263. package/dist/cli/chunks/safe-db-WQ62IQKV.js +2 -0
  264. package/dist/cli/chunks/schedule-XJRP57TE.js +2 -0
  265. package/dist/cli/chunks/scheduler-EZH5SDIM.js +2 -0
  266. package/dist/cli/chunks/{security-A2FK2DER.js → security-MQ2VB7PY.js} +3 -3
  267. package/dist/cli/chunks/{shared-rvf-adapter-V7IBEGQQ.js → shared-rvf-adapter-TAZEU6QK.js} +2 -2
  268. package/dist/cli/chunks/{shared-rvf-dual-writer-SMGECN2K.js → shared-rvf-dual-writer-B7N6AOCY.js} +2 -2
  269. package/dist/cli/chunks/sqlite-persistence-HPEVCTIB.js +2 -0
  270. package/dist/cli/chunks/status-handler-NZP7DFHE.js +47 -0
  271. package/dist/cli/chunks/{structural-health-6BRP74EW.js → structural-health-ALLUQ4X6.js} +2 -2
  272. package/dist/cli/chunks/{sync-4PDTGP34.js → sync-MM7OCUYD.js} +2 -2
  273. package/dist/cli/chunks/{sync-KI573HOR.js → sync-WJJG5J6V.js} +2 -2
  274. package/dist/cli/chunks/{task-handler-QQGSAK6T.js → task-handler-CAQUEEB4.js} +2 -2
  275. package/dist/cli/chunks/{task-handlers-VUPCDYTI.js → task-handlers-25BJ7D3W.js} +3 -3
  276. package/dist/cli/chunks/{test-CJLXBSRH.js → test-HW7GVGVN.js} +4 -4
  277. package/dist/cli/chunks/{test-scheduling-IKPQPQUB.js → test-scheduling-HTMFJMSP.js} +3 -3
  278. package/dist/cli/chunks/{token-bootstrap-FHLC3SHC.js → token-bootstrap-F2DCLWGW.js} +2 -2
  279. package/dist/cli/chunks/{token-usage-NCXAK7TB.js → token-usage-RJZDMBDP.js} +2 -2
  280. package/dist/cli/chunks/{transformers-SZFBEILB.js → transformers-3YFW3EUO.js} +2 -2
  281. package/dist/cli/chunks/{tree-sitter-wasm-parser-LFGJRML7.js → tree-sitter-wasm-parser-U3PQPIK7.js} +2 -2
  282. package/dist/cli/chunks/{types-NKXH7VTP.js → types-7Q762WDO.js} +2 -2
  283. package/dist/cli/chunks/unified-memory-ATILROKR.js +2 -0
  284. package/dist/cli/chunks/unified-memory-hnsw-XJXAX7DW.js +2 -0
  285. package/dist/cli/chunks/unified-persistence-3TN5PBWE.js +2 -0
  286. package/dist/cli/chunks/{upgrade-PFCFH6M5.js → upgrade-F7MKJWBQ.js} +2 -2
  287. package/dist/cli/chunks/{validate-YEBJRWQM.js → validate-B27AVRA6.js} +2 -2
  288. package/dist/cli/chunks/{validate-swarm-TD2NA6QF.js → validate-swarm-GYZR3GNL.js} +2 -2
  289. package/dist/cli/chunks/{vibium-ACC4GIOT.js → vibium-W4XQMPJP.js} +2 -2
  290. package/dist/cli/chunks/visual-security-VFWRBCNA.js +2 -0
  291. package/dist/cli/chunks/{web-tree-sitter-IWVW5FIE.js → web-tree-sitter-I7CDCFJU.js} +2 -2
  292. package/dist/cli/chunks/{windsurf-installer-5PVGLJ3T.js → windsurf-installer-UYLHFDHU.js} +2 -2
  293. package/dist/cli/chunks/{witness-chain-VZB4LJOJ.js → witness-chain-B66SYZKU.js} +2 -2
  294. package/dist/cli/chunks/witness-chain-JC5LEXRV.js +2 -0
  295. package/dist/cli/chunks/{witness-key-manager-X632AZTN.js → witness-key-manager-U4JPAHVW.js} +2 -2
  296. package/dist/cli/chunks/{workflow-VNAYFUVY.js → workflow-DYMO47FF.js} +4 -4
  297. package/dist/cli/chunks/workflow-orchestrator-TKQUF2KN.js +2 -0
  298. package/dist/cli/chunks/{wrappers-KO3QXNZP.js → wrappers-7S6DQTEA.js} +2 -2
  299. package/dist/cli/commands/daemon.js +3 -3
  300. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +2 -2
  301. package/dist/cli/commands/hooks-handlers/routing-hooks.js +7 -0
  302. package/dist/cli/commands/llm-router.js +35 -6
  303. package/dist/cli/commands/plugin.js +4 -4
  304. package/dist/cli/commands/quality-gate.js +5 -1
  305. package/dist/cli/handlers/status-handler.js +18 -2
  306. package/dist/cli/index.js +1 -1
  307. package/dist/cli/utils/index.js +2 -2
  308. package/dist/context/compaction/index.js +11 -11
  309. package/dist/context/compaction/tier1-microcompact.js +1 -1
  310. package/dist/context/compaction/tier2-session-summary.js +1 -1
  311. package/dist/context/compaction/tier3-llm-compact.js +1 -1
  312. package/dist/context/compaction/tier4-reactive.js +1 -1
  313. package/dist/coordination/claims/index.js +8 -8
  314. package/dist/coordination/consensus/consensus-engine.js +4 -4
  315. package/dist/coordination/consensus/factory.js +4 -4
  316. package/dist/coordination/consensus/index.js +8 -8
  317. package/dist/coordination/consensus/providers/claude-provider.js +1 -1
  318. package/dist/coordination/consensus/providers/gemini-provider.js +1 -1
  319. package/dist/coordination/consensus/providers/index.js +7 -7
  320. package/dist/coordination/consensus/providers/native-learning-provider.js +1 -1
  321. package/dist/coordination/consensus/providers/ollama-provider.js +1 -1
  322. package/dist/coordination/consensus/providers/openai-provider.js +1 -1
  323. package/dist/coordination/consensus/providers/openrouter-provider.js +1 -1
  324. package/dist/coordination/consensus/strategies/index.js +3 -3
  325. package/dist/coordination/cross-domain-router.js +2 -2
  326. package/dist/coordination/dynamic-scaling/dynamic-scaler.js +1 -1
  327. package/dist/coordination/dynamic-scaling/index.js +2 -2
  328. package/dist/coordination/fleet-tiers/index.js +3 -3
  329. package/dist/coordination/fleet-tiers/tier-selector.js +2 -2
  330. package/dist/coordination/handlers/code-intelligence-handlers.js +2 -2
  331. package/dist/coordination/handlers/coverage-collection.js +1 -1
  332. package/dist/coordination/handlers/coverage-handlers.js +3 -3
  333. package/dist/coordination/handlers/index.js +7 -7
  334. package/dist/coordination/handlers/misc-handlers.js +1 -1
  335. package/dist/coordination/handlers/quality-handlers.js +2 -2
  336. package/dist/coordination/handlers/requirements-handlers.js +2 -2
  337. package/dist/coordination/handlers/security-handlers.js +2 -2
  338. package/dist/coordination/handlers/test-execution-handlers.js +1 -1
  339. package/dist/coordination/index.js +20 -20
  340. package/dist/coordination/mincut/dream-integration.js +1 -1
  341. package/dist/coordination/mincut/index.js +14 -14
  342. package/dist/coordination/mincut/mincut-health-monitor.js +2 -2
  343. package/dist/coordination/mincut/mincut-persistence.js +1 -1
  344. package/dist/coordination/mincut/morphogenetic-growth.js +1 -1
  345. package/dist/coordination/mincut/neural-goap.js +1 -1
  346. package/dist/coordination/mincut/queen-integration.js +5 -5
  347. package/dist/coordination/mincut/shared-singleton.js +3 -3
  348. package/dist/coordination/mincut/strange-loop.js +1 -1
  349. package/dist/coordination/mincut/time-crystal.js +8 -8
  350. package/dist/coordination/mixins/consensus-enabled-domain.js +2 -2
  351. package/dist/coordination/mixins/index.js +3 -3
  352. package/dist/coordination/protocol-executor.js +2 -2
  353. package/dist/coordination/protocols/code-intelligence-index.js +4 -4
  354. package/dist/coordination/protocols/defect-investigation.js +2 -2
  355. package/dist/coordination/protocols/morning-sync.js +1 -1
  356. package/dist/coordination/protocols/quality-gate.js +2 -2
  357. package/dist/coordination/queen-coordinator.js +4 -4
  358. package/dist/coordination/queen-task-management.js +1 -1
  359. package/dist/coordination/services/index.js +1 -1
  360. package/dist/coordination/task-executor.js +6 -6
  361. package/dist/domains/chaos-resilience/coordinator.js +6 -6
  362. package/dist/domains/chaos-resilience/index.js +5 -5
  363. package/dist/domains/chaos-resilience/plugin.js +6 -6
  364. package/dist/domains/chaos-resilience/services/chaos-engineer.js +3 -3
  365. package/dist/domains/chaos-resilience/services/index.js +3 -3
  366. package/dist/domains/chaos-resilience/services/load-tester.js +2 -2
  367. package/dist/domains/chaos-resilience/services/performance-profiler.js +2 -2
  368. package/dist/domains/code-intelligence/coordinator-consensus.js +1 -1
  369. package/dist/domains/code-intelligence/coordinator-gnn.js +1 -1
  370. package/dist/domains/code-intelligence/coordinator-hypergraph.js +2 -2
  371. package/dist/domains/code-intelligence/coordinator.js +9 -9
  372. package/dist/domains/code-intelligence/index.js +7 -7
  373. package/dist/domains/code-intelligence/plugin.js +6 -6
  374. package/dist/domains/code-intelligence/services/c4-model/index.js +3 -3
  375. package/dist/domains/code-intelligence/services/impact-analyzer.js +2 -2
  376. package/dist/domains/code-intelligence/services/index.js +6 -6
  377. package/dist/domains/code-intelligence/services/knowledge-graph.js +4 -4
  378. package/dist/domains/code-intelligence/services/metric-collector/loc-counter.js +1 -1
  379. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +1 -1
  380. package/dist/domains/code-intelligence/services/product-factors-bridge.js +5 -5
  381. package/dist/domains/code-intelligence/services/semantic-analyzer.js +2 -2
  382. package/dist/domains/coverage-analysis/coordinator.js +9 -9
  383. package/dist/domains/coverage-analysis/index.js +10 -10
  384. package/dist/domains/coverage-analysis/plugin.js +4 -4
  385. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +1 -1
  386. package/dist/domains/coverage-analysis/services/gap-detector.js +1 -1
  387. package/dist/domains/coverage-analysis/services/ghost-coverage-analyzer.js +1 -1
  388. package/dist/domains/coverage-analysis/services/index.js +7 -7
  389. package/dist/domains/coverage-analysis/services/risk-scorer.js +1 -1
  390. package/dist/domains/coverage-analysis/services/sublinear-analyzer.js +3 -3
  391. package/dist/domains/defect-intelligence/coordinator.js +5 -5
  392. package/dist/domains/defect-intelligence/index.js +5 -5
  393. package/dist/domains/defect-intelligence/plugin.js +6 -6
  394. package/dist/domains/defect-intelligence/services/causal-root-cause-analyzer.js +2 -2
  395. package/dist/domains/defect-intelligence/services/defect-predictor.js +4 -4
  396. package/dist/domains/defect-intelligence/services/index.js +4 -4
  397. package/dist/domains/defect-intelligence/services/pattern-learner.js +2 -2
  398. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +1 -1
  399. package/dist/domains/domain-interface.js +1 -1
  400. package/dist/domains/index.js +14 -14
  401. package/dist/domains/learning-optimization/coordinator.d.ts +3 -0
  402. package/dist/domains/learning-optimization/coordinator.js +6 -0
  403. package/dist/domains/learning-optimization/interfaces.d.ts +2 -0
  404. package/dist/domains/learning-optimization/plugin.d.ts +3 -0
  405. package/dist/domains/learning-optimization/plugin.js +5 -0
  406. package/dist/domains/quality-assessment/coherence/gate-controller.js +2 -2
  407. package/dist/domains/quality-assessment/coherence/lambda-calculator.js +1 -1
  408. package/dist/domains/quality-assessment/coherence/partition-detector.js +1 -1
  409. package/dist/domains/quality-assessment/coordinator-gate-evaluation.js +1 -1
  410. package/dist/domains/quality-assessment/coordinator-reports.js +1 -1
  411. package/dist/domains/quality-assessment/coordinator-rl-integration.js +2 -2
  412. package/dist/domains/quality-assessment/coordinator.js +5 -5
  413. package/dist/domains/quality-assessment/index.js +9 -9
  414. package/dist/domains/quality-assessment/plugin.js +6 -6
  415. package/dist/domains/quality-assessment/services/coherence-gate.js +6 -6
  416. package/dist/domains/quality-assessment/services/deployment-advisor.js +1 -1
  417. package/dist/domains/quality-assessment/services/index.js +4 -4
  418. package/dist/domains/quality-assessment/services/quality-analyzer.js +2 -2
  419. package/dist/domains/quality-assessment/services/quality-gate.js +1 -1
  420. package/dist/domains/requirements-validation/services/product-factors-assessment/analyzers/brutal-honesty-analyzer.js +2 -2
  421. package/dist/domains/requirements-validation/services/product-factors-assessment/analyzers/sfdipot-analyzer.js +2 -2
  422. package/dist/domains/requirements-validation/services/product-factors-assessment/code-intelligence/codebase-analyzer.js +1 -1
  423. package/dist/domains/requirements-validation/services/product-factors-assessment/formatters/gherkin-formatter.js +1 -1
  424. package/dist/domains/requirements-validation/services/product-factors-assessment/formatters/html-formatter.js +2 -2
  425. package/dist/domains/requirements-validation/services/product-factors-assessment/formatters/markdown-formatter.js +1 -1
  426. package/dist/domains/requirements-validation/services/product-factors-assessment/generators/question-generator.js +3 -3
  427. package/dist/domains/requirements-validation/services/product-factors-assessment/generators/test-idea-generator.js +3 -3
  428. package/dist/domains/requirements-validation/services/product-factors-assessment/patterns/domain-registry.js +1 -1
  429. package/dist/domains/requirements-validation/services/product-factors-assessment/patterns/index.js +1 -1
  430. package/dist/domains/requirements-validation/services/product-factors-assessment/skills/skill-integration.js +1 -1
  431. package/dist/domains/security-compliance/coordinator.js +1 -1
  432. package/dist/domains/security-compliance/index.js +1 -1
  433. package/dist/domains/security-compliance/services/compliance-validator.js +1 -1
  434. package/dist/domains/security-compliance/services/scanners/dast-helpers.js +1 -1
  435. package/dist/domains/security-compliance/services/scanners/dast-scanner.js +2 -2
  436. package/dist/domains/security-compliance/services/scanners/dependency-scanner.js +4 -4
  437. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +3 -3
  438. package/dist/domains/security-compliance/services/scanners/scanner-orchestrator.js +2 -2
  439. package/dist/domains/test-execution/coordinator.js +8 -8
  440. package/dist/domains/test-execution/index.js +9 -9
  441. package/dist/domains/test-execution/interfaces.js +1 -1
  442. package/dist/domains/test-execution/plugin.js +3 -3
  443. package/dist/domains/test-execution/services/e2e/adaptive-locator-service.js +1 -1
  444. package/dist/domains/test-execution/services/e2e/assertion-handlers.js +2 -2
  445. package/dist/domains/test-execution/services/e2e/browser-orchestrator.js +3 -3
  446. package/dist/domains/test-execution/services/e2e/e2e-coordinator.js +7 -7
  447. package/dist/domains/test-execution/services/e2e/index.js +10 -10
  448. package/dist/domains/test-execution/services/e2e/step-executors.js +6 -6
  449. package/dist/domains/test-execution/services/e2e/step-retry-handler.js +3 -3
  450. package/dist/domains/test-execution/services/e2e/wait-condition-handler.js +1 -1
  451. package/dist/domains/test-execution/services/e2e-runner.js +6 -6
  452. package/dist/domains/test-execution/services/flaky-detector.js +1 -1
  453. package/dist/domains/test-execution/services/index.js +9 -9
  454. package/dist/domains/test-execution/services/retry-handler.js +1 -1
  455. package/dist/domains/test-execution/services/test-executor.js +1 -1
  456. package/dist/domains/test-execution/services/test-prioritizer.js +3 -3
  457. package/dist/domains/test-execution/services/user-flow-generator.js +3 -3
  458. package/dist/domains/test-execution/test-prioritization-types.js +1 -1
  459. package/dist/domains/test-execution/types/index.js +3 -3
  460. package/dist/domains/test-generation/coordinator.js +5 -5
  461. package/dist/domains/test-generation/factories/index.js +1 -1
  462. package/dist/domains/test-generation/factories/test-generator-factory.js +1 -1
  463. package/dist/domains/test-generation/generators/base-test-generator.js +1 -1
  464. package/dist/domains/test-generation/generators/go-test-generator.js +2 -2
  465. package/dist/domains/test-generation/generators/index.js +13 -13
  466. package/dist/domains/test-generation/generators/jest-vitest-generator.js +1 -1
  467. package/dist/domains/test-generation/generators/junit5-generator.js +2 -2
  468. package/dist/domains/test-generation/generators/kotlin-junit-generator.js +2 -2
  469. package/dist/domains/test-generation/generators/mocha-generator.js +1 -1
  470. package/dist/domains/test-generation/generators/node-test-generator.js +1 -1
  471. package/dist/domains/test-generation/generators/pytest-generator.js +2 -2
  472. package/dist/domains/test-generation/generators/rust-test-generator.js +3 -3
  473. package/dist/domains/test-generation/generators/swift-testing-generator.js +2 -2
  474. package/dist/domains/test-generation/generators/xunit-generator.js +2 -2
  475. package/dist/domains/test-generation/index.js +7 -7
  476. package/dist/domains/test-generation/interfaces/index.js +1 -1
  477. package/dist/domains/test-generation/plugin.js +5 -5
  478. package/dist/domains/test-generation/services/code-transform-integration.js +1 -1
  479. package/dist/domains/test-generation/services/index.js +10 -10
  480. package/dist/domains/test-generation/services/pattern-matcher.js +2 -2
  481. package/dist/domains/test-generation/services/test-generator.js +5 -5
  482. package/dist/domains/visual-accessibility/coordinator.js +1 -1
  483. package/dist/early-exit/early-exit-controller.js +4 -4
  484. package/dist/early-exit/early-exit-decision.js +2 -2
  485. package/dist/early-exit/index.js +5 -5
  486. package/dist/early-exit/quality-signal.js +1 -1
  487. package/dist/early-exit/speculative-executor.js +1 -1
  488. package/dist/index.js +18 -18
  489. package/dist/integrations/agentic-flow/agent-booster/adapter.js +4 -4
  490. package/dist/integrations/agentic-flow/agent-booster/index.js +10 -10
  491. package/dist/integrations/agentic-flow/index.js +6 -6
  492. package/dist/integrations/agentic-flow/metrics/index.js +3 -3
  493. package/dist/integrations/agentic-flow/metrics/metrics-tracker.js +2 -2
  494. package/dist/integrations/agentic-flow/metrics/pattern-updater.js +1 -1
  495. package/dist/integrations/agentic-flow/model-router/budget-enforcer.js +1 -1
  496. package/dist/integrations/agentic-flow/model-router/complexity-analyzer.js +7 -7
  497. package/dist/integrations/agentic-flow/model-router/example.js +1 -1
  498. package/dist/integrations/agentic-flow/model-router/index.js +16 -16
  499. package/dist/integrations/agentic-flow/model-router/router.js +6 -6
  500. package/dist/integrations/agentic-flow/model-router/signal-collector.js +1 -1
  501. package/dist/integrations/agentic-flow/model-router/tier-recommender.js +1 -1
  502. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.js +11 -6
  503. package/dist/integrations/browser/agent-browser/client.js +4 -4
  504. package/dist/integrations/browser/agent-browser/index.js +4 -4
  505. package/dist/integrations/browser/agent-browser/session-manager.js +1 -1
  506. package/dist/integrations/browser/client-factory.js +3 -3
  507. package/dist/integrations/browser/index.js +8 -8
  508. package/dist/integrations/browser/page-pool.js +1 -1
  509. package/dist/integrations/browser/stealth/index.js +2 -2
  510. package/dist/integrations/browser/stealth/stealth-client.js +3 -3
  511. package/dist/integrations/browser/web-content-fetcher.js +1 -1
  512. package/dist/integrations/coherence/coherence-service.js +2 -2
  513. package/dist/integrations/coherence/engines/category-adapter.js +1 -1
  514. package/dist/integrations/coherence/engines/causal-adapter.js +1 -1
  515. package/dist/integrations/coherence/engines/cohomology-adapter.js +1 -1
  516. package/dist/integrations/coherence/engines/homotopy-adapter.js +1 -1
  517. package/dist/integrations/coherence/engines/index.js +6 -6
  518. package/dist/integrations/coherence/engines/spectral-adapter.js +1 -1
  519. package/dist/integrations/coherence/engines/witness-adapter.js +1 -1
  520. package/dist/integrations/coherence/index.js +7 -7
  521. package/dist/integrations/coherence/threshold-tuner.js +1 -1
  522. package/dist/integrations/coherence/wasm-loader.js +2 -2
  523. package/dist/integrations/rl-suite/algorithms/a2c.js +2 -2
  524. package/dist/integrations/rl-suite/algorithms/actor-critic.js +2 -2
  525. package/dist/integrations/rl-suite/algorithms/ddpg.js +1 -1
  526. package/dist/integrations/rl-suite/algorithms/decision-transformer.js +1 -1
  527. package/dist/integrations/rl-suite/algorithms/dqn.js +2 -2
  528. package/dist/integrations/rl-suite/algorithms/eprop.js +2 -2
  529. package/dist/integrations/rl-suite/algorithms/index.js +10 -10
  530. package/dist/integrations/rl-suite/algorithms/policy-gradient.js +2 -2
  531. package/dist/integrations/rl-suite/algorithms/ppo.js +2 -2
  532. package/dist/integrations/rl-suite/algorithms/q-learning.js +3 -3
  533. package/dist/integrations/rl-suite/algorithms/sarsa.js +2 -2
  534. package/dist/integrations/rl-suite/base-algorithm.js +1 -1
  535. package/dist/integrations/rl-suite/index.js +6 -6
  536. package/dist/integrations/rl-suite/neural/index.js +2 -2
  537. package/dist/integrations/rl-suite/orchestrator.js +11 -11
  538. package/dist/integrations/ruvector/ast-complexity.js +1 -1
  539. package/dist/integrations/ruvector/coverage-router.js +1 -1
  540. package/dist/integrations/ruvector/diff-risk-classifier.js +1 -1
  541. package/dist/integrations/ruvector/graph-boundaries.js +1 -1
  542. package/dist/integrations/ruvector/hypergraph-engine.js +1 -1
  543. package/dist/integrations/ruvector/hypergraph-schema.js +1 -1
  544. package/dist/integrations/ruvector/index.js +52 -52
  545. package/dist/integrations/ruvector/persistent-q-router.js +2 -2
  546. package/dist/integrations/ruvector/q-learning-router.js +1 -1
  547. package/dist/integrations/ruvector/solver-adapter.js +1 -1
  548. package/dist/integrations/ruvector/sona-persistence.d.ts +13 -11
  549. package/dist/integrations/ruvector/sona-persistence.js +1 -1
  550. package/dist/integrations/vibium/client.js +3 -3
  551. package/dist/integrations/vibium/fallback.js +2 -2
  552. package/dist/integrations/vibium/index.js +9 -9
  553. package/dist/kernel/agent-coordinator.js +1 -1
  554. package/dist/kernel/event-bus.js +1 -1
  555. package/dist/kernel/hybrid-backend.js +1 -1
  556. package/dist/kernel/index.js +11 -11
  557. package/dist/kernel/kernel.js +27 -27
  558. package/dist/kernel/memory-factory.js +2 -2
  559. package/dist/kernel/unified-persistence.js +1 -1
  560. package/dist/learning/aqe-learning-engine.d.ts +0 -1
  561. package/dist/learning/aqe-learning-engine.js +2 -36
  562. package/dist/learning/pattern-lifecycle.js +1 -1
  563. package/dist/learning/pattern-routing-guidance.d.ts +16 -0
  564. package/dist/learning/pattern-routing-guidance.js +34 -0
  565. package/dist/learning/qe-reasoning-bank-types.d.ts +2 -0
  566. package/dist/learning/qe-reasoning-bank.js +2 -1
  567. package/dist/learning/real-qe-reasoning-bank.d.ts +2 -0
  568. package/dist/learning/real-qe-reasoning-bank.js +4 -2
  569. package/dist/learning/token-tracker.js +1 -1
  570. package/dist/logging/index.js +1 -1
  571. package/dist/logging/logger-factory.js +1 -1
  572. package/dist/mcp/bundle.js +445 -432
  573. package/dist/mcp/entry.js +1 -1
  574. package/dist/mcp/handlers/agent-handlers.js +2 -2
  575. package/dist/mcp/handlers/core-handlers.js +9 -9
  576. package/dist/mcp/handlers/domain-handler-configs.js +2 -2
  577. package/dist/mcp/handlers/domain-handlers.js +2 -2
  578. package/dist/mcp/handlers/handler-factory.js +3 -3
  579. package/dist/mcp/handlers/index.js +7 -7
  580. package/dist/mcp/handlers/memory-handlers.js +1 -1
  581. package/dist/mcp/handlers/task-handlers.js +3 -3
  582. package/dist/mcp/handlers/team-handlers.js +1 -1
  583. package/dist/mcp/index.js +11 -11
  584. package/dist/mcp/metrics/index.js +1 -1
  585. package/dist/mcp/protocol-server.js +13 -13
  586. package/dist/mcp/security/cve-prevention.js +23 -23
  587. package/dist/mcp/security/index.js +9 -9
  588. package/dist/mcp/security/validators/index.js +6 -6
  589. package/dist/mcp/services/index.js +1 -1
  590. package/dist/mcp/services/task-router.js +1 -1
  591. package/dist/mcp/tool-registry.js +4 -4
  592. package/dist/mcp/tools/base.js +1 -1
  593. package/dist/mcp/tools/code-intelligence/analyze.js +4 -4
  594. package/dist/mcp/tools/code-intelligence/c4.js +6 -6
  595. package/dist/mcp/tools/coverage-analysis/index.js +4 -4
  596. package/dist/mcp/tools/defect-intelligence/predict.js +2 -2
  597. package/dist/mcp/tools/embeddings/embedding.js +2 -2
  598. package/dist/mcp/tools/embeddings/index.js +1 -1
  599. package/dist/mcp/tools/index.js +20 -20
  600. package/dist/mcp/tools/learning-optimization/optimize.d.ts +11 -0
  601. package/dist/mcp/tools/learning-optimization/optimize.js +21 -0
  602. package/dist/mcp/tools/mincut/index.js +2 -2
  603. package/dist/mcp/tools/quality-assessment/evaluate.js +1 -1
  604. package/dist/mcp/tools/quality-assessment/gate.js +5 -2
  605. package/dist/mcp/tools/qx-analysis/analyze.js +5 -5
  606. package/dist/mcp/tools/qx-analysis/heuristics-engine.js +1 -1
  607. package/dist/mcp/tools/qx-analysis/index.js +6 -6
  608. package/dist/mcp/tools/registry.js +25 -25
  609. package/dist/mcp/tools/requirements-validation/quality-criteria.js +1 -1
  610. package/dist/mcp/tools/requirements-validation/validate.js +1 -1
  611. package/dist/mcp/tools/security-compliance/scan.js +1 -1
  612. package/dist/mcp/tools/test-execution/e2e-execute.js +3 -3
  613. package/dist/mcp/tools/test-execution/execute.js +1 -1
  614. package/dist/mcp/tools/test-execution/index.js +2 -2
  615. package/dist/mcp/tools/test-generation/generate.js +3 -3
  616. package/dist/mcp/tools/visual-accessibility/index.js +3 -3
  617. package/dist/plugins/index.js +8 -8
  618. package/dist/plugins/lifecycle.js +5 -5
  619. package/dist/plugins/sources/github.js +1 -1
  620. package/dist/plugins/sources/local.js +1 -1
  621. package/dist/plugins/sources/npm.js +1 -1
  622. package/dist/shared/base-domain-plugin.js +1 -1
  623. package/dist/shared/c4-model/index.js +1 -1
  624. package/dist/shared/embeddings/index.js +4 -4
  625. package/dist/shared/embeddings/nomic-embedder.js +3 -3
  626. package/dist/shared/embeddings/ollama-client.js +1 -1
  627. package/dist/shared/entities/agent.js +1 -1
  628. package/dist/shared/entities/index.js +2 -2
  629. package/dist/shared/events/index.js +1 -1
  630. package/dist/shared/git/index.js +1 -1
  631. package/dist/shared/http/http-client.js +1 -1
  632. package/dist/shared/http/index.js +1 -1
  633. package/dist/shared/index.js +15 -15
  634. package/dist/shared/io/file-reader.js +1 -1
  635. package/dist/shared/io/index.js +1 -1
  636. package/dist/shared/llm/billing-modes.d.ts +5 -0
  637. package/dist/shared/llm/billing-modes.js +42 -3
  638. package/dist/shared/llm/circuit-breaker.js +1 -1
  639. package/dist/shared/llm/index.d.ts +4 -1
  640. package/dist/shared/llm/index.js +15 -11
  641. package/dist/shared/llm/interfaces.d.ts +34 -3
  642. package/dist/shared/llm/interfaces.js +17 -0
  643. package/dist/shared/llm/metrics/cost-metrics.js +2 -2
  644. package/dist/shared/llm/metrics/index.js +2 -2
  645. package/dist/shared/llm/metrics/router-metrics.js +1 -1
  646. package/dist/shared/llm/model-registry.js +1 -1
  647. package/dist/shared/llm/provider-manager.js +24 -17
  648. package/dist/shared/llm/provider-registry.d.ts +135 -0
  649. package/dist/shared/llm/provider-registry.js +227 -0
  650. package/dist/shared/llm/providers/azure-openai.js +2 -2
  651. package/dist/shared/llm/providers/bedrock.js +2 -2
  652. package/dist/shared/llm/providers/claude-code.js +1 -1
  653. package/dist/shared/llm/providers/claude.js +4 -4
  654. package/dist/shared/llm/providers/codex.js +1 -1
  655. package/dist/shared/llm/providers/cognitum.js +1 -1
  656. package/dist/shared/llm/providers/external-cli.d.ts +129 -0
  657. package/dist/shared/llm/providers/external-cli.js +385 -0
  658. package/dist/shared/llm/providers/gemini.js +1 -1
  659. package/dist/shared/llm/providers/index.js +10 -10
  660. package/dist/shared/llm/providers/ollama.js +2 -2
  661. package/dist/shared/llm/providers/openai.js +2 -2
  662. package/dist/shared/llm/providers/openrouter.js +1 -1
  663. package/dist/shared/llm/router/config-store.d.ts +14 -0
  664. package/dist/shared/llm/router/config-store.js +102 -14
  665. package/dist/shared/llm/router/external-provider-config.d.ts +47 -0
  666. package/dist/shared/llm/router/external-provider-config.js +105 -0
  667. package/dist/shared/llm/router/hybrid-router.js +7 -7
  668. package/dist/shared/llm/router/index.js +4 -4
  669. package/dist/shared/llm/router/routing-rules.js +1 -1
  670. package/dist/shared/llm/router/types.d.ts +50 -4
  671. package/dist/shared/llm/router/types.js +10 -0
  672. package/dist/shared/llm/translation/index.js +3 -3
  673. package/dist/shared/llm/translation/message-formatter.js +7 -1
  674. package/dist/shared/llm/translation/prompt-translator.js +2 -2
  675. package/dist/shared/metrics/code-metrics.js +2 -2
  676. package/dist/shared/metrics/index.js +2 -2
  677. package/dist/shared/parsers/index.js +3 -3
  678. package/dist/shared/security/compliance-patterns.js +1 -1
  679. package/dist/shared/security/index.js +8 -8
  680. package/dist/shared/security/osv-client.js +1 -1
  681. package/dist/test-scheduling/index.js +9 -9
  682. package/dist/test-scheduling/phase-scheduler.js +1 -1
  683. package/dist/test-scheduling/pipeline.js +9 -9
  684. package/dist/validation/provider-llm-executor.js +5 -5
  685. package/dist/workers/daemon.js +3 -3
  686. package/dist/workers/index.js +5 -5
  687. package/dist/workers/quality-daemon/index.js +15 -15
  688. package/dist/workers/workers/compliance-checker.js +2 -2
  689. package/dist/workers/workers/coverage-tracker.js +1 -1
  690. package/dist/workers/workers/defect-predictor.js +1 -1
  691. package/dist/workers/workers/flaky-detector.js +1 -1
  692. package/dist/workers/workers/learning-consolidation.js +4 -4
  693. package/dist/workers/workers/performance-baseline.js +1 -1
  694. package/dist/workers/workers/quality-gate.js +1 -1
  695. package/dist/workers/workers/regression-monitor.js +1 -1
  696. package/dist/workers/workers/security-scan.js +1 -1
  697. package/dist/workers/workers/test-health.js +1 -1
  698. package/dist/workflows/browser/index.js +1 -1
  699. package/package.json +8 -3
  700. package/dist/cli/chunks/adapter-6CNMDJVJ.js +0 -2
  701. package/dist/cli/chunks/aqe-learning-engine-JGHHNSFX.js +0 -2
  702. package/dist/cli/chunks/base-ND3KAA2L.js +0 -2
  703. package/dist/cli/chunks/browser-workflow-EBSNGTSH.js +0 -2
  704. package/dist/cli/chunks/chunk-3I5ZTLFY.js +0 -2
  705. package/dist/cli/chunks/chunk-4EWKERKV.js +0 -3
  706. package/dist/cli/chunks/chunk-4NXABNLF.js +0 -2
  707. package/dist/cli/chunks/chunk-A6V5NZCV.js +0 -21
  708. package/dist/cli/chunks/chunk-QR6NVCRT.js +0 -12
  709. package/dist/cli/chunks/chunk-TL5FMEKW.js +0 -2
  710. package/dist/cli/chunks/chunk-XPUPST5T.js +0 -2
  711. package/dist/cli/chunks/client-NEGGUFEM.js +0 -2
  712. package/dist/cli/chunks/core-handlers-Q2XPFYQ5.js +0 -2
  713. package/dist/cli/chunks/cross-domain-router-WNZMUQ3G.js +0 -2
  714. package/dist/cli/chunks/dream-OL5XLAYS.js +0 -2
  715. package/dist/cli/chunks/heartbeat-scheduler-XUAW3I3Q.js +0 -2
  716. package/dist/cli/chunks/hnsw-adapter-EDK2YUZJ.js +0 -2
  717. package/dist/cli/chunks/hnsw-index-RDMT66NM.js +0 -2
  718. package/dist/cli/chunks/hybrid-router-BALMPXND.js +0 -2
  719. package/dist/cli/chunks/impact-analyzer-P6XLP3QX.js +0 -2
  720. package/dist/cli/chunks/init-wizard-HMU5OPKQ.js +0 -2
  721. package/dist/cli/chunks/kernel-HMSENQ6R.js +0 -2
  722. package/dist/cli/chunks/knowledge-graph-G7W72UC5.js +0 -2
  723. package/dist/cli/chunks/llm-router-XCBGZRKA.js +0 -36
  724. package/dist/cli/chunks/llm-router-service-VCM7LAGO.js +0 -2
  725. package/dist/cli/chunks/load-test-H5FATYS2.js +0 -2
  726. package/dist/cli/chunks/memory-backend-OPHD5UCR.js +0 -2
  727. package/dist/cli/chunks/memory-handlers-EA5UFT4G.js +0 -2
  728. package/dist/cli/chunks/pattern-null-store-XJOXEDQO.js +0 -2
  729. package/dist/cli/chunks/protocol-executor-XVN7GTLL.js +0 -2
  730. package/dist/cli/chunks/provider-manager-NQICCJZZ.js +0 -2
  731. package/dist/cli/chunks/qe-reasoning-bank-SVCH233Z.js +0 -2
  732. package/dist/cli/chunks/queen-coordinator-Z3PBE4EH.js +0 -2
  733. package/dist/cli/chunks/router-HMWZW2SF.js +0 -2
  734. package/dist/cli/chunks/routing-feedback-ZZYHE2CL.js +0 -2
  735. package/dist/cli/chunks/rvf-native-adapter-ZPT4RLBE.js +0 -2
  736. package/dist/cli/chunks/safe-db-VMYUKPV6.js +0 -2
  737. package/dist/cli/chunks/schedule-DOQ4X4MH.js +0 -2
  738. package/dist/cli/chunks/scheduler-FE2DH224.js +0 -2
  739. package/dist/cli/chunks/sqlite-persistence-TKCACSFQ.js +0 -2
  740. package/dist/cli/chunks/status-handler-UHY36LOR.js +0 -47
  741. package/dist/cli/chunks/unified-memory-2PA3CIQT.js +0 -2
  742. package/dist/cli/chunks/unified-memory-hnsw-W43H4ZKY.js +0 -2
  743. package/dist/cli/chunks/unified-persistence-SOW7AAZL.js +0 -2
  744. package/dist/cli/chunks/visual-security-R6BVIOYU.js +0 -2
  745. package/dist/cli/chunks/witness-chain-GSJW7VDF.js +0 -2
  746. package/dist/cli/chunks/workflow-orchestrator-TXEMI5DD.js +0 -2
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.10");process.exit(0)}
2
- import{d as J,e as B,f as te,g as j}from"./chunk-K6SXDKWV.js";import{a as ne}from"./chunk-YC5UJVV3.js";import{b as _e}from"./chunk-UHHWEWDA.js";import{a as ie}from"./chunk-7QNN4GQU.js";import{b as De,c as nt}from"./chunk-KQVTTP2S.js";import{a as re,b as Fe,d as Oe,f as it}from"./chunk-GSN4QIDI.js";import{c as Ie}from"./chunk-A233TTUX.js";import{b as P,c as w}from"./chunk-54RIPGMC.js";import{a as v,b as xe,c as Ce}from"./chunk-OLETDPH2.js";import{i as C}from"./chunk-4TSLLWE7.js";import{B as Q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-VUCCPPQ6.js";import{a as Te,d as $,f as rt}from"./chunk-W3DCBOLL.js";var G=$(E=>{var ft=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function ze(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)ue(n,s)&&r.push(s);return r}E._objectKeys=ze;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=ze(n),s=r.length,i=0;i<s;i++)if(le(n[r[i]]))return!0}}return!1}E.hasUndefined=le;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
3
- `)}var Pt=(function(n){ft(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=$(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,m=void 0;for(typeof t=="function"?m=t:m=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&m(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=wt[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}g.applyOperation=O;function $e(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}g.applyPatch=$e;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Y;function Je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$e(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof g.JsonPatchError)return s;throw s}}g.validate=Je;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var Be=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,s=At(n);if(!s)s=new Et(n),me.set(n,s);else{var i=Tt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?pe(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var je=$(I=>{var Ot=de();Object.assign(I,Ot);var It=Be();Object.assign(I,It);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});nt();Ce();var q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-TKCACSFQ.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,m=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],m+=d[S]*d[S];if(m=Math.sqrt(m),m===0)continue;let p=h/(o*m),y=this.calculateReuseInfo(f,p);i.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};it();Ce();F();function at(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Me=1e4,Le=2166136261;function ke(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var He="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=He[s>>4]+He[s&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=oe[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ke(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=lt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ut([r,s])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ke(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:ct(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=oe[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new ne(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ue(n){return new ae(n)}function Qe(n){return Q()?new se(n):null}var ye=rt(je(),1),ge=ye.default??ye,_t=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");process.exit(0)}
2
+ import{d as J,e as B,f as te,g as j}from"./chunk-YQOQVSYU.js";import{a as ne}from"./chunk-GMLRIZ4E.js";import{b as _e}from"./chunk-VNODKACB.js";import{a as ie}from"./chunk-2W3D5A4R.js";import{b as De,c as nt}from"./chunk-6KI6LAAZ.js";import{a as re,b as Fe,d as Oe,f as it}from"./chunk-HQWFZQMJ.js";import{c as Ie}from"./chunk-EDRPTLAX.js";import{b as P,c as w}from"./chunk-E67ZXRG6.js";import{a as v,b as xe,c as Ce}from"./chunk-L3GBNX7B.js";import{i as C}from"./chunk-52VGZJSD.js";import{B as Q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-AN5CGTTJ.js";import{a as Te,d as $,f as rt}from"./chunk-ZMYV4R32.js";var G=$(E=>{var ft=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function ze(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)ue(n,s)&&r.push(s);return r}E._objectKeys=ze;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=ze(n),s=r.length,i=0;i<s;i++)if(le(n[r[i]]))return!0}}return!1}E.hasUndefined=le;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
3
+ `)}var Pt=(function(n){ft(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=$(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,m=void 0;for(typeof t=="function"?m=t:m=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&m(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=wt[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}g.applyOperation=O;function $e(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}g.applyPatch=$e;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Y;function Je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$e(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof g.JsonPatchError)return s;throw s}}g.validate=Je;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var Be=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,s=At(n);if(!s)s=new Et(n),me.set(n,s);else{var i=Tt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?pe(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var je=$(I=>{var Ot=de();Object.assign(I,Ot);var It=Be();Object.assign(I,It);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});nt();Ce();var q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-HPEVCTIB.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,m=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],m+=d[S]*d[S];if(m=Math.sqrt(m),m===0)continue;let p=h/(o*m),y=this.calculateReuseInfo(f,p);i.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};it();Ce();F();function at(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Me=1e4,Le=2166136261;function ke(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var He="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=He[s>>4]+He[s&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=oe[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ke(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=lt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ut([r,s])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ke(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:ct(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=oe[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new ne(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ue(n){return new ae(n)}function Qe(n){return Q()?new se(n):null}var ye=rt(je(),1),ge=ye.default??ye,_t=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{d as J,e as B,f as te,g as j}from"./chunk-K6SXDKWV.js";import{a as ne}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,i)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ve=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return H()?new ve(n):null}F();var Mt=128,Lt=8,kt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ve(n){return new Pe(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ye=1-_;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),s=Math.max(_,1-A(e)),i=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(_,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),s=Math.sqrt(A(t));if(s<_)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ye)return new Float32Array(e);let r=Ye/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},we=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,m=new Float32Array(r);m[0]=d*Math.cos(h),m[1]=d*Math.sin(h);let p=i.get(u);if(p&&p.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*N}let y=T.project(m);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=s.get(u)??[];for(let N=0;N<S.length;N++){let x=f/Math.max(1,S.length);c.push({id:S[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ke(n){return zt()?new we(n):null}function zt(){return D().useHyperbolicHnsw}F();var Se=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ke(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ze(n){return new Se(n)}var be=null;function et(){return be||(be=Ue({dimensions:1e4})),be}var Ee;function $t(){return Ee===void 0&&(Ee=Qe()),Ee}var U=null,Re=0;function tt(n){return(!U||Re!==n)&&(U=Ve({dimension:n,maxPatterns:1e4}),Re=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ae=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-EQKXBLRX.js"),{HnswAdapter:c}=await import("./hnsw-adapter-EDK2YUZJ.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-RDMT66NM.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=et().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=$t();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{tt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=tt(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let m=h.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,h.similarity);i.push({pattern:p,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let m of h){let p=await this.get(m.key);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,m.score);i.push({pattern:p,score:m.score,matchType:"vector",similarity:m.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(p=>[p.id,p.ftsScore])),m=new Set(i.map(p=>p.pattern.id));for(let p of i){let y=h.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of d){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);i.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(m=>m.pattern.id));for(let m of d)h.has(m.pattern.id)||i.push(m)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),m=c-h,p=Math.pow(.5,m/a),y=d.pattern.usageCount>0?p:.5;d.score=d.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ie(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let m=d.get(h.pattern.id);m&&(h.nullSummary=m,h.score=ie.applyNullDiscount(h.score,m,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&i&&this.hdcCache.size>0)try{let u=et(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,m)=>m.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),m=o?f*.4+d*.4+h*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(H()&&this.deltaTracker)try{let y={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=te(h);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Re=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ze({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Jr(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Te("fs"),{join:s}=Te("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let l=_e(a,u.embeddingDimension);if(l){o=!0;let f=new q(()=>l,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),f}}catch{}if(!o){let l=new q((f,d)=>{let h=()=>{try{return Fe(f)}catch{return null}},m=h();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return re(f,d)}catch(p){if(m=h(),m&&m.dimension()===d)return m;if(Ie(f,p instanceof Error?p.message:String(p)))return re(f,d);throw p}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ae(n,e)}export{Jr as a};
49
+ )`).run(e,e,i)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ve=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return H()?new ve(n):null}F();var Mt=128,Lt=8,kt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ve(n){return new Pe(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ye=1-_;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),s=Math.max(_,1-A(e)),i=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(_,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),s=Math.sqrt(A(t));if(s<_)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ye)return new Float32Array(e);let r=Ye/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},we=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,m=new Float32Array(r);m[0]=d*Math.cos(h),m[1]=d*Math.sin(h);let p=i.get(u);if(p&&p.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*N}let y=T.project(m);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=s.get(u)??[];for(let N=0;N<S.length;N++){let x=f/Math.max(1,S.length);c.push({id:S[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ke(n){return zt()?new we(n):null}function zt(){return D().useHyperbolicHnsw}F();var Se=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ke(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ze(n){return new Se(n)}var be=null;function et(){return be||(be=Ue({dimensions:1e4})),be}var Ee;function $t(){return Ee===void 0&&(Ee=Qe()),Ee}var U=null,Re=0;function tt(n){return(!U||Re!==n)&&(U=Ve({dimension:n,maxPatterns:1e4}),Re=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ae=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-NDZSNMYX.js"),{HnswAdapter:c}=await import("./hnsw-adapter-7QOBHKRB.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-6WUKYJH7.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=et().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=$t();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{tt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=tt(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let m=h.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,h.similarity);i.push({pattern:p,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let m of h){let p=await this.get(m.key);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,m.score);i.push({pattern:p,score:m.score,matchType:"vector",similarity:m.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(p=>[p.id,p.ftsScore])),m=new Set(i.map(p=>p.pattern.id));for(let p of i){let y=h.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of d){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);i.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(m=>m.pattern.id));for(let m of d)h.has(m.pattern.id)||i.push(m)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),m=c-h,p=Math.pow(.5,m/a),y=d.pattern.usageCount>0?p:.5;d.score=d.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ie(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let m=d.get(h.pattern.id);m&&(h.nullSummary=m,h.score=ie.applyNullDiscount(h.score,m,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&i&&this.hdcCache.size>0)try{let u=et(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,m)=>m.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),m=o?f*.4+d*.4+h*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(H()&&this.deltaTracker)try{let y={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=te(h);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Re=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ze({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Jr(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Te("fs"),{join:s}=Te("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let l=_e(a,u.embeddingDimension);if(l){o=!0;let f=new q(()=>l,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),f}}catch{}if(!o){let l=new q((f,d)=>{let h=()=>{try{return Fe(f)}catch{return null}},m=h();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return re(f,d)}catch(p){if(m=h(),m&&m.dimension()===d)return m;if(Ie(f,p instanceof Error?p.message:String(p)))return re(f,d);throw p}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ae(n,e)}export{Jr as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.10");process.exit(0)}
2
- import{a as K}from"./chunk-2E35LWYJ.js";import{a as D,b as _,c as H,d as M}from"./chunk-EZY3DAIX.js";import{c as Y,d as J,e as Z,f as ee}from"./chunk-HEY2ZRL7.js";import{b as C,f as U,i as $}from"./chunk-K6SXDKWV.js";import{g as k}from"./chunk-4PRQMFVO.js";import{d as X}from"./chunk-7GZJMPTD.js";import{i as j,m as de}from"./chunk-37GWETSW.js";import{a as B}from"./chunk-TL5FMEKW.js";import{c as T}from"./chunk-DR4V75BF.js";import{b as q,c as E}from"./chunk-54RIPGMC.js";import{a as f,b as W,c as z}from"./chunk-OLETDPH2.js";import{S as pe,b as G}from"./chunk-VUCCPPQ6.js";B();z();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var A=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");process.exit(0)}
2
+ import{a as K}from"./chunk-TK5XLF3Z.js";import{a as D,b as _,c as H,d as M,f as te}from"./chunk-4M7YZ2X7.js";import{c as Y,d as J,e as Z,f as ee}from"./chunk-44NPKZGI.js";import{b as C,f as U,i as $}from"./chunk-YQOQVSYU.js";import{g as k}from"./chunk-UWZYXI3R.js";import{d as X}from"./chunk-S6WHYOWV.js";import{i as j,m as me}from"./chunk-M73KM3AZ.js";import{a as B}from"./chunk-GEQWCK4F.js";import{c as T}from"./chunk-IOJ34SXJ.js";import{b as q,c as E}from"./chunk-E67ZXRG6.js";import{a as f,b as W,c as z}from"./chunk-L3GBNX7B.js";import{S as de,b as G}from"./chunk-AN5CGTTJ.js";B();z();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var A=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -278,7 +278,7 @@ On promotion:
278
278
  - Move from short-term to long-term tier
279
279
  - Boost confidence by 10%
280
280
  - Enable for cross-domain transfer to related domains
281
- - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as te}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},me=.4,ge=20,he=3;function fe(n){return 1/(1+Math.exp(-n))}function ye(n,e){if(!e||e.visits===0)return{score:n,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/ge,1)*me,t=fe(e.qValue);return{score:n*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function re(n){let e=n.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,i=n.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*i,0),1),baseEpsilon:t,safetyMultiplier:i}}function ne(n,e){if(e<=0||n.length<2)return;let r=Math.round(e*1e6);if(r<=0||te(0,1e6)>=r)return;let t=Math.min(4,n.length),i=te(1,t),o=n[i];n[i]=n[0],n[0]=o,n[0].exploration=!0,n[0].reasoning=[...n[0].reasoning,"(exploration)"]}function ie(n){let e=n.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function ae(n){return`${n.taskType}|${n.priority??"normal"}|${n.domain??"any"}`}function I(n,e,r,t,i=x,o,s){let a=[];for(let[c,u]of Object.entries(i)){let l=0,p=[],m=n.filter(d=>u.domains.includes(d)).length,y=Math.min(n.length,he),b=m>0?Math.min(m/y,1)*.4:0;if(l+=b*t.similarity,b>0&&p.push(`Domain match: ${(b*100).toFixed(0)}%`),e&&e.length>0){let d=e.filter(R=>u.capabilities.some(P=>P.toLowerCase().includes(R.toLowerCase()))).length,g=d>0?d/e.length*.3:0;l+=g*t.capabilities,g>0&&p.push(`Capability match: ${(g*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=u.performanceScore*.3*t.performance,p.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),o&&u.languages&&u.languages.length>0){let d=t.language??1,g=o.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===g)){let P=.15*d;l+=P,p.push(`Language match: ${o}`)}}let w=r.get(c)||0;if(w>0){let d=Math.min(.1,w*.02);l+=d,p.push(`Pattern matches: ${w}`)}let S=l;if(s){let d=s(c),g=ye(S,d);l=g.score,g.qWeight>0&&p.push(`Q-bonus (w=${g.qWeight.toFixed(2)}, v=${g.qVisits})`),a.push({agent:c,score:l,reasoning:p,staticScore:S,qWeight:g.qWeight,qValue:g.qValue,qVisits:g.qVisits})}else a.push({agent:c,score:l,reasoning:p,staticScore:S})}return a.sort((c,u)=>u.score-c.score),a}var O={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function oe(){try{return!ee()||!Z()||Y().getVerticesByType("agent").length===0?!1:J().isCritical()}catch{return!1}}de();function se(n,e){if(n.length===e)return n;if(n.length>e){let r=n.length/e,t=new Array(e).fill(0);for(let i=0;i<e;i++){let o=Math.floor(i*r),s=Math.floor((i+1)*r),a=0;for(let c=o;c<s;c++)a+=n[c];t[i]=a/(s-o)}return Q(t)}else{let r=new Array(e).fill(0),t=(n.length-1)/(e-1);for(let i=0;i<e;i++){let o=i*t,s=Math.floor(o),a=Math.min(s+1,n.length-1),c=o-s;r[i]=n[s]*(1-c)+n[a]*c}return Q(r)}}function ce(n,e){let r=new Array(e).fill(0),t=n.toLowerCase().trim();for(let i=0;i<3;i++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(i+1)%e;r[a]+=Math.sin(s*(i+1))/(o+1)}return Q(r)}function Q(n){let e=Math.sqrt(n.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<n.length;r++)n[r]/=e;return n}B();z();pe();var v=T.create("PatternPromotion");async function le(n,e){let r=U(n);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],n].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:n.id,patternName:n.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${n.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),v.info("Pattern promotion blocked due to coherence violation",{name:n.name,energy:a.energy}),!1}}return!0}async function L(n,e){let r=await e.patternStore.promote(n);if(r.success){try{e.getSqliteStore().promotePattern(n)}catch(t){v.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(G().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let i=new F(t),o=await e.getPattern(n);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==n&&i.recordCoOccurrence(n,a.id)}}}catch(t){v.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(n);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(n,t.embedding)}catch(t){v.warn("RVF dual-write on promote failed (non-fatal)",{patternId:n,error:f(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:n},"reasoning-bank")).catch(t=>{v.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),v.info("Promoted pattern to long-term",{patternId:n}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${n}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:n,newTier:"long-term"}}),r}else return v.error("Failed to promote pattern",r.error,{patternId:n}),r}async function ue(n){let{signal:e}=n;e?.throwIfAborted();let r=await n.patternStore.getStats(),t=0,i=0;for(let[o,s]of Object.entries(O)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let u=await n.searchPatterns("",{domain:a,limit:50});if(u.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){i++;continue}for(let{pattern:m}of u.value){e?.throwIfAborted();let y=await n.searchPatterns(m.name,{domain:l,limit:1});if(y.success&&y.value.length>0&&y.value[0].score>.8){i++;continue}let b=Math.max(.3,(m.confidence||.5)*.8);(await n.storePattern({patternType:m.patternType,qeDomain:l,name:`${m.name} (from ${a})`,description:`${m.description} [Transferred from ${a} domain]`,template:m.template,context:{...m.context,relatedDomains:[a,l],tags:[...m.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:b})).success?t++:i++}}}return v.info("Cross-domain transfer complete",{transferred:t,skipped:i}),{transferred:t,skipped:i}}var be=`
281
+ - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as re}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},ge=.4,he=20,fe=3;function ye(n){return 1/(1+Math.exp(-n))}function be(n,e){if(!e||e.visits===0)return{score:n,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/he,1)*ge,t=ye(e.qValue);return{score:n*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function ne(n){let e=n.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,i=n.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*i,0),1),baseEpsilon:t,safetyMultiplier:i}}function ie(n,e){if(e<=0||n.length<2)return;let r=Math.round(e*1e6);if(r<=0||re(0,1e6)>=r)return;let t=Math.min(4,n.length),i=re(1,t),o=n[i];n[i]=n[0],n[0]=o,n[0].exploration=!0,n[0].reasoning=[...n[0].reasoning,"(exploration)"]}function ae(n){let e=n.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function oe(n){return`${n.taskType}|${n.priority??"normal"}|${n.domain??"any"}`}function I(n,e,r,t,i=x,o,s){let a=[];for(let[c,u]of Object.entries(i)){let l=0,p=[],m=n.filter(d=>u.domains.includes(d)).length,y=Math.min(n.length,fe),b=m>0?Math.min(m/y,1)*.4:0;if(l+=b*t.similarity,b>0&&p.push(`Domain match: ${(b*100).toFixed(0)}%`),e&&e.length>0){let d=e.filter(R=>u.capabilities.some(P=>P.toLowerCase().includes(R.toLowerCase()))).length,g=d>0?d/e.length*.3:0;l+=g*t.capabilities,g>0&&p.push(`Capability match: ${(g*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=u.performanceScore*.3*t.performance,p.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),o&&u.languages&&u.languages.length>0){let d=t.language??1,g=o.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===g)){let P=.15*d;l+=P,p.push(`Language match: ${o}`)}}let w=r.get(c)||0;if(w>0){let d=Math.min(.1,w*.02);l+=d,p.push(`Pattern matches: ${w}`)}let S=l;if(s){let d=s(c),g=be(S,d);l=g.score,g.qWeight>0&&p.push(`Q-bonus (w=${g.qWeight.toFixed(2)}, v=${g.qVisits})`),a.push({agent:c,score:l,reasoning:p,staticScore:S,qWeight:g.qWeight,qValue:g.qValue,qVisits:g.qVisits})}else a.push({agent:c,score:l,reasoning:p,staticScore:S})}return a.sort((c,u)=>u.score-c.score),a}var O={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function se(){try{return!ee()||!Z()||Y().getVerticesByType("agent").length===0?!1:J().isCritical()}catch{return!1}}me();function ce(n,e){if(n.length===e)return n;if(n.length>e){let r=n.length/e,t=new Array(e).fill(0);for(let i=0;i<e;i++){let o=Math.floor(i*r),s=Math.floor((i+1)*r),a=0;for(let c=o;c<s;c++)a+=n[c];t[i]=a/(s-o)}return Q(t)}else{let r=new Array(e).fill(0),t=(n.length-1)/(e-1);for(let i=0;i<e;i++){let o=i*t,s=Math.floor(o),a=Math.min(s+1,n.length-1),c=o-s;r[i]=n[s]*(1-c)+n[a]*c}return Q(r)}}function le(n,e){let r=new Array(e).fill(0),t=n.toLowerCase().trim();for(let i=0;i<3;i++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(i+1)%e;r[a]+=Math.sin(s*(i+1))/(o+1)}return Q(r)}function Q(n){let e=Math.sqrt(n.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<n.length;r++)n[r]/=e;return n}B();z();de();var v=T.create("PatternPromotion");async function ue(n,e){let r=U(n);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],n].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:n.id,patternName:n.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${n.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),v.info("Pattern promotion blocked due to coherence violation",{name:n.name,energy:a.energy}),!1}}return!0}async function L(n,e){let r=await e.patternStore.promote(n);if(r.success){try{e.getSqliteStore().promotePattern(n)}catch(t){v.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(G().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let i=new F(t),o=await e.getPattern(n);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==n&&i.recordCoOccurrence(n,a.id)}}}catch(t){v.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(n);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(n,t.embedding)}catch(t){v.warn("RVF dual-write on promote failed (non-fatal)",{patternId:n,error:f(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:n},"reasoning-bank")).catch(t=>{v.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),v.info("Promoted pattern to long-term",{patternId:n}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${n}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:n,newTier:"long-term"}}),r}else return v.error("Failed to promote pattern",r.error,{patternId:n}),r}async function pe(n){let{signal:e}=n;e?.throwIfAborted();let r=await n.patternStore.getStats(),t=0,i=0;for(let[o,s]of Object.entries(O)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let u=await n.searchPatterns("",{domain:a,limit:50});if(u.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){i++;continue}for(let{pattern:m}of u.value){e?.throwIfAborted();let y=await n.searchPatterns(m.name,{domain:l,limit:1});if(y.success&&y.value.length>0&&y.value[0].score>.8){i++;continue}let b=Math.max(.3,(m.confidence||.5)*.8);(await n.storePattern({patternType:m.patternType,qeDomain:l,name:`${m.name} (from ${a})`,description:`${m.description} [Transferred from ${a} domain]`,template:m.template,context:{...m.context,relatedDomains:[a,l],tags:[...m.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:b})).success?t++:i++}}}return v.info("Cross-domain transfer complete",{transferred:t,skipped:i}),{transferred:t,skipped:i}}var ve=`
282
282
  CREATE TABLE IF NOT EXISTS pattern_citations (
283
283
  source_pattern_id TEXT NOT NULL,
284
284
  target_pattern_id TEXT NOT NULL,
@@ -289,7 +289,7 @@ On promotion:
289
289
  );
290
290
  CREATE INDEX IF NOT EXISTS idx_citations_source ON pattern_citations(source_pattern_id);
291
291
  CREATE INDEX IF NOT EXISTS idx_citations_target ON pattern_citations(target_pattern_id);
292
- `,F=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(be),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,i]=e<r?[e,r]:[r,e];this.db.prepare(`
292
+ `,F=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(ve),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,i]=e<r?[e,r]:[r,e];this.db.prepare(`
293
293
  INSERT INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
294
294
  VALUES (?, ?, 1.0, 'co-occurrence')
295
295
  ON CONFLICT(source_pattern_id, target_pattern_id)
@@ -311,10 +311,10 @@ On promotion:
311
311
  `).all(),c=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let u of a)c.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var h=T.create("QEReasoningBank"),V=class{constructor(e,r,t={},i){this.memory=e;this.eventBus=r;this.coherenceService=i;this.config={...N,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=K(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=X(),this.sqliteStore.initialize().catch(e=>{h.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){h.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();h.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;h.warn("Cross-domain seeding failed (non-fatal)",{error:t})}h.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){h.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let i=(()=>{let a=process.env.AQE_RVF_BACKFILL_LIMIT,c=a?Number(a):NaN;return Number.isFinite(c)&&c>0?Math.floor(c):1e3})(),s=this.getSqliteStore().getRecentEmbeddings(i).filter(({embedding:a})=>a&&a.length>0).map(({patternId:a,embedding:c})=>({id:a,vector:c instanceof Float32Array?c:new Float32Array(c)}));if(s.length>0){let{accepted:a,rejected:c}=t.ingest(s);h.info("Backfilled RVF from SQLite",{requested:s.length,accepted:a,cap:i,truncated:s.length>=i}),c>0&&h.warn("RVF backfill partially rejected",{accepted:a,rejected:c})}}catch(i){h.warn("RVF backfill failed (non-fatal)",{error:f(i)})}return}for(let t of A){e?.throwIfAborted();try{await this.storePattern(t)}catch(i){if(e?.aborted)throw i;h.warn("Failed to load pattern",{name:t.name,error:i})}}h.info("Loaded foundational patterns",{count:A.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),ue({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(k().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{h.warn("Witness chain PATTERN_CREATE failed",{error:f(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){h.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:f(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,i=!0;return typeof e=="string"&&(e.trim()===""?(i=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:i})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return q(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{h.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let t=await this.getPattern(e.patternId),i=this.getPromotionDeps();t&&await le(t,i)&&(await L(e.patternId,i),h.info("Pattern promoted to long-term",{name:t.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?L(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:C(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),i=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),o=i.success?i.value.map(d=>d.pattern):[],s=new Map;for(let[d,g]of Object.entries(x)){let R=o.filter(P=>g.domains.includes(P.qeDomain)).length;R>0&&s.set(d,R)}let a=ae({taskType:ie(e.task),priority:"normal",domain:r[0]}),c=this.buildQValueLookup(a),u=I(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,c),l=1;try{let d=oe(),g=re({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:d});l=g.safetyMultiplier,ne(u,g.epsilon)}catch{}let p=u[0],m=u.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let d=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=p.score;let b=u.reduce((d,g)=>d+(g.qWeight??0),0),w=u.length>0?b/u.length:0,S={recommendedAgent:p.agent,confidence:p.score,alternatives:m.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:o,guidance:y,reasoning:p.reasoning.join("; "),exploration:p.exploration===!0,criticality:l,qWeight:w};return q(S)}catch(r){return E(W(r))}}buildQValueLookup(e){try{let r=j();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
314
+ `);for(let u of a)c.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var h=T.create("QEReasoningBank"),V=class{constructor(e,r,t={},i){this.memory=e;this.eventBus=r;this.coherenceService=i;this.config={...N,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=K(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=X(),this.sqliteStore.initialize().catch(e=>{h.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){h.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();h.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;h.warn("Cross-domain seeding failed (non-fatal)",{error:t})}h.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){h.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let i=(()=>{let a=process.env.AQE_RVF_BACKFILL_LIMIT,c=a?Number(a):NaN;return Number.isFinite(c)&&c>0?Math.floor(c):1e3})(),s=this.getSqliteStore().getRecentEmbeddings(i).filter(({embedding:a})=>a&&a.length>0).map(({patternId:a,embedding:c})=>({id:a,vector:c instanceof Float32Array?c:new Float32Array(c)}));if(s.length>0){let{accepted:a,rejected:c}=t.ingest(s);h.info("Backfilled RVF from SQLite",{requested:s.length,accepted:a,cap:i,truncated:s.length>=i}),c>0&&h.warn("RVF backfill partially rejected",{accepted:a,rejected:c})}}catch(i){h.warn("RVF backfill failed (non-fatal)",{error:f(i)})}return}for(let t of A){e?.throwIfAborted();try{await this.storePattern(t)}catch(i){if(e?.aborted)throw i;h.warn("Failed to load pattern",{name:t.name,error:i})}}h.info("Loaded foundational patterns",{count:A.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),pe({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(k().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{h.warn("Witness chain PATTERN_CREATE failed",{error:f(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){h.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:f(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,i=!0;return typeof e=="string"&&(e.trim()===""?(i=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:i})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return q(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{h.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let t=await this.getPattern(e.patternId),i=this.getPromotionDeps();t&&await ue(t,i)&&(await L(e.patternId,i),h.info("Pattern promoted to long-term",{name:t.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?L(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:C(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),i=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),o=i.success?i.value.map(d=>d.pattern):[],s=new Map;for(let[d,g]of Object.entries(x)){let R=o.filter(P=>g.domains.includes(P.qeDomain)).length;R>0&&s.set(d,R)}let a=oe({taskType:ae(e.task),priority:"normal",domain:r[0]}),c=this.buildQValueLookup(a),u=I(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,c),l=1;try{let d=se(),g=ne({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:d});l=g.safetyMultiplier,ie(u,g.epsilon)}catch{}let p=u[0],m=u.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let d=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=p.score;let b=u.reduce((d,g)=>d+(g.qWeight??0),0),w=u.length>0?b/u.length:0,S={recommendedAgent:p.agent,confidence:p.score,alternatives:m.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:o,guidance:y,reasoning:p.reasoning.join("; "),exploration:p.exploration===!0,criticality:l,qWeight:w};return q(te(e.includePatternGuidance,S,i.success?i.value:[]))}catch(r){return E(W(r))}}buildQValueLookup(e){try{let r=j();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
315
315
  SELECT q_value, visits FROM rl_q_values
316
316
  WHERE algorithm = 'q-learning'
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return H(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-4AKAVZIY.js"),t=await r(e);return t.length!==this.config.embeddingDimension?se(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-4AKAVZIY.js");if(t())throw r;process.env.DEBUG&&h.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return ce(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of $)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,i=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function yt(n,e,r,t){return new V(n,e,r,t)}export{N as a,A as b,x as c,ie as d,I as e,O as f,V as g,yt as h};
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return H(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-ZBF5EQOG.js"),t=await r(e);return t.length!==this.config.embeddingDimension?ce(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-ZBF5EQOG.js");if(t())throw r;process.env.DEBUG&&h.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return le(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of $)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,i=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function vt(n,e,r,t){return new V(n,e,r,t)}export{N as a,A as b,x as c,ae as d,I as e,O as f,V as g,vt as h};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.10");process.exit(0)}
2
- import{c as T}from"./chunk-W3DCBOLL.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.12");process.exit(0)}
2
+ import{c as T}from"./chunk-ZMYV4R32.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
@@ -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.13.10");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.13.12");process.exit(0)}
2
2
  import*as h from"fs";import*as M from"path";var S=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function x(s){for(let v of S){let i=M.join(s,v);if(h.existsSync(i))try{let n=JSON.parse(h.readFileSync(i,"utf-8"));if(n.total&&n.total.lines)return L(n,s);let o=new Map;for(let[r,C]of Object.entries(n)){let c=C,g=Object.keys(c.s),u=g.filter(a=>c.s[a]>0).length,b=Object.keys(c.b),p=0,m=0;for(let a of b)for(let y of c.b[a])p++,y>0&&m++;let e=Object.keys(c.f),t=e.filter(a=>c.f[a]>0).length,f=new Set,d=new Set;for(let a of g){let y=c.statementMap[a];for(let F=y.start.line;F<=y.end.line;F++)d.add(F),c.s[a]>0&&f.add(F)}let l=[...d].filter(a=>!f.has(a)).sort((a,y)=>a-y);o.set(r,{path:r,lines:{covered:f.size,total:d.size},branches:{covered:m,total:p},functions:{covered:t,total:e.length},statements:{covered:u,total:g.length},uncoveredLines:l,uncoveredBranches:l.slice(0,Math.floor(l.length/2))})}return o.size>0?o:null}catch{continue}}return null}function L(s,v){let i=new Map;for(let[n,o]of Object.entries(s)){if(n==="total")continue;let r=o;i.set(n,{path:n,lines:{covered:r.lines.covered,total:r.lines.total},branches:{covered:r.branches.covered,total:r.branches.total},functions:{covered:r.functions.covered,total:r.functions.total},statements:{covered:r.statements.covered,total:r.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return i.size>0?i:null}function B(s,v){let n=v.split(`
3
3
  `).length,r=[s.replace(".ts",".test.ts").replace("/src/","/tests/"),s.replace(".ts",".spec.ts").replace("/src/","/tests/"),s.replace(".ts",".test.ts"),s.replace("/src/","/test/").replace(".ts",".test.ts")].some(d=>h.existsSync(d)),C=(v.match(/\bexport\b/g)||[]).length,c=(v.match(/\b(function|=>)\b/g)||[]).length,g=(v.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,u;if(r){let d=Math.min(g*.005,.15),l=Math.min(n*1e-4,.1);u=.85-d-l}else u=.2+(C>5?.1:0);u=Math.max(.05,Math.min(.95,u));let b=Math.floor(n*u),p=Math.max(c,1),m=Math.max(g,1),e=Math.floor(b*.7),t=Math.floor(p*u*.9),f=Array.from({length:n-b},(d,l)=>l+b+1);return{path:s,lines:{covered:b,total:n},branches:{covered:Math.min(e,m),total:m},functions:{covered:Math.min(t,p),total:p},statements:{covered:b,total:n},uncoveredLines:f,uncoveredBranches:f.slice(0,Math.floor(f.length/2))}}function j(s,v){let i=v||process.cwd(),n=x(i),o=[],r=!1;if(n&&n.size>0){r=!0;for(let e of s){let t=M.resolve(e),f=n.get(t)||n.get(e)||n.get(M.relative(i,t));if(f)o.push({...f,path:e});else{let l=(h.existsSync(e)?h.readFileSync(e,"utf-8"):"").split(`
4
4
  `).length;o.push({path:e,lines:{covered:0,total:l},branches:{covered:0,total:1},functions:{covered:0,total:1},statements:{covered:0,total:l},uncoveredLines:Array.from({length:l},(a,y)=>y+1),uncoveredBranches:[]})}}}else for(let e of s){let t=h.existsSync(e)?h.readFileSync(e,"utf-8"):"";o.push(B(e,t))}let C=o.reduce((e,t)=>e+t.lines.total,0),c=o.reduce((e,t)=>e+t.lines.covered,0),g=o.reduce((e,t)=>e+t.branches.total,0),u=o.reduce((e,t)=>e+t.branches.covered,0),b=o.reduce((e,t)=>e+t.functions.total,0),p=o.reduce((e,t)=>e+t.functions.covered,0),m=(e,t)=>t>0?Math.round(e/t*100):0;return{files:o,summary:{line:m(c,C),branch:m(u,g),function:m(p,b),statement:m(c,C),files:o.length},instrumented:r}}export{j as a};