agentic-qe 3.14.8 → 3.15.1

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 (375) hide show
  1. package/.claude/skills/release/SKILL.md +6 -0
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +189 -0
  4. package/README.md +143 -366
  5. package/assets/readme/credit-ruflo.svg +1 -0
  6. package/assets/readme/credit-ruvector.svg +1 -0
  7. package/assets/readme/project-header.svg +1 -0
  8. package/assets/readme/quality-loop.svg +1 -0
  9. package/assets/skills/skills-manifest.json +1 -1
  10. package/dist/adapters/a2a/notifications/retry-queue.js +5 -1
  11. package/dist/adapters/ag-ui/json-patch.js +14 -7
  12. package/dist/adapters/ag-ui/state-delta-cache.js +20 -12
  13. package/dist/cli/bundle.js +5 -5
  14. package/dist/cli/chunks/adapter-Q6RPGMUE.js +2 -0
  15. package/dist/cli/chunks/{agent-booster-wasm-67OKGDGZ.js → agent-booster-wasm-XUHRLKWP.js} +2 -2
  16. package/dist/cli/chunks/{agent-handler-4HZEQ3WQ.js → agent-handler-CL7MJP5W.js} +2 -2
  17. package/dist/cli/chunks/{agent-memory-branch-IBHZQSRN.js → agent-memory-branch-F7RV72FC.js} +2 -2
  18. package/dist/cli/chunks/aqe-learning-engine-JQPXIU7C.js +2 -0
  19. package/dist/cli/chunks/{arena-LCLRGUIK.js → arena-GRRNK7IN.js} +4 -4
  20. package/dist/cli/chunks/{arena-EJBIGSF4.js → arena-LHLVOQHW.js} +2 -2
  21. package/dist/cli/chunks/{audit-PY4JNDQQ.js → audit-EOP2K34L.js} +3 -3
  22. package/dist/cli/chunks/base-5SK64NXB.js +2 -0
  23. package/dist/cli/chunks/{better-sqlite3-2JG5K6XT.js → better-sqlite3-YERQ5DOL.js} +2 -2
  24. package/dist/cli/chunks/{brain-handler-3UYK55GA.js → brain-handler-FBXBM5XE.js} +3 -3
  25. package/dist/cli/chunks/{branch-enumerator-GOSWOX46.js → branch-enumerator-NWO6LNHB.js} +2 -2
  26. package/dist/cli/chunks/{browser-DC2JV47Z.js → browser-EDCG7TNF.js} +2 -2
  27. package/dist/cli/chunks/browser-workflow-WN7XNTCJ.js +2 -0
  28. package/dist/cli/chunks/{chunk-Z5UZOYQS.js → chunk-25IWHVMW.js} +2 -2
  29. package/dist/cli/chunks/chunk-27S47AYK.js +3 -0
  30. package/dist/cli/chunks/{chunk-SUNXA2UR.js → chunk-2IPBCXTT.js} +2 -2
  31. package/dist/cli/chunks/chunk-2K3QFLX2.js +2 -0
  32. package/dist/cli/chunks/{chunk-775WGWLL.js → chunk-35XRY6ZW.js} +2 -2
  33. package/dist/cli/chunks/{chunk-RTD4U7IW.js → chunk-3NOSMJS4.js} +2 -2
  34. package/dist/cli/chunks/{chunk-GVLRE3BV.js → chunk-3TZRJ5QD.js} +3 -3
  35. package/dist/cli/chunks/{chunk-RJJIPTVH.js → chunk-46DUU44C.js} +2 -2
  36. package/dist/cli/chunks/{chunk-H5UH234L.js → chunk-4AEFJEZH.js} +1 -1
  37. package/dist/cli/chunks/{chunk-EXQGHTPD.js → chunk-4KHSWNFW.js} +4 -4
  38. package/dist/cli/chunks/{chunk-CLUHGBLN.js → chunk-4KSCJ462.js} +1 -1
  39. package/dist/cli/chunks/{chunk-3EKG7HFV.js → chunk-4P7CGSRL.js} +3 -3
  40. package/dist/cli/chunks/{chunk-XFT4FYTC.js → chunk-4THIRDBL.js} +2 -2
  41. package/dist/cli/chunks/{chunk-7TNCEVWX.js → chunk-4XEZ562Q.js} +2 -2
  42. package/dist/cli/chunks/{chunk-CIEXUYY7.js → chunk-53C7TGC4.js} +1 -1
  43. package/dist/cli/chunks/{chunk-LQVS5IWH.js → chunk-53HWWWFZ.js} +2 -2
  44. package/dist/cli/chunks/{chunk-EMOZ5O5S.js → chunk-54JYUOSR.js} +1 -1
  45. package/dist/cli/chunks/{chunk-J24AJEDE.js → chunk-5B5TA3X4.js} +2 -2
  46. package/dist/cli/chunks/{chunk-BITFGVZ4.js → chunk-5C4UYXQL.js} +2 -2
  47. package/dist/cli/chunks/{chunk-F6JJNBE5.js → chunk-5JJWVFUV.js} +1 -1
  48. package/dist/cli/chunks/{chunk-M7QKCHLQ.js → chunk-5QEXDXHQ.js} +2 -2
  49. package/dist/cli/chunks/{chunk-I6NZFBT3.js → chunk-5TEDVUEB.js} +2 -2
  50. package/dist/cli/chunks/{chunk-673XJBGW.js → chunk-66HKJJFH.js} +2 -2
  51. package/dist/cli/chunks/{chunk-AR2S4DOB.js → chunk-6AVVC7Y3.js} +1 -1
  52. package/dist/cli/chunks/{chunk-EBV3WFIR.js → chunk-6DF6X3SZ.js} +2 -2
  53. package/dist/cli/chunks/{chunk-GHMJFICO.js → chunk-6MGJMGAD.js} +2 -2
  54. package/dist/cli/chunks/{chunk-XECZYQT5.js → chunk-6Q7PWKWV.js} +2 -2
  55. package/dist/cli/chunks/{chunk-VV2JVYOI.js → chunk-6U6JQS4Z.js} +2 -2
  56. package/dist/cli/chunks/{chunk-BHPTHC5O.js → chunk-6WW6A6JM.js} +2 -2
  57. package/dist/cli/chunks/{chunk-G3C7Z6FO.js → chunk-7B3XVVYP.js} +2 -2
  58. package/dist/cli/chunks/{chunk-J5HTQHJK.js → chunk-7FGSX4UD.js} +2 -2
  59. package/dist/cli/chunks/{chunk-YIWBJ637.js → chunk-A5LOELVV.js} +2 -2
  60. package/dist/cli/chunks/{chunk-VCSNNLWL.js → chunk-ADEYBXAS.js} +2 -2
  61. package/dist/cli/chunks/{chunk-A53MMSGC.js → chunk-ALLABEUK.js} +2 -2
  62. package/dist/cli/chunks/{chunk-HBAFXWSO.js → chunk-ARGMYSDY.js} +1 -1
  63. package/dist/cli/chunks/{chunk-HPVYJ6JH.js → chunk-ARWSPV2C.js} +2 -2
  64. package/dist/cli/chunks/{chunk-VSPNIDQK.js → chunk-AVOYMVD6.js} +2 -2
  65. package/dist/cli/chunks/{chunk-BUVJIVFG.js → chunk-B3DWOR5R.js} +1 -1
  66. package/dist/cli/chunks/{chunk-K6EOHGKS.js → chunk-BW7S6LIJ.js} +2 -2
  67. package/dist/cli/chunks/{chunk-4HXFPBAA.js → chunk-C3BW3Q27.js} +1 -1
  68. package/dist/cli/chunks/{chunk-JRK5GX56.js → chunk-CFZJEOCD.js} +1 -1
  69. package/dist/cli/chunks/{chunk-3S5IIK32.js → chunk-CHX65QXY.js} +1 -1
  70. package/dist/cli/chunks/{chunk-FRC7AFB4.js → chunk-CTK7NMSJ.js} +2 -2
  71. package/dist/cli/chunks/{chunk-RM6OC35G.js → chunk-CTLHNFPM.js} +1 -1
  72. package/dist/cli/chunks/{chunk-3576QGPP.js → chunk-D3LREV4P.js} +1 -1
  73. package/dist/cli/chunks/{chunk-TCQWVVSR.js → chunk-DKWB4ERY.js} +1 -1
  74. package/dist/cli/chunks/{chunk-JQAJUXRE.js → chunk-DREYYJ7A.js} +2 -2
  75. package/dist/cli/chunks/{chunk-OZJQN7YE.js → chunk-DV7I6CRH.js} +2 -2
  76. package/dist/cli/chunks/{chunk-AEYJ4ZLA.js → chunk-EQ3BJS37.js} +1 -1
  77. package/dist/cli/chunks/{chunk-KNSQWM2E.js → chunk-FIIHSEXP.js} +2 -2
  78. package/dist/cli/chunks/{chunk-LRGTPUJA.js → chunk-FQYXPSWD.js} +2 -2
  79. package/dist/cli/chunks/{chunk-QQVE65ER.js → chunk-FRGNM6SW.js} +2 -2
  80. package/dist/cli/chunks/{chunk-AOD2ES44.js → chunk-FTHXV7N7.js} +2 -2
  81. package/dist/cli/chunks/{chunk-DZHXCOSK.js → chunk-GAKVCN3C.js} +1 -1
  82. package/dist/cli/chunks/{chunk-LMAI74EP.js → chunk-GDSYJHVB.js} +1 -1
  83. package/dist/cli/chunks/{chunk-VAXTPLO3.js → chunk-GUHJWBPN.js} +2 -2
  84. package/dist/cli/chunks/{chunk-OX7MJFLC.js → chunk-GUKBN3BS.js} +2 -2
  85. package/dist/cli/chunks/{chunk-R6I5I724.js → chunk-HU4QGCIJ.js} +2 -2
  86. package/dist/cli/chunks/{chunk-LTHV4PIG.js → chunk-HVAYG54D.js} +2 -2
  87. package/dist/cli/chunks/{chunk-AJMAKUS3.js → chunk-IUGY6Z4Q.js} +2 -2
  88. package/dist/cli/chunks/{chunk-WFKE7NZ5.js → chunk-J2WALRWR.js} +2 -2
  89. package/dist/cli/chunks/{chunk-Z6G3QVZ4.js → chunk-J4ULR4QR.js} +19 -19
  90. package/dist/cli/chunks/{chunk-YHX74M7C.js → chunk-JEXPSOT2.js} +2 -2
  91. package/dist/cli/chunks/{chunk-25EEIAHS.js → chunk-JHKMUY4W.js} +2 -2
  92. package/dist/cli/chunks/{chunk-L5T32SRF.js → chunk-JQVECGYL.js} +1 -1
  93. package/dist/cli/chunks/{chunk-UHLZKH6B.js → chunk-JSHASVQ2.js} +25 -25
  94. package/dist/cli/chunks/{chunk-SPS472C5.js → chunk-JW2HNT3J.js} +2 -2
  95. package/dist/cli/chunks/{chunk-SMBGK7XI.js → chunk-JY6HWYC4.js} +1 -1
  96. package/dist/cli/chunks/{chunk-F57FTFWS.js → chunk-JYF3QF4C.js} +2 -2
  97. package/dist/cli/chunks/{chunk-CBWM5NOO.js → chunk-K4NB3MYN.js} +2 -2
  98. package/dist/cli/chunks/{chunk-LKFBW2QM.js → chunk-KBK4GBJQ.js} +2 -2
  99. package/dist/cli/chunks/{chunk-6F7MFHTY.js → chunk-KHVWIUAF.js} +2 -2
  100. package/dist/cli/chunks/{chunk-JDOVO4E4.js → chunk-KP6LNSDO.js} +126 -130
  101. package/dist/cli/chunks/{chunk-T53ZN4NO.js → chunk-KTBA2HJC.js} +2 -2
  102. package/dist/cli/chunks/{chunk-WVEHKAIH.js → chunk-L5GEWKR3.js} +3 -3
  103. package/dist/cli/chunks/chunk-LDDIYDIP.js +742 -0
  104. package/dist/cli/chunks/{chunk-QPACHVDI.js → chunk-LI7N45GM.js} +1 -1
  105. package/dist/cli/chunks/{chunk-UQGIC5OX.js → chunk-LQI5GVH7.js} +1 -1
  106. package/dist/cli/chunks/{chunk-T4WQPE77.js → chunk-MEOAKMKF.js} +1 -1
  107. package/dist/cli/chunks/{chunk-BT3MI2BW.js → chunk-N4HQ6FE2.js} +1 -1
  108. package/dist/cli/chunks/{chunk-JRLZ7LZ3.js → chunk-N5OSH5JO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-BZIPW2PA.js → chunk-NF6SLLE6.js} +2 -2
  110. package/dist/cli/chunks/{chunk-QYCZYJH7.js → chunk-NGDRSF6Y.js} +2 -2
  111. package/dist/cli/chunks/{chunk-O4QB2GFL.js → chunk-NK2BR4QZ.js} +2 -2
  112. package/dist/cli/chunks/{chunk-B2QKBQYD.js → chunk-NS4RIZ4F.js} +1 -1
  113. package/dist/cli/chunks/{chunk-CQEWL32R.js → chunk-NTLWHLAY.js} +1 -1
  114. package/dist/cli/chunks/{chunk-NWUFTLSF.js → chunk-NWNZMXNO.js} +2 -2
  115. package/dist/cli/chunks/{chunk-6GJWT2OY.js → chunk-OABFAREV.js} +2 -2
  116. package/dist/cli/chunks/{chunk-T7YCNOW5.js → chunk-OH4SKOAM.js} +2 -2
  117. package/dist/cli/chunks/{chunk-BL6273KR.js → chunk-OKS25EGZ.js} +3 -3
  118. package/dist/cli/chunks/{chunk-NJEEKYEP.js → chunk-OPBPFNBO.js} +2 -2
  119. package/dist/cli/chunks/{chunk-SKJQKOFJ.js → chunk-P24ZBDZY.js} +2 -2
  120. package/dist/cli/chunks/{chunk-KKXH25IH.js → chunk-PBWR2SKH.js} +2 -2
  121. package/dist/cli/chunks/{chunk-TGRHO4ES.js → chunk-PDLVO3ZR.js} +2 -2
  122. package/dist/cli/chunks/{chunk-GK5WLUX3.js → chunk-PGARKOE6.js} +1 -1
  123. package/dist/cli/chunks/{chunk-XAESN54Q.js → chunk-PNK5KHSI.js} +1 -1
  124. package/dist/cli/chunks/{chunk-BFIXUKOR.js → chunk-PZBYZV5M.js} +1 -1
  125. package/dist/cli/chunks/{chunk-EKO5QL2B.js → chunk-PZDI7WQ3.js} +1 -1
  126. package/dist/cli/chunks/{chunk-BCCSV3RH.js → chunk-Q7ONRZBD.js} +1 -1
  127. package/dist/cli/chunks/{chunk-N3ASALOL.js → chunk-QMHWJBD3.js} +2 -2
  128. package/dist/cli/chunks/{chunk-OA75C4HY.js → chunk-QOOADAT7.js} +2 -2
  129. package/dist/cli/chunks/{chunk-ES7TAJRJ.js → chunk-QVTV47TM.js} +2 -2
  130. package/dist/cli/chunks/{chunk-7X3LMTRA.js → chunk-R2ICZKQA.js} +2 -2
  131. package/dist/cli/chunks/{chunk-D2Y36V5J.js → chunk-RDI3W4H6.js} +2 -2
  132. package/dist/cli/chunks/{chunk-QP7EKLWU.js → chunk-REGPCPEJ.js} +2 -2
  133. package/dist/cli/chunks/{chunk-U2QTL5T2.js → chunk-RXKOZ6VS.js} +3 -3
  134. package/dist/cli/chunks/{chunk-OVMG6EEF.js → chunk-SRXXPZVT.js} +2 -2
  135. package/dist/cli/chunks/{chunk-CXUC7YKA.js → chunk-SUFXUM6W.js} +2 -2
  136. package/dist/cli/chunks/{chunk-77WL5HQW.js → chunk-T5K6ZCA6.js} +1 -1
  137. package/dist/cli/chunks/{chunk-3X2JSW3R.js → chunk-TBCQWD5A.js} +1 -1
  138. package/dist/cli/chunks/{chunk-BOIUENWW.js → chunk-TCJ65NPY.js} +1 -1
  139. package/dist/cli/chunks/{chunk-HE3BDBAO.js → chunk-TJCMG3QE.js} +2 -2
  140. package/dist/cli/chunks/{chunk-56M4QNXU.js → chunk-TLUMENRZ.js} +2 -2
  141. package/dist/cli/chunks/{chunk-JTOFLDU7.js → chunk-TR37Q7A6.js} +6 -6
  142. package/dist/cli/chunks/{chunk-SVP3BP52.js → chunk-UE33MZOC.js} +2 -2
  143. package/dist/cli/chunks/{chunk-T6W2EYHC.js → chunk-UGUZFUQG.js} +2 -2
  144. package/dist/cli/chunks/{chunk-3FCHH4VP.js → chunk-UOHZRR5C.js} +1 -1
  145. package/dist/cli/chunks/{chunk-QKM4XT2F.js → chunk-UTFNHITI.js} +2 -2
  146. package/dist/cli/chunks/{chunk-6GNWVPMR.js → chunk-V3ISBQ5Q.js} +2 -2
  147. package/dist/cli/chunks/{chunk-6VTC3OHD.js → chunk-V5RP2SU3.js} +2 -2
  148. package/dist/cli/chunks/{chunk-5X4HDW5W.js → chunk-VEKRK3R6.js} +2 -2
  149. package/dist/cli/chunks/{chunk-TUZNWRYC.js → chunk-VGYLV6VD.js} +1 -1
  150. package/dist/cli/chunks/{chunk-C647D42G.js → chunk-VLL7ASGH.js} +2 -2
  151. package/dist/cli/chunks/{chunk-QH7C4PTX.js → chunk-W5HQQTVH.js} +1 -1
  152. package/dist/cli/chunks/{chunk-A5CLVZC3.js → chunk-W5NHBYYS.js} +2 -2
  153. package/dist/cli/chunks/{chunk-ISBOHF6Y.js → chunk-W6K77PQR.js} +1 -1
  154. package/dist/cli/chunks/{chunk-AUFV2G2J.js → chunk-WFDDWRWY.js} +5 -5
  155. package/dist/cli/chunks/{chunk-AJ5PCJQ2.js → chunk-WHBDSJUE.js} +3 -3
  156. package/dist/cli/chunks/{chunk-4RNCVSVN.js → chunk-WONHFDWF.js} +2 -2
  157. package/dist/cli/chunks/{chunk-VW7AXJQS.js → chunk-WPG6SW7C.js} +2 -2
  158. package/dist/cli/chunks/{chunk-GA63ESNT.js → chunk-WQZR6DS6.js} +2 -2
  159. package/dist/cli/chunks/{chunk-G36RZF2Y.js → chunk-WTFVYFRZ.js} +1 -1
  160. package/dist/cli/chunks/{chunk-F2WAB4WK.js → chunk-WYE3ICSL.js} +2 -2
  161. package/dist/cli/chunks/{chunk-TT45RCLN.js → chunk-X4PGLEPQ.js} +2 -2
  162. package/dist/cli/chunks/{chunk-QDRFLM77.js → chunk-X6W35QXO.js} +2 -2
  163. package/dist/cli/chunks/{chunk-HHANMCD2.js → chunk-XCVD57GW.js} +1 -1
  164. package/dist/cli/chunks/{chunk-GQJ4QDEN.js → chunk-XYZUBAR6.js} +4 -4
  165. package/dist/cli/chunks/{chunk-TP7L4EX6.js → chunk-XZGRHJGC.js} +2 -2
  166. package/dist/cli/chunks/{chunk-BTBJ2NLH.js → chunk-YDM2DPUU.js} +2 -2
  167. package/dist/cli/chunks/{chunk-NEXBTLN6.js → chunk-YDMPTCJ3.js} +2 -2
  168. package/dist/cli/chunks/{chunk-4PY44TKH.js → chunk-YM3GAJMN.js} +2 -2
  169. package/dist/cli/chunks/{chunk-UNFE4RPV.js → chunk-YTMWPGVR.js} +1 -1
  170. package/dist/cli/chunks/{chunk-DSJJHPPS.js → chunk-YWX7KLNG.js} +3 -3
  171. package/dist/cli/chunks/{chunk-UIWXKRTK.js → chunk-ZE6WJDXM.js} +2 -2
  172. package/dist/cli/chunks/{chunk-W7JUD4EZ.js → chunk-ZX4I7IND.js} +2 -2
  173. package/dist/cli/chunks/{chunk-PVJLQ2YZ.js → chunk-ZZV6GR46.js} +1 -1
  174. package/dist/cli/chunks/{ci-5LIV2HW5.js → ci-K7DG4GSO.js} +3 -3
  175. package/dist/cli/chunks/{ci-output-UO5BDFU4.js → ci-output-EBSUG6HP.js} +2 -2
  176. package/dist/cli/chunks/{circuit-breaker-UQDPXYRD.js → circuit-breaker-P6N6YIRZ.js} +2 -2
  177. package/dist/cli/chunks/{claude-flow-setup-62QES3QX.js → claude-flow-setup-P6EZPQZT.js} +2 -2
  178. package/dist/cli/chunks/client-ZYH66YRI.js +2 -0
  179. package/dist/cli/chunks/{cline-installer-X7VZTSZG.js → cline-installer-EVZZ3EFY.js} +2 -2
  180. package/dist/cli/chunks/{code-H3BF4L4H.js → code-3WLBG2XK.js} +3 -3
  181. package/dist/cli/chunks/{code-index-extractor-BJGFZGGL.js → code-index-extractor-ZP6D4WL2.js} +2 -2
  182. package/dist/cli/chunks/{codex-installer-KVZWKU6S.js → codex-installer-XAUI4SB7.js} +2 -2
  183. package/dist/cli/chunks/{completions-YMILE6V7.js → completions-RHFNDDG3.js} +2 -2
  184. package/dist/cli/chunks/{complexity-analyzer-J26N2PWG.js → complexity-analyzer-DCW7Q3OR.js} +2 -2
  185. package/dist/cli/chunks/{continuedev-installer-MAR42OV7.js → continuedev-installer-53SQA5T6.js} +2 -2
  186. package/dist/cli/chunks/{copilot-installer-CVOJF6OT.js → copilot-installer-SXXMFB6T.js} +2 -2
  187. package/dist/cli/chunks/core-handlers-XKSPHEHE.js +2 -0
  188. package/dist/cli/chunks/{cost-tracker-SXLWXE55.js → cost-tracker-CKLDQ5AZ.js} +2 -2
  189. package/dist/cli/chunks/{coverage-D7HCHFP3.js → coverage-AWCS2SP7.js} +3 -3
  190. package/dist/cli/chunks/cross-domain-router-6VYNFQZA.js +2 -0
  191. package/dist/cli/chunks/{cursor-installer-X37VHIKW.js → cursor-installer-4TYF5V5J.js} +2 -2
  192. package/dist/cli/chunks/{daemon-LIW47IDM.js → daemon-CTZXGN5V.js} +4 -4
  193. package/dist/cli/chunks/{daemon-JN7SOH6F.js → daemon-OOY4H6RJ.js} +3 -3
  194. package/dist/cli/chunks/{dag-attention-scheduler-QCHHIZBT.js → dag-attention-scheduler-3WG24Q33.js} +2 -2
  195. package/dist/cli/chunks/{detect-WRFCWAX5.js → detect-O7MUZ6NX.js} +2 -2
  196. package/dist/cli/chunks/{dist-node-6FWT4XZO.js → dist-node-H4XI7BAF.js} +2 -2
  197. package/dist/cli/chunks/{domain-handler-SNFPNMRT.js → domain-handler-FU4WZ23B.js} +2 -2
  198. package/dist/cli/chunks/{domain-plugins-MXKHH62P.js → domain-plugins-XK26KYNJ.js} +2 -2
  199. package/dist/cli/chunks/{domain-transfer-47UJNERX.js → domain-transfer-6B5NOVH6.js} +2 -2
  200. package/dist/cli/chunks/dream-DRSSIHPP.js +2 -0
  201. package/dist/cli/chunks/{embed-and-insert-pattern-LZFAUNBQ.js → embed-and-insert-pattern-XNZXPZNL.js} +2 -2
  202. package/dist/cli/chunks/{eval-AMUXTMJB.js → eval-J3Q5TTI7.js} +2 -2
  203. package/dist/cli/chunks/{experience-capture-middleware-3D65TR2C.js → experience-capture-middleware-COKIGMXW.js} +3 -3
  204. package/dist/cli/chunks/{fast-paths-Y7BBMM56.js → fast-paths-IHWPJI6I.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-VESRRQ6V.js → feature-flags-G7ONDNTT.js} +2 -2
  206. package/dist/cli/chunks/{feature-flags-JMQQ7JW4.js → feature-flags-WUXFWZLR.js} +2 -2
  207. package/dist/cli/chunks/{file-discovery-JJKQQUV6.js → file-discovery-JN3YMBOJ.js} +2 -2
  208. package/dist/cli/chunks/{fleet-WIGHICJF.js → fleet-OUHUZJE4.js} +3 -3
  209. package/dist/cli/chunks/{gnn-wrapper-BFNPETTT.js → gnn-wrapper-PRH55ZT6.js} +2 -2
  210. package/dist/cli/chunks/{heartbeat-handler-HDXKTGUI.js → heartbeat-handler-6YF35AQS.js} +4 -4
  211. package/dist/cli/chunks/heartbeat-scheduler-FMICCNWK.js +2 -0
  212. package/dist/cli/chunks/hnsw-adapter-4TGBNJEZ.js +2 -0
  213. package/dist/cli/chunks/hnsw-index-J4NSCPAZ.js +2 -0
  214. package/dist/cli/chunks/{hnsw-legacy-bridge-6A7OTAPT.js → hnsw-legacy-bridge-7PAFSTJO.js} +2 -2
  215. package/dist/cli/chunks/{hnswlib-node-LKV2H47B.js → hnswlib-node-UETDZNNN.js} +2 -2
  216. package/dist/cli/chunks/{hooks-KDSFYQQG.js → hooks-QQNUKQAS.js} +10 -10
  217. package/dist/cli/chunks/hybrid-backend-NKPA3QE7.js +2 -0
  218. package/dist/cli/chunks/{hypergraph-engine-GDLPEPUC.js → hypergraph-engine-5GDGE3ET.js} +2 -2
  219. package/dist/cli/chunks/{hypergraph-handler-4UMFA2EW.js → hypergraph-handler-C3F2OJYA.js} +3 -3
  220. package/dist/cli/chunks/impact-analyzer-MWX7XY7X.js +2 -0
  221. package/dist/cli/chunks/{init-handler-4GCHPQHD.js → init-handler-C7ZBDAC5.js} +6 -6
  222. package/dist/cli/chunks/init-wizard-EX5N5Q7X.js +2 -0
  223. package/dist/cli/chunks/kernel-EQLZDHDD.js +2 -0
  224. package/dist/cli/chunks/{kilocode-installer-HJZMT2G5.js → kilocode-installer-VLJENC76.js} +2 -2
  225. package/dist/cli/chunks/{kiro-installer-WUPY67HG.js → kiro-installer-UYPYM6LA.js} +2 -2
  226. package/dist/cli/chunks/knowledge-graph-A3WSMQ6U.js +2 -0
  227. package/dist/cli/chunks/{learning-AXKIS7IG.js → learning-SFIWIG6Z.js} +3 -3
  228. package/dist/cli/chunks/{llm-router-HUDPNZLJ.js → llm-router-V633KAS5.js} +4 -4
  229. package/dist/cli/chunks/llm-router-service-A6XYWTL6.js +2 -0
  230. package/dist/cli/chunks/{load-RM44POD7.js → load-UWZV4JRA.js} +2 -2
  231. package/dist/cli/chunks/load-test-WF2PCXLI.js +2 -0
  232. package/dist/cli/chunks/{mcp-5JVQRBOP.js → mcp-XVFHUKCP.js} +2 -2
  233. package/dist/cli/chunks/{memory-VGZ2V6PL.js → memory-BQ5652VK.js} +5 -5
  234. package/dist/cli/chunks/memory-backend-BKGLI2RF.js +2 -0
  235. package/dist/cli/chunks/{memory-handlers-EI537Z32.js → memory-handlers-PWI3G4P4.js} +2 -2
  236. package/dist/cli/chunks/{multi-model-executor-WPRKCSCM.js → multi-model-executor-X6AQ7VVR.js} +2 -2
  237. package/dist/cli/chunks/{opencode-installer-YAJMRCQO.js → opencode-installer-N3V2Z4EF.js} +2 -2
  238. package/dist/cli/chunks/{orchestrator-MUGWBUYP.js → orchestrator-KNEKS4F7.js} +5 -5
  239. package/dist/cli/chunks/pattern-null-store-YTBLEH7D.js +2 -0
  240. package/dist/cli/chunks/{pattern-usage-recorder-ZQJJ2YNG.js → pattern-usage-recorder-MZIM6XWU.js} +2 -2
  241. package/dist/cli/chunks/{pipeline-F4DXDUDC.js → pipeline-LNLBKSXR.js} +2 -2
  242. package/dist/cli/chunks/{platform-HI3A3OWF.js → platform-OMUDXHD3.js} +2 -2
  243. package/dist/cli/chunks/{plugin-XRITPTR7.js → plugin-HGY6KKZW.js} +2 -2
  244. package/dist/cli/chunks/{prime-radiant-advanced-wasm-HHNJP7CQ.js → prime-radiant-advanced-wasm-LZBHLQYN.js} +2 -2
  245. package/dist/cli/chunks/{project-root-2VN4WO2A.js → project-root-VPSCDBMD.js} +2 -2
  246. package/dist/cli/chunks/protocol-executor-HFR2D54O.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-ZEVHSEBG.js → protocol-handler-LZXT3TXU.js} +2 -2
  248. package/dist/cli/chunks/{prove-C4BLZWBS.js → prove-I4VKQEYQ.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-MYFBQUYV.js +2 -0
  250. package/dist/cli/chunks/{quality-M3DTE4KK.js → quality-VVAWK2DD.js} +2 -2
  251. package/dist/cli/chunks/{quality-gate-V6KS7ML3.js → quality-gate-RGXLWYT6.js} +3 -3
  252. package/dist/cli/chunks/queen-coordinator-CQQMOTIW.js +2 -0
  253. package/dist/cli/chunks/{real-embeddings-YWSE3IRT.js → real-embeddings-WM66PMQ6.js} +2 -2
  254. package/dist/cli/chunks/{ref-validation-ZWOTFA3T.js → ref-validation-ZIWJNI6M.js} +2 -2
  255. package/dist/cli/chunks/{roocode-installer-GJBIWETD.js → roocode-installer-QYSI3STC.js} +2 -2
  256. package/dist/cli/chunks/router-GKWLPA3N.js +2 -0
  257. package/dist/cli/chunks/routing-feedback-WA4D5JRF.js +2 -0
  258. package/dist/cli/chunks/{routing-handler-CFYLGNAR.js → routing-handler-BID3EOLE.js} +2 -2
  259. package/dist/cli/chunks/{ruvector-commands-EDKG456B.js → ruvector-commands-DXIFMF4W.js} +2 -2
  260. package/dist/cli/chunks/rvf-dual-writer-H3ZXS5MA.js +2 -0
  261. package/dist/cli/chunks/rvf-migration-adapter-J7MTCOQA.js +2 -0
  262. package/dist/cli/chunks/{rvf-migration-coordinator-ZMEYMAI6.js → rvf-migration-coordinator-EV5E6SAO.js} +2 -2
  263. package/dist/cli/chunks/rvf-native-adapter-HXBY4VYI.js +2 -0
  264. package/dist/cli/chunks/{rvf-store-integrity-AH6PNJP6.js → rvf-store-integrity-IT6DCCJK.js} +2 -2
  265. package/dist/cli/chunks/safe-db-INVJ5LHR.js +2 -0
  266. package/dist/cli/chunks/schedule-XRIPPL52.js +2 -0
  267. package/dist/cli/chunks/scheduler-HBN3KPRW.js +2 -0
  268. package/dist/cli/chunks/{security-ZU2GW3ZM.js → security-AAFAEATQ.js} +3 -3
  269. package/dist/cli/chunks/{shared-rvf-adapter-5FOVSL3T.js → shared-rvf-adapter-QIHSYHAF.js} +2 -2
  270. package/dist/cli/chunks/{shared-rvf-dual-writer-IO4DC4XV.js → shared-rvf-dual-writer-V7OZ6TBR.js} +2 -2
  271. package/dist/cli/chunks/sqlite-persistence-6KNLT5Q2.js +2 -0
  272. package/dist/cli/chunks/{standalone-memory-3UXDZ7HI.js → standalone-memory-ALZI6VPX.js} +2 -2
  273. package/dist/cli/chunks/{status-handler-264CHTWS.js → status-handler-DED5A3OW.js} +2 -2
  274. package/dist/cli/chunks/{structural-health-E2QPUOZE.js → structural-health-CB7L3NWH.js} +2 -2
  275. package/dist/cli/chunks/{sync-2ACMWM7D.js → sync-QNPGETIO.js} +2 -2
  276. package/dist/cli/chunks/{sync-N2L2OST4.js → sync-S6Z2U46T.js} +2 -2
  277. package/dist/cli/chunks/{task-handler-IB5CVOTY.js → task-handler-CGHXYFIF.js} +2 -2
  278. package/dist/cli/chunks/{task-handlers-QBMYNJHE.js → task-handlers-A6BGQJIB.js} +3 -3
  279. package/dist/cli/chunks/{test-7RGLRDSP.js → test-IISTF5W6.js} +4 -4
  280. package/dist/cli/chunks/{test-scheduling-RJABJT2W.js → test-scheduling-FKYX4OLF.js} +7 -7
  281. package/dist/cli/chunks/{token-bootstrap-JVHMHB72.js → token-bootstrap-OKO3JEKT.js} +2 -2
  282. package/dist/cli/chunks/{token-usage-3ECHQVCY.js → token-usage-25BRFKJ5.js} +2 -2
  283. package/dist/cli/chunks/{transformers-KJH3IJWI.js → transformers-TBVVSZMF.js} +2 -2
  284. package/dist/cli/chunks/{tree-sitter-wasm-parser-XN6PFI32.js → tree-sitter-wasm-parser-N7KCOQT4.js} +2 -2
  285. package/dist/cli/chunks/{types-5BAPXOLS.js → types-TFHWJGRK.js} +2 -2
  286. package/dist/cli/chunks/unified-memory-WVELSL6T.js +2 -0
  287. package/dist/cli/chunks/unified-memory-hnsw-7P5MVKXD.js +2 -0
  288. package/dist/cli/chunks/unified-persistence-YLFCEWYY.js +2 -0
  289. package/dist/cli/chunks/{upgrade-S5NFQZID.js → upgrade-4VWQU7RD.js} +2 -2
  290. package/dist/cli/chunks/{validate-BIBWOLJD.js → validate-FF7WVXMP.js} +2 -2
  291. package/dist/cli/chunks/{validate-swarm-WAA3LBHH.js → validate-swarm-NRLH4EDC.js} +2 -2
  292. package/dist/cli/chunks/visual-security-T5OM742H.js +2 -0
  293. package/dist/cli/chunks/{web-tree-sitter-OTBQTHAV.js → web-tree-sitter-VVU3LULW.js} +2 -2
  294. package/dist/cli/chunks/{windsurf-installer-NNQ22EW6.js → windsurf-installer-Q2ZNWG2D.js} +2 -2
  295. package/dist/cli/chunks/witness-chain-D6X4OZP5.js +2 -0
  296. package/dist/cli/chunks/{witness-chain-E7MUBOJW.js → witness-chain-FP3D4PQL.js} +2 -2
  297. package/dist/cli/chunks/{witness-chain-repair-FW4QSN4C.js → witness-chain-repair-3LG4BF7C.js} +2 -2
  298. package/dist/cli/chunks/{witness-chain-verifier-YMROEBVL.js → witness-chain-verifier-LACGL6BK.js} +2 -2
  299. package/dist/cli/chunks/{witness-key-manager-4CGRNDMJ.js → witness-key-manager-GQZIB5ZE.js} +2 -2
  300. package/dist/cli/chunks/{workflow-4VRSTRAN.js → workflow-JPA5Y7L6.js} +4 -4
  301. package/dist/cli/chunks/workflow-orchestrator-OORDDKT3.js +2 -0
  302. package/dist/cli/chunks/{wrappers-4M4UTGEU.js → wrappers-2B5NHICD.js} +2 -2
  303. package/dist/cli/utils/workflow-parser.js +73 -57
  304. package/dist/domains/code-intelligence/services/metric-collector/test-counter.d.ts +1 -1
  305. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +17 -15
  306. package/dist/domains/test-execution/services/retry-handler.js +6 -3
  307. package/dist/governance/ab-benchmarking.d.ts +5 -1
  308. package/dist/governance/ab-benchmarking.js +64 -29
  309. package/dist/mcp/bundle.js +414 -412
  310. package/dist/mcp/security/rate-limiter.d.ts +1 -0
  311. package/dist/mcp/security/rate-limiter.js +22 -5
  312. package/dist/mcp/services/session-store.js +17 -17
  313. package/dist/mcp/tools/planning/goap-status.d.ts +2 -0
  314. package/dist/mcp/tools/planning/goap-status.js +8 -2
  315. package/dist/planning/goap-planner.d.ts +3 -0
  316. package/dist/planning/goap-planner.js +80 -37
  317. package/dist/shared/embeddings/embedding-cache.js +1 -1
  318. package/dist/shared/embeddings/nomic-embedder.js +17 -7
  319. package/dist/shared/embeddings/ollama-client.js +5 -3
  320. package/dist/shared/git/git-analyzer.js +31 -30
  321. package/dist/shared/http/http-client.js +20 -13
  322. package/dist/shared/io/file-reader.js +11 -8
  323. package/dist/shared/llm/cache.d.ts +8 -29
  324. package/dist/shared/llm/cache.js +6 -2
  325. package/dist/shared/llm/cost-tracker.js +2 -1
  326. package/dist/shared/llm/provider-manager.js +4 -22
  327. package/dist/shared/llm/providers/gemini.d.ts +1 -0
  328. package/dist/shared/llm/providers/gemini.js +14 -5
  329. package/dist/shared/llm/providers/openrouter.js +6 -3
  330. package/dist/shared/metrics/code-metrics.js +1 -1
  331. package/dist/shared/metrics/system-metrics.js +8 -2
  332. package/dist/shared/retry-engine.js +2 -12
  333. package/dist/test-scheduling/executors/vitest-executor.js +26 -17
  334. package/package.json +3 -1
  335. package/dist/cli/chunks/adapter-XYCOXQCC.js +0 -2
  336. package/dist/cli/chunks/aqe-learning-engine-DTJCROTG.js +0 -2
  337. package/dist/cli/chunks/base-5TQ34GMD.js +0 -2
  338. package/dist/cli/chunks/browser-workflow-KWX4ESTJ.js +0 -2
  339. package/dist/cli/chunks/chunk-7STWD4KJ.js +0 -3
  340. package/dist/cli/chunks/chunk-PFXCRRR6.js +0 -736
  341. package/dist/cli/chunks/chunk-U64QORFO.js +0 -2
  342. package/dist/cli/chunks/client-AJZKCP4I.js +0 -2
  343. package/dist/cli/chunks/core-handlers-MQHEMGDV.js +0 -2
  344. package/dist/cli/chunks/cross-domain-router-3QNMZV5R.js +0 -2
  345. package/dist/cli/chunks/dream-OSWAITPT.js +0 -2
  346. package/dist/cli/chunks/heartbeat-scheduler-BVRVVIE2.js +0 -2
  347. package/dist/cli/chunks/hnsw-adapter-MZTHXULS.js +0 -2
  348. package/dist/cli/chunks/hnsw-index-KHEX4VDG.js +0 -2
  349. package/dist/cli/chunks/hybrid-backend-2B3LCLR4.js +0 -2
  350. package/dist/cli/chunks/impact-analyzer-4R4VWOGQ.js +0 -2
  351. package/dist/cli/chunks/init-wizard-TAOPXHHD.js +0 -2
  352. package/dist/cli/chunks/kernel-6I6VZUWY.js +0 -2
  353. package/dist/cli/chunks/knowledge-graph-KFMTTUR5.js +0 -2
  354. package/dist/cli/chunks/llm-router-service-2D74XVM3.js +0 -2
  355. package/dist/cli/chunks/load-test-53FWOWNS.js +0 -2
  356. package/dist/cli/chunks/memory-backend-KFJDDPEZ.js +0 -2
  357. package/dist/cli/chunks/pattern-null-store-7DMU5CJ4.js +0 -2
  358. package/dist/cli/chunks/protocol-executor-2EMTBTMG.js +0 -2
  359. package/dist/cli/chunks/qe-reasoning-bank-VZHZZPHE.js +0 -2
  360. package/dist/cli/chunks/queen-coordinator-7MYTTUHI.js +0 -2
  361. package/dist/cli/chunks/router-ZD4LXAWA.js +0 -2
  362. package/dist/cli/chunks/routing-feedback-FSLMDVGD.js +0 -2
  363. package/dist/cli/chunks/rvf-dual-writer-LTKTDRFS.js +0 -2
  364. package/dist/cli/chunks/rvf-migration-adapter-IF24EVC5.js +0 -2
  365. package/dist/cli/chunks/rvf-native-adapter-E6JNBKMZ.js +0 -2
  366. package/dist/cli/chunks/safe-db-F6TRB5KZ.js +0 -2
  367. package/dist/cli/chunks/schedule-HBD4BYTE.js +0 -2
  368. package/dist/cli/chunks/scheduler-6FYWPMQC.js +0 -2
  369. package/dist/cli/chunks/sqlite-persistence-DOU72F5Z.js +0 -2
  370. package/dist/cli/chunks/unified-memory-GHAYAXWZ.js +0 -2
  371. package/dist/cli/chunks/unified-memory-hnsw-CCC63YXT.js +0 -2
  372. package/dist/cli/chunks/unified-persistence-HKRHI5PG.js +0 -2
  373. package/dist/cli/chunks/visual-security-APOXJ3Q3.js +0 -2
  374. package/dist/cli/chunks/witness-chain-7IP5IJGT.js +0 -2
  375. package/dist/cli/chunks/workflow-orchestrator-2HNW5ZMQ.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.14.8");process.exit(0)}
2
- import{d as V,e as X,g as ae,h as G}from"./chunk-GK5WLUX3.js";import{a as oe}from"./chunk-HHANMCD2.js";import{a as ce}from"./chunk-CBWM5NOO.js";import{c as Ue,n as R,o as W}from"./chunk-3EKG7HFV.js";import{i as O}from"./chunk-UQGIC5OX.js";import{c as P,d as S}from"./chunk-EKO5QL2B.js";import{a as b,b as Fe,e as Oe}from"./chunk-HPVYJ6JH.js";import{B as $,D as L,G as ie,P as k,S as _,b as F}from"./chunk-R6I5I724.js";import{c as ke}from"./chunk-6GJWT2OY.js";import{b as _e,c as ut}from"./chunk-Z5UZOYQS.js";import{c as j,e as Ne,f as Me}from"./chunk-BOIUENWW.js";import{a as se,b as He,d as Le,f as ht}from"./chunk-4PY44TKH.js";import{c as B,e as dt}from"./chunk-XAESN54Q.js";var Z=B(T=>{var bt=T&&T.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(T,"__esModule",{value:!0});var Pt=Object.prototype.hasOwnProperty;function pe(n,e){return Pt.call(n,e)}T.hasOwnProperty=pe;function Ve(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)pe(n,i)&&r.push(i);return r}T._objectKeys=Ve;function Et(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}T._deepClone=Et;function At(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}T.isInteger=At;function fe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}T.escapePathComponent=fe;function Tt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}T.unescapePathComponent=Tt;function ge(n,e){var t;for(var r in n)if(pe(n,r)){if(n[r]===e)return fe(r)+"/";if(typeof n[r]=="object"&&(t=ge(n[r],e),t!=""))return fe(r)+"/"+t}return""}T._getPathRecursive=ge;function Rt(n,e){if(n===e)return"/";var t=ge(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}T.getPath=Rt;function me(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(me(n[e]))return!0}else if(typeof n=="object"){for(var r=Ve(n),i=r.length,s=0;s<i;s++)if(me(n[r[s]]))return!0}}return!1}T.hasUndefined=me;function We(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
- `)}var xt=(function(n){bt(e,n);function e(t,r,i,s,a){var l=this.constructor,d=n.call(this,We(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,l.prototype),d.message=We(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);T.PatchError=xt});var ye=B(v=>{Object.defineProperty(v,"__esModule",{value:!0});var C=Z();v.JsonPatchError=C.PatchError;v.deepClone=C._deepClone;var U={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=ee(t,this.path);r&&(r=C._deepClone(r));var i=N(t,{op:"remove",path:this.from}).removed;return N(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=ee(t,this.from);return N(t,{op:"add",path:this.path,value:C._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Ct={add:function(n,e,t){return C.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:U.move,copy:U.copy,test:U.test,_get:U._get};function ee(n,e){if(e=="")return n;var t={op:"_get",path:e};return N(n,t),t.value}v.getValueByPointer=ee;function N(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):te(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=ee(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=C._deepClone(n));var l=e.path||"",d=l.split("/"),o=n,c=1,h=d.length,m=void 0,u=void 0,f=void 0;for(typeof t=="function"?f=t:f=te;;){if(u=d[c],u&&u.indexOf("~")!=-1&&(u=C.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&c>0&&d[c-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&&m===void 0&&(o[u]===void 0?m=d.slice(0,c).join("/"):c==h-1&&(m=e.path),m!==void 0&&f(e,0,n,m)),c++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!C.isInteger(u))throw new v.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);C.isInteger(u)&&(u=~~u)}if(c>=h){if(t&&e.op==="add"&&u>o.length)throw new v.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Ct[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(c>=h){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&c<h&&(!o||typeof o!="object"))throw new v.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}v.applyOperation=N;function Xe(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=C._deepClone(n));for(var s=new Array(e.length),a=0,l=e.length;a<l;a++)s[a]=N(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}v.applyPatch=Xe;function It(n,e,t){var r=N(n,e);if(r.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}v.applyReducer=It;function te(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new v.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new v.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 v.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 v.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 v.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")&&C.hasUndefined(n.value))throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new v.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 v.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},l=Ge([a],t);if(l&&l.name==="OPERATION_PATH_UNRESOLVABLE")throw new v.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}v.validator=te;function Ge(n,e,t){try{if(!Array.isArray(n))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xe(C._deepClone(e),C._deepClone(n),t||!0);else{t=t||te;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof v.JsonPatchError)return i;throw i}}v.validate=Ge;function J(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var l=Object.keys(n);if(s=l.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=s;i--!==0;)if(a=l[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}v._areEquals=J});var Ye=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var A=Z(),Dt=ye(),Se=new WeakMap,Ft=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ot=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function _t(n){return Se.get(n)}function Nt(n,e){return n.observers.get(e)}function Mt(n,e){n.observers.delete(e.callback)}function Ht(n,e){e.unobserve()}q.unobserve=Ht;function Lt(n,e){var t=[],r,i=_t(n);if(!i)i=new Ft(n),Se.set(n,i);else{var s=Nt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=A._deepClone(n),e){r.callback=e,r.next=null;var a=function(){ve(r)},l=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",l),window.addEventListener("keyup",l),window.addEventListener("mousedown",l),window.addEventListener("keydown",l),window.addEventListener("change",l))}return r.patches=t,r.object=n,r.unobserve=function(){ve(r),clearTimeout(r.next),Mt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",l),window.removeEventListener("keyup",l),window.removeEventListener("mousedown",l),window.removeEventListener("keydown",l),window.removeEventListener("change",l))},i.observers.set(e,new Ot(e,r)),r}q.observe=Lt;function ve(n,e){e===void 0&&(e=!1);var t=Se.get(n.object);we(t.value,n.object,n.patches,"",e),n.patches.length&&Dt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ve;function we(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=A._objectKeys(e),a=A._objectKeys(n),l=!1,d=!1,o=a.length-1;o>=0;o--){var c=a[o],h=n[c];if(A.hasOwnProperty(e,c)&&!(e[c]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var m=e[c];typeof h=="object"&&h!=null&&typeof m=="object"&&m!=null&&Array.isArray(h)===Array.isArray(m)?we(h,m,t,r+"/"+A.escapePathComponent(c),i):h!==m&&(l=!0,i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"replace",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(m)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"remove",path:r+"/"+A.escapePathComponent(c)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),l=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var c=s[o];!A.hasOwnProperty(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(e[c])})}}}function kt(n,e,t){t===void 0&&(t=!1);var r=[];return we(n,e,r,"",t),r}q.compare=kt});var Ke=B(M=>{var Ut=ye();Object.assign(M,Ut);var qt=Ye();Object.assign(M,qt);var re=Z();M.JsonPatchError=re.PatchError;M.deepClone=re._deepClone;M.escapePathComponent=re.escapePathComponent;M.unescapePathComponent=re.unescapePathComponent});var x=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};ut();import{existsSync as Yt}from"node:fs";import{join as at}from"node:path";Oe();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??Y,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{!this.embeddingSpaceId&&!R()&&await W(),this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=R()?.spaceId??this.embeddingSpaceId??null;Ue(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=b(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF initialization failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: check the embedder endpoint and @ruvector/rvf-node binding, or set RUVECTOR_USE_RVF_PATTERN_STORE=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-DOU72F5Z.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),l=new Set((a.entries??[]).map(c=>Array.isArray(c)?c[0]:void 0).filter(c=>typeof c=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(c=>c.id)),o=[...l].filter(c=>!d.has(c));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: ${b(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=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return S(new x(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=R()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return S(new x(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return S(new x(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return S(new x(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:V({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let d=R()?.spaceId??this.embeddingSpaceId;if(!d||t.embeddingSpaceId!==d)return S(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let d=e instanceof Float32Array?e:new Float32Array(e),o=this.adapter.search(d,i*2);for(let c of o){let h=await this.get(c.id);if(h&&this.matchesFilters(h,t)){let m=this.calculateReuseInfo(h,c.score);s.push({pattern:h,score:c.score,matchType:"vector",similarity:c.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}catch(d){console.warn("[RvfPatternStore] RVF search failed:",b(d))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let d=R()?.spaceId??this.embeddingSpaceId,o=this.sqliteStore.getAllEmbeddings(),c=e,h=Math.sqrt(c.reduce((m,u)=>m+u*u,0));if(h>0)for(let m of o){if(!d||m.spaceId!==d)continue;let u=this.sqliteStore.getPattern(m.patternId);if(!u||!this.matchesFilters(u,t))continue;let f=m.embedding;if(!f||f.length!==c.length)continue;let g=0,y=0;for(let E=0;E<c.length;E++)g+=c[E]*f[E],y+=f[E]*f[E];if(y=Math.sqrt(y),y===0)continue;let p=g/(h*y),w=this.calculateReuseInfo(u,p);s.push({pattern:u,score:p,matchType:"vector",similarity:p,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.getPatterns({limit:i*2}),o=new Set(s.map(c=>c.pattern.id));for(let c of d)o.has(c.id)||this.matchesFilters(c,t)&&s.push({pattern:c,score:c.confidence,matchType:"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}catch{}let a=typeof e=="string"?e:t.textQuery;if(a?.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(a,i*2),o=new Set(s.map(h=>h.pattern.id)),c=new Map(d.map(h=>[h.id,h.ftsScore*h.coverage]));for(let h of s){let m=c.get(h.pattern.id);m!==void 0&&(h.score=le(h.score,m))}for(let h of d){if(o.has(h.id))continue;let m=await this.get(h.id);if(m&&this.matchesFilters(m,t)){let u=.5*h.ftsScore*h.coverage;s.push({pattern:m,score:u,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}catch{}s.sort((d,o)=>o.score-d.score);let l=performance.now()-r;return this.searchOps++,this.totalSearchMs+=l,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return S(new Error(`recordUsage failed: ${b(s)}`))}}async promote(e){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return S(new Error(`promote failed: ${b(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,b(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return S(new Error(`SQLite delete failed: ${b(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=X&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",b(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};ht();Oe();_();function mt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let l of s){if(a==null)break;if(typeof a=="object")a=a[l];else{a=void 0;break}}if(a!==void 0)return a}}function pt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),l=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=l}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function K(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>K(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>K(n,r))}case"NOT":return e.child?!K(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=mt(n,e.field);return pt(t,e.operator,e.value)}default:return!0}}function qe(n,e){return e?n.filter(t=>K(t,e)):n}_();_();var $e=1e4,ze=2166136261;function Je(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 he=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;he[n]=e}var Qe="0123456789abcdef";function gt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Qe[i>>4]+Qe[i&15]}return t}function yt(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 vt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let l=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&l++;l>=r&&(s|=d)}t[i]=s}return t}function St(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=he[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function wt(n,e,t){return 1-St(n,e,t)}var de=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??$e,this.baseSeed=e?.seed??ze,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=Je(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=yt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return vt([r,i])}similarity(e,t){return wt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new oe(e),i=0;for(;i<this.byteLen;){let a=r.next(),l=Math.min(4,this.byteLen-i);for(let d=0;d<l;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ue=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??$e,this.baseSeed=e?.seed??ze,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=Je(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:gt(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=he[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new oe(e),s=0;for(;s<t;){let l=i.next(),d=t-s,o=d<4?d:4;for(let c=0;c<o;c++)r[s++]=l>>>c*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Be(n){return new ue(n)}function je(n){return $()?new de(n):null}var Pe=dt(Ke(),1),be=Pe.default??Pe,Qt=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{d as V,e as X,g as ae,h as G}from"./chunk-PGARKOE6.js";import{a as oe}from"./chunk-XCVD57GW.js";import{a as ce}from"./chunk-K4NB3MYN.js";import{c as Ue,n as R,o as W}from"./chunk-4P7CGSRL.js";import{i as O}from"./chunk-LQI5GVH7.js";import{c as P,d as S}from"./chunk-PZDI7WQ3.js";import{a as b,b as Fe,e as Oe}from"./chunk-ARWSPV2C.js";import{B as $,D as L,G as ie,P as k,S as _,b as F}from"./chunk-HU4QGCIJ.js";import{c as ke}from"./chunk-OABFAREV.js";import{b as _e,c as ut}from"./chunk-25IWHVMW.js";import{c as j,e as Ne,f as Me}from"./chunk-TCJ65NPY.js";import{a as se,b as He,d as Le,f as ht}from"./chunk-YM3GAJMN.js";import{c as B,e as dt}from"./chunk-PNK5KHSI.js";var Z=B(T=>{var bt=T&&T.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(T,"__esModule",{value:!0});var Pt=Object.prototype.hasOwnProperty;function pe(n,e){return Pt.call(n,e)}T.hasOwnProperty=pe;function Ve(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)pe(n,i)&&r.push(i);return r}T._objectKeys=Ve;function Et(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}T._deepClone=Et;function At(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}T.isInteger=At;function fe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}T.escapePathComponent=fe;function Tt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}T.unescapePathComponent=Tt;function ge(n,e){var t;for(var r in n)if(pe(n,r)){if(n[r]===e)return fe(r)+"/";if(typeof n[r]=="object"&&(t=ge(n[r],e),t!=""))return fe(r)+"/"+t}return""}T._getPathRecursive=ge;function Rt(n,e){if(n===e)return"/";var t=ge(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}T.getPath=Rt;function me(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(me(n[e]))return!0}else if(typeof n=="object"){for(var r=Ve(n),i=r.length,s=0;s<i;s++)if(me(n[r[s]]))return!0}}return!1}T.hasUndefined=me;function We(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var xt=(function(n){bt(e,n);function e(t,r,i,s,a){var l=this.constructor,d=n.call(this,We(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,l.prototype),d.message=We(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);T.PatchError=xt});var ye=B(v=>{Object.defineProperty(v,"__esModule",{value:!0});var C=Z();v.JsonPatchError=C.PatchError;v.deepClone=C._deepClone;var U={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=ee(t,this.path);r&&(r=C._deepClone(r));var i=N(t,{op:"remove",path:this.from}).removed;return N(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=ee(t,this.from);return N(t,{op:"add",path:this.path,value:C._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Ct={add:function(n,e,t){return C.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:U.move,copy:U.copy,test:U.test,_get:U._get};function ee(n,e){if(e=="")return n;var t={op:"_get",path:e};return N(n,t),t.value}v.getValueByPointer=ee;function N(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):te(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=ee(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=J(n,e.value),a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=C._deepClone(n));var l=e.path||"",d=l.split("/"),o=n,c=1,h=d.length,m=void 0,u=void 0,f=void 0;for(typeof t=="function"?f=t:f=te;;){if(u=d[c],u&&u.indexOf("~")!=-1&&(u=C.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&c>0&&d[c-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&&m===void 0&&(o[u]===void 0?m=d.slice(0,c).join("/"):c==h-1&&(m=e.path),m!==void 0&&f(e,0,n,m)),c++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!C.isInteger(u))throw new v.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);C.isInteger(u)&&(u=~~u)}if(c>=h){if(t&&e.op==="add"&&u>o.length)throw new v.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Ct[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(c>=h){var a=U[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&c<h&&(!o||typeof o!="object"))throw new v.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}v.applyOperation=N;function Xe(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=C._deepClone(n));for(var s=new Array(e.length),a=0,l=e.length;a<l;a++)s[a]=N(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}v.applyPatch=Xe;function It(n,e,t){var r=N(n,e);if(r.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}v.applyReducer=It;function te(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new v.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new v.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 v.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 v.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 v.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")&&C.hasUndefined(n.value))throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new v.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 v.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},l=Ge([a],t);if(l&&l.name==="OPERATION_PATH_UNRESOLVABLE")throw new v.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}v.validator=te;function Ge(n,e,t){try{if(!Array.isArray(n))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xe(C._deepClone(e),C._deepClone(n),t||!0);else{t=t||te;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof v.JsonPatchError)return i;throw i}}v.validate=Ge;function J(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var l=Object.keys(n);if(s=l.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=s;i--!==0;)if(a=l[i],!J(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}v._areEquals=J});var Ye=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var A=Z(),Dt=ye(),Se=new WeakMap,Ft=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ot=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function _t(n){return Se.get(n)}function Nt(n,e){return n.observers.get(e)}function Mt(n,e){n.observers.delete(e.callback)}function Ht(n,e){e.unobserve()}q.unobserve=Ht;function Lt(n,e){var t=[],r,i=_t(n);if(!i)i=new Ft(n),Se.set(n,i);else{var s=Nt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=A._deepClone(n),e){r.callback=e,r.next=null;var a=function(){ve(r)},l=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",l),window.addEventListener("keyup",l),window.addEventListener("mousedown",l),window.addEventListener("keydown",l),window.addEventListener("change",l))}return r.patches=t,r.object=n,r.unobserve=function(){ve(r),clearTimeout(r.next),Mt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",l),window.removeEventListener("keyup",l),window.removeEventListener("mousedown",l),window.removeEventListener("keydown",l),window.removeEventListener("change",l))},i.observers.set(e,new Ot(e,r)),r}q.observe=Lt;function ve(n,e){e===void 0&&(e=!1);var t=Se.get(n.object);we(t.value,n.object,n.patches,"",e),n.patches.length&&Dt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ve;function we(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=A._objectKeys(e),a=A._objectKeys(n),l=!1,d=!1,o=a.length-1;o>=0;o--){var c=a[o],h=n[c];if(A.hasOwnProperty(e,c)&&!(e[c]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var m=e[c];typeof h=="object"&&h!=null&&typeof m=="object"&&m!=null&&Array.isArray(h)===Array.isArray(m)?we(h,m,t,r+"/"+A.escapePathComponent(c),i):h!==m&&(l=!0,i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"replace",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(m)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"remove",path:r+"/"+A.escapePathComponent(c)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),l=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var c=s[o];!A.hasOwnProperty(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(e[c])})}}}function kt(n,e,t){t===void 0&&(t=!1);var r=[];return we(n,e,r,"",t),r}q.compare=kt});var Ke=B(M=>{var Ut=ye();Object.assign(M,Ut);var qt=Ye();Object.assign(M,qt);var re=Z();M.JsonPatchError=re.PatchError;M.deepClone=re._deepClone;M.escapePathComponent=re.escapePathComponent;M.unescapePathComponent=re.unescapePathComponent});var x=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};ut();import{existsSync as Yt}from"node:fs";import{join as at}from"node:path";Oe();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??Y,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{!this.embeddingSpaceId&&!R()&&await W(),this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=R()?.spaceId??this.embeddingSpaceId??null;Ue(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=b(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF initialization failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: check the embedder endpoint and @ruvector/rvf-node binding, or set RUVECTOR_USE_RVF_PATTERN_STORE=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-6KNLT5Q2.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),l=new Set((a.entries??[]).map(c=>Array.isArray(c)?c[0]:void 0).filter(c=>typeof c=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(c=>c.id)),o=[...l].filter(c=>!d.has(c));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: ${b(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=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return S(new x(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=R()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return S(new x(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return S(new x(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return S(new x(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:V({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let d=R()?.spaceId??this.embeddingSpaceId;if(!d||t.embeddingSpaceId!==d)return S(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let d=e instanceof Float32Array?e:new Float32Array(e),o=this.adapter.search(d,i*2);for(let c of o){let h=await this.get(c.id);if(h&&this.matchesFilters(h,t)){let m=this.calculateReuseInfo(h,c.score);s.push({pattern:h,score:c.score,matchType:"vector",similarity:c.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}catch(d){console.warn("[RvfPatternStore] RVF search failed:",b(d))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let d=R()?.spaceId??this.embeddingSpaceId,o=this.sqliteStore.getAllEmbeddings(),c=e,h=Math.sqrt(c.reduce((m,u)=>m+u*u,0));if(h>0)for(let m of o){if(!d||m.spaceId!==d)continue;let u=this.sqliteStore.getPattern(m.patternId);if(!u||!this.matchesFilters(u,t))continue;let f=m.embedding;if(!f||f.length!==c.length)continue;let g=0,y=0;for(let E=0;E<c.length;E++)g+=c[E]*f[E],y+=f[E]*f[E];if(y=Math.sqrt(y),y===0)continue;let p=g/(h*y),w=this.calculateReuseInfo(u,p);s.push({pattern:u,score:p,matchType:"vector",similarity:p,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.getPatterns({limit:i*2}),o=new Set(s.map(c=>c.pattern.id));for(let c of d)o.has(c.id)||this.matchesFilters(c,t)&&s.push({pattern:c,score:c.confidence,matchType:"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}catch{}let a=typeof e=="string"?e:t.textQuery;if(a?.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(a,i*2),o=new Set(s.map(h=>h.pattern.id)),c=new Map(d.map(h=>[h.id,h.ftsScore*h.coverage]));for(let h of s){let m=c.get(h.pattern.id);m!==void 0&&(h.score=le(h.score,m))}for(let h of d){if(o.has(h.id))continue;let m=await this.get(h.id);if(m&&this.matchesFilters(m,t)){let u=.5*h.ftsScore*h.coverage;s.push({pattern:m,score:u,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}catch{}s.sort((d,o)=>o.score-d.score);let l=performance.now()-r;return this.searchOps++,this.totalSearchMs+=l,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return S(new Error(`recordUsage failed: ${b(s)}`))}}async promote(e){if(!this.sqliteStore)return S(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return S(new Error(`promote failed: ${b(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,b(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return S(new Error(`SQLite delete failed: ${b(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=X&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",b(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};ht();Oe();_();function mt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let l of s){if(a==null)break;if(typeof a=="object")a=a[l];else{a=void 0;break}}if(a!==void 0)return a}}function pt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),l=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=l}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function K(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>K(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>K(n,r))}case"NOT":return e.child?!K(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=mt(n,e.field);return pt(t,e.operator,e.value)}default:return!0}}function qe(n,e){return e?n.filter(t=>K(t,e)):n}_();_();var $e=1e4,ze=2166136261;function Je(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 he=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;he[n]=e}var Qe="0123456789abcdef";function gt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Qe[i>>4]+Qe[i&15]}return t}function yt(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 vt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let l=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&l++;l>=r&&(s|=d)}t[i]=s}return t}function St(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=he[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function wt(n,e,t){return 1-St(n,e,t)}var de=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??$e,this.baseSeed=e?.seed??ze,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=Je(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=yt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return vt([r,i])}similarity(e,t){return wt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new oe(e),i=0;for(;i<this.byteLen;){let a=r.next(),l=Math.min(4,this.byteLen-i);for(let d=0;d<l;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ue=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??$e,this.baseSeed=e?.seed??ze,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=Je(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:gt(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=he[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new oe(e),s=0;for(;s<t;){let l=i.next(),d=t-s,o=d<4?d:4;for(let c=0;c<o;c++)r[s++]=l>>>c*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Be(n){return new ue(n)}function je(n){return $()?new de(n):null}var Pe=dt(Ke(),1),be=Pe.default??Pe,Qt=`
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 V,e as X,g as ae,h as G}from"./chunk-GK5WLUX3.js";import{a as oe}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,s)}}};_();var zt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Ee=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...zt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,l=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:l,metadata:i,compressedSize:l.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let l=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(l,o.sparseChanges)}return l}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),l=i.slice(s),d=a.findIndex(h=>h.deltaType==="genesis");d>=0&&(l.unshift(a[d]),a.splice(d,1)),this.history.set(e,l);let o=l[0]?.version??0,c=this.snapshots.get(e);return c&&this.snapshots.set(e,c.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,l=s<t.length?t[s]:0;Math.abs(a-l)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:l})}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 tt(n){return L()?new Ee(n):null}_();var Jt=128,Bt=8,jt=1e4,Ae=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Jt,this.beta=e?.beta??Bt,this.maxPatterns=e?.maxPatterns??jt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let c=0;c<this.patterns.length;c++)r[c]=this.beta*this.dotProduct(this.patterns[c].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let c=1;c<i.length;c++)i[c]>a&&(a=i[c],s=c);let l=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,l.pattern);return{pattern:new Float32Array(l.pattern),metadata:{...l.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let l=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-l+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function rt(n){return new Ae(n)}_();var Wt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},H=1e-5,nt=1-H;function Vt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function I(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Xt(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 D=class n{static poincareDistance(e,t){let r=I(Xt(e,t)),i=Math.max(H,1-I(e)),s=Math.max(H,1-I(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Vt(e,t),i=I(e),s=I(t),a=Math.max(H,1+2*r+i*s),l=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let c=0;c<e.length;c++)o[c]=(l*e[c]+d*t[c])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(H,1-I(e)),i=Math.sqrt(I(t));if(i<H)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let l=0;l<t.length;l++)a[l]=s/i*t[l];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(I(e));if(t<=nt)return new Float32Array(e);let r=nt/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(I(e));if(t<H)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Te=class{config;points=new Map;constructor(e){if(this.config={...Wt,...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:D.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=D.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:D.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let l=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;l.length>0;){let{id:d,depth:o,angOff:c,angSpan:h}=l.shift(),m=Math.tanh(.3*(o+.1)),u=c+h/2,f=new Float32Array(r);f[0]=m*Math.cos(u),f[1]=m*Math.sin(u);let g=s.get(d);if(g&&g.features.length>0){let w=m*.1;for(let E=2;E<r&&E-2<g.features.length;E++)f[E]=g.features[E-2]*w}let y=D.project(f);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:g?.parentId}});let p=i.get(d)??[];for(let w=0;w<p.length;w++){let E=h/Math.max(1,p.length);l.push({id:p[w],depth:o+1,angOff:c+w*E,angSpan:E})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function it(n){return Gt()?new Te(n):null}function Gt(){return F().useHyperbolicHnsw}_();var Re=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=it(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=D.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=D.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function st(n){return new Re(n)}var xe=null;function ot(){return xe||(xe=Be({dimensions:1e4})),xe}var Ce;function Kt(){return Ce===void 0&&(Ce=je()),Ce}var Q=null,Ie=0,ct;function lt(n,e){return(!Q||Ie!==n||ct!==e)&&(Q=rt({dimension:n,maxPatterns:1e4}),Ie=n,ct=e),Q}var Y={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:X,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}},De=class{constructor(e,t={}){this.memory=e;this.config={...Y,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ne(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=R()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(!R()&&!this.config.embeddingSpaceId&&await W(),this.hnswSpaceId=R()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-6A7OTAPT.js"),{HnswAdapter:l}=await import("./hnsw-adapter-MZTHXULS.js"),d=new l("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(d),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-KHEX4VDG.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,l)=>setTimeout(()=>l(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",b(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=R()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:l,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!l||l.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,l,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",b(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=tt()),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:",b(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=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return S(new x(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=R()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,l=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),l=!0}catch(o){return d(),S(new x(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&l)return S(new x(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),S(new x(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(c){return l||d(),S(new x(e.id,l?"COMMITTED_PENDING_INDEX":"FAILED",c))}}if($())try{let c=ot().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,c.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,b(o))}try{let o=Kt();if(o){let c=[e.patternType,e.qeDomain];e.context?.tags&&c.push(...e.context.tags),e.name&&c.push(e.name);let h=o.fingerprintPattern(c);this.hdcTokenCache.set(e.id,h)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,b(o))}if(ie()&&e.embedding&&i)try{lt(e.embedding.length,i).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,b(o))}if(L()&&this.deltaTracker)try{let o={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,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,b(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,b(o))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{let a=R()?.spaceId??this.config.embeddingSpaceId;if(Array.isArray(e)&&(!a||t.embeddingSpaceId!==a))throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");if(Array.isArray(e)&&t.useVectorSearch!==!1&&a&&ie())try{let f=lt(e.length,a);if(f.getPatternCount()>0){let g=f.recall(new Float32Array(e));if(g&&g.similarity>.98){let y=g.metadata.id,p=await this.get(y);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,g.similarity);s.push({pattern:p,score:g.similarity,matchType:"vector",similarity:g.similarity,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",b(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=await this.ensureHNSW();if(f){let g=await f.search(e,i*2);for(let y of g){let p=await this.get(y.key);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,y.score);s.push({pattern:p,score:y.score,matchType:"vector",similarity:y.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}let l=typeof e=="string"?e:t.textQuery;if(l?.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(l,i*2);if(f.length>0){let g=new Map(f.map(p=>[p.id,p.ftsScore*p.coverage])),y=new Set(s.map(p=>p.pattern.id));for(let p of s){let w=g.get(p.pattern.id);w!==void 0&&(p.score=le(p.score,w))}for(let p of f){if(y.has(p.id))continue;let w=await this.get(p.id);if(w&&this.matchesFilters(w,t)){let E=.5*p.ftsScore*p.coverage;s.push({pattern:w,score:E,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(l??"",t,i-s.length),g=new Set(s.map(y=>y.pattern.id));for(let y of f)g.has(y.pattern.id)||s.push(y)}let d=720*60*60*1e3,o=Date.now();for(let f of s){let g=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),y=o-g,p=Math.pow(.5,y/d),w=f.pattern.usageCount>0?p:.5;f.score=f.score*(.7+.3*w)}let c=this.sqliteStore?.getDatabase();if(c&&s.length>0)try{this.nullStore||(this.nullStore=new ce(c));let f=this.nullStore.getNullSummaries(s.map(g=>g.pattern.id));for(let g of s){let y=f.get(g.pattern.id);y&&(g.nullSummary=y,g.score=ce.applyNullDiscount(g.score,y,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",b(f))}s.sort((f,g)=>g.score-f.score);let h=s;t.filter&&(h=qe(s,t.filter));let m=h.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),P(m)}catch(a){return S(Fe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let l=[...a];if($()&&s&&this.hdcCache.size>0)try{let d=ot(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),c=l.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));c.sort((u,f)=>f.similarity-u.similarity);let h=c.map(u=>u.id),m=l.filter(u=>!this.hdcCache.has(u));l=[...h,...m]}catch{}for(let d of l){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let c=0;if(s){let h=o.name.toLowerCase(),m=o.description.toLowerCase();h.includes(s)&&(c+=.5),m.includes(s)&&(s.length/m.length>.3?c+=.5:c+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){c+=.2;break}c=Math.min(c,1)}else c=o.qualityScore;(c>0||!s)&&i.push({pattern:o,score:s?.5*c:o.qualityScore,matchType:s?"lexical":"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,c=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,m=e.successRate,u=Math.min(e.reuseCount/10,1),f=o?h*.4+m*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:c,reuseConfidence:f}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return S(new Error(`Pattern not found: ${e}`));let a=new Date,l=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/l,c=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+c)),m=V({confidence:h,usageCount:l,successRate:o}),u={...s,usageCount:l,successfulUses:d,successRate:o,confidence:h,qualityScore:m,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,b(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},p={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,p,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,b(y))}let f=ae(u);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return S(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,c]of this.domainIndex)e[o]=c.size;for(let[o,c]of this.typeIndex)t[o]=c.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let l=await this.ensureHNSW(),d=l!==null?await l.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ae(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,c=o>10080*60*1e3,h=s.qualityScore<.2,m=s.usageCount===0&&o>1440*60*1e3;(c&&h||m)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let l=this.patternCache.get(a);l&&r.push(l)}r.sort((a,l)=>a.qualityScore-l.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Ie=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=st({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let l=Math.exp(-s.distance),d=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l,matchType:"vector",similarity:l,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function le(n,e){return Math.max(n,.75*n+.25*e)}function ln(n,e){try{if(F().useRVFPatternStore&&Le()){let r=process.env.AQE_PROJECT_ROOT??_e(),i=at(r,".agentic-qe"),s=at(i,"patterns.rvf");if(Yt(i)){let a={...Y,...e},l=!1;try{let d=ke(i,a.embeddingDimension);if(d){l=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!l){let d=new z((o,c)=>{let h,m=()=>{try{return He(o)}catch(f){return h=f,null}},u=m();if(!u&&j(h)&&(!Ne(o)||(u=m(),!u&&j(h))))throw h;if(u){let f=u.dimension();if(f!==c){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${f}, requested=${c})`)}return u}try{return se(o,c)}catch(f){if(u=m(),u){if(u.dimension()!==c){let g=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${g}, requested=${c})`)}return u}if(j(h))throw h;if(Me(o,f instanceof Error?f.message:String(f),h))return se(o,c);throw f}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new De(n,e)}export{x as a,Y as b,le as c,ln as d};
49
+ )`).run(e,e,s)}}};_();var zt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Ee=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...zt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,l=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:l,metadata:i,compressedSize:l.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let l=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(l,o.sparseChanges)}return l}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),l=i.slice(s),d=a.findIndex(h=>h.deltaType==="genesis");d>=0&&(l.unshift(a[d]),a.splice(d,1)),this.history.set(e,l);let o=l[0]?.version??0,c=this.snapshots.get(e);return c&&this.snapshots.set(e,c.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,l=s<t.length?t[s]:0;Math.abs(a-l)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:l})}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 tt(n){return L()?new Ee(n):null}_();var Jt=128,Bt=8,jt=1e4,Ae=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Jt,this.beta=e?.beta??Bt,this.maxPatterns=e?.maxPatterns??jt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let c=0;c<this.patterns.length;c++)r[c]=this.beta*this.dotProduct(this.patterns[c].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let c=1;c<i.length;c++)i[c]>a&&(a=i[c],s=c);let l=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,l.pattern);return{pattern:new Float32Array(l.pattern),metadata:{...l.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let l=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-l+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function rt(n){return new Ae(n)}_();var Wt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},H=1e-5,nt=1-H;function Vt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function I(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Xt(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 D=class n{static poincareDistance(e,t){let r=I(Xt(e,t)),i=Math.max(H,1-I(e)),s=Math.max(H,1-I(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Vt(e,t),i=I(e),s=I(t),a=Math.max(H,1+2*r+i*s),l=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let c=0;c<e.length;c++)o[c]=(l*e[c]+d*t[c])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(H,1-I(e)),i=Math.sqrt(I(t));if(i<H)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let l=0;l<t.length;l++)a[l]=s/i*t[l];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(I(e));if(t<=nt)return new Float32Array(e);let r=nt/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(I(e));if(t<H)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Te=class{config;points=new Map;constructor(e){if(this.config={...Wt,...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:D.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=D.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:D.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let l=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;l.length>0;){let{id:d,depth:o,angOff:c,angSpan:h}=l.shift(),m=Math.tanh(.3*(o+.1)),u=c+h/2,f=new Float32Array(r);f[0]=m*Math.cos(u),f[1]=m*Math.sin(u);let g=s.get(d);if(g&&g.features.length>0){let w=m*.1;for(let E=2;E<r&&E-2<g.features.length;E++)f[E]=g.features[E-2]*w}let y=D.project(f);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:o,parentId:g?.parentId}});let p=i.get(d)??[];for(let w=0;w<p.length;w++){let E=h/Math.max(1,p.length);l.push({id:p[w],depth:o+1,angOff:c+w*E,angSpan:E})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function it(n){return Gt()?new Te(n):null}function Gt(){return F().useHyperbolicHnsw}_();var Re=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=it(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=D.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=D.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function st(n){return new Re(n)}var xe=null;function ot(){return xe||(xe=Be({dimensions:1e4})),xe}var Ce;function Kt(){return Ce===void 0&&(Ce=je()),Ce}var Q=null,Ie=0,ct;function lt(n,e){return(!Q||Ie!==n||ct!==e)&&(Q=rt({dimension:n,maxPatterns:1e4}),Ie=n,ct=e),Q}var Y={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:X,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}},De=class{constructor(e,t={}){this.memory=e;this.config={...Y,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ne(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=R()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(!R()&&!this.config.embeddingSpaceId&&await W(),this.hnswSpaceId=R()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-7PAFSTJO.js"),{HnswAdapter:l}=await import("./hnsw-adapter-4TGBNJEZ.js"),d=new l("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(d),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-J4NSCPAZ.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,l)=>setTimeout(()=>l(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",b(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=R()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:l,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!l||l.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,l,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",b(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=tt()),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:",b(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=G(e);if(!t.valid)return S(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return S(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return S(new x(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=R()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return S(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,l=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=this.sqliteStore.storePattern(e,e.embedding,i);o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),l=!0}catch(o){return d(),S(new x(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&l)return S(new x(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),S(new x(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(c){return l||d(),S(new x(e.id,l?"COMMITTED_PENDING_INDEX":"FAILED",c))}}if($())try{let c=ot().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,c.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,b(o))}try{let o=Kt();if(o){let c=[e.patternType,e.qeDomain];e.context?.tags&&c.push(...e.context.tags),e.name&&c.push(e.name);let h=o.fingerprintPattern(c);this.hdcTokenCache.set(e.id,h)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,b(o))}if(ie()&&e.embedding&&i)try{lt(e.embedding.length,i).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,b(o))}if(L()&&this.deltaTracker)try{let o={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,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,b(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,b(o))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:O(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):S(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{let a=R()?.spaceId??this.config.embeddingSpaceId;if(Array.isArray(e)&&(!a||t.embeddingSpaceId!==a))throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");if(Array.isArray(e)&&t.useVectorSearch!==!1&&a&&ie())try{let f=lt(e.length,a);if(f.getPatternCount()>0){let g=f.recall(new Float32Array(e));if(g&&g.similarity>.98){let y=g.metadata.id,p=await this.get(y);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,g.similarity);s.push({pattern:p,score:g.similarity,matchType:"vector",similarity:g.similarity,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",b(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=await this.ensureHNSW();if(f){let g=await f.search(e,i*2);for(let y of g){let p=await this.get(y.key);if(p&&this.matchesFilters(p,t)){let w=this.calculateReuseInfo(p,y.score);s.push({pattern:p,score:y.score,matchType:"vector",similarity:y.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}let l=typeof e=="string"?e:t.textQuery;if(l?.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(l,i*2);if(f.length>0){let g=new Map(f.map(p=>[p.id,p.ftsScore*p.coverage])),y=new Set(s.map(p=>p.pattern.id));for(let p of s){let w=g.get(p.pattern.id);w!==void 0&&(p.score=le(p.score,w))}for(let p of f){if(y.has(p.id))continue;let w=await this.get(p.id);if(w&&this.matchesFilters(w,t)){let E=.5*p.ftsScore*p.coverage;s.push({pattern:w,score:E,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(l??"",t,i-s.length),g=new Set(s.map(y=>y.pattern.id));for(let y of f)g.has(y.pattern.id)||s.push(y)}let d=720*60*60*1e3,o=Date.now();for(let f of s){let g=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),y=o-g,p=Math.pow(.5,y/d),w=f.pattern.usageCount>0?p:.5;f.score=f.score*(.7+.3*w)}let c=this.sqliteStore?.getDatabase();if(c&&s.length>0)try{this.nullStore||(this.nullStore=new ce(c));let f=this.nullStore.getNullSummaries(s.map(g=>g.pattern.id));for(let g of s){let y=f.get(g.pattern.id);y&&(g.nullSummary=y,g.score=ce.applyNullDiscount(g.score,y,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",b(f))}s.sort((f,g)=>g.score-f.score);let h=s;t.filter&&(h=qe(s,t.filter));let m=h.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),P(m)}catch(a){return S(Fe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let l=[...a];if($()&&s&&this.hdcCache.size>0)try{let d=ot(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),c=l.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));c.sort((u,f)=>f.similarity-u.similarity);let h=c.map(u=>u.id),m=l.filter(u=>!this.hdcCache.has(u));l=[...h,...m]}catch{}for(let d of l){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let c=0;if(s){let h=o.name.toLowerCase(),m=o.description.toLowerCase();h.includes(s)&&(c+=.5),m.includes(s)&&(s.length/m.length>.3?c+=.5:c+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){c+=.2;break}c=Math.min(c,1)}else c=o.qualityScore;(c>0||!s)&&i.push({pattern:o,score:s?.5*c:o.qualityScore,matchType:s?"lexical":"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,c=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,m=e.successRate,u=Math.min(e.reuseCount/10,1),f=o?h*.4+m*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:c,reuseConfidence:f}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return S(new Error(`Pattern not found: ${e}`));let a=new Date,l=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/l,c=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+c)),m=V({confidence:h,usageCount:l,successRate:o}),u={...s,usageCount:l,successfulUses:d,successRate:o,confidence:h,qualityScore:m,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,b(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},p={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,p,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,b(y))}let f=ae(u);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return S(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return S(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,c]of this.domainIndex)e[o]=c.size;for(let[o,c]of this.typeIndex)t[o]=c.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let l=await this.ensureHNSW(),d=l!==null?await l.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=ae(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,c=o>10080*60*1e3,h=s.qualityScore<.2,m=s.usageCount===0&&o>1440*60*1e3;(c&&h||m)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let l=this.patternCache.get(a);l&&r.push(l)}r.sort((a,l)=>a.qualityScore-l.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Ie=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=st({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let l=Math.exp(-s.distance),d=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l,matchType:"vector",similarity:l,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function le(n,e){return Math.max(n,.75*n+.25*e)}function ln(n,e){try{if(F().useRVFPatternStore&&Le()){let r=process.env.AQE_PROJECT_ROOT??_e(),i=at(r,".agentic-qe"),s=at(i,"patterns.rvf");if(Yt(i)){let a={...Y,...e},l=!1;try{let d=ke(i,a.embeddingDimension);if(d){l=!0;let o=new z(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!l){let d=new z((o,c)=>{let h,m=()=>{try{return He(o)}catch(f){return h=f,null}},u=m();if(!u&&j(h)&&(!Ne(o)||(u=m(),!u&&j(h))))throw h;if(u){let f=u.dimension();if(f!==c){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${f}, requested=${c})`)}return u}try{return se(o,c)}catch(f){if(u=m(),u){if(u.dimension()!==c){let g=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${g}, requested=${c})`)}return u}if(j(h))throw h;if(Me(o,f instanceof Error?f.message:String(f),h))return se(o,c);throw f}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new De(n,e)}export{x as a,Y as b,le as c,ln as d};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -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.14.8");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
2
  var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as q,join as H}from"path";import{existsSync as z,readFileSync as E}from"fs";var _=$(Q),L={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...L,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=q(this.options.repoRoot,".git","refs","heads");if(!z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
3
  `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=q(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=E(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
@@ -1,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.14.8");process.exit(0)}
2
- import{b as G,d as z}from"./chunk-OVMG6EEF.js";import{a as F,e as le}from"./chunk-HPVYJ6JH.js";import{b as k,c as pe}from"./chunk-Z5UZOYQS.js";z();le();z();import*as C from"node:http";import*as _ from"node:https";import{createHash as ce}from"node:crypto";import{URL as X}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},me="AQE embedder endpoint identity canary v1",ue="/v1/embeddings";function J(t){if(t.startsWith("unix:"))return t;try{let e=new X(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function fe(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new X(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},R=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=fe(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new _.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new C.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([me]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=ce("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return G(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ue,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=C.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?_.request:C.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,M=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);M(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as K,resolve as ge}from"node:path";import{existsSync as he,mkdirSync as Ee}from"node:fs";import{createRequire as be}from"node:module";var ye=be(import.meta.url);function we(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:ge(k(),t):K(k(),".agentic-qe","memory.db")}var Q="_system",Y="embedder_identity:",x=null,U=!1;function Z(){if(x)return x;if(U)return null;try{let t=ye("better-sqlite3"),e=we(),n=K(e,"..");he(n)||Ee(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{b as G,d as z}from"./chunk-SRXXPZVT.js";import{a as F,e as le}from"./chunk-ARWSPV2C.js";import{b as k,c as pe}from"./chunk-25IWHVMW.js";z();le();z();import*as C from"node:http";import*as _ from"node:https";import{createHash as ce}from"node:crypto";import{URL as X}from"node:url";var T={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},me="AQE embedder endpoint identity canary v1",ue="/v1/embeddings";function J(t){if(t.startsWith("unix:"))return t;try{let e=new X(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function fe(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new X(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},R=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??T.model,expectedDim:e.expectedDim??T.expectedDim,connectTimeoutMs:e.connectTimeoutMs??T.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,failureThreshold:e.failureThreshold??T.failureThreshold,failureWindowMs:e.failureWindowMs??T.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=fe(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new _.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new C.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([me]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=ce("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return G(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ue,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=C.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?_.request:C.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,M=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);M(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as K,resolve as ge}from"node:path";import{existsSync as he,mkdirSync as Ee}from"node:fs";import{createRequire as be}from"node:module";var ye=be(import.meta.url);function we(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:ge(k(),t):K(k(),".agentic-qe","memory.db")}var Q="_system",Y="embedder_identity:",x=null,U=!1;function Z(){if(x)return x;if(U)return null;try{let t=ye("better-sqlite3"),e=we(),n=K(e,"..");he(n)||Ee(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS kv_store (
4
4
  key TEXT NOT NULL,
5
5
  namespace TEXT NOT NULL,
@@ -10,4 +10,4 @@ import{b as G,d as z}from"./chunk-OVMG6EEF.js";import{a as F,e as le}from"./chun
10
10
  );
11
11
  CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
12
  `),x=r,r}catch{return U=!0,null}}function ee(t){let e=Z();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(Q,Y+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function te(t){let e=Z();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Y+t.endpoint,Q,JSON.stringify(n))}function ne(){if(x)try{x.close()}catch{}x=null,U=!1}z();import{createHash as re}from"node:crypto";import{existsSync as ve,readFileSync as Ae,renameSync as Te,writeFileSync as xe}from"node:fs";var ie="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Se(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function oe(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return re("sha256").update(e).digest("hex").slice(0,16)}function B(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=re("sha256").update("aqe:embedding-space:v1\0").update(Se(t)).digest("hex");return{...t,spaceId:e}}function Be(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}function Ce(t){return`${t}.space.json`}function Ve(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=Ce(t);if(ve(r)){let s;try{s=JSON.parse(Ae(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;xe(i,`${JSON.stringify(a)}
13
- `,{encoding:"utf8",mode:384}),Te(i,r)}var V=null,f=null,N=null,O=!1,P="",v=null,p=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,se=36e5;function L(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function ae(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(O)throw new Error(`Transformer initialization previously failed: ${P}`);if(N)return N;let e={...H,...t};return N=(async()=>{try{if(e.endpoint){let l=J(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new R({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),A=B({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=ee(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),te(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Ne(v);return}let n;try{n=await import("./transformers-KJH3IJWI.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}V=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await V("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(ie,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=B({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:oe(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw O=!0,P=F(n),new Error(`Failed to initialize transformer model: ${P}`)}})(),N}function Ne(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??D(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Xe(t,e={}){let n={...H,...e};if(ae(t))return new Array(D()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=c.get(r);if(l&&Date.now()-l.timestamp<se)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(c.size>=n.maxCacheSize){let l=c.keys().next().value;l&&c.delete(l)}c.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Je(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)ae(t[o])?i[o]=new Array(D()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=c.get(L(t[o]));l&&Date.now()-l.timestamp<se?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),M=await f(y,{pooling:"mean",normalize:!0}),h=M.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(M.data.slice(u,u+d)),S=b+g,de=a[S];if(i[de]=E,n.enableCache){if(c.size>=n.maxCacheSize){let j=c.keys().next().value;j&&c.delete(j)}c.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function Ke(){c.clear(),console.log("[RealEmbeddings] Cache cleared")}function Qe(){return{size:c.size,hitRate:0}}function Ye(){return!O&&f!==null}function D(){return 384}function Ze(){V=null,f=null,N=null,O=!1,P="",c.clear(),v&&v.close(),v=null,p=null,A=null,ne()}function et(){return v!==null}function tt(){return p}function nt(){return A}async function rt(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{ie as a,Be as b,Ve as c,H as d,Xe as e,Je as f,Ke as g,Qe as h,Ye as i,D as j,Ze as k,et as l,tt as m,nt as n,rt as o};
13
+ `,{encoding:"utf8",mode:384}),Te(i,r)}var V=null,f=null,N=null,O=!1,P="",v=null,p=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},c=new Map,se=36e5;function L(t){return p?`endpoint:${p.fingerprint}:${t}`:`inproc:${t}`}function ae(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(O)throw new Error(`Transformer initialization previously failed: ${P}`);if(N)return N;let e={...H,...t};return N=(async()=>{try{if(e.endpoint){let l=J(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new R({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:D()}),p=await v.probe(),A=B({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:p.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:p.endpoint,runtimeFingerprint:p.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${p.dim} fingerprint=${p.fingerprint}`);try{let m=ee(p.endpoint);m&&m.fingerprint!==p.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${p.fingerprint} dim=${p.dim}. Vectors written before this change may no longer be comparable.`),te(p)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=Ne(v);return}let n;try{n=await import("./transformers-TBVVSZMF.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}V=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await V("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(ie,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=B({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:oe(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw O=!0,P=F(n),new Error(`Failed to initialize transformer model: ${P}`)}})(),N}function Ne(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??D(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Xe(t,e={}){let n={...H,...e};if(ae(t))return new Array(D()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=c.get(r);if(l&&Date.now()-l.timestamp<se)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(c.size>=n.maxCacheSize){let l=c.keys().next().value;l&&c.delete(l)}c.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Je(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)ae(t[o])?i[o]=new Array(D()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=c.get(L(t[o]));l&&Date.now()-l.timestamp<se?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),M=await f(y,{pooling:"mean",normalize:!0}),h=M.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(M.data.slice(u,u+d)),S=b+g,de=a[S];if(i[de]=E,n.enableCache){if(c.size>=n.maxCacheSize){let j=c.keys().next().value;j&&c.delete(j)}c.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function Ke(){c.clear(),console.log("[RealEmbeddings] Cache cleared")}function Qe(){return{size:c.size,hitRate:0}}function Ye(){return!O&&f!==null}function D(){return 384}function Ze(){V=null,f=null,N=null,O=!1,P="",c.clear(),v&&v.close(),v=null,p=null,A=null,ne()}function et(){return v!==null}function tt(){return p}function nt(){return A}async function rt(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{ie as a,Be as b,Ve as c,H as d,Xe as e,Je as f,Ke as g,Qe as h,Ye as i,D as j,Ze as k,et as l,tt as m,nt as n,rt as o};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{c as r,e as u}from"./chunk-HPVYJ6JH.js";u();var a='expected [{ "functionName": "add", "args": [2, 3], "expected": 5 }]',p={type:"object",description:"One caller-owned specification example",properties:{functionName:{type:"string",description:"Named export of the source file to call"},args:{type:"array",description:"Positional JSON arguments; length must equal the function arity",items:{}},expected:{description:"Expected JSON return value (use null for a null result)"}},required:["functionName","args","expected"]};function s(o,n="Behavior example value"){let i=(e,t)=>{if(!(e===null||typeof e=="string"||typeof e=="boolean")&&!(typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0))){if(typeof e!="object"||t.has(e))throw new r(`${n} must be finite JSON data (no undefined, functions, NaN/Infinity, cycles, or negative zero)`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new r(`${n} must contain only plain JSON objects`);t.add(e);for(let c of Array.isArray(e)?Array.from(e):Object.values(e))i(c,t);t.delete(e)}};i(o,new Set)}function l(o){if(o!==void 0){if(!Array.isArray(o))throw new r(`behaviorExamples must be an array; ${a}`);return o.forEach((n,i)=>{let e=`behaviorExamples[${i}]`;if(typeof n!="object"||n===null||Array.isArray(n))throw new r(`${e} must be an object; ${a}`);let t=n;if(typeof t.functionName!="string"||t.functionName.trim()==="")throw new r(`${e}.functionName must be a non-empty string`);if(!Array.isArray(t.args))throw new r(`${e}.args must be an array of arguments`);if(!Object.prototype.hasOwnProperty.call(t,"expected"))throw new r(`${e}.expected is required (use null for a null result)`);s(t.args,`${e}.args`),s(t.expected,`${e}.expected`)}),o}}export{p as a,s as b,l as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{c as r,e as u}from"./chunk-ARWSPV2C.js";u();var a='expected [{ "functionName": "add", "args": [2, 3], "expected": 5 }]',p={type:"object",description:"One caller-owned specification example",properties:{functionName:{type:"string",description:"Named export of the source file to call"},args:{type:"array",description:"Positional JSON arguments; length must equal the function arity",items:{}},expected:{description:"Expected JSON return value (use null for a null result)"}},required:["functionName","args","expected"]};function s(o,n="Behavior example value"){let i=(e,t)=>{if(!(e===null||typeof e=="string"||typeof e=="boolean")&&!(typeof e=="number"&&Number.isFinite(e)&&!Object.is(e,-0))){if(typeof e!="object"||t.has(e))throw new r(`${n} must be finite JSON data (no undefined, functions, NaN/Infinity, cycles, or negative zero)`);if(!Array.isArray(e)&&Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw new r(`${n} must contain only plain JSON objects`);t.add(e);for(let c of Array.isArray(e)?Array.from(e):Object.values(e))i(c,t);t.delete(e)}};i(o,new Set)}function l(o){if(o!==void 0){if(!Array.isArray(o))throw new r(`behaviorExamples must be an array; ${a}`);return o.forEach((n,i)=>{let e=`behaviorExamples[${i}]`;if(typeof n!="object"||n===null||Array.isArray(n))throw new r(`${e} must be an object; ${a}`);let t=n;if(typeof t.functionName!="string"||t.functionName.trim()==="")throw new r(`${e}.functionName must be a non-empty string`);if(!Array.isArray(t.args))throw new r(`${e}.args must be an array of arguments`);if(!Object.prototype.hasOwnProperty.call(t,"expected"))throw new r(`${e}.expected is required (use null for a null result)`);s(t.args,`${e}.args`),s(t.expected,`${e}.expected`)}),o}}export{p as a,s as b,l as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{b as d,d as c}from"./chunk-BITFGVZ4.js";import{a as l,e as g}from"./chunk-HPVYJ6JH.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{b as d,d as c}from"./chunk-5C4UYXQL.js";import{a as l,e as g}from"./chunk-ARWSPV2C.js";g();c();import{existsSync as y,readFileSync as p}from"node:fs";import{join as o,dirname as u}from"node:path";import{fileURLToPath as m}from"node:url";var i=class extends Error{constructor(t,n,r){super(t);this.code=n;this.cause=r;this.name="PatternLoaderError"}code;cause},s=class a{static instance=null;config;patterns;isLoading=!1;constructor(e={}){this.config={basePath:e.basePath??this.getDefaultBasePath(),throwOnMissing:e.throwOnMissing??!1,validatePatterns:e.validatePatterns??!0},this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]}}static getInstance(e){return a.instance||(a.instance=new a(e)),a.instance}static resetInstance(){a.instance=null}getDefaultBasePath(){try{let e=import.meta.url,t=m(e),n=u(t),r=o(n,"..","..","..");return o(r,"assets","patterns")}catch{return o(process.cwd(),"assets","patterns")}}async loadPatterns(){if(!this.isLoading){this.isLoading=!0,this.patterns.errors=[];try{this.patterns.index=this.loadJsonFile("index.json");let[e,t,n,r]=await Promise.all([Promise.resolve(this.loadJsonFile("adr-051-booster-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-router-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-embedding-patterns.json")),Promise.resolve(this.loadJsonFile("adr-051-reasoning-patterns.json"))]);this.patterns.booster=e,this.patterns.router=t,this.patterns.embedding=n,this.patterns.reasoning=r,this.patterns.loadedAt=new Date,this.config.validatePatterns&&this.validateLoadedPatterns()}finally{this.isLoading=!1}}}loadJsonFile(e){let t=o(this.config.basePath,e);try{if(!y(t)){let r=`Pattern file not found: ${t}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"FILE_NOT_FOUND");return null}let n=p(t,"utf-8");return d(n)}catch(n){if(n instanceof i)throw n;let r=`Failed to load pattern file ${e}: ${l(n)}`;if(this.patterns.errors.push(r),this.config.throwOnMissing)throw new i(r,"PARSE_ERROR",n instanceof Error?n:void 0);return null}}validateLoadedPatterns(){this.patterns.booster&&(Array.isArray(this.patterns.booster.patterns)||this.patterns.errors.push("Booster patterns file missing patterns array")),this.patterns.router&&(Array.isArray(this.patterns.router.patterns)||this.patterns.errors.push("Router patterns file missing patterns array")),this.patterns.embedding&&(Array.isArray(this.patterns.embedding.patterns)||this.patterns.errors.push("Embedding patterns file missing patterns array")),this.patterns.reasoning&&(Array.isArray(this.patterns.reasoning.patterns)||this.patterns.errors.push("Reasoning patterns file missing patterns array"))}async ensureLoaded(){this.patterns.loadedAt||await this.loadPatterns()}async getIndex(){return await this.ensureLoaded(),this.patterns.index}async getBoosterPatterns(){return await this.ensureLoaded(),this.patterns.booster}async getRouterPatterns(){return await this.ensureLoaded(),this.patterns.router}async getEmbeddingPatterns(){return await this.ensureLoaded(),this.patterns.embedding}async getReasoningPatterns(){return await this.ensureLoaded(),this.patterns.reasoning}async getBoosterPatternByKey(e){let t=await this.getBoosterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getRouterPatternByKey(e){let t=await this.getRouterPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEmbeddingPatternByKey(e){let t=await this.getEmbeddingPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getReasoningPatternByKey(e){let t=await this.getReasoningPatterns();return t?t.patterns.find(r=>r.key===e)??null:null}async getEligibleBoosterTransforms(){let e=await this.getBoosterPatternByKey("booster-transform-eligibility");return e?e.eligibility_criteria.simple_transforms:[]}async getTierHierarchy(){let e=await this.getRouterPatternByKey("router-5tier-complexity");return e?e.tier_hierarchy:null}async getQualityGateThresholds(){let e=await this.getReasoningPatternByKey("reasoning-pattern-quality-gates");return e?e.gate_thresholds:null}isLoaded(){return this.patterns.loadedAt!==null}getLoadedAt(){return this.patterns.loadedAt}getErrors(){return[...this.patterns.errors]}async getStatistics(){let e=await this.getIndex();return e?e.pattern_statistics:null}async reload(){this.patterns={index:null,booster:null,router:null,embedding:null,reasoning:null,loadedAt:null,errors:[]},await this.loadPatterns()}async getAllPatterns(){return await this.ensureLoaded(),{...this.patterns}}};function x(){return s.getInstance()}export{x as a};
@@ -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.14.8");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
2
  var a=class extends Error{constructor(r){super(r),this.name="TestRunnerExecutionError"}};function y(t,r,s,e,n,i){let d=(i?.testResults??[]).filter(u=>u.status==="failed"&&(t==="vitest"&&u.message||!u.assertionResults?.some(f=>f.status==="failed"))),o;if(s===null?o="terminated without an exit code":e.passed+e.failed+e.skipped===0?o="reported zero tests":d.length>0||(i?.numRuntimeErrorTestSuites??0)>0||(i?.numFailedTestSuites??0)>0&&e.failed===0?o="reported a suite execution error":(s!==0||i?.success===!1)&&e.failed===0&&(o="failed without a failed assertion"),!o)return;let l=[...d.map(u=>u.message).filter(Boolean),n.trim()].filter(Boolean).join(`
3
3
  `).slice(0,4e3);return new a(`${t} ${o} for ${r} (exit code ${s??"unknown"}).`+(l?`
4
4
  ${l}`:""))}import{mkdtempSync as p,readFileSync as m,rmSync as g}from"node:fs";import{tmpdir as R}from"node:os";import{join as c}from"node:path";function h(t,r){if(!r)return;let s;try{s=m(r,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw new Error("Could not read the current Vitest JSON report.")}try{let e=JSON.parse(s);if(!e||!Array.isArray(e.testResults))throw new Error("Invalid report")}catch{throw new Error("The current Vitest JSON report is malformed.")}return s}function b(){let t=p(c(R(),"aqe-vitest-report-")),r=c(t,"report.json"),s=!1;return{path:r,args:[`--outputFile=${r}`],read:e=>h(e,r),cleanup:()=>{if(!s){s=!0;try{g(t,{recursive:!0,force:!0})}catch{}}}}}function j(t){let r=t.some(n=>/(^|[\\/])vitest(\.cmd|\.js|\.mjs)?$/i.test(n)),s=t.some((n,i)=>n==="--reporter=json"||n==="--reporter"&&t[i+1]==="json"),e=t.some(n=>n.startsWith("--outputFile"));return r&&s&&!e}export{a,y as b,b as c,j as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{a as N,d as P}from"./chunk-SVP3BP52.js";import{b,e as k}from"./chunk-VCSNNLWL.js";import{a as T,b as E}from"./chunk-GA63ESNT.js";import{a as H,b as O}from"./chunk-VW7AXJQS.js";import{a as p,d as F}from"./chunk-OVMG6EEF.js";import{b as z,f as S}from"./chunk-XAESN54Q.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{a as N,d as P}from"./chunk-UE33MZOC.js";import{b,e as k}from"./chunk-ADEYBXAS.js";import{a as T,b as E}from"./chunk-WQZR6DS6.js";import{a as H,b as O}from"./chunk-WPG6SW7C.js";import{a as p,d as F}from"./chunk-SRXXPZVT.js";import{b as z,f as S}from"./chunk-PNK5KHSI.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.8");process.exit(0)}
2
- import{b as c,d as f,e as g,f as X}from"./chunk-BZIPW2PA.js";import{createHash as I}from"crypto";import{existsSync as O,readFileSync as b,writeFileSync as D,openSync as F,writeSync as y,closeSync as S}from"fs";X();var U=[`CREATE TABLE IF NOT EXISTS qe_patterns (
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{b as c,d as f,e as g,f as X}from"./chunk-NF6SLLE6.js";import{createHash as I}from"crypto";import{existsSync as O,readFileSync as b,writeFileSync as D,openSync as F,writeSync as y,closeSync as S}from"fs";X();var U=[`CREATE TABLE IF NOT EXISTS qe_patterns (
3
3
  id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
4
4
  domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
5
5
  confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
@@ -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.14.8");process.exit(0)}
2
- import{b as w,c as E,e as T}from"./chunk-XAESN54Q.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{b as w,c as E,e as T}from"./chunk-PNK5KHSI.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};
@@ -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.14.8");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
2
  var i={copilot:{id:"copilot",name:"GitHub Copilot",configPath:".vscode/mcp.json",configFormat:"json",configKey:"servers",rulesPath:".github/copilot-instructions.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cursor:{id:"cursor",name:"Cursor",configPath:".cursor/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".cursorrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cline:{id:"cline",name:"Cline",configPath:".vscode/cline_mcp_settings.json",configFormat:"json",configKey:"mcpServers",rulesPath:".vscode/cline_custom_modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},kilocode:{id:"kilocode",name:"Kilo Code",configPath:".kilocode/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".kilocode/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},roocode:{id:"roocode",name:"Roo Code",configPath:".roo/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".roo/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},codex:{id:"codex",name:"OpenAI Codex CLI",configPath:".codex/config.toml",configFormat:"toml",configKey:"mcp_servers",rulesPath:"AGENTS.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},windsurf:{id:"windsurf",name:"Windsurf",configPath:".windsurf/mcp_config.json",configFormat:"json",configKey:"mcpServers",rulesPath:".windsurfrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},continuedev:{id:"continuedev",name:"Continue.dev",configPath:".continue/config.yaml",configFormat:"yaml",configKey:"mcpServers",rulesPath:".continue/rules/aqe-qe-standards.yaml",rulesFormat:"yaml",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1}},l=["fleet_init","fleet_status","fleet_health","agent_list","agent_metrics","agent_status","team_list","team_health","task_list","task_status","test_generate_enhanced","coverage_analyze_sublinear","quality_assess","defect_predict","code_index","memory_store","memory_retrieve","memory_query","memory_usage","model_route","routing_metrics","aqe_health"];function u(t){return t?{AQE_MEMORY_BACKEND:"memory",AQE_V3_MODE:"true"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_V3_MODE:"true"}}function m(t,o){let e={command:"npx",args:["-y","agentic-qe@latest","mcp"],env:u(o)};return t&&(e.disabled=!1,e.alwaysAllow=l),e}function g(t,o){let e=m(t.supportsAutoApprove,o);if(t.id==="copilot"){let r={[t.configKey]:{"agentic-qe":{type:"stdio",...e}}};return JSON.stringify(r,null,2)+`
3
3
  `}let n={[t.configKey]:{"agentic-qe":e}};return JSON.stringify(n,null,2)+`
4
4
  `}function f(t){return`# Agentic QE MCP Server
@@ -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.14.8");process.exit(0)}
2
- import{b as y}from"./chunk-JRLZ7LZ3.js";import{a as R,c as N,d as m,e as f,f as A,j as I}from"./chunk-AEYJ4ZLA.js";import{o as g,s as O}from"./chunk-BZIPW2PA.js";O();var h=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.readonly||(this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.1");process.exit(0)}
2
+ import{b as y}from"./chunk-N5OSH5JO.js";import{a as R,c as N,d as m,e as f,f as A,j as I}from"./chunk-EQ3BJS37.js";import{o as g,s as O}from"./chunk-NF6SLLE6.js";O();var h=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=g();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.readonly||(this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,