agentic-qe 3.15.14 → 3.15.16

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 (513) hide show
  1. package/.claude/agents/v3/templates/qx-report-template.html +1 -1
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +136 -0
  4. package/assets/agents/v3/templates/qx-report-template.html +1 -1
  5. package/assets/skills/skills-manifest.json +1 -1
  6. package/dist/audit/witness-chain.d.ts +7 -0
  7. package/dist/audit/witness-chain.js +10 -0
  8. package/dist/cli/bundle.js +6 -6
  9. package/dist/cli/chunks/adapter-6CQ2PIP5.js +2 -0
  10. package/dist/cli/chunks/agent-booster-wasm-45NWEKVS.js +2 -0
  11. package/dist/cli/chunks/{agent-handler-P3IY7XEE.js → agent-handler-LVHMYFEF.js} +2 -2
  12. package/dist/cli/chunks/{agent-memory-branch-WWKC2H3G.js → agent-memory-branch-YDWOJFEQ.js} +2 -2
  13. package/dist/cli/chunks/aqe-learning-engine-73RR52VS.js +2 -0
  14. package/dist/cli/chunks/{arena-EIV5OALF.js → arena-CZKHXDDS.js} +2 -2
  15. package/dist/cli/chunks/{arena-4BMFF6BS.js → arena-ELDZH3CZ.js} +4 -4
  16. package/dist/cli/chunks/{audit-DNTI453H.js → audit-5MT4T47Z.js} +3 -3
  17. package/dist/cli/chunks/base-SMCMMVGP.js +2 -0
  18. package/dist/cli/chunks/{better-sqlite3-TQBQGNC6.js → better-sqlite3-6TGYPC2B.js} +2 -2
  19. package/dist/cli/chunks/{brain-handler-HY57CNAO.js → brain-handler-HQWZFO52.js} +3 -3
  20. package/dist/cli/chunks/{branch-enumerator-THPMZPHQ.js → branch-enumerator-WVILM4SO.js} +2 -2
  21. package/dist/cli/chunks/{browser-O6JJOZCK.js → browser-RX5ALU3H.js} +2 -2
  22. package/dist/cli/chunks/browser-workflow-A2MEZ66K.js +2 -0
  23. package/dist/cli/chunks/{chunk-CIINJHOX.js → chunk-24OX5TQJ.js} +1 -1
  24. package/dist/cli/chunks/{chunk-6P4Q4RTC.js → chunk-24QHCVX6.js} +1 -1
  25. package/dist/cli/chunks/{chunk-U6IOQKCT.js → chunk-2H4XH6FT.js} +2 -2
  26. package/dist/cli/chunks/{chunk-OGEIHS76.js → chunk-2YZ4G6NW.js} +1 -1
  27. package/dist/cli/chunks/chunk-32BPDLRZ.js +27 -0
  28. package/dist/cli/chunks/{chunk-5PLBQZ5J.js → chunk-32GN3JKR.js} +1 -1
  29. package/dist/cli/chunks/{chunk-AJVLVF7V.js → chunk-3HD7E6HN.js} +2 -2
  30. package/dist/cli/chunks/{chunk-X7CUI7KH.js → chunk-4D4DENG6.js} +2 -2
  31. package/dist/cli/chunks/{chunk-E2JLAW3U.js → chunk-4LQFBY5L.js} +6 -6
  32. package/dist/cli/chunks/{chunk-E3QIQMMN.js → chunk-4NFQLP6R.js} +1 -1
  33. package/dist/cli/chunks/{chunk-7Y3LXH57.js → chunk-525CFDUE.js} +2 -2
  34. package/dist/cli/chunks/chunk-5B5QPCNU.js +65 -0
  35. package/dist/cli/chunks/{chunk-X6Q2N5S5.js → chunk-5JZRZI4S.js} +2 -2
  36. package/dist/cli/chunks/{chunk-MB4UKUBV.js → chunk-5LAVKGLH.js} +2 -2
  37. package/dist/cli/chunks/chunk-5NNNEWLS.js +755 -0
  38. package/dist/cli/chunks/{chunk-NKOLILT7.js → chunk-5PBLPQ5T.js} +2 -2
  39. package/dist/cli/chunks/chunk-5QO3R3TU.js +6 -0
  40. package/dist/cli/chunks/{chunk-7T6L3LFN.js → chunk-5SPCGMBB.js} +2 -2
  41. package/dist/cli/chunks/{chunk-2QLE6NDW.js → chunk-5V3TI2LG.js} +1 -1
  42. package/dist/cli/chunks/{chunk-A2T56XVL.js → chunk-5VZL4UVN.js} +2 -2
  43. package/dist/cli/chunks/{chunk-TWOV3I3A.js → chunk-63GMRQ25.js} +1 -1
  44. package/dist/cli/chunks/{chunk-YGOSSVY5.js → chunk-63ZKI4PX.js} +6 -6
  45. package/dist/cli/chunks/{chunk-FHPNWHY7.js → chunk-67Z5R7RJ.js} +2 -2
  46. package/dist/cli/chunks/{chunk-PCQZIAXB.js → chunk-6DPYNAOK.js} +2 -2
  47. package/dist/cli/chunks/{chunk-WCM6WE7G.js → chunk-6ICX3FEG.js} +3 -3
  48. package/dist/cli/chunks/{chunk-JB7R77SH.js → chunk-6XXZDV2C.js} +2 -2
  49. package/dist/cli/chunks/{chunk-FJOIBZUB.js → chunk-6ZBXSOX6.js} +2 -2
  50. package/dist/cli/chunks/{chunk-WZQADC5R.js → chunk-72XSEQMW.js} +2 -2
  51. package/dist/cli/chunks/{chunk-AYLEH2UF.js → chunk-7TE5ONQQ.js} +1 -1
  52. package/dist/cli/chunks/{chunk-7QUSNBAA.js → chunk-A5GBXCP5.js} +2 -2
  53. package/dist/cli/chunks/{chunk-7724KXM2.js → chunk-AAMLQ2LF.js} +3 -3
  54. package/dist/cli/chunks/chunk-AG2EWGXS.js +21 -0
  55. package/dist/cli/chunks/{chunk-2UZBLC5H.js → chunk-AGRV5B3T.js} +2 -2
  56. package/dist/cli/chunks/{chunk-V6SE2ZU2.js → chunk-AJMJNQMP.js} +1 -1
  57. package/dist/cli/chunks/{chunk-2HPNGK7A.js → chunk-AR67RJPY.js} +2 -2
  58. package/dist/cli/chunks/{chunk-G7HGUQAE.js → chunk-ASEOFRIG.js} +2 -2
  59. package/dist/cli/chunks/{chunk-7TH4PJSU.js → chunk-BEKDKVQT.js} +2 -2
  60. package/dist/cli/chunks/{chunk-M5JEA6ZY.js → chunk-BY5OF7OH.js} +2 -2
  61. package/dist/cli/chunks/{chunk-OLUOVNUF.js → chunk-C5FP5GW3.js} +2 -2
  62. package/dist/cli/chunks/{chunk-R5RRWLRI.js → chunk-C6D5AHBO.js} +2 -2
  63. package/dist/cli/chunks/{chunk-K7GFYFBO.js → chunk-CAKMOVZ6.js} +2 -2
  64. package/dist/cli/chunks/{chunk-6NIGSY5L.js → chunk-CEYSYSK5.js} +2 -2
  65. package/dist/cli/chunks/{chunk-U4TML2VD.js → chunk-CGGUM2YJ.js} +2 -2
  66. package/dist/cli/chunks/{chunk-YE54T2NQ.js → chunk-CJSHWQXP.js} +2 -2
  67. package/dist/cli/chunks/{chunk-7SQTLUEN.js → chunk-CRPIYUTJ.js} +2 -2
  68. package/dist/cli/chunks/{chunk-65EE2EST.js → chunk-D6COXLYE.js} +2 -2
  69. package/dist/cli/chunks/{chunk-4WLIOPHX.js → chunk-DTMAS2GB.js} +2 -2
  70. package/dist/cli/chunks/{chunk-E7QTWGPI.js → chunk-DVYHMDFR.js} +470 -411
  71. package/dist/cli/chunks/chunk-DXD6K2ZP.js +3 -0
  72. package/dist/cli/chunks/{chunk-HSDWPQQY.js → chunk-E3D4GPLP.js} +3 -3
  73. package/dist/cli/chunks/{chunk-JJHLGGPP.js → chunk-EA4YQVKS.js} +1 -1
  74. package/dist/cli/chunks/{chunk-EIEEST4T.js → chunk-EGYE5UPQ.js} +2 -2
  75. package/dist/cli/chunks/{chunk-O756AOUX.js → chunk-EK7OLYOZ.js} +2 -2
  76. package/dist/cli/chunks/{chunk-57DRT6UA.js → chunk-F742SZAX.js} +2 -2
  77. package/dist/cli/chunks/{chunk-6OI5SK7M.js → chunk-FBDVGRSC.js} +1 -1
  78. package/dist/cli/chunks/{chunk-H3C5FJRH.js → chunk-FDDC72IA.js} +2 -2
  79. package/dist/cli/chunks/{chunk-IQRPR4KB.js → chunk-FL64OUBA.js} +2 -2
  80. package/dist/cli/chunks/{chunk-BNG4J3CE.js → chunk-FLNAW7C4.js} +2 -2
  81. package/dist/cli/chunks/{chunk-C3OIBFAA.js → chunk-G5RHFBAY.js} +2 -2
  82. package/dist/cli/chunks/{chunk-NPCXGX7N.js → chunk-GAHNO6JJ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-PNRPVQGI.js → chunk-GFWHUQSF.js} +2 -2
  84. package/dist/cli/chunks/{chunk-OCN53CCK.js → chunk-GJYHWYXR.js} +2 -2
  85. package/dist/cli/chunks/{chunk-5Z4MO2F3.js → chunk-GQ6TUIKY.js} +1 -1
  86. package/dist/cli/chunks/{chunk-N736GLWZ.js → chunk-GSKMOPL7.js} +2 -2
  87. package/dist/cli/chunks/{chunk-43XHGWYH.js → chunk-HCH4Y6XX.js} +2 -2
  88. package/dist/cli/chunks/{chunk-QP6GL3O5.js → chunk-HGWXF45W.js} +1 -1
  89. package/dist/cli/chunks/{chunk-PGN4TARY.js → chunk-HJ6ZGVTB.js} +2 -2
  90. package/dist/cli/chunks/{chunk-M2TG7VDK.js → chunk-HLUXXCHF.js} +1 -1
  91. package/dist/cli/chunks/{chunk-UMHFTQTR.js → chunk-HVRRLYX6.js} +4 -4
  92. package/dist/cli/chunks/{chunk-L7PC675Y.js → chunk-I7MQIM2U.js} +1 -1
  93. package/dist/cli/chunks/{chunk-JSSU4RIK.js → chunk-IESR7TNB.js} +2 -2
  94. package/dist/cli/chunks/{chunk-H4LYXLAT.js → chunk-IHRXZZQM.js} +1 -1
  95. package/dist/cli/chunks/{chunk-HV43NX4A.js → chunk-IOKYCMTJ.js} +6 -6
  96. package/dist/cli/chunks/{chunk-NZQYJCO6.js → chunk-IOQ6ZQ5W.js} +1 -1
  97. package/dist/cli/chunks/{chunk-JO26SG47.js → chunk-IOYG4VFL.js} +2 -2
  98. package/dist/cli/chunks/{chunk-6O63ZTVX.js → chunk-IUBJVHNB.js} +2 -2
  99. package/dist/cli/chunks/{chunk-XSPMLJCQ.js → chunk-J442IZLE.js} +1 -1
  100. package/dist/cli/chunks/{chunk-LTGQJYYO.js → chunk-J4ELZNLY.js} +2 -2
  101. package/dist/cli/chunks/chunk-J7I6PABJ.js +153 -0
  102. package/dist/cli/chunks/chunk-JDIYMZCQ.js +2 -0
  103. package/dist/cli/chunks/{chunk-TOJF3ZG4.js → chunk-JHQCRRJI.js} +2 -2
  104. package/dist/cli/chunks/{chunk-QUZ745UQ.js → chunk-JQ3DYUMS.js} +2 -2
  105. package/dist/cli/chunks/{chunk-P2TPH3TC.js → chunk-KITOPKRG.js} +2 -2
  106. package/dist/cli/chunks/{chunk-QNQE3EOH.js → chunk-KKU2QGSJ.js} +2 -2
  107. package/dist/cli/chunks/chunk-KL7OKSU2.js +4 -0
  108. package/dist/cli/chunks/{chunk-L5VSLPMW.js → chunk-KNSRL6NO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-INGXD5IX.js → chunk-KPRCB5LT.js} +2 -2
  110. package/dist/cli/chunks/{chunk-GY4P7KAI.js → chunk-KQYJ4VQ5.js} +1 -1
  111. package/dist/cli/chunks/{chunk-Z2S7DNFP.js → chunk-KU2AUFGX.js} +2 -2
  112. package/dist/cli/chunks/{chunk-O5CEL447.js → chunk-KVF4NXGQ.js} +2 -2
  113. package/dist/cli/chunks/{chunk-2IJO3657.js → chunk-KXCLACFG.js} +2 -2
  114. package/dist/cli/chunks/{chunk-ZJGFQK27.js → chunk-L2DWPVNJ.js} +1 -1
  115. package/dist/cli/chunks/{chunk-E7OR6V3V.js → chunk-L6QSTQME.js} +2 -2
  116. package/dist/cli/chunks/{chunk-RE6JTSDM.js → chunk-LE4QJREF.js} +1 -1
  117. package/dist/cli/chunks/{chunk-DSQESXL4.js → chunk-LKTTUHLF.js} +2 -2
  118. package/dist/cli/chunks/{chunk-YGC5QKQ4.js → chunk-LQLPB2T6.js} +2 -2
  119. package/dist/cli/chunks/{chunk-VGZOPQQY.js → chunk-LRSX2FJM.js} +1 -1
  120. package/dist/cli/chunks/chunk-M4FRQ4TE.js +12 -0
  121. package/dist/cli/chunks/chunk-M7WJCTG3.js +2 -0
  122. package/dist/cli/chunks/{chunk-56NSE3LJ.js → chunk-MAFQV4U4.js} +2 -2
  123. package/dist/cli/chunks/{chunk-MKYOE7NE.js → chunk-MD43XRX5.js} +1 -1
  124. package/dist/cli/chunks/{chunk-3TF27MG5.js → chunk-MI5MFHRA.js} +2 -2
  125. package/dist/cli/chunks/{chunk-JK6PMLQQ.js → chunk-MO55CVMT.js} +32 -32
  126. package/dist/cli/chunks/{chunk-X6NJOT3V.js → chunk-N7HL5PHH.js} +1 -1
  127. package/dist/cli/chunks/chunk-NAEWCFQT.js +14 -0
  128. package/dist/cli/chunks/{chunk-WUGXXNK4.js → chunk-NDJ7P2EP.js} +1 -1
  129. package/dist/cli/chunks/{chunk-D5GB5PUU.js → chunk-NO3IV5Q5.js} +1 -1
  130. package/dist/cli/chunks/{chunk-3XACRXBY.js → chunk-NQXXI77K.js} +2 -2
  131. package/dist/cli/chunks/{chunk-EC65UZ77.js → chunk-NVEWF4JV.js} +1 -1
  132. package/dist/cli/chunks/{chunk-JI67T6Q2.js → chunk-NZU4ACBZ.js} +2 -2
  133. package/dist/cli/chunks/chunk-O5W3FIO6.js +63 -0
  134. package/dist/cli/chunks/{chunk-YEFTK4HD.js → chunk-OAEE6JWQ.js} +2 -2
  135. package/dist/cli/chunks/{chunk-JAOCHPYX.js → chunk-OCV2XEWQ.js} +2 -2
  136. package/dist/cli/chunks/{chunk-IDBA5GK2.js → chunk-P3EYRILV.js} +2 -2
  137. package/dist/cli/chunks/{chunk-4RPBODN5.js → chunk-PEQDY4BO.js} +2 -2
  138. package/dist/cli/chunks/{chunk-CPPYZYXC.js → chunk-PF7RBAYL.js} +2 -2
  139. package/dist/cli/chunks/{chunk-WCPSR4MJ.js → chunk-PHT5N7SC.js} +2 -2
  140. package/dist/cli/chunks/{chunk-O2AAYJUV.js → chunk-PINSJCM3.js} +1 -1
  141. package/dist/cli/chunks/{chunk-HEDGFKC5.js → chunk-PPUZWYUG.js} +2 -2
  142. package/dist/cli/chunks/{chunk-XMCSKYDE.js → chunk-QPEOLAAS.js} +1 -1
  143. package/dist/cli/chunks/{chunk-7MUO4DEH.js → chunk-QQWBWEJS.js} +18 -18
  144. package/dist/cli/chunks/{chunk-UFP7SN5V.js → chunk-QVDCVD5D.js} +2 -2
  145. package/dist/cli/chunks/{chunk-NHEG2DLN.js → chunk-RJIEG3NA.js} +2 -2
  146. package/dist/cli/chunks/{chunk-KJ5A54ZH.js → chunk-RV74I3YO.js} +2 -2
  147. package/dist/cli/chunks/{chunk-UDSB3XCG.js → chunk-S75SOOZL.js} +2 -2
  148. package/dist/cli/chunks/{chunk-BPDAQB3F.js → chunk-SASBO5Y5.js} +2 -2
  149. package/dist/cli/chunks/{chunk-VJBJRFUO.js → chunk-SDLWKRVL.js} +9 -9
  150. package/dist/cli/chunks/{chunk-J6ASX536.js → chunk-SHKOCGNK.js} +2 -2
  151. package/dist/cli/chunks/{chunk-J35JWDJE.js → chunk-SI6DPU5D.js} +1 -1
  152. package/dist/cli/chunks/{chunk-V3MGY76S.js → chunk-SJ6Y4725.js} +2 -2
  153. package/dist/cli/chunks/{chunk-FTYRPEJS.js → chunk-SR52XP5F.js} +1 -1
  154. package/dist/cli/chunks/{chunk-ZUE524JL.js → chunk-SSUAAX3F.js} +2 -2
  155. package/dist/cli/chunks/{chunk-VG32EEUG.js → chunk-SSYAQZXA.js} +2 -2
  156. package/dist/cli/chunks/{chunk-HTVGHHX2.js → chunk-SUDMM5SO.js} +2 -2
  157. package/dist/cli/chunks/{chunk-K2SMP4OD.js → chunk-TIUKLYAI.js} +1 -1
  158. package/dist/cli/chunks/{chunk-VCVRZD4Y.js → chunk-TVGI32MB.js} +33 -33
  159. package/dist/cli/chunks/{chunk-CAZM63TP.js → chunk-U2A7NHZA.js} +2 -2
  160. package/dist/cli/chunks/{chunk-WBC6WB32.js → chunk-UE5ZOZR2.js} +2 -2
  161. package/dist/cli/chunks/{chunk-BQJ7CV53.js → chunk-UHEOGZLX.js} +12 -12
  162. package/dist/cli/chunks/chunk-UNGBRZDK.js +12 -0
  163. package/dist/cli/chunks/{chunk-XN3KCKAM.js → chunk-V5NHZV7S.js} +2 -2
  164. package/dist/cli/chunks/{chunk-UNYTHZDZ.js → chunk-VJCIEHEF.js} +1 -1
  165. package/dist/cli/chunks/{chunk-5Y7UFHJD.js → chunk-VMDFFTCK.js} +1 -1
  166. package/dist/cli/chunks/chunk-VSIKHWZ4.js +29 -0
  167. package/dist/cli/chunks/{chunk-UPWLMIDY.js → chunk-VWPM27GU.js} +2 -2
  168. package/dist/cli/chunks/{chunk-USAKCGHC.js → chunk-VXFLJNCA.js} +2 -2
  169. package/dist/cli/chunks/{chunk-WKI46WWN.js → chunk-W5HQUIML.js} +2 -2
  170. package/dist/cli/chunks/{chunk-Z54G2YOL.js → chunk-WP4RETKG.js} +2 -2
  171. package/dist/cli/chunks/{chunk-IRPNEXOU.js → chunk-XIIQ5QTT.js} +2 -2
  172. package/dist/cli/chunks/{chunk-O32BFQV4.js → chunk-XIQW7EFL.js} +2 -2
  173. package/dist/cli/chunks/{chunk-TW6Z6W4X.js → chunk-XWUWX7BV.js} +13 -13
  174. package/dist/cli/chunks/{chunk-57FX3GP6.js → chunk-Y4PFUMOU.js} +1 -1
  175. package/dist/cli/chunks/chunk-YAPLJR7K.js +2 -0
  176. package/dist/cli/chunks/{chunk-4T7XV5KQ.js → chunk-YLMNVLDK.js} +1 -1
  177. package/dist/cli/chunks/{chunk-TSP6SU5V.js → chunk-YNMJEDN5.js} +2 -2
  178. package/dist/cli/chunks/{chunk-PWQWKYBG.js → chunk-YPBSUGMI.js} +1 -1
  179. package/dist/cli/chunks/{chunk-QP2HLKTS.js → chunk-YRAX7SFJ.js} +2 -2
  180. package/dist/cli/chunks/{chunk-O3ERGUXH.js → chunk-YTHTQPWR.js} +1 -1
  181. package/dist/cli/chunks/{chunk-MR2OPUSA.js → chunk-YU2BDRSD.js} +1 -1
  182. package/dist/cli/chunks/chunk-ZB3LEFYG.js +2 -0
  183. package/dist/cli/chunks/{chunk-2W5MQDHM.js → chunk-ZFL436FN.js} +2 -2
  184. package/dist/cli/chunks/{chunk-7MISCSL5.js → chunk-ZJH5MU2I.js} +2 -2
  185. package/dist/cli/chunks/{chunk-52KOPIMI.js → chunk-ZQ2XW3IP.js} +2 -2
  186. package/dist/cli/chunks/chunk-ZR2TKVXQ.js +14 -0
  187. package/dist/cli/chunks/{ci-UMA2SMNW.js → ci-MFUR4CWV.js} +2 -2
  188. package/dist/cli/chunks/{ci-config-UQSILJFQ.js → ci-config-PNDLQ6XV.js} +2 -2
  189. package/dist/cli/chunks/{ci-output-U6YZLLKH.js → ci-output-PFZ4M7NC.js} +2 -2
  190. package/dist/cli/chunks/{circuit-breaker-ATYQP6X2.js → circuit-breaker-5HH6NLZN.js} +2 -2
  191. package/dist/cli/chunks/{claude-flow-setup-6YHFD7AN.js → claude-flow-setup-QCKYLGLC.js} +2 -2
  192. package/dist/cli/chunks/client-MHQRTZM4.js +2 -0
  193. package/dist/cli/chunks/{cline-installer-EPE7IOZE.js → cline-installer-EASVPFXR.js} +2 -2
  194. package/dist/cli/chunks/{code-NUEJ4XYO.js → code-UJXDVYRK.js} +4 -3
  195. package/dist/cli/chunks/{code-index-extractor-D4DBT6OL.js → code-index-extractor-BZJ3UDP4.js} +2 -2
  196. package/dist/cli/chunks/{codex-installer-633SM4LR.js → codex-installer-XSQZUVOZ.js} +4 -4
  197. package/dist/cli/chunks/{completions-WUKVIW3L.js → completions-OWOOJFI2.js} +2 -2
  198. package/dist/cli/chunks/{complexity-analyzer-F73ACR5H.js → complexity-analyzer-KP5TOHDT.js} +2 -2
  199. package/dist/cli/chunks/{continuedev-installer-QH42TKMS.js → continuedev-installer-IFKQXLHM.js} +2 -2
  200. package/dist/cli/chunks/{copilot-installer-Y3XC7BTT.js → copilot-installer-IGJ6KGQY.js} +2 -2
  201. package/dist/cli/chunks/core-handlers-UAK3LLJE.js +2 -0
  202. package/dist/cli/chunks/{cost-tracker-57QPV7E3.js → cost-tracker-MMDDNKZB.js} +2 -2
  203. package/dist/cli/chunks/{coverage-IBCHMBCR.js → coverage-LUH2B7NT.js} +3 -3
  204. package/dist/cli/chunks/cross-domain-router-WTRZQPNQ.js +2 -0
  205. package/dist/cli/chunks/{cursor-installer-F4UYQHIN.js → cursor-installer-4YLM5GWM.js} +2 -2
  206. package/dist/cli/chunks/daemon-CAVZ7OFV.js +18 -0
  207. package/dist/cli/chunks/{daemon-XR4Q6YZF.js → daemon-MZKVM4CJ.js} +3 -3
  208. package/dist/cli/chunks/{dag-attention-scheduler-ZR5ZD3TW.js → dag-attention-scheduler-X4CYW665.js} +2 -2
  209. package/dist/cli/chunks/{detect-GEGYURLL.js → detect-7BM2XINO.js} +2 -2
  210. package/dist/cli/chunks/{dist-node-JU3KT2JO.js → dist-node-Y5APLEYB.js} +2 -2
  211. package/dist/cli/chunks/{domain-handler-7QI3FJGE.js → domain-handler-X3ZRJNAH.js} +2 -2
  212. package/dist/cli/chunks/{domain-plugins-O2YRM2PD.js → domain-plugins-2UW5KQJB.js} +2 -2
  213. package/dist/cli/chunks/{domain-transfer-7J3S2OS6.js → domain-transfer-35W4CIBV.js} +2 -2
  214. package/dist/cli/chunks/dream-EJY24JN6.js +2 -0
  215. package/dist/cli/chunks/embed-and-insert-pattern-COG4C7ZI.js +3 -0
  216. package/dist/cli/chunks/embedding-space-SBM2MZD2.js +2 -0
  217. package/dist/cli/chunks/{eval-RVMCIUOR.js → eval-4QA2SROK.js} +2 -2
  218. package/dist/cli/chunks/experience-capture-middleware-Z6BF6KYM.js +40 -0
  219. package/dist/cli/chunks/{fast-paths-QUKPKWKZ.js → fast-paths-FIORX6GN.js} +2 -2
  220. package/dist/cli/chunks/{feature-flags-K7JXNKJI.js → feature-flags-6LYI2T4G.js} +2 -2
  221. package/dist/cli/chunks/{feature-flags-5JCSKL2P.js → feature-flags-ZOO7LMIC.js} +2 -2
  222. package/dist/cli/chunks/file-discovery-UZSFSS4V.js +2 -0
  223. package/dist/cli/chunks/{fleet-II4Q6HXK.js → fleet-7WF53H4F.js} +3 -3
  224. package/dist/cli/chunks/{gnn-wrapper-M7VO2EMS.js → gnn-wrapper-KJ6B7BRM.js} +2 -2
  225. package/dist/cli/chunks/{heartbeat-handler-ND5CY26N.js → heartbeat-handler-DEKKMOVW.js} +4 -4
  226. package/dist/cli/chunks/heartbeat-scheduler-NVR356I7.js +2 -0
  227. package/dist/cli/chunks/hnsw-adapter-LFMPLUJU.js +2 -0
  228. package/dist/cli/chunks/hnsw-index-POCPMVJH.js +2 -0
  229. package/dist/cli/chunks/{hnsw-legacy-bridge-N3AUUUU7.js → hnsw-legacy-bridge-L27WS27N.js} +2 -2
  230. package/dist/cli/chunks/{hnswlib-node-NZY3E5EN.js → hnswlib-node-4YOQC6L4.js} +2 -2
  231. package/dist/cli/chunks/{hooks-QVJDTII5.js → hooks-TAOKV4EJ.js} +23 -22
  232. package/dist/cli/chunks/hybrid-backend-4STAO7CV.js +2 -0
  233. package/dist/cli/chunks/{hypergraph-engine-ZRY6MTDV.js → hypergraph-engine-BODRJLHL.js} +2 -2
  234. package/dist/cli/chunks/{hypergraph-handler-56DO4XZQ.js → hypergraph-handler-RKMYJNTU.js} +3 -3
  235. package/dist/cli/chunks/impact-analyzer-3VIIISBQ.js +2 -0
  236. package/dist/cli/chunks/{init-guard-DTF4EVUY.js → init-guard-MXHSLSB2.js} +2 -2
  237. package/dist/cli/chunks/{init-handler-M6CNQHMX.js → init-handler-HUE57IFW.js} +6 -6
  238. package/dist/cli/chunks/init-wizard-PL6QN6RQ.js +2 -0
  239. package/dist/cli/chunks/kernel-CCDWT7KS.js +2 -0
  240. package/dist/cli/chunks/{kilocode-installer-IJN7XKBH.js → kilocode-installer-S333IKYQ.js} +2 -2
  241. package/dist/cli/chunks/{kiro-installer-UKKPGPDC.js → kiro-installer-WM5DLQWC.js} +2 -2
  242. package/dist/cli/chunks/knowledge-graph-KFOMEN3H.js +2 -0
  243. package/dist/cli/chunks/{learning-W2HETWQ4.js → learning-LNHMQLH5.js} +3 -3
  244. package/dist/cli/chunks/{llm-router-Y546K4VX.js → llm-router-EWFXYZZR.js} +4 -4
  245. package/dist/cli/chunks/llm-router-service-7NBE2EX6.js +2 -0
  246. package/dist/cli/chunks/{load-MKAB2AXE.js → load-FGYGWVDK.js} +2 -2
  247. package/dist/cli/chunks/load-test-UNZUWY3F.js +2 -0
  248. package/dist/cli/chunks/{mcp-AZKUS6K3.js → mcp-2FHNAAOM.js} +2 -2
  249. package/dist/cli/chunks/{memory-ZDOQN2KU.js → memory-DZMQ73AB.js} +5 -5
  250. package/dist/cli/chunks/memory-backend-DFGKWA2Q.js +2 -0
  251. package/dist/cli/chunks/memory-handlers-MP426XRJ.js +2 -0
  252. package/dist/cli/chunks/{multi-model-executor-WWVXDHG4.js → multi-model-executor-6F2UAEUW.js} +2 -2
  253. package/dist/cli/chunks/{opencode-installer-YUJNXXWS.js → opencode-installer-XY3BGOTZ.js} +2 -2
  254. package/dist/cli/chunks/{orchestrator-Z6PWPLRE.js → orchestrator-B4CNKUOS.js} +17 -17
  255. package/dist/cli/chunks/pattern-null-store-SSVF5TE5.js +2 -0
  256. package/dist/cli/chunks/{pattern-usage-recorder-TPWPX32U.js → pattern-usage-recorder-R4GUFNMD.js} +2 -2
  257. package/dist/cli/chunks/{pipeline-4BBGTE4M.js → pipeline-FG5RKVRO.js} +2 -2
  258. package/dist/cli/chunks/{platform-5GSHXCV5.js → platform-3BT4KEVJ.js} +2 -2
  259. package/dist/cli/chunks/{plugin-OFDVF5HS.js → plugin-WI4RIN7O.js} +2 -2
  260. package/dist/cli/chunks/{prime-radiant-advanced-wasm-NC6MUYGJ.js → prime-radiant-advanced-wasm-7ECDNQFS.js} +2 -2
  261. package/dist/cli/chunks/project-root-BEANNYWU.js +2 -0
  262. package/dist/cli/chunks/protocol-executor-FQVIHXZ7.js +2 -0
  263. package/dist/cli/chunks/{protocol-handler-MPOAAEPA.js → protocol-handler-WNODKPGW.js} +2 -2
  264. package/dist/cli/chunks/{prove-CDKMAIVM.js → prove-5RHAEPYZ.js} +2 -2
  265. package/dist/cli/chunks/qe-reasoning-bank-5TFYSE24.js +2 -0
  266. package/dist/cli/chunks/{quality-ZH4F7R7R.js → quality-WPHR7BGQ.js} +2 -2
  267. package/dist/cli/chunks/{quality-gate-IDRMW6OE.js → quality-gate-4RKTEZMX.js} +3 -3
  268. package/dist/cli/chunks/queen-coordinator-Y2OUL7IN.js +2 -0
  269. package/dist/cli/chunks/real-embeddings-OXLYU7JW.js +2 -0
  270. package/dist/cli/chunks/{ref-validation-Z5GCGVXK.js → ref-validation-TPAWHOHH.js} +2 -2
  271. package/dist/cli/chunks/{roocode-installer-IZ2S7PH2.js → roocode-installer-7AVHFNDI.js} +2 -2
  272. package/dist/cli/chunks/router-EP34O3KB.js +2 -0
  273. package/dist/cli/chunks/routing-feedback-FJCRKXNG.js +2 -0
  274. package/dist/cli/chunks/{routing-handler-NAX35VUW.js → routing-handler-YKEDVJSH.js} +2 -2
  275. package/dist/cli/chunks/{ruvector-commands-5YW2SOFF.js → ruvector-commands-JUAMM354.js} +2 -2
  276. package/dist/cli/chunks/rvf-dual-writer-ILITJSFG.js +2 -0
  277. package/dist/cli/chunks/rvf-migration-adapter-XF6W4C2N.js +2 -0
  278. package/dist/cli/chunks/rvf-migration-coordinator-CMKG56AR.js +2 -0
  279. package/dist/cli/chunks/rvf-native-adapter-7YFW6S4Y.js +2 -0
  280. package/dist/cli/chunks/{rvf-store-integrity-IPGCAT6C.js → rvf-store-integrity-VJDUIRTX.js} +2 -2
  281. package/dist/cli/chunks/safe-db-TCAU4FUT.js +2 -0
  282. package/dist/cli/chunks/schedule-NB5KV435.js +2 -0
  283. package/dist/cli/chunks/scheduler-JKXGKVK6.js +2 -0
  284. package/dist/cli/chunks/{security-3IH4BO5Z.js → security-ORDN3RD2.js} +3 -3
  285. package/dist/cli/chunks/{shared-rvf-adapter-ABY7PAY2.js → shared-rvf-adapter-CF4BCIO7.js} +2 -2
  286. package/dist/cli/chunks/{shared-rvf-dual-writer-6KENLN2W.js → shared-rvf-dual-writer-C32UBR6D.js} +2 -2
  287. package/dist/cli/chunks/sqlite-persistence-IXCNZRTW.js +2 -0
  288. package/dist/cli/chunks/{standalone-memory-RLFAUGOW.js → standalone-memory-OXRJYZXN.js} +2 -2
  289. package/dist/cli/chunks/{status-handler-FCOZBPE5.js → status-handler-BCX5D4HY.js} +2 -2
  290. package/dist/cli/chunks/{structural-health-4RDA5UUM.js → structural-health-LFG7RUU6.js} +2 -2
  291. package/dist/cli/chunks/sync-OSF7C2NL.js +2 -0
  292. package/dist/cli/chunks/{sync-KGEEXXCC.js → sync-YJEE2K2L.js} +2 -2
  293. package/dist/cli/chunks/task-handler-6LXKPTXJ.js +64 -0
  294. package/dist/cli/chunks/{task-handlers-6H7L2UT4.js → task-handlers-CILP36I7.js} +4 -4
  295. package/dist/cli/chunks/{test-S7IG6EIX.js → test-SD457QJ6.js} +4 -4
  296. package/dist/cli/chunks/test-runner-process-VKD65QQU.js +2 -0
  297. package/dist/cli/chunks/{test-scheduling-7XYXI4L2.js → test-scheduling-ISI2O4Q5.js} +3 -3
  298. package/dist/cli/chunks/token-bootstrap-VUELSBOS.js +2 -0
  299. package/dist/cli/chunks/{token-usage-Y2YTPOFE.js → token-usage-XOC5KG7S.js} +2 -2
  300. package/dist/cli/chunks/{transformers-UCJ3HHHC.js → transformers-LSLQAARK.js} +2 -2
  301. package/dist/cli/chunks/tree-sitter-wasm-parser-YAIPHRIL.js +2 -0
  302. package/dist/cli/chunks/{types-6CMFPETH.js → types-5BLCGLCR.js} +2 -2
  303. package/dist/cli/chunks/unified-memory-GI76TXFV.js +2 -0
  304. package/dist/cli/chunks/unified-memory-hnsw-GXJ5BTZO.js +2 -0
  305. package/dist/cli/chunks/unified-persistence-OP7FDQPD.js +2 -0
  306. package/dist/cli/chunks/{upgrade-K25DN6WU.js → upgrade-RQJYLK3J.js} +2 -2
  307. package/dist/cli/chunks/{validate-T4V3TBY3.js → validate-QBHWXXCK.js} +2 -2
  308. package/dist/cli/chunks/{validate-swarm-XSRC576T.js → validate-swarm-IKXBKFB5.js} +2 -2
  309. package/dist/cli/chunks/visual-security-GZ2MOKWB.js +2 -0
  310. package/dist/cli/chunks/{web-tree-sitter-YOZXHRTN.js → web-tree-sitter-ZF6FIE5R.js} +2 -2
  311. package/dist/cli/chunks/{windsurf-installer-ITPU2IYL.js → windsurf-installer-HQGDZT5D.js} +2 -2
  312. package/dist/cli/chunks/witness-chain-DCHCAMSQ.js +2 -0
  313. package/dist/cli/chunks/witness-chain-P3XXXA62.js +2 -0
  314. package/dist/cli/chunks/witness-chain-repair-PUX2NFDL.js +2 -0
  315. package/dist/cli/chunks/{witness-chain-verifier-DTDSVKOG.js → witness-chain-verifier-PX2OQ6XT.js} +2 -2
  316. package/dist/cli/chunks/{witness-key-manager-EWACWGAW.js → witness-key-manager-RXYQNFJB.js} +2 -2
  317. package/dist/cli/chunks/{workflow-ZIQ4FV42.js → workflow-FBKCA4H6.js} +4 -4
  318. package/dist/cli/chunks/workflow-orchestrator-P2APAJAA.js +2 -0
  319. package/dist/cli/chunks/wrappers-TWSKBTWD.js +2 -0
  320. package/dist/cli/commands/code.js +4 -0
  321. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +10 -2
  322. package/dist/cli/handlers/task-handler.d.ts +5 -0
  323. package/dist/cli/handlers/task-handler.js +21 -1
  324. package/dist/cli/utils/task-result.d.ts +11 -0
  325. package/dist/cli/utils/task-result.js +39 -0
  326. package/dist/coordination/handlers/test-execution-handlers.js +92 -58
  327. package/dist/coordination/mincut/mincut-persistence.js +29 -25
  328. package/dist/domains/code-intelligence/coordinator.d.ts +4 -0
  329. package/dist/domains/code-intelligence/coordinator.js +46 -13
  330. package/dist/domains/code-intelligence/interfaces.d.ts +10 -1
  331. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +32 -7
  332. package/dist/domains/code-intelligence/services/semantic-analyzer.js +112 -53
  333. package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
  334. package/dist/domains/quality-assessment/coordinator.js +2 -1
  335. package/dist/domains/test-execution/coordinator.js +10 -5
  336. package/dist/domains/test-execution/interfaces.d.ts +12 -0
  337. package/dist/domains/test-execution/plugin.js +6 -2
  338. package/dist/domains/test-execution/services/retry-handler.d.ts +2 -0
  339. package/dist/domains/test-execution/services/retry-handler.js +14 -9
  340. package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
  341. package/dist/domains/test-execution/services/test-executor.js +28 -9
  342. package/dist/domains/visual-accessibility/coordinator.d.ts +15 -7
  343. package/dist/domains/visual-accessibility/coordinator.js +15 -7
  344. package/dist/domains/visual-accessibility/interfaces.d.ts +27 -3
  345. package/dist/domains/visual-accessibility/services/accessibility-contrast.d.ts +39 -0
  346. package/dist/domains/visual-accessibility/services/accessibility-contrast.js +93 -0
  347. package/dist/domains/visual-accessibility/services/accessibility-tester-browser.d.ts +18 -3
  348. package/dist/domains/visual-accessibility/services/accessibility-tester-browser.js +50 -40
  349. package/dist/domains/visual-accessibility/services/accessibility-tester-checks.d.ts +27 -0
  350. package/dist/domains/visual-accessibility/services/accessibility-tester-checks.js +137 -0
  351. package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +5 -0
  352. package/dist/domains/visual-accessibility/services/accessibility-tester.js +43 -24
  353. package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.d.ts +2 -3
  354. package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.js +8 -14
  355. package/dist/feedback/coverage-learner.js +13 -9
  356. package/dist/feedback/test-outcome-tracker.js +13 -9
  357. package/dist/governance/witness-chain.d.ts +5 -0
  358. package/dist/governance/witness-chain.js +22 -6
  359. package/dist/init/init-wizard-hooks.d.ts +1 -1
  360. package/dist/init/init-wizard-hooks.js +7 -8
  361. package/dist/init/phases/08-mcp.js +9 -0
  362. package/dist/init/settings-merge.d.ts +13 -0
  363. package/dist/init/settings-merge.js +49 -2
  364. package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
  365. package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
  366. package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
  367. package/dist/integrations/agent-booster-wasm/index.js +25 -2
  368. package/dist/integrations/agent-booster-wasm/package.json +16 -0
  369. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +22 -0
  370. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +115 -45
  371. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.d.ts +6 -0
  372. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.js +51 -33
  373. package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +17 -9
  374. package/dist/integrations/embeddings/cache/EmbeddingCache.d.ts +8 -0
  375. package/dist/integrations/embeddings/cache/EmbeddingCache.js +24 -10
  376. package/dist/integrations/ruvector/delta-tracker.d.ts +11 -0
  377. package/dist/integrations/ruvector/delta-tracker.js +16 -0
  378. package/dist/integrations/ruvector/sona-persistence.d.ts +10 -0
  379. package/dist/integrations/ruvector/sona-persistence.js +49 -24
  380. package/dist/kernel/unified-memory.d.ts +24 -0
  381. package/dist/kernel/unified-memory.js +63 -8
  382. package/dist/learning/aqe-learning-engine.js +1 -1
  383. package/dist/learning/dream/dream-engine.d.ts +3 -2
  384. package/dist/learning/dream/dream-engine.js +42 -24
  385. package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
  386. package/dist/learning/dream/dream-lock-retry.js +66 -0
  387. package/dist/learning/dream/speculative-dreamer.js +1 -1
  388. package/dist/learning/embed-and-insert-pattern.js +4 -2
  389. package/dist/learning/embedder-endpoint-client.d.ts +31 -0
  390. package/dist/learning/embedder-endpoint-client.js +103 -10
  391. package/dist/learning/embedding-space.d.ts +12 -0
  392. package/dist/learning/embedding-space.js +17 -0
  393. package/dist/learning/experience-capture-middleware.js +25 -13
  394. package/dist/learning/experience-capture.js +1 -1
  395. package/dist/learning/experience-consolidation.d.ts +18 -0
  396. package/dist/learning/experience-consolidation.js +55 -8
  397. package/dist/learning/experience-space-verification.d.ts +71 -0
  398. package/dist/learning/experience-space-verification.js +147 -0
  399. package/dist/learning/pattern-lifecycle.d.ts +40 -4
  400. package/dist/learning/pattern-lifecycle.js +153 -76
  401. package/dist/learning/pattern-null-store.d.ts +5 -0
  402. package/dist/learning/pattern-null-store.js +8 -0
  403. package/dist/learning/pattern-promotion.js +6 -3
  404. package/dist/learning/pattern-store.d.ts +6 -0
  405. package/dist/learning/pattern-store.js +19 -6
  406. package/dist/learning/qe-reasoning-bank.js +2 -2
  407. package/dist/learning/real-embeddings.js +3 -1
  408. package/dist/learning/real-qe-reasoning-bank.d.ts +5 -0
  409. package/dist/learning/real-qe-reasoning-bank.js +77 -47
  410. package/dist/learning/rvf-pattern-store.js +6 -2
  411. package/dist/learning/sqlite-persistence.d.ts +6 -0
  412. package/dist/learning/sqlite-persistence.js +10 -0
  413. package/dist/mcp/bundle.js +642 -571
  414. package/dist/mcp/entry.js +4 -0
  415. package/dist/mcp/handlers/domain-handler-configs.js +2 -0
  416. package/dist/mcp/handlers/trajectory-judge.js +1 -1
  417. package/dist/mcp/protocol-server.js +1 -0
  418. package/dist/mcp/tools/visual-accessibility/index.js +8 -2
  419. package/dist/mcp/types.d.ts +6 -0
  420. package/dist/optimization/session-cache.d.ts +17 -1
  421. package/dist/optimization/session-cache.js +40 -36
  422. package/dist/planning/goap-planner.d.ts +6 -0
  423. package/dist/planning/goap-planner.js +35 -19
  424. package/dist/planning/plan-executor.js +24 -15
  425. package/dist/routing/co-execution-repository.js +12 -9
  426. package/dist/routing/routing-feedback.d.ts +8 -0
  427. package/dist/routing/routing-feedback.js +46 -24
  428. package/dist/routing/routing-outcomes-migration.js +7 -2
  429. package/dist/shared/llm/spend-ledger.d.ts +9 -0
  430. package/dist/shared/llm/spend-ledger.js +64 -39
  431. package/dist/shared/sqlite-lock-wait.d.ts +27 -0
  432. package/dist/shared/sqlite-lock-wait.js +37 -0
  433. package/dist/shared/sqlite-write-queue.d.ts +28 -0
  434. package/dist/shared/sqlite-write-queue.js +38 -0
  435. package/dist/shared/test-runner-project.d.ts +69 -0
  436. package/dist/shared/test-runner-project.js +186 -0
  437. package/dist/skills/security-visual-testing/index.d.ts +3 -1
  438. package/dist/skills/security-visual-testing/index.js +49 -35
  439. package/dist/skills/security-visual-testing/types.d.ts +19 -3
  440. package/dist/workers/workers/heartbeat-scheduler.js +5 -5
  441. package/dist/workers/workers/learning-consolidation.js +8 -7
  442. package/package.json +4 -2
  443. package/dist/cli/chunks/adapter-23KA2YW7.js +0 -2
  444. package/dist/cli/chunks/agent-booster-wasm-2DLAEZK6.js +0 -2
  445. package/dist/cli/chunks/aqe-learning-engine-MUICAXW5.js +0 -2
  446. package/dist/cli/chunks/base-XPWGYDKD.js +0 -2
  447. package/dist/cli/chunks/browser-workflow-UMQVBVGK.js +0 -2
  448. package/dist/cli/chunks/chunk-3FITMWWJ.js +0 -21
  449. package/dist/cli/chunks/chunk-ARRBXCII.js +0 -4
  450. package/dist/cli/chunks/chunk-BBYJBZHG.js +0 -14
  451. package/dist/cli/chunks/chunk-BM3EJLMV.js +0 -153
  452. package/dist/cli/chunks/chunk-D3ZZ2NLL.js +0 -62
  453. package/dist/cli/chunks/chunk-DLTB5KCR.js +0 -2
  454. package/dist/cli/chunks/chunk-DRLSJJIC.js +0 -6
  455. package/dist/cli/chunks/chunk-HAYKLXCT.js +0 -744
  456. package/dist/cli/chunks/chunk-HHBF2BZC.js +0 -65
  457. package/dist/cli/chunks/chunk-K7RT6ITZ.js +0 -2
  458. package/dist/cli/chunks/chunk-L752CNG3.js +0 -13
  459. package/dist/cli/chunks/chunk-MQXWG55U.js +0 -12
  460. package/dist/cli/chunks/chunk-WM2QRIRD.js +0 -14
  461. package/dist/cli/chunks/chunk-WRC3HLUY.js +0 -29
  462. package/dist/cli/chunks/chunk-XTZGAG6P.js +0 -27
  463. package/dist/cli/chunks/chunk-YKQWIXUY.js +0 -2
  464. package/dist/cli/chunks/client-E43GWLQH.js +0 -2
  465. package/dist/cli/chunks/core-handlers-R5A3SQDY.js +0 -2
  466. package/dist/cli/chunks/cross-domain-router-LLYVPZF6.js +0 -2
  467. package/dist/cli/chunks/daemon-BYYPIJ7G.js +0 -18
  468. package/dist/cli/chunks/dream-6C4NURSE.js +0 -2
  469. package/dist/cli/chunks/embed-and-insert-pattern-URES5Q6J.js +0 -3
  470. package/dist/cli/chunks/experience-capture-middleware-SYJQSBKE.js +0 -40
  471. package/dist/cli/chunks/file-discovery-J5IE5KP7.js +0 -2
  472. package/dist/cli/chunks/heartbeat-scheduler-FC5PBTMN.js +0 -2
  473. package/dist/cli/chunks/hnsw-adapter-47UIVOBG.js +0 -2
  474. package/dist/cli/chunks/hnsw-index-3AKVLOZQ.js +0 -2
  475. package/dist/cli/chunks/hybrid-backend-YAOSNX47.js +0 -2
  476. package/dist/cli/chunks/impact-analyzer-4FMJXM4M.js +0 -2
  477. package/dist/cli/chunks/init-wizard-RTLCRWDT.js +0 -2
  478. package/dist/cli/chunks/kernel-2OWIGGGT.js +0 -2
  479. package/dist/cli/chunks/knowledge-graph-25XXKDJN.js +0 -2
  480. package/dist/cli/chunks/llm-router-service-G3EIN4UB.js +0 -2
  481. package/dist/cli/chunks/load-test-D6QYNIVT.js +0 -2
  482. package/dist/cli/chunks/memory-backend-LDFFZMEQ.js +0 -2
  483. package/dist/cli/chunks/memory-handlers-3SQVY7FE.js +0 -2
  484. package/dist/cli/chunks/pattern-null-store-KDVRM7PW.js +0 -2
  485. package/dist/cli/chunks/project-root-DDGBWDP6.js +0 -2
  486. package/dist/cli/chunks/protocol-executor-KBOLLCWA.js +0 -2
  487. package/dist/cli/chunks/qe-reasoning-bank-GRXBT7FC.js +0 -2
  488. package/dist/cli/chunks/queen-coordinator-L2QWMJ5Q.js +0 -2
  489. package/dist/cli/chunks/real-embeddings-I2UVNNB3.js +0 -2
  490. package/dist/cli/chunks/router-FT5WJPUH.js +0 -2
  491. package/dist/cli/chunks/routing-feedback-EO2MKOUX.js +0 -2
  492. package/dist/cli/chunks/rvf-dual-writer-WHBFQJVU.js +0 -2
  493. package/dist/cli/chunks/rvf-migration-adapter-YT3APF2I.js +0 -2
  494. package/dist/cli/chunks/rvf-migration-coordinator-VUIZHTVG.js +0 -2
  495. package/dist/cli/chunks/rvf-native-adapter-37PUFKQD.js +0 -2
  496. package/dist/cli/chunks/safe-db-TDZKUOZJ.js +0 -2
  497. package/dist/cli/chunks/schedule-CRKTRY2A.js +0 -2
  498. package/dist/cli/chunks/scheduler-6ZBDVQWN.js +0 -2
  499. package/dist/cli/chunks/sqlite-persistence-FFJQAIKW.js +0 -2
  500. package/dist/cli/chunks/sync-54LUAUTK.js +0 -2
  501. package/dist/cli/chunks/task-handler-K3OXHYKU.js +0 -62
  502. package/dist/cli/chunks/test-runner-process-OTQDAJLN.js +0 -2
  503. package/dist/cli/chunks/token-bootstrap-3QMABE45.js +0 -2
  504. package/dist/cli/chunks/tree-sitter-wasm-parser-D6JTTHTP.js +0 -2
  505. package/dist/cli/chunks/unified-memory-QARWQKJ2.js +0 -2
  506. package/dist/cli/chunks/unified-memory-hnsw-LHY3DXCP.js +0 -2
  507. package/dist/cli/chunks/unified-persistence-WEYYGLHM.js +0 -2
  508. package/dist/cli/chunks/visual-security-O4ALMCXQ.js +0 -2
  509. package/dist/cli/chunks/witness-chain-B3YW5NMS.js +0 -2
  510. package/dist/cli/chunks/witness-chain-PIYR72HJ.js +0 -2
  511. package/dist/cli/chunks/witness-chain-repair-YUG7E3UX.js +0 -2
  512. package/dist/cli/chunks/workflow-orchestrator-3ZN2BCGY.js +0 -2
  513. package/dist/cli/chunks/wrappers-PW2O27LL.js +0 -2
@@ -1,65 +0,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.14");process.exit(0)}
2
- import{d as V,e as X,g as ae,h as G}from"./chunk-JJHLGGPP.js";import{a as oe}from"./chunk-5Z4MO2F3.js";import{a as ce}from"./chunk-UMHFTQTR.js";import{d as Ue,e as qe,f as Qe,s as x,t as W}from"./chunk-L752CNG3.js";import{i as O}from"./chunk-QP6GL3O5.js";import{c as P,d as S}from"./chunk-RE6JTSDM.js";import{B as $,D as L,G as ie,P as k,S as _,b as F}from"./chunk-E7OR6V3V.js";import{c as ke}from"./chunk-O756AOUX.js";import{c as _e,d as ft}from"./chunk-2UZBLC5H.js";import{c as j,e as Ne,f as Me}from"./chunk-L7PC675Y.js";import{a as se,b as He,d as Le,f as mt}from"./chunk-2W5MQDHM.js";import{a as b,b as Fe,e as Oe}from"./chunk-L5VSLPMW.js";import{c as B,e as ht}from"./chunk-V6SE2ZU2.js";var Z=B(R=>{var Et=R&&R.__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(R,"__esModule",{value:!0});var At=Object.prototype.hasOwnProperty;function pe(n,e){return At.call(n,e)}R.hasOwnProperty=pe;function Ge(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}R._objectKeys=Ge;function Tt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}R._deepClone=Tt;function Rt(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}R.isInteger=Rt;function fe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}R.escapePathComponent=fe;function xt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}R.unescapePathComponent=xt;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""}R._getPathRecursive=ge;function Ct(n,e){if(n===e)return"/";var t=ge(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}R.getPath=Ct;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=Ge(n),i=r.length,s=0;s<i;s++)if(me(n[r[s]]))return!0}}return!1}R.hasUndefined=me;function Xe(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 It=(function(n){Et(e,n);function e(t,r,i,s,a){var l=this.constructor,d=n.call(this,Xe(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=Xe(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);R.PatchError=It});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}}},Dt={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=Dt[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 Ye(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=Ye;function Ft(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=Ft;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=Ke([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 Ke(n,e,t){try{if(!Array.isArray(n))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ye(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=Ke;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 Ze=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var A=Z(),Ot=ye(),Se=new WeakMap,_t=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Nt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Mt(n){return Se.get(n)}function Ht(n,e){return n.observers.get(e)}function Lt(n,e){n.observers.delete(e.callback)}function kt(n,e){e.unobserve()}q.unobserve=kt;function Ut(n,e){var t=[],r,i=Mt(n);if(!i)i=new _t(n),Se.set(n,i);else{var s=Ht(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),Lt(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 Nt(e,r)),r}q.observe=Ut;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&&Ot.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 qt(n,e,t){t===void 0&&(t=!1);var r=[];return we(n,e,r,"",t),r}q.compare=qt});var et=B(M=>{var Qt=ye();Object.assign(M,Qt);var $t=Ze();Object.assign(M,$t);var re=Z();M.JsonPatchError=re.PatchError;M.deepClone=re._deepClone;M.escapePathComponent=re.escapePathComponent;M.unescapePathComponent=re.unescapePathComponent});var T=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}};function rr(n){return n instanceof T&&n.disposition==="COMMITTED_PENDING_INDEX"?n.patternId:null}ft();import{existsSync as Zt}from"node:fs";import{join as ct}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&&!x()&&await W();let e=x()?.spaceId??this.embeddingSpaceId??null;e?(this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),Qe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)):(this.rvfInitError=Ue,this.adapter=null,this.initialized=!0,qe())}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-FFJQAIKW.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 T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=x()?.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 T(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return S(new T(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 T(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=x()?.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=x()?.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}}};mt();Oe();_();function gt(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"&&Object.hasOwn(a,l))a=a[l];else{a=void 0;break}}if(a!==void 0)return a}}function yt(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=gt(n,e.field);return yt(t,e.operator,e.value)}default:return!0}}function $e(n,e){return e?n.filter(t=>K(t,e)):n}_();_();var Je=1e4,Be=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 ze="0123456789abcdef";function vt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=ze[i>>4]+ze[i&15]}return t}function St(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 wt(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 bt(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 Pt(n,e,t){return 1-bt(n,e,t)}var de=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Je,this.baseSeed=e?.seed??Be,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=St(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 wt([r,i])}similarity(e,t){return Pt(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??Je,this.baseSeed=e?.seed??Be,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:vt(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 We(n){return new ue(n)}function Ve(n){return $()?new de(n):null}var Pe=ht(et(),1),be=Pe.default??Pe,zt=`
4
- CREATE TABLE IF NOT EXISTS pattern_deltas (
5
- id TEXT PRIMARY KEY,
6
- pattern_id TEXT NOT NULL,
7
- version INTEGER NOT NULL,
8
- timestamp INTEGER NOT NULL,
9
- type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
10
- patch TEXT NOT NULL DEFAULT '[]',
11
- reverse_patch TEXT NOT NULL DEFAULT '[]',
12
- metadata TEXT
13
- );
14
- CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
15
- ON pattern_deltas (pattern_id, version);
16
- CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
17
- ON pattern_deltas (timestamp);
18
- `;function tt(n,e){let t=be.compare(n,e),r=be.compare(e,n);return{forward:t,reverse:r}}function Jt(n,e){let t=JSON.parse(JSON.stringify(n));return be.applyPatch(t,e).newDocument}function rt(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var ne=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(zt),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
- INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
- `)),this.prepared.set("getHistory",this.db.prepare(`
22
- SELECT * FROM pattern_deltas
23
- WHERE pattern_id = ?
24
- ORDER BY version ASC
25
- `)),this.prepared.set("currentVersion",this.db.prepare(`
26
- SELECT MAX(version) as max_version FROM pattern_deltas
27
- WHERE pattern_id = ?
28
- `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
- SELECT * FROM pattern_deltas
30
- WHERE timestamp > ?
31
- ORDER BY timestamp ASC
32
- `)),this.prepared.set("countForPattern",this.db.prepare(`
33
- SELECT COUNT(*) as cnt FROM pattern_deltas
34
- WHERE pattern_id = ?
35
- `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
- DELETE FROM pattern_deltas
37
- WHERE pattern_id = ? AND version IN (
38
- SELECT version FROM pattern_deltas
39
- WHERE pattern_id = ?
40
- ORDER BY version ASC
41
- LIMIT ?
42
- )
43
- `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:O(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:l}=tt(t,r),d={id:O(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:l,metadata:i};return this.insertEvent(d),this.enforceRetention(e),d}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:l,reverse:d}=tt(a,s),o={id:O(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:l,reversePatch:d,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(rt)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(rt)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=Jt(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
- WHERE pattern_id = ? AND version != 0 AND id IN (
45
- SELECT id FROM pattern_deltas
46
- WHERE pattern_id = ? AND version != 0
47
- ORDER BY version ASC
48
- LIMIT ?
49
- )`).run(e,e,s)}}};_();var Bt={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={...Bt,...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 nt(n){return L()?new Ee(n):null}_();var jt=128,Wt=8,Vt=1e4,Ae=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??jt,this.beta=e?.beta??Wt,this.maxPatterns=e?.maxPatterns??Vt,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 it(n){return new Ae(n)}_();var Xt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},H=1e-5,st=1-H;function Gt(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 Yt(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(Yt(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=Gt(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<=st)return new Float32Array(e);let r=st/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={...Xt,...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 at(n){return Kt()?new Te(n):null}function Kt(){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=at(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 ot(n){return new Re(n)}var xe=null;function lt(){return xe||(xe=We({dimensions:1e4})),xe}var Ce;function er(){return Ce===void 0&&(Ce=Ve()),Ce}var Q=null,Ie=0,dt;function ut(n,e){return(!Q||Ie!==n||dt!==e)&&(Q=it({dimension:n,maxPatterns:1e4}),Ie=n,dt=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=x()?.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(!x()&&!this.config.embeddingSpaceId&&await W(),this.hnswSpaceId=x()?.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-N3AUUUU7.js"),{HnswAdapter:l}=await import("./hnsw-adapter-47UIVOBG.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-3AKVLOZQ.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=x()?.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=nt()),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 T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=x()?.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 T(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&l)return S(new T(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),S(new T(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 T(e.id,l?"COMMITTED_PENDING_INDEX":"FAILED",c))}}if($())try{let c=lt().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=er();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{ut(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=x()?.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=ut(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=$e(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=lt(),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=ot({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 hn(n,e){try{if(F().useRVFPatternStore&&Le()){let r=process.env.AQE_PROJECT_ROOT??_e(),i=ct(r,".agentic-qe"),s=ct(i,"patterns.rvf");if(Zt(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{T as a,rr as b,Y as c,le as d,hn as e};
50
- /*! Bundled license information:
51
-
52
- fast-json-patch/commonjs/helpers.js:
53
- (*!
54
- * https://github.com/Starcounter-Jack/JSON-Patch
55
- * (c) 2017-2022 Joachim Wester
56
- * MIT licensed
57
- *)
58
-
59
- fast-json-patch/commonjs/duplex.js:
60
- (*!
61
- * https://github.com/Starcounter-Jack/JSON-Patch
62
- * (c) 2017-2021 Joachim Wester
63
- * MIT license
64
- *)
65
- */
@@ -1,2 +0,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.14");process.exit(0)}
2
- var o=!1;function r(t){if(!o){for(let e of["ALTER TABLE routing_outcomes ADD COLUMN exploration INTEGER NOT NULL DEFAULT 0","ALTER TABLE routing_outcomes ADD COLUMN criticality REAL","ALTER TABLE routing_outcomes ADD COLUMN q_weight REAL"])try{t.prepare(e).run()}catch{}try{t.prepare("CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration)").run()}catch{}o=!0}}export{r as a};
@@ -1,13 +0,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.14");process.exit(0)}
2
- import{b as Q,d as q}from"./chunk-BNG4J3CE.js";import{c as z,d as me}from"./chunk-2UZBLC5H.js";import{a as F,e as pe}from"./chunk-L5VSLPMW.js";q();pe();q();import*as _ from"node:http";import*as D from"node:https";import{createHash as ue}from"node:crypto";import{URL as X}from"node:url";var N={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},fe="AQE embedder endpoint identity canary v1",ge="/v1/embeddings";function J(t){if(t.startsWith("unix:"))return t;try{let e=new X(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function he(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new X(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var U=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}trip(){this.trippedAt=Date.now()}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},P=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??N.model,expectedDim:e.expectedDim??N.expectedDim,connectTimeoutMs:e.connectTimeoutMs??N.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??N.requestTimeoutMs,failureThreshold:e.failureThreshold??N.failureThreshold,failureWindowMs:e.failureWindowMs??N.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=he(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new D.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new _.Agent({keepAlive:!0});this.breaker=new U(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([fe]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=ue("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}async probeThroughOpenBreaker(){try{return await this.probe()}catch(e){throw this.breaker.trip(),e}}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return Q(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(ge,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=_.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?D.request:_.request);let o=this.parsed.safeUrl,c=this.opts.connectTimeoutMs,S=this.opts.requestTimeoutMs;return new Promise((p,k)=>{let w=!1,M=d=>{w||(w=!0,p(d))},b=d=>{w||(w=!0,k(d))},I=s(i,d=>{let h=[];d.on("data",f=>h.push(Buffer.from(f))),d.on("end",()=>{let f=Buffer.concat(h).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){b(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${f.slice(0,200)}`));return}try{let y=JSON.parse(f);M(y)}catch(y){b(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${y.message}`))}}),d.on("error",f=>b(f))});I.on("socket",d=>{d.setTimeout(c);let h=()=>{d.setTimeout(S)};d.connecting?d.once("connect",h):h(),d.on("timeout",()=>{let f=d.connecting?"connect":"request",y=d.connecting?c:S,R=new Error(`[EmbedderEndpointClient] ${f} timeout after ${y}ms`);b(R),I.destroy(R)})}),I.on("error",d=>b(d)),I.write(n),I.end()})}};me();import{join as K,resolve as Ee}from"node:path";import{existsSync as be,mkdirSync as ye}from"node:fs";import{createRequire as we}from"node:module";var Ie=we(import.meta.url);function ve(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:Ee(z(),t):K(z(),".agentic-qe","memory.db")}var Y="_system",Z="embedder_identity:",C=null,B=!1;function ee(){if(C)return C;if(B)return null;try{let t=Ie("better-sqlite3"),e=ve(),n=K(e,"..");be(n)||ye(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
- CREATE TABLE IF NOT EXISTS kv_store (
4
- key TEXT NOT NULL,
5
- namespace TEXT NOT NULL,
6
- value TEXT NOT NULL,
7
- expires_at INTEGER,
8
- created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
9
- PRIMARY KEY (namespace, key)
10
- );
11
- CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
- `),C=r,r}catch{return B=!0,null}}function te(t){let e=ee();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(Y,Z+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function ne(t){let e=ee();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Z+t.endpoint,Y,JSON.stringify(n))}function re(){if(C)try{C.close()}catch{}C=null,B=!1}q();import{createHash as oe}from"node:crypto";import{existsSync as xe,readFileSync as Te,renameSync as Se,writeFileSync as Ne}from"node:fs";var se="aqe embedding-space compatibility canary v1";var v=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Ce(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function ae(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return oe("sha256").update(e).digest("hex").slice(0,16)}function V(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=oe("sha256").update("aqe:embedding-space:v1\0").update(Ce(t)).digest("hex");return{...t,spaceId:e}}function We(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}var Re="[VectorSearch] WARN: semantic vector search is not active: no embedding runtime was available when the ANN indexes were opened (set AQE_EMBEDDER_ENDPOINT, or install @huggingface/transformers). Any existing vectors in patterns.rvf and brain.rvf are kept and will be used once an embedder is available; until then pattern search uses SQLite text matching.",Ge="VECTOR_SPACE_UNVERIFIED: no embedding runtime was available when the RVF index was opened; index left unbound (existing vectors are kept)",ie=!1;function je(){ie||(ie=!0,console.warn(Re))}function _e(t){return`${t}.space.json`}function Qe(t,e,n){if(!e)throw new v("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=_e(t);if(xe(r)){let s;try{s=JSON.parse(Te(r,"utf8"))}catch{throw new v("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new v("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new v("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new v("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;Ne(i,`${JSON.stringify(a)}
13
- `,{encoding:"utf8",mode:384}),Se(i,r)}var H=null,g=null,x=null,E=!1,A="",L=null,m=null,l=null,T=null,G={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},u=new Map,de=36e5;function W(t){return l?`endpoint:${l.fingerprint}:${t}`:`inproc:${t}`}function le(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function O(t={},e=!1){if(E&&!e)throw new Error(`Transformer initialization previously failed: ${A}`);if(x)return x;let n={...G,...t};return x=(async()=>{try{if(n.endpoint){let S=J(n.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${S}`),m=new P({endpoint:n.endpoint,token:n.endpointToken,model:n.modelName,expectedDim:$()}),l=await m.probe(),T=V({provider:"openai-compatible-endpoint",model:n.modelName,dimensions:l.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:l.endpoint,runtimeFingerprint:l.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${l.dim} fingerprint=${l.fingerprint}`);try{let p=te(l.endpoint);p&&p.fingerprint!==l.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${p.fingerprint} dim=${p.dim}, current fingerprint=${l.fingerprint} dim=${l.dim}. Vectors written before this change may no longer be comparable.`),ne(l)}catch(p){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(p)}`)}g=Me(m),E=!1,A="";return}let r;try{r=await import("./transformers-UCJ3HHHC.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}H=r.pipeline,console.log(`[RealEmbeddings] Loading model: ${n.modelName}`);let a=performance.now();g=await H("feature-extraction",n.modelName,{quantized:n.quantized});let i=g;if(!i)throw new Error("Transformer pipeline returned no embedding model");let s=await i(se,{pooling:"mean",normalize:!0}),o=Array.from(s.data);T=V({provider:"huggingface-transformers",model:n.modelName,dimensions:o.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${n.quantized?"quantized":"full"}`,runtimeFingerprint:ae(o)}),E=!1,A="";let c=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${c.toFixed(0)}ms`)}catch(r){throw E=!0,A=F(r),new Error(`Failed to initialize transformer model: ${A}`)}})(),x}function Me(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??$(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function et(t,e={}){let n={...G,...e};if(le(t))return new Array($()).fill(0);if(g||await O(e),!g)throw new Error("Embedding model failed to initialize");let r=W(t);if(n.enableCache){let c=u.get(r);if(c&&Date.now()-c.timestamp<de)return c.embedding}let a=performance.now(),i=await g(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(u.size>=n.maxCacheSize){let c=u.keys().next().value;c&&u.delete(c)}u.set(r,{embedding:s,timestamp:Date.now()})}return s}async function tt(t,e={}){let n={...G,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)le(t[o])?i[o]=new Array($()).fill(0):s.push(o);if(s.length===0)return i;if(g||await O(e),!g)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let c=u.get(W(t[o]));c&&Date.now()-c.timestamp<de?i[o]=c.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),c=32;for(let p=0;p<r.length;p+=c){let k=Math.min(p+c,r.length),w=r.slice(p,k),M=await g(w,{pooling:"mean",normalize:!0}),b=M.dims||[w.length,384],I=b[0],d=b[1];for(let h=0;h<I;h++){let f=h*d,y=Array.from(M.data.slice(f,f+d)),R=p+h,ce=a[R];if(i[ce]=y,n.enableCache){if(u.size>=n.maxCacheSize){let j=u.keys().next().value;j&&u.delete(j)}u.set(W(r[R]),{embedding:y,timestamp:Date.now()})}}}let S=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${S.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function nt(){u.clear(),console.log("[RealEmbeddings] Cache cleared")}function rt(){return{size:u.size,hitRate:0}}function it(){return!E&&g!==null}function $(){return 384}function ot(){H=null,g=null,x=null,E=!1,A="",u.clear(),m&&m.close(),m=null,l=null,T=null,re()}function st(){E&&(E=!1,A="",x=null,m&&m.close(),m=null,l=null)}async function at(t={}){if(E)return L??=Pe(t).finally(()=>{L=null}),L;let e=m;if(!e||!e.getBreakerState().open)return;let n=await e.probeThroughOpenBreaker();if(l&&n.fingerprint!==l.fingerprint)throw new Error(`[RealEmbeddings] endpoint identity changed since this process bound to it (fingerprint ${l.fingerprint} -> ${n.fingerprint}); restart to use the new embedding space`)}async function Pe(t){m&&m.close(),m=null,l=null,x=null,await O(t,!0)}function dt(){return m!==null}function lt(){return l}function ct(){return T}async function pt(){if(T)return T;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await O({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),T):null}export{J as a,se as b,We as c,Ge as d,je as e,Qe as f,G as g,et as h,tt as i,nt as j,rt as k,it as l,$ as m,ot as n,st as o,at as p,dt as q,lt as r,ct as s,pt as t};
@@ -1,12 +0,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.14");process.exit(0)}
2
- import{c as H,d as J}from"./chunk-H3C5FJRH.js";import{h as G}from"./chunk-E2JLAW3U.js";import{g as U}from"./chunk-Z2S7DNFP.js";import{e as N}from"./chunk-HHBF2BZC.js";import{e as T}from"./chunk-JJHLGGPP.js";import{b as v,c as C}from"./chunk-O5CEL447.js";import{b as B}from"./chunk-HV43NX4A.js";import{b,d as _}from"./chunk-XN3KCKAM.js";import{i as W}from"./chunk-QP6GL3O5.js";import{c as k,d as E}from"./chunk-RE6JTSDM.js";import{a as oe}from"./chunk-YKQWIXUY.js";import{c as q}from"./chunk-C3OIBFAA.js";import{S as se,b as z}from"./chunk-E7OR6V3V.js";import{a as y,e as $}from"./chunk-L5VSLPMW.js";import{randomUUID as te}from"crypto";$();_();import{randomUUID as ce}from"node:crypto";var D=C(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${ce()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",D,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let s=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",D,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),n!==void 0&&s.push("--quality",String(n)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",D,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-QARWQKJ2.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(o=>o.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
3
- INSERT OR REPLACE INTO qe_trajectories
4
- (id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
5
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
6
- `).run(e.id,e.task,e.agent||null,null,r,a,e.success?1:0,JSON.stringify(e.steps),e.feedback||null)}catch(t){console.debug("[TrajectoryBridge] Trajectory persistence failed:",t instanceof Error?t.message:t)}}};var V=C(),X={low:[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i],high:[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/database.*migration/i,/distributed/i,/concurrent/i]},R=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;routingHistory=[];async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async routeTask(e){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",V,"hooks","model-route","--task",e],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}),n=i.match(/model[:\s]+["']?(haiku|sonnet|opus)/i),r=i.match(/confidence[:\s]+([0-9.]+)/i),a=i.match(/reason(?:ing)?[:\s]+["']?([^"'\n]+)/i);if(n)return{model:n[1].toLowerCase(),confidence:r?parseFloat(r[1]):.7,reasoning:a?.[1]?.trim()}}catch(t){console.debug("[ModelRouterBridge] Claude Flow routing failed:",t instanceof Error?t.message:t)}return this.localRoute(e)}async recordOutcome(e){if(this.routingHistory.push(e),this.routingHistory.length>1e3&&(this.routingHistory=this.routingHistory.slice(-500)),this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process");t("npx",["--no-install",V,"hooks","model-outcome","--task",e.task,"--model",e.model,"--outcome",e.outcome],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch(t){console.debug("[ModelRouterBridge] Outcome recording failed:",t instanceof Error?t.message:t)}}getStats(){let e={totalRoutings:this.routingHistory.length,modelDistribution:{haiku:0,sonnet:0,opus:0},successRate:{haiku:0,sonnet:0,opus:0}},t={haiku:0,sonnet:0,opus:0};for(let i of this.routingHistory)e.modelDistribution[i.model]++,i.outcome==="success"&&t[i.model]++;for(let i of["haiku","sonnet","opus"]){let n=e.modelDistribution[i];e.successRate[i]=n>0?t[i]/n:0}return e}isClaudeFlowAvailable(){return this.claudeFlowAvailable}localRoute(e){let t=e.toLowerCase();for(let i of X.low)if(i.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task detected - using haiku for speed"};for(let i of X.high)if(i.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task detected - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task description - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity task - using sonnet for balance"}}};_();$();var M=C(),S=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;analysisCache=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async analyze(e,t="medium"){let i=e||this.options.projectRoot,n=`${i}:${t}`,r=this.analysisCache.get(n);if(r)return r;if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=a("npx",["--no-install",M,"hooks","pretrain","--path",i,"--depth",t],{encoding:"utf-8",timeout:12e4,cwd:this.options.projectRoot});try{let o=b(s),d={success:!0,repositoryPath:i,depth:t,analysis:o.analysis||void 0,agentConfigs:o.agentConfigs};return this.analysisCache.set(n,d),d}catch{return{success:!0,repositoryPath:i,depth:t}}}catch(a){console.debug("[PretrainBridge] Claude Flow analyze failed, using local:",a instanceof Error?a.message:a)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",M,"hooks","build-agents","--format",e],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot});try{return b(i)}catch(n){return console.debug("[PretrainBridge] Agent config parse error:",n instanceof Error?n.message:n),[]}}catch(t){console.debug("[PretrainBridge] Claude Flow generateAgentConfigs failed:",t instanceof Error?t.message:t)}return this.generateLocalAgentConfigs()}async transferPatterns(e,t=.7){if(this.claudeFlowAvailable)try{let{execFileSync:i}=await import("child_process"),n=i("npx",["--no-install",M,"hooks","transfer","--source-path",e,"--min-confidence",String(t)],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot}),r=n.match(/transferred[:\s]+(\d+)/i),a=n.match(/skipped[:\s]+(\d+)/i);return{transferred:r?parseInt(r[1]):0,skipped:a?parseInt(a[1]):0}}catch(i){console.debug("[PretrainBridge] Claude Flow transferPatterns failed:",i instanceof Error?i.message:i)}return{transferred:0,skipped:0}}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async localAnalyze(e,t){try{let{glob:i}=await import("tinyglobby"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),d=await i(t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],{cwd:e,ignore:["node_modules/**","dist/**","coverage/**",".git/**"],expandDirectories:!1,onlyFiles:!0}),c=new Set,g=new Set;for(let p of d.slice(0,100))(p.endsWith(".ts")||p.endsWith(".tsx"))&&c.add("typescript"),(p.endsWith(".js")||p.endsWith(".jsx"))&&c.add("javascript"),p.endsWith(".py")&&c.add("python"),p.endsWith(".go")&&c.add("go"),p.endsWith(".rs")&&c.add("rust");let w=a(e,"package.json");if(n(w))try{let p=b(r(w,"utf-8")),f={...p.dependencies,...p.devDependencies};f.react&&g.add("react"),f.vue&&g.add("vue"),f.angular&&g.add("angular"),f.vitest&&g.add("vitest"),f.jest&&g.add("jest"),f.playwright&&g.add("playwright"),f.express&&g.add("express"),f.fastify&&g.add("fastify")}catch(p){console.debug("[PretrainBridge] package.json parse error:",p instanceof Error?p.message:p)}let m={success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(c),frameworks:Array.from(g),patterns:[],complexity:d.length>500?3:d.length>100?2:1}};return this.analysisCache.set(`${e}:${t}`,m),m}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}generateLocalAgentConfigs(){return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-quality-gate",type:"worker",capabilities:["quality-assessment","risk-scoring"],model:"sonnet"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}};var Q=class{constructor(e){this.options=e;this.trajectory=new P(e),this.modelRouter=new R(e),this.pretrain=new S(e)}options;trajectory;modelRouter;pretrain;initialized=!1;async initialize(){this.initialized||(await Promise.all([this.trajectory.initialize(),this.modelRouter.initialize(),this.pretrain.initialize()]),this.initialized=!0)}getStatus(){return{available:this.isAvailable(),features:{trajectories:this.trajectory.isClaudeFlowAvailable(),modelRouting:this.modelRouter.isClaudeFlowAvailable(),pretrain:this.pretrain.isClaudeFlowAvailable(),patternSearch:this.trajectory.isClaudeFlowAvailable()}}}isAvailable(){return this.trajectory.isClaudeFlowAvailable()||this.modelRouter.isClaudeFlowAvailable()||this.pretrain.isClaudeFlowAvailable()}};function K(u){return new Q(u)}import{createHash as le}from"node:crypto";oe();se();var F=q.create("experience-capture"),Z={"catches-bug":1,flaky:-1,"false-positive":-1,"new-coverage":.3,redundant:0,"code-smell":-.5,neutral:0},ue=new Set(Object.keys(Z));function Y(u){return typeof u=="string"&&ue.has(u)}function de(u){if(Y(u))return Z[u]}var pe={namespace:"qe-experiences",minQualityForPatternExtraction:.7,similarityThreshold:.85,promotionThreshold:T,maxExperiencesPerDomain:1e3,enableCrossDomainSharing:!0,autoCleanup:!0,cleanupIntervalMs:864e5},L=class{constructor(e,t,i,n={}){this.memory=e;this.patternStore=t;this.eventBus=i;this.config={...pe,...n}}memory;patternStore;eventBus;config;initialized=!1;cleanupTimer;activeExperiences=new Map;stats={totalCaptured:0,successfulCaptures:0,patternsExtracted:0,patternsPromoted:0,byDomain:new Map};sessionCaptureCount=0;witnessChain;nullRecorder;setWitnessChain(e){this.witnessChain=e}setNullRecorder(e){this.nullRecorder=e}async initialize(){this.initialized||(await this.loadStats(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0,console.log("[ExperienceCapture] Initialized"))}startCapture(e,t){let i=`exp-${Date.now()}-${W().slice(0,8)}`,n={id:i,task:e,agent:t?.agent,domain:t?.domain,model:t?.model,startedAt:Date.now(),completedAt:0,durationMs:0,steps:[],success:!1,quality:0,trajectoryId:t?.trajectoryId,metadata:t?.metadata,appliedPatterns:t?.appliedPatterns};return this.activeExperiences.set(i,n),i}recordStep(e,t){let i=this.activeExperiences.get(e);if(!i){console.warn(`[ExperienceCapture] Experience not found: ${e}`);return}i.steps.push({...t,timestamp:Date.now()})}async completeCapture(e,t){let i=this.activeExperiences.get(e);if(!i)return E(new Error(`Experience not found: ${e}`));let n=Date.now();i.completedAt=n,i.durationMs=n-i.startedAt,i.success=t.success,i.feedback=t.feedback,t.outcomeBasis&&(i.outcomeBasis=t.outcomeBasis),t.quality!==void 0?i.quality=t.quality:i.quality=this.calculateQuality(i);let r=t.testOutcome??i.metadata?.testOutcome;if(r&&Y(r)&&(i.testOutcome=r,i.reward=de(r)),this.witnessChain&&z().useWitnessChain)try{let o=this.witnessChain.appendWitness({type:"experience-capture",decision:i.success?"PASS":"FAIL",context:{experienceId:i.id,task:i.task,quality:i.quality,domain:i.domain,reward:i.reward},evidence:i.reward});i.witnessHash=o.hash}catch(o){F.warn("Failed to create witness receipt for experience",{experienceId:i.id,error:o instanceof Error?o.message:String(o)})}this.activeExperiences.delete(e),await this.storeExperience(i),this.updateStats(i);let a=i.reward!==void 0?i.reward<0:!i.success;if(this.nullRecorder&&a&&i.appliedPatterns?.length){let o=`${i.domain??"unknown"}:${i.agent??"unknown"}`;for(let d of i.appliedPatterns)try{this.nullRecorder({patternId:d,contextFingerprint:o,failureMode:i.testOutcome??i.feedback??"task-failure",trajectoryRef:i.trajectoryId,evidenceClass:"EXECUTED"})}catch(c){F.warn("Failed to record pattern null",{patternId:d,error:c instanceof Error?c.message:String(c)})}}let s=i.reward===void 0||i.reward>0;if(i.outcomeBasis!==void 0||i.success&&i.quality>=this.config.minQualityForPatternExtraction&&s){let o=await this.extractPattern(i);(o.newPattern||o.reinforced)&&(i.patterns=[o.patternId])}return this.emitExperienceCaptured(i),k(i)}getActiveExperience(e){return this.activeExperiences.get(e)}getPendingCount(){return this.activeExperiences.size}async flushPending(){let e=Array.from(this.activeExperiences.entries());if(e.length===0)return 0;let t=0;for(let[i,n]of e){let r=Date.now();n.completedAt=r,n.durationMs=r-n.startedAt,n.quality=n.quality||this.calculateQuality(n),n.metadata={...n.metadata,flushedByCompaction:!0},await this.storeExperience(n),this.updateStats(n),this.activeExperiences.delete(i),t++}return F.info(`Flushed ${t} pending experiences before compaction`),t}async getExperience(e){let t=`${this.config.namespace}:experience:${e}`;return await this.memory.get(t)??null}async searchExperiences(e={}){let t=e.limit||100,i=[],n;e.domain?n=await this.memory.search(`${this.config.namespace}:index:domain:${e.domain}:*`,t*2):n=await this.memory.search(`${this.config.namespace}:experience:*`,t*2);for(let r of n){if(i.length>=t)break;let a=r.includes(":index:")?await this.memory.get(r):null,s=a?await this.getExperience(a):await this.memory.get(r);s&&(e.agent&&s.agent!==e.agent||e.success!==void 0&&s.success!==e.success||e.minQuality!==void 0&&s.quality<e.minQuality||i.push(s))}return i}async getStats(){let e={};for(let[t,i]of this.stats.byDomain)e[t]=i;return{totalExperiences:this.stats.totalCaptured,byDomain:e,successRate:this.stats.totalCaptured>0?this.stats.successfulCaptures/this.stats.totalCaptured:0,avgQuality:await this.calculateAvgQuality(),patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted}}async extractPattern(e){if(!this.patternStore)return{newPattern:!1,reinforced:!1,promoted:!1};let t=this.experienceIdentity(e),i=await this.patternStore.search(t,{limit:1,domain:e.domain,patternType:this.detectPatternType(e.task),useVectorSearch:!1});if(i.success&&i.value.length>0){let a=i.value[0],s=a.pattern.context?.experienceOrigin;if(s?.task===e.task&&s.domain===(e.domain??null)&&s.patternType===this.detectPatternType(e.task)&&a.pattern.patternType===s.patternType&&(!e.domain||a.pattern.qeDomain===e.domain)){let o=await this.patternStore.recordUsage(a.pattern.id,e.success,this.usageOutcomeTag(e)),d=await this.patternStore.get(a.pattern.id),c=!1;return d&&e.success&&d.tier==="short-term"&&d.usageCount>=this.config.promotionThreshold&&(await this.patternStore.promote(a.pattern.id)).success&&(c=!0,this.stats.patternsPromoted++,console.log(`[ExperienceCapture] Pattern promoted: ${a.pattern.id} (${d.usageCount} uses)`)),{newPattern:!1,patternId:a.pattern.id,reinforced:o.success,promoted:c}}}let n=this.experienceToPatternOptions(e),r=await this.patternStore.create(n);return r.success?(this.stats.patternsExtracted++,await this.patternStore.recordUsage(r.value.id,e.success,this.usageOutcomeTag(e)),{newPattern:!0,patternId:r.value.id,reinforced:!1,promoted:!1}):{newPattern:!1,reinforced:!1,promoted:!1}}async shareAcrossDomains(e){if(!this.config.enableCrossDomainSharing||!e.domain)return;let t=this.getRelatedDomains(e.domain);for(let i of t){let n=`${this.config.namespace}:shared:${i}:${e.id}`;await this.memory.set(n,{sourceExperience:e.id,sourceDomain:e.domain,sharedAt:Date.now()},{persist:!0})}}async cleanup(){let t=0;for(let i of this.stats.byDomain.keys()){let n=this.stats.byDomain.get(i)||0;if(n>this.config.maxExperiencesPerDomain){let r=await this.searchExperiences({domain:i,limit:n});r.sort((s,o)=>s.quality-o.quality||s.startedAt-o.startedAt);let a=n-this.config.maxExperiencesPerDomain;for(let s=0;s<Math.min(a,r.length);s++){let o=r[s];await this.softDeleteExperience(o.id),t++}}}return console.log(`[ExperienceCapture] Cleanup: ${t} archived (0 destroyed)`),{removed:0,consolidated:0,archived:t}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),await this.saveStats(),this.sessionCaptureCount===0&&console.warn("[ExperienceCapture] WARNING: Zero experiences captured this session. Learning cannot improve without experience data. Ensure tasks call startCapture()/completeCapture() to feed the learning loop."),this.activeExperiences.clear(),this.initialized=!1}async storeExperience(e){let t=`${this.config.namespace}:experience:${e.id}`;if(await this.memory.set(t,e,{persist:!0}),e.domain){let i=`${this.config.namespace}:index:domain:${e.domain}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}if(e.agent){let i=`${this.config.namespace}:index:agent:${e.agent}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}}async deleteExperience(e){await this.softDeleteExperience(e)}async softDeleteExperience(e){let t=await this.getExperience(e);if(!t)return;let i=`${this.config.namespace}:experience:${e}`,n={...t,_archived:!0};await this.memory.set(i,n,{persist:!0})}calculateQuality(e){if(e.steps.length===0)return e.success?.5:.2;let t=e.steps.filter(n=>n.quality!==void 0);if(t.length===0)return e.success?.6:.3;let i=t.reduce((n,r)=>n+(r.quality||0),0)/t.length;return e.success?Math.min(1,i+.1):Math.max(0,i-.2)}updateStats(e){if(this.stats.totalCaptured++,this.sessionCaptureCount++,e.success&&this.stats.successfulCaptures++,e.domain){let t=this.stats.byDomain.get(e.domain)||0;this.stats.byDomain.set(e.domain,t+1)}}async calculateAvgQuality(){let e=await this.searchExperiences({limit:100});return e.length===0?0:e.reduce((i,n)=>i+n.quality,0)/e.length}usageOutcomeTag(e){let t=typeof e.metadata?.runId=="string"?e.metadata.runId:void 0;return e.outcomeBasis!==void 0?B({measured:!0,success:e.success,basis:e.outcomeBasis},t):B({measured:!1,success:null,basis:"task-completed"},t)}experienceToPatternOptions(e){let t=this.detectPatternType(e.task),n=`Task: {{task}}
7
-
8
- Steps:
9
- ${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
10
- `)}
11
-
12
- Duration: ${e.durationMs}ms`;return{patternType:t,qeDomain:e.domain,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:[...this.extractTags(e),this.experienceIdentity(e)],experienceOrigin:{task:e.task,domain:e.domain??null,patternType:t},testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}experienceIdentity(e){return le("sha256").update(JSON.stringify([e.task,e.domain??null,this.detectPatternType(e.task)])).digest("hex")}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t} ${this.experienceIdentity(e)}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){F.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function ee(u,e,t,i){return new L(u,e,t,i)}var ge={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:T},I=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ge,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await H(J),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=N(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=G(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-6KENLN2W.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=ee(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-B3YW5NMS.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-B3YW5NMS.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-WEYYGLHM.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-WEYYGLHM.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-KDVRM7PW.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-5JCSKL2P.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-7J3S2OS6.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=r.byDomain?.[a]??0,o=r.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:r.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=K({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=U(i.value,t.value);return k(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return k([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),k([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${te().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${te().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(c){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(c))}let a=`${i??"unknown"}:${t??"unknown"}`,s;try{let c=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});c.success&&c.value.length>0&&(s=c.value.map(g=>g.pattern.id))}catch{}let o;this.experienceCapture&&(o=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:s}));let d={id:o||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(d.id,d),d.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let{glob:i}=await import("tinyglobby"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),d=await i(t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],{cwd:e,ignore:["node_modules/**","dist/**","coverage/**",".git/**"],expandDirectories:!1,onlyFiles:!0}),c=new Set,g=new Set;for(let m of d.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&c.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&c.add("javascript"),m.endsWith(".py")&&c.add("python"),m.endsWith(".go")&&c.add("go"),m.endsWith(".rs")&&c.add("rust");let w=a(e,"package.json");if(n(w))try{let m=b(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(c),frameworks:Array.from(g),patterns:[],complexity:d.length>500?3:d.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},me={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ie=class{config;constructor(e){this.config={...me,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),s=h(i.map(l=>l.tokenMetrics.costUsd)),o=h(n.map(l=>l.tokenMetrics.costUsd)),d=h(i.map(l=>l.tokenMetrics.savingsUsd)),c=h(n.map(l=>l.tokenMetrics.savingsUsd));if(o>s*1.1&&c<=d*1.05){let l=Math.min(1,(o-s)/(s||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(l),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(l=>l.qualityMetrics.gatePassRate)),w=h(n.map(l=>l.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(l=>l.learningMetrics.patternCount)),f=h(n.map(l=>l.learningMetrics.patternCount)),ne=h(i.map(l=>l.learningMetrics.averageConfidence)),O=h(n.map(l=>l.learningMetrics.averageConfidence)),re=Math.abs(f-p),ae=Math.abs(O-ne);re<1&&ae<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${O.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let x=h(i.map(l=>l.performanceMetrics.p95LatencyMs)),j=h(n.map(l=>l.performanceMetrics.p95LatencyMs));if(j>x*1.2&&x>0){let l=Math.min(1,(j-x)/(x||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${x.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(l),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(u){return u.length===0?0:u.reduce((e,t)=>e+t,0)/u.length}function A(u){return Math.max(0,Math.min(1,u))}function he(u,e,t){return new I(u,e,t)}function st(u,e,t){return he(u,{projectRoot:e},t)}export{ge as a,I as b,me as c,ie as d,he as e,st as f};
@@ -1,14 +0,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.14");process.exit(0)}
2
- import{a as _}from"./chunk-K7RT6ITZ.js";import{a as w}from"./chunk-IQRPR4KB.js";import{d as k,f as q}from"./chunk-VG32EEUG.js";import{r as M,v as U}from"./chunk-JK6PMLQQ.js";import{b as f,d as P}from"./chunk-XN3KCKAM.js";import{a as g,e as F}from"./chunk-L5VSLPMW.js";import{a as R}from"./chunk-V6SE2ZU2.js";import{randomUUID as Q}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e=Object.create(null);for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},I=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??I}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,L={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},N=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...L,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:N,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};q();var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
3
- SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
4
- `).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
5
- INSERT OR REPLACE INTO routing_outcomes (
6
- id, task_json, decision_json, used_agent,
7
- followed_recommendation, success, quality_score,
8
- duration_ms, error, model_tier, advisor_consultation_json
9
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
10
- `).run(e.id,JSON.stringify(e.task),JSON.stringify(e.decision),e.usedAgent,e.followedRecommendation?1:0,e.outcome.success?1:0,e.outcome.qualityScore,e.outcome.durationMs,e.outcome.error||null,o,i),this.persistCount++,this.persistCount%m.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[RoutingFeedbackCollector] Failed to persist outcome:",g(t))}}loadAdvisorConsultationSidecar(e){try{let{readdirSync:t,readFileSync:o}=R("fs"),{join:i}=R("path"),{homedir:r}=R("os"),s=i(r(),".agentic-qe","advisor","consultations"),n=t(s).filter(l=>l.endsWith(".json")).sort().reverse();if(n.length===0)return;let c=n[0],d=JSON.parse(o(i(s,c),"utf-8"));return Date.now()-new Date(d.timestamp).getTime()>300*1e3?void 0:d}catch{return}}inferTier(e){let t=e.toLowerCase();return t.includes("booster")||t==="tier-0"?"booster":t==="tier-1"||t.includes("haiku")?"haiku":t==="tier-2"||t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"sonnet"}enforceRetention(e){try{let t=this.maxOutcomes*2;e.prepare(`
11
- DELETE FROM routing_outcomes WHERE id NOT IN (
12
- SELECT id FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
13
- )
14
- `).run(t)}catch(t){console.warn("[RoutingFeedbackCollector] Retention cleanup failed:",g(t))}}loadCalibratorState(){if(!(!this.db||!this.calibrator))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:ema_calibrator_state'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.calibrator.deserialize(o),console.log("[RoutingFeedbackCollector] Loaded EMA calibrator state from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load calibrator state:",g(e))}}persistCalibratorState(){if(!(!this.db||!this.calibrator))try{let e=this.db.getDatabase(),t=JSON.stringify(this.calibrator.serialize());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:ema_calibrator_state",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist calibrator state:",g(e))}}loadEconomicState(){if(!(!this.db||!this.economicModel))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:economic_quality_estimates'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.economicModel.deserializeEstimates(o),console.log("[RoutingFeedbackCollector] Loaded economic quality estimates from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load economic state:",g(e))}}persistEconomicState(){if(!(!this.db||!this.economicModel))try{let e=this.db.getDatabase(),t=JSON.stringify(this.economicModel.serializeEstimates());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:economic_quality_estimates",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist economic state:",g(e))}}connectRouter(e){this.router=e}enableCalibration(e){this.calibrator=new p(e)}getCalibratedWeight(e){return this.calibrator?.getCalibratedWeight(e)??1}enableAutoEscalation(e){this.escalationTracker=new b(e)}getEscalationState(e){return this.escalationTracker?.getState(e)??null}enableEconomicRouting(e,t){let o=t??k();this.economicModel=new E(o,e),this.loadEconomicState()}getEconomicReport(){return this.economicModel?.getEconomicReport()??null}getEconomicScore(e){return this.economicModel?.scoreTiers(e)??null}recordOutcome(e,t,o,i,r){let s=r;s||(s=this.loadAdvisorConsultationSidecar(e));let n={id:`outcome-${Date.now()}-${Q().slice(0,8)}`,task:e,decision:t,usedAgent:o,followedRecommendation:o===t.recommended,outcome:i,timestamp:new Date,advisorConsultation:s};if(this.outcomeStore.add(n),this.persistOutcome(n),this.router&&this.router.updateAgentPerformance(o,i.success,i.qualityScore,i.durationMs),this.calibrator&&(this.calibrator.recordOutcome(o,i.success,i.qualityScore),this.persistCount%10===0&&this.persistCalibratorState()),this.escalationTracker){let c=t.recommended===o?"sonnet":"haiku",d=this.escalationTracker.recordOutcome(o,i.success,c);d.action!=="none"&&console.log(`[RoutingFeedbackCollector] Agent "${o}" ${d.action}d: ${d.previousTier} \u2192 ${d.newTier}`)}if(this.economicModel){let c=this.inferTier(o);this.economicModel.updateFromOutcome(n,c),this.economicPersistCounter++,this.economicPersistCounter%m.ECONOMIC_PERSIST_INTERVAL===0&&this.persistEconomicState()}return n}getAgentMetrics(e){let t=this.outcomeStore.getByAgent(e);if(t.length===0)return null;let o=t.filter(u=>u.outcome.success).length,i=t.reduce((u,h)=>u+h.outcome.durationMs,0),r=t.reduce((u,h)=>u+h.outcome.qualityScore,0),s=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.decision.recommended===e).length,n=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.usedAgent===e).length,c=t.slice(-10),d=c.filter(u=>u.outcome.success).length/c.length,a=o/t.length,l;return d>a+.1?l="improving":d<a-.1?l="declining":l="stable",{agentId:e,totalTasks:t.length,successfulTasks:o,successRate:o/t.length,avgQualityScore:r/t.length,avgDurationMs:i/t.length,overriddenCount:s,selectedOverOthersCount:n,trend:l,updatedAt:new Date}}getAllAgentMetrics(){let e=[];for(let t of w){let o=this.getAgentMetrics(t.id);o&&e.push(o)}return e.sort((t,o)=>o.successRate-t.successRate)}analyzeRoutingAccuracy(){let e=this.outcomeStore.getAll();if(e.length===0)return{totalOutcomes:0,followedRecommendations:0,overrideRate:0,recommendationSuccessRate:0,overrideSuccessRate:0,confidenceCorrelation:0};let t=e.filter(n=>n.followedRecommendation),o=e.filter(n=>!n.followedRecommendation),i=t.filter(n=>n.outcome.success).length,r=o.filter(n=>n.outcome.success).length,s=this.calculateConfidenceCorrelation(e);return{totalOutcomes:e.length,followedRecommendations:t.length,overrideRate:o.length/e.length,recommendationSuccessRate:t.length>0?i/t.length:0,overrideSuccessRate:o.length>0?r/o.length:0,confidenceCorrelation:s}}calculateConfidenceCorrelation(e){if(e.length<2)return 0;let t=e.map(a=>a.decision.confidence),o=e.map(a=>a.outcome.success?1:0),i=t.reduce((a,l)=>a+l,0)/t.length,r=o.reduce((a,l)=>a+l,0)/o.length,s=0,n=0,c=0;for(let a=0;a<e.length;a++){let l=t[a]-i,u=o[a]-r;s+=l*u,n+=l*l,c+=u*u}let d=Math.sqrt(n*c);return d===0?0:s/d}getImprovementRecommendations(){let e=[],t=this.analyzeRoutingAccuracy();if(t.totalOutcomes<50)return e.push("Collect more routing outcomes for reliable analysis (at least 50)"),e;t.overrideRate>.3&&t.overrideSuccessRate>t.recommendationSuccessRate&&e.push("Users are frequently overriding recommendations with better results. Consider adjusting routing weights or updating agent capabilities."),t.confidenceCorrelation<.3&&e.push("Low correlation between confidence and success. Consider improving semantic matching or adjusting weight distribution.");let o=this.getAllAgentMetrics(),i=o.filter(s=>s.successRate<.5&&s.totalTasks>=10);i.length>0&&e.push(`Agents with low success rates: ${i.map(s=>s.agentId).join(", ")}. Consider reviewing their capability mappings.`);let r=o.filter(s=>s.trend==="declining"&&s.totalTasks>=10);return r.length>0&&e.push(`Agents with declining performance: ${r.map(s=>s.agentId).join(", ")}. Monitor for potential issues.`),e.length===0&&e.push("Routing performance is healthy. Continue collecting feedback."),e}exportOutcomes(){return this.outcomeStore.getAll()}importOutcomes(e){for(let t of e)this.outcomeStore.add(t)}getStats(){let e=this.outcomeStore.getAll(),t=new Set(e.map(o=>o.usedAgent));return{totalOutcomes:this.outcomeStore.size,uniqueAgentsUsed:t.size,recentOverrides:this.outcomeStore.getRecentOverrides().length}}clear(){this.outcomeStore.clear()}};function se(m=1e4,e){return new O(m,e)}export{b as a,O as b,se as c};