agentic-qe 3.11.4 → 3.11.5

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 (398) hide show
  1. package/.claude/hooks/aqe-hook.cjs +44 -10
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +58 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/audit/witness-chain.d.ts +25 -0
  6. package/dist/audit/witness-chain.js +69 -22
  7. package/dist/audit/witness-key-manager.d.ts +11 -0
  8. package/dist/audit/witness-key-manager.js +24 -0
  9. package/dist/cli/brain-commands.js +2 -1
  10. package/dist/cli/bundle.js +5 -5
  11. package/dist/cli/chunks/adapter-KNM5R47J.js +2 -0
  12. package/dist/cli/chunks/{agent-booster-wasm-62I6ZNRW.js → agent-booster-wasm-CSTBLNYZ.js} +2 -2
  13. package/dist/cli/chunks/{agent-handler-E2TZKKBS.js → agent-handler-M4W4GTXN.js} +2 -2
  14. package/dist/cli/chunks/{agent-memory-branch-JHAHC2NH.js → agent-memory-branch-VGXFYLSQ.js} +2 -2
  15. package/dist/cli/chunks/aqe-learning-engine-MXPJLVR3.js +2 -0
  16. package/dist/cli/chunks/{arena-72ZV65BR.js → arena-FKSD3LLM.js} +4 -4
  17. package/dist/cli/chunks/{arena-KLG3YSSR.js → arena-IQBRGWAG.js} +2 -2
  18. package/dist/cli/chunks/audit-7NSGRR4Z.js +3 -0
  19. package/dist/cli/chunks/base-X4EXQ2AS.js +2 -0
  20. package/dist/cli/chunks/{hnswlib-node-LAFK5QZ4.js → better-sqlite3-2KR4LQRU.js} +2 -2
  21. package/dist/cli/chunks/brain-handler-M6A3UB66.js +89 -0
  22. package/dist/cli/chunks/{branch-enumerator-C7MPNYT7.js → branch-enumerator-2JGKY4BB.js} +2 -2
  23. package/dist/cli/chunks/{browser-UUDUDYLR.js → browser-J43WQPJL.js} +2 -2
  24. package/dist/cli/chunks/browser-workflow-4HX6RP5F.js +2 -0
  25. package/dist/cli/chunks/{chunk-UJMTKXPI.js → chunk-26WEI3P4.js} +2 -2
  26. package/dist/cli/chunks/{chunk-TQ373GGI.js → chunk-2XPMATEK.js} +2 -2
  27. package/dist/cli/chunks/{chunk-QJ5NCYJ3.js → chunk-2XQHG56O.js} +2 -2
  28. package/dist/cli/chunks/{chunk-EONKMHKO.js → chunk-354367AP.js} +2 -2
  29. package/dist/cli/chunks/{chunk-THKZVOZV.js → chunk-37ZUF5NX.js} +1 -1
  30. package/dist/cli/chunks/{chunk-5P7Q5YNC.js → chunk-3I4TCMOJ.js} +1 -1
  31. package/dist/cli/chunks/{chunk-PQUXFSN6.js → chunk-3JF5A72M.js} +2 -2
  32. package/dist/cli/chunks/{chunk-B5XUWHKQ.js → chunk-3LY7OCSO.js} +1 -1
  33. package/dist/cli/chunks/{chunk-HJ24KMC2.js → chunk-3V36WMIO.js} +1 -1
  34. package/dist/cli/chunks/{chunk-6JUOH6L4.js → chunk-3WR35GFF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-T76RFXQX.js → chunk-4LODYRNV.js} +2 -2
  36. package/dist/cli/chunks/{chunk-D5S47YUS.js → chunk-4MHN7JWC.js} +3 -3
  37. package/dist/cli/chunks/chunk-4QOI5JS7.js +14 -0
  38. package/dist/cli/chunks/{chunk-63QUN3JK.js → chunk-4RTWPR3X.js} +1 -1
  39. package/dist/cli/chunks/chunk-4XJ2A3HY.js +65 -0
  40. package/dist/cli/chunks/{chunk-KUZMVH6N.js → chunk-4Y3LGBKJ.js} +3 -3
  41. package/dist/cli/chunks/{chunk-JFLSQH2X.js → chunk-52U5BFZP.js} +2 -2
  42. package/dist/cli/chunks/{chunk-YNK6SUPU.js → chunk-53YOYZW5.js} +2 -2
  43. package/dist/cli/chunks/{chunk-O7PVZ32A.js → chunk-5WMU7XCF.js} +1 -1
  44. package/dist/cli/chunks/{chunk-ZKCKOQJI.js → chunk-62OTU2AP.js} +2 -2
  45. package/dist/cli/chunks/{chunk-3SKIZDKL.js → chunk-62UM7Q5N.js} +1 -1
  46. package/dist/cli/chunks/{chunk-SFDUT5WM.js → chunk-6Q57K4YD.js} +2 -2
  47. package/dist/cli/chunks/{chunk-3SBUL72V.js → chunk-6R3YOAKO.js} +2 -2
  48. package/dist/cli/chunks/chunk-6T65OKUM.js +2 -0
  49. package/dist/cli/chunks/{chunk-TCVEKRPI.js → chunk-7BCRULCP.js} +2 -2
  50. package/dist/cli/chunks/{chunk-VKJQAKYG.js → chunk-7DTMENY6.js} +2 -2
  51. package/dist/cli/chunks/{chunk-XQ6DW5FV.js → chunk-7KXPNNMR.js} +2 -2
  52. package/dist/cli/chunks/{chunk-N2BJN6AO.js → chunk-7P6X4BFO.js} +3 -3
  53. package/dist/cli/chunks/{chunk-SL3SNOO2.js → chunk-7YSBATSN.js} +2 -2
  54. package/dist/cli/chunks/{chunk-5U2WHPXL.js → chunk-ABU64UWB.js} +1 -1
  55. package/dist/cli/chunks/{chunk-4RHNPRAP.js → chunk-AF6P5RWY.js} +2 -2
  56. package/dist/cli/chunks/{chunk-4JFH3MVA.js → chunk-AGJOGUP5.js} +1 -1
  57. package/dist/cli/chunks/{chunk-5Z4FBCBK.js → chunk-AL5VJJN4.js} +1 -1
  58. package/dist/cli/chunks/{chunk-Z2REKBD6.js → chunk-AOQYORVA.js} +2 -2
  59. package/dist/cli/chunks/{chunk-X64BEXUY.js → chunk-AOXJFDH5.js} +117 -113
  60. package/dist/cli/chunks/{chunk-DRMHVY4T.js → chunk-AXKWV5NF.js} +4 -4
  61. package/dist/cli/chunks/{chunk-3FJZMQJ7.js → chunk-B2VBDMDI.js} +2 -2
  62. package/dist/cli/chunks/{chunk-ARPBG6FQ.js → chunk-BJLA2IX7.js} +2 -2
  63. package/dist/cli/chunks/{chunk-6W3QHS45.js → chunk-BLPWJQTY.js} +2 -2
  64. package/dist/cli/chunks/{chunk-O5NEJIHB.js → chunk-BTLUWH4R.js} +2 -2
  65. package/dist/cli/chunks/{chunk-Y4AXOHW4.js → chunk-C4EZNOWK.js} +1 -1
  66. package/dist/cli/chunks/{chunk-FRFVN6AA.js → chunk-C5C4W572.js} +2 -2
  67. package/dist/cli/chunks/{chunk-7AWK43JN.js → chunk-CDJP6COA.js} +2 -2
  68. package/dist/cli/chunks/{chunk-VJGHRWMH.js → chunk-CKOF27L7.js} +2 -2
  69. package/dist/cli/chunks/{chunk-3E7D3A35.js → chunk-D45QLJEL.js} +1 -1
  70. package/dist/cli/chunks/{chunk-MALOUGSF.js → chunk-DFRRWOEX.js} +2 -2
  71. package/dist/cli/chunks/{chunk-JDFPAJGB.js → chunk-DLBVADWQ.js} +92 -92
  72. package/dist/cli/chunks/{chunk-7IKWF2AD.js → chunk-DPL762HU.js} +1 -1
  73. package/dist/cli/chunks/{chunk-RFQBDMAP.js → chunk-DVW66FPU.js} +1 -1
  74. package/dist/cli/chunks/{chunk-JPENUVCI.js → chunk-EDOGRFAG.js} +1 -1
  75. package/dist/cli/chunks/{chunk-HWBMYR5W.js → chunk-EEKG35K5.js} +5 -5
  76. package/dist/cli/chunks/{chunk-WQZ2WRO4.js → chunk-EK3HPH6A.js} +1 -1
  77. package/dist/cli/chunks/{chunk-WZYNY3VF.js → chunk-FGD6HINU.js} +1 -1
  78. package/dist/cli/chunks/{chunk-ZSBJNE35.js → chunk-FGSIID5C.js} +2 -2
  79. package/dist/cli/chunks/{chunk-TCWR6TDN.js → chunk-FHTYEAQ3.js} +2 -2
  80. package/dist/cli/chunks/{chunk-BRLUNIR4.js → chunk-FII3WCCY.js} +2 -2
  81. package/dist/cli/chunks/{chunk-VCUCD3B5.js → chunk-FIPKIIMS.js} +2 -2
  82. package/dist/cli/chunks/{chunk-6545AS2J.js → chunk-FMNXHVIN.js} +2 -2
  83. package/dist/cli/chunks/{chunk-VO6YJGB4.js → chunk-G2ZIJZJ7.js} +2 -2
  84. package/dist/cli/chunks/{chunk-7ADD2ZQL.js → chunk-GODAWJMZ.js} +2 -2
  85. package/dist/cli/chunks/{chunk-AQIEK4SY.js → chunk-GW6XWMX2.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GOQ4P2PB.js → chunk-HC6KTVFR.js} +2 -2
  87. package/dist/cli/chunks/{chunk-2KNFS3L5.js → chunk-HJWT4KME.js} +1 -1
  88. package/dist/cli/chunks/{chunk-NV3TXXOW.js → chunk-I3ANRYQ6.js} +2 -2
  89. package/dist/cli/chunks/{chunk-IQBZBUP5.js → chunk-I3NWKPXJ.js} +2 -2
  90. package/dist/cli/chunks/chunk-IBDQWKI3.js +2 -0
  91. package/dist/cli/chunks/{chunk-LW5DHT3Z.js → chunk-IU5RSN6M.js} +2 -2
  92. package/dist/cli/chunks/{chunk-XHRLBJTM.js → chunk-J5XDKVI7.js} +2 -2
  93. package/dist/cli/chunks/{chunk-QEVX4GWF.js → chunk-J6PFPY7V.js} +2 -2
  94. package/dist/cli/chunks/{chunk-AE6HXMOG.js → chunk-JATLFS6A.js} +1 -1
  95. package/dist/cli/chunks/{chunk-HJO4RNOW.js → chunk-JBKZ5TUM.js} +2 -2
  96. package/dist/cli/chunks/{chunk-7QTB5XIQ.js → chunk-JDSHUECG.js} +2 -2
  97. package/dist/cli/chunks/{chunk-GRQ36XUH.js → chunk-K4C25BWV.js} +2 -2
  98. package/dist/cli/chunks/{chunk-BMQDELPA.js → chunk-K4I7UIU5.js} +1 -1
  99. package/dist/cli/chunks/{chunk-AJXGGTX7.js → chunk-KP3R2M2G.js} +1 -1
  100. package/dist/cli/chunks/chunk-KQVIWE3W.js +2 -0
  101. package/dist/cli/chunks/{chunk-ZFCVT43J.js → chunk-KVVJVMDM.js} +2 -2
  102. package/dist/cli/chunks/{chunk-WMIRAD3J.js → chunk-LOE2JETO.js} +2 -2
  103. package/dist/cli/chunks/{chunk-54B6P2WS.js → chunk-LPR2R3AN.js} +3 -3
  104. package/dist/cli/chunks/{chunk-EZRHSHOQ.js → chunk-M6FW56MV.js} +2 -2
  105. package/dist/cli/chunks/{chunk-IF3HPQNV.js → chunk-MCHEUSY4.js} +1 -1
  106. package/dist/cli/chunks/{chunk-NBBLPDJX.js → chunk-MEIU7457.js} +2 -2
  107. package/dist/cli/chunks/{chunk-4BFCLSDN.js → chunk-MHMQ6MCT.js} +2 -2
  108. package/dist/cli/chunks/{chunk-UQ72K44T.js → chunk-MIU5RUBJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-LKURMUBU.js → chunk-MMEXHZUC.js} +37 -12
  110. package/dist/cli/chunks/{chunk-SRVTNG6L.js → chunk-MTBGOWJA.js} +2 -2
  111. package/dist/cli/chunks/{chunk-TPMBFARK.js → chunk-NCSXLMDL.js} +67 -22
  112. package/dist/cli/chunks/{chunk-TU6YN43Q.js → chunk-O7J54OHN.js} +1 -1
  113. package/dist/cli/chunks/{chunk-JCTCM6IR.js → chunk-OGNTCZKK.js} +1 -1
  114. package/dist/cli/chunks/{chunk-FSGMRQFC.js → chunk-OS2HHJTM.js} +2 -2
  115. package/dist/cli/chunks/{chunk-TSWF3AGQ.js → chunk-OS62Y77J.js} +2 -2
  116. package/dist/cli/chunks/{chunk-VQU7DMEY.js → chunk-PVDXNQPL.js} +2 -2
  117. package/dist/cli/chunks/{chunk-DNOU2HVQ.js → chunk-PW72M2FE.js} +2 -2
  118. package/dist/cli/chunks/{chunk-HH6NCBSP.js → chunk-Q5TR6ETB.js} +22 -22
  119. package/dist/cli/chunks/{chunk-PFWJQPUC.js → chunk-QKK7VBVB.js} +2 -2
  120. package/dist/cli/chunks/{chunk-JNQN5DNS.js → chunk-RFLHPLET.js} +1 -1
  121. package/dist/cli/chunks/{chunk-IB3ZPLFA.js → chunk-RJN2RM76.js} +2 -2
  122. package/dist/cli/chunks/{chunk-PEIQDQXN.js → chunk-RKXZLTWR.js} +2 -2
  123. package/dist/cli/chunks/{chunk-5VSQAGA2.js → chunk-SE3JFUKP.js} +1 -1
  124. package/dist/cli/chunks/{chunk-LMJUMUQJ.js → chunk-SK754ZSH.js} +4 -4
  125. package/dist/cli/chunks/{chunk-UCYTY4LG.js → chunk-SO6G4IX3.js} +2 -2
  126. package/dist/cli/chunks/{chunk-ICCTQ5LO.js → chunk-SUL3I6QZ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-G3TFNY4T.js → chunk-TBT3OFRW.js} +2 -2
  128. package/dist/cli/chunks/{chunk-AYGEWPN4.js → chunk-TEIWJ3GJ.js} +1 -1
  129. package/dist/cli/chunks/{chunk-YKSWC7I4.js → chunk-TRNBQFFG.js} +8 -20
  130. package/dist/cli/chunks/{chunk-NSPCZPTB.js → chunk-TTJJ4DQE.js} +2 -2
  131. package/dist/cli/chunks/{chunk-2WPSMQIL.js → chunk-UBI2EOS3.js} +1 -1
  132. package/dist/cli/chunks/{chunk-ADFKY3X2.js → chunk-UBY322ED.js} +2 -2
  133. package/dist/cli/chunks/{chunk-QSDIY3E2.js → chunk-UORTQXJ2.js} +1 -1
  134. package/dist/cli/chunks/{chunk-ODZSQVEW.js → chunk-URP75DL4.js} +1 -1
  135. package/dist/cli/chunks/{chunk-37ZDGJ3H.js → chunk-V6NAB5UZ.js} +1 -1
  136. package/dist/cli/chunks/{chunk-YZ5EQR37.js → chunk-VMFAANWX.js} +2 -2
  137. package/dist/cli/chunks/{chunk-NFJT7XXR.js → chunk-VMWRMINE.js} +1 -1
  138. package/dist/cli/chunks/{chunk-MCT4CD5M.js → chunk-VN2HHBZN.js} +2 -2
  139. package/dist/cli/chunks/{chunk-QMC5MTBV.js → chunk-W72FJA2H.js} +2 -2
  140. package/dist/cli/chunks/chunk-W7TYKPLY.js +27 -0
  141. package/dist/cli/chunks/{chunk-YUHM72VQ.js → chunk-WHHQIL4F.js} +2 -2
  142. package/dist/cli/chunks/{chunk-4YT5YN5G.js → chunk-WMZ2QGGS.js} +2 -2
  143. package/dist/cli/chunks/{chunk-Q7ORVHJB.js → chunk-WPSK237F.js} +3 -3
  144. package/dist/cli/chunks/{chunk-ZYZT2CDX.js → chunk-XKQY2Z3Q.js} +1 -1
  145. package/dist/cli/chunks/{chunk-WNMDWP5A.js → chunk-XLT3FYS7.js} +2 -2
  146. package/dist/cli/chunks/{chunk-U34OZXD6.js → chunk-XT4TDLOB.js} +2 -2
  147. package/dist/cli/chunks/{chunk-6GYGAW53.js → chunk-Y25PO65W.js} +2 -2
  148. package/dist/cli/chunks/{chunk-3SRPFBU7.js → chunk-Y6DWJKHU.js} +3 -3
  149. package/dist/cli/chunks/{chunk-D6CKKNYC.js → chunk-YBPLJRVT.js} +2 -2
  150. package/dist/cli/chunks/{chunk-LLUPRGOR.js → chunk-YFCULQBP.js} +2 -2
  151. package/dist/cli/chunks/{chunk-HT6WAYIR.js → chunk-YGVDP6X7.js} +1 -1
  152. package/dist/cli/chunks/{chunk-RCPD6F4R.js → chunk-YR2JKBZO.js} +2 -2
  153. package/dist/cli/chunks/{chunk-P6S6ZVB5.js → chunk-YZSTZUGJ.js} +1 -1
  154. package/dist/cli/chunks/{chunk-CNF3ZWLM.js → chunk-ZG5UAEEO.js} +2 -2
  155. package/dist/cli/chunks/{chunk-MWFJC5HR.js → chunk-ZLBY25MB.js} +1 -1
  156. package/dist/cli/chunks/chunk-ZMPAM4DY.js +2 -0
  157. package/dist/cli/chunks/{chunk-A4OMK3FO.js → chunk-ZPP57WQU.js} +2 -2
  158. package/dist/cli/chunks/{chunk-U3AVZGQA.js → chunk-ZXEWTZFR.js} +1 -1
  159. package/dist/cli/chunks/{ci-HQCRSCC7.js → ci-CBNVLOOQ.js} +2 -2
  160. package/dist/cli/chunks/{ci-output-YBVXLA6O.js → ci-output-I4HY2FYJ.js} +2 -2
  161. package/dist/cli/chunks/{circuit-breaker-ULGMF2QN.js → circuit-breaker-5VRBKGWL.js} +2 -2
  162. package/dist/cli/chunks/{claude-flow-setup-MKZ2LJXK.js → claude-flow-setup-XPJPKHIO.js} +2 -2
  163. package/dist/cli/chunks/client-AHXNCOHK.js +2 -0
  164. package/dist/cli/chunks/{cline-installer-WZQ6XBWN.js → cline-installer-OFRDUUWZ.js} +2 -2
  165. package/dist/cli/chunks/{code-H3KGH45S.js → code-QIZQVB3E.js} +2 -2
  166. package/dist/cli/chunks/{code-index-extractor-NUVEAJ7C.js → code-index-extractor-LMUUWEX4.js} +2 -2
  167. package/dist/cli/chunks/{codex-installer-JQI6E6CV.js → codex-installer-N2MKIZ2S.js} +2 -2
  168. package/dist/cli/chunks/{completions-NDF4PFE7.js → completions-Y36S3C5J.js} +2 -2
  169. package/dist/cli/chunks/{complexity-analyzer-XCZH66HG.js → complexity-analyzer-73YS3WUD.js} +2 -2
  170. package/dist/cli/chunks/{continuedev-installer-Z4AJGZ7S.js → continuedev-installer-SAOTP6J3.js} +2 -2
  171. package/dist/cli/chunks/{copilot-installer-K4IPAL7C.js → copilot-installer-A4HXF6HE.js} +2 -2
  172. package/dist/cli/chunks/core-handlers-EEFLLMAZ.js +2 -0
  173. package/dist/cli/chunks/{cost-tracker-35KXAB23.js → cost-tracker-P26XUVZS.js} +2 -2
  174. package/dist/cli/chunks/{coverage-QW5I4TYZ.js → coverage-HVNHSMVJ.js} +3 -3
  175. package/dist/cli/chunks/cross-domain-router-LT3H4SNJ.js +2 -0
  176. package/dist/cli/chunks/{cursor-installer-P4Z7RMIZ.js → cursor-installer-46BQFTYZ.js} +2 -2
  177. package/dist/cli/chunks/{daemon-WQWTCYBM.js → daemon-Y54O3FLT.js} +3 -3
  178. package/dist/cli/chunks/daemon-YE7K2AZF.js +10 -0
  179. package/dist/cli/chunks/{dag-attention-scheduler-7XD2VGON.js → dag-attention-scheduler-ETA7YY52.js} +2 -2
  180. package/dist/cli/chunks/{detect-GZ3P4DI7.js → detect-5WLQ2J3E.js} +2 -2
  181. package/dist/cli/chunks/{dist-node-6WWAW7OP.js → dist-node-45WW6I7J.js} +2 -2
  182. package/dist/cli/chunks/{domain-handler-3GTLWARQ.js → domain-handler-J7DQV74M.js} +2 -2
  183. package/dist/cli/chunks/domain-transfer-GD2EGQVR.js +2 -0
  184. package/dist/cli/chunks/dream-4K3BK4IG.js +2 -0
  185. package/dist/cli/chunks/{embed-and-insert-pattern-BGIMA77V.js → embed-and-insert-pattern-JELNEA2D.js} +2 -2
  186. package/dist/cli/chunks/{eval-SXV6DRDD.js → eval-A4PA5G2U.js} +2 -2
  187. package/dist/cli/chunks/{experience-capture-middleware-TT6WCT2S.js → experience-capture-middleware-MLHTYWTA.js} +3 -3
  188. package/dist/cli/chunks/{fast-paths-HTAZHEQP.js → fast-paths-QYDTITRV.js} +2 -2
  189. package/dist/cli/chunks/{feature-flags-WBUKU54W.js → feature-flags-H4MSY26Z.js} +2 -2
  190. package/dist/cli/chunks/{feature-flags-DIE3Z2B4.js → feature-flags-MQYYRHIK.js} +2 -2
  191. package/dist/cli/chunks/{file-discovery-SKDETFS3.js → file-discovery-RMFVJNGL.js} +2 -2
  192. package/dist/cli/chunks/{fleet-WCWEPAVU.js → fleet-7KZQOTAC.js} +4 -4
  193. package/dist/cli/chunks/{gnn-wrapper-KWZOWBYS.js → gnn-wrapper-NMZFTGVH.js} +2 -2
  194. package/dist/cli/chunks/{heartbeat-handler-3AGYHVG2.js → heartbeat-handler-7BQDK7MG.js} +4 -4
  195. package/dist/cli/chunks/heartbeat-scheduler-IMPPGQUK.js +2 -0
  196. package/dist/cli/chunks/hnsw-adapter-EIAA6R2L.js +2 -0
  197. package/dist/cli/chunks/hnsw-index-ZXXP6AXZ.js +2 -0
  198. package/dist/cli/chunks/{hnsw-legacy-bridge-6OJJDZHL.js → hnsw-legacy-bridge-TPPGBPKF.js} +2 -2
  199. package/dist/cli/chunks/{better-sqlite3-URULPKRF.js → hnswlib-node-E6NSZPP2.js} +2 -2
  200. package/dist/cli/chunks/{hooks-OXEBTLXV.js → hooks-CYZIUYSH.js} +48 -52
  201. package/dist/cli/chunks/hybrid-router-LXWG4MLH.js +2 -0
  202. package/dist/cli/chunks/{hypergraph-engine-NL74PRHD.js → hypergraph-engine-WC6DMTYQ.js} +2 -2
  203. package/dist/cli/chunks/{hypergraph-handler-KZ54AEEL.js → hypergraph-handler-GTGA3TXJ.js} +3 -3
  204. package/dist/cli/chunks/impact-analyzer-TP5LRFYH.js +2 -0
  205. package/dist/cli/chunks/{init-handler-XKZXRXPG.js → init-handler-N3Z72JNI.js} +6 -6
  206. package/dist/cli/chunks/init-wizard-AIOA5KOY.js +2 -0
  207. package/dist/cli/chunks/kernel-SQALRU6Q.js +2 -0
  208. package/dist/cli/chunks/{kilocode-installer-WISQMJK7.js → kilocode-installer-FUX4V6II.js} +2 -2
  209. package/dist/cli/chunks/{kiro-installer-O7TBB3GM.js → kiro-installer-ZSNZT7ZR.js} +2 -2
  210. package/dist/cli/chunks/knowledge-graph-JFVT6SNN.js +2 -0
  211. package/dist/cli/chunks/{learning-6IZBGVRU.js → learning-UQY64COU.js} +3 -3
  212. package/dist/cli/chunks/{llm-router-QDMQPPQ7.js → llm-router-CMHGGX6N.js} +4 -4
  213. package/dist/cli/chunks/llm-router-service-XHFKTH3I.js +2 -0
  214. package/dist/cli/chunks/{load-KLAJJGL5.js → load-E6WH4QN2.js} +2 -2
  215. package/dist/cli/chunks/load-test-JEIFJKNN.js +2 -0
  216. package/dist/cli/chunks/{mcp-SZOPQZIZ.js → mcp-UM5VTW6N.js} +2 -2
  217. package/dist/cli/chunks/{memory-G3WY74C6.js → memory-7Q3XDUE5.js} +5 -5
  218. package/dist/cli/chunks/memory-backend-NT7I37CP.js +2 -0
  219. package/dist/cli/chunks/memory-handlers-746D7NE7.js +2 -0
  220. package/dist/cli/chunks/{multi-model-executor-TDNQGTOT.js → multi-model-executor-LZENWVRR.js} +2 -2
  221. package/dist/cli/chunks/{opencode-installer-NGYGEDMV.js → opencode-installer-O2JAIPLF.js} +2 -2
  222. package/dist/cli/chunks/{orchestrator-KPI5DY2C.js → orchestrator-DKZWXDRI.js} +5 -5
  223. package/dist/cli/chunks/pattern-null-store-6QU6WHDW.js +2 -0
  224. package/dist/cli/chunks/pattern-usage-recorder-CLUL4M55.js +2 -0
  225. package/dist/cli/chunks/{pipeline-CSDCC675.js → pipeline-2VDLTR5J.js} +2 -2
  226. package/dist/cli/chunks/{platform-Q5XKEVKH.js → platform-4N4Q5XYX.js} +2 -2
  227. package/dist/cli/chunks/{plugin-XKKR3GVL.js → plugin-GY5AU5CS.js} +2 -2
  228. package/dist/cli/chunks/{prime-radiant-advanced-wasm-22QVNKEN.js → prime-radiant-advanced-wasm-TQ4DKDZS.js} +2 -2
  229. package/dist/cli/chunks/protocol-executor-GT2MZYUU.js +2 -0
  230. package/dist/cli/chunks/{protocol-handler-REQKTJGG.js → protocol-handler-T3LZ3WRG.js} +2 -2
  231. package/dist/cli/chunks/{prove-NOFUFSQN.js → prove-OV7S5J4W.js} +2 -2
  232. package/dist/cli/chunks/provider-manager-OATJ7R3D.js +2 -0
  233. package/dist/cli/chunks/qe-reasoning-bank-IJXNQ67O.js +2 -0
  234. package/dist/cli/chunks/{quality-3DQ2H5TK.js → quality-AXD4NLQA.js} +2 -2
  235. package/dist/cli/chunks/queen-coordinator-6RBHWCUG.js +2 -0
  236. package/dist/cli/chunks/{real-embeddings-FCGNYWLL.js → real-embeddings-2PUCC7FG.js} +2 -2
  237. package/dist/cli/chunks/{roocode-installer-HX3CNRIR.js → roocode-installer-WJ5ARGLW.js} +2 -2
  238. package/dist/cli/chunks/router-XKQRT5JK.js +2 -0
  239. package/dist/cli/chunks/routing-feedback-ACPSD4LW.js +2 -0
  240. package/dist/cli/chunks/{routing-handler-YRZ2LDCR.js → routing-handler-CU6657SZ.js} +2 -2
  241. package/dist/cli/chunks/{ruvector-commands-GCQVBJ4E.js → ruvector-commands-IIF6VSFW.js} +2 -2
  242. package/dist/cli/chunks/{rvf-dual-writer-B562P3ZC.js → rvf-dual-writer-YMQI7XO2.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-adapter-NAGFKCMD.js → rvf-migration-adapter-HDE3PR2W.js} +2 -2
  244. package/dist/cli/chunks/{rvf-migration-coordinator-WWFBEJ5Q.js → rvf-migration-coordinator-MQV5OA7K.js} +2 -2
  245. package/dist/cli/chunks/rvf-native-adapter-SIWRKE33.js +2 -0
  246. package/dist/cli/chunks/safe-db-LCPUYMX4.js +2 -0
  247. package/dist/cli/chunks/schedule-HIQJCWXG.js +2 -0
  248. package/dist/cli/chunks/scheduler-QE5EJ5LE.js +2 -0
  249. package/dist/cli/chunks/{security-IFOYTD75.js → security-UM3IGDSM.js} +3 -3
  250. package/dist/cli/chunks/{shared-rvf-adapter-TYD5TQ35.js → shared-rvf-adapter-I3SOJ6M4.js} +2 -2
  251. package/dist/cli/chunks/{shared-rvf-dual-writer-YGOOVDQZ.js → shared-rvf-dual-writer-KQGC2UO7.js} +2 -2
  252. package/dist/cli/chunks/sqlite-persistence-EU54UTMH.js +2 -0
  253. package/dist/cli/chunks/status-handler-OX4CJZME.js +46 -0
  254. package/dist/cli/chunks/{structural-health-KZI6YMKV.js → structural-health-PYUMVBXJ.js} +2 -2
  255. package/dist/cli/chunks/{sync-Z5BDDBMK.js → sync-2TED3YTY.js} +2 -2
  256. package/dist/cli/chunks/{sync-ABZNNYRC.js → sync-VALFNTA6.js} +2 -2
  257. package/dist/cli/chunks/{task-handler-5ACZEPJ7.js → task-handler-VPGAJVPC.js} +2 -2
  258. package/dist/cli/chunks/{task-handlers-UZWDPL6A.js → task-handlers-IB4UAMU6.js} +3 -3
  259. package/dist/cli/chunks/{test-APO3MCVV.js → test-OMRJOZB6.js} +4 -4
  260. package/dist/cli/chunks/{test-scheduling-EFZA5G5C.js → test-scheduling-ZL3YFPBU.js} +3 -3
  261. package/dist/cli/chunks/{token-bootstrap-J2OPLNUK.js → token-bootstrap-DNWZI7SH.js} +2 -2
  262. package/dist/cli/chunks/{token-usage-VHWVNN4R.js → token-usage-IYO7RGFF.js} +2 -2
  263. package/dist/cli/chunks/{transformers-PX4HPO75.js → transformers-53ALC34T.js} +2 -2
  264. package/dist/cli/chunks/{tree-sitter-wasm-parser-44HA2Z3F.js → tree-sitter-wasm-parser-WUKJ2I2Q.js} +2 -2
  265. package/dist/cli/chunks/{types-IMOP7F4R.js → types-47FTEPMV.js} +2 -2
  266. package/dist/cli/chunks/unified-memory-CJLMC2I4.js +2 -0
  267. package/dist/cli/chunks/unified-memory-hnsw-FDGR4D2J.js +2 -0
  268. package/dist/cli/chunks/unified-persistence-UFH5GLDN.js +2 -0
  269. package/dist/cli/chunks/{upgrade-OZ3O6ZZI.js → upgrade-QPLMJA5Z.js} +2 -2
  270. package/dist/cli/chunks/{validate-DRY5BMWX.js → validate-3GVKZOVF.js} +2 -2
  271. package/dist/cli/chunks/{validate-swarm-QD3LYPUF.js → validate-swarm-XCRTLVM6.js} +2 -2
  272. package/dist/cli/chunks/{vibium-2J3H2ITD.js → vibium-CH4VPKVZ.js} +2 -2
  273. package/dist/cli/chunks/visual-security-4ARJ7J2Y.js +2 -0
  274. package/dist/cli/chunks/{web-tree-sitter-KRNUOGKI.js → web-tree-sitter-JDBNAZTV.js} +2 -2
  275. package/dist/cli/chunks/{windsurf-installer-PQIPH3WP.js → windsurf-installer-3MNPVJBP.js} +2 -2
  276. package/dist/cli/chunks/witness-chain-73QC33ED.js +2 -0
  277. package/dist/cli/chunks/{witness-chain-HPLOYPS7.js → witness-chain-HR5UBV5J.js} +2 -2
  278. package/dist/cli/chunks/witness-key-manager-G5SQTIBZ.js +2 -0
  279. package/dist/cli/chunks/{workflow-OAQ3FWCY.js → workflow-43EMD5FY.js} +4 -4
  280. package/dist/cli/chunks/workflow-orchestrator-RKMMPXNA.js +2 -0
  281. package/dist/cli/chunks/{wrappers-UPIU6S5S.js → wrappers-3N7AYNM3.js} +2 -2
  282. package/dist/cli/commands/audit.d.ts +12 -0
  283. package/dist/cli/commands/audit.js +64 -4
  284. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +45 -19
  285. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +13 -0
  286. package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
  287. package/dist/cli/commands/hooks-handlers/task-hooks.js +19 -1
  288. package/dist/cli/handlers/status-handler.d.ts +18 -0
  289. package/dist/cli/handlers/status-handler.js +47 -0
  290. package/dist/coordination/mincut/queen-integration.js +24 -7
  291. package/dist/coordination/protocol-executor.js +2 -1
  292. package/dist/coordination/queen-lifecycle.js +4 -1
  293. package/dist/domains/code-intelligence/coordinator.js +10 -6
  294. package/dist/domains/code-intelligence/services/product-factors-bridge.js +3 -1
  295. package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +6 -0
  296. package/dist/domains/defect-intelligence/services/defect-predictor.js +21 -0
  297. package/dist/domains/learning-optimization/interfaces.d.ts +7 -0
  298. package/dist/domains/learning-optimization/plugin.js +5 -0
  299. package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +10 -0
  300. package/dist/domains/learning-optimization/services/learning-coordinator.js +57 -0
  301. package/dist/domains/test-execution/plugin.js +2 -2
  302. package/dist/domains/test-execution/services/flaky-detector.js +1 -1
  303. package/dist/domains/test-generation/coordinator.js +22 -8
  304. package/dist/domains/test-generation/interfaces.d.ts +3 -0
  305. package/dist/domains/test-generation/services/test-generator.js +9 -1
  306. package/dist/integrations/ruvector/delta-tracker.js +10 -1
  307. package/dist/integrations/ruvector/sona-persistence.d.ts +24 -0
  308. package/dist/integrations/ruvector/sona-persistence.js +76 -0
  309. package/dist/integrations/ruvector/sona-three-loop.d.ts +15 -0
  310. package/dist/integrations/ruvector/sona-three-loop.js +17 -0
  311. package/dist/kernel/unified-memory-schemas.d.ts +2 -2
  312. package/dist/kernel/unified-memory-schemas.js +48 -2
  313. package/dist/kernel/unified-memory.d.ts +22 -0
  314. package/dist/kernel/unified-memory.js +43 -0
  315. package/dist/learning/aqe-learning-engine.js +3 -1
  316. package/dist/learning/dream/concept-graph.d.ts +31 -1
  317. package/dist/learning/dream/concept-graph.js +109 -3
  318. package/dist/learning/dream/dream-engine.d.ts +13 -1
  319. package/dist/learning/dream/dream-engine.js +146 -10
  320. package/dist/learning/dream/index.d.ts +1 -1
  321. package/dist/learning/dream/types.d.ts +23 -0
  322. package/dist/learning/pattern-store.d.ts +2 -2
  323. package/dist/learning/pattern-store.js +14 -3
  324. package/dist/learning/qe-reasoning-bank.js +34 -31
  325. package/dist/learning/routing-topology-gate.d.ts +12 -2
  326. package/dist/learning/routing-topology-gate.js +15 -3
  327. package/dist/learning/rvf-pattern-store.d.ts +1 -1
  328. package/dist/learning/rvf-pattern-store.js +21 -8
  329. package/dist/learning/sqlite-persistence.js +12 -9
  330. package/dist/mcp/bundle.js +516 -442
  331. package/dist/mcp/qe-tool-bridge.js +7 -2
  332. package/dist/mcp/tools/base.d.ts +29 -0
  333. package/dist/mcp/tools/base.js +25 -0
  334. package/dist/mcp/tools/coverage-analysis/index.js +6 -4
  335. package/dist/mcp/tools/learning-optimization/dream.d.ts +4 -13
  336. package/dist/mcp/tools/learning-optimization/dream.js +10 -96
  337. package/dist/mcp/tools/planning/goap-execute.d.ts +13 -1
  338. package/dist/mcp/tools/planning/goap-execute.js +33 -18
  339. package/dist/mcp/tools/registry.js +7 -2
  340. package/dist/persistence/rvf-migration-coordinator.js +2 -1
  341. package/dist/planning/actions/qe-action-library.js +124 -1
  342. package/dist/planning/goap-planner.d.ts +14 -2
  343. package/dist/planning/goap-planner.js +51 -9
  344. package/dist/planning/index.d.ts +1 -1
  345. package/dist/planning/plan-executor.d.ts +84 -4
  346. package/dist/planning/plan-executor.js +221 -56
  347. package/dist/planning/types.d.ts +27 -0
  348. package/dist/shared/events/domain-events.d.ts +2 -0
  349. package/dist/workers/workers/learning-consolidation.js +21 -1
  350. package/package.json +1 -1
  351. package/dist/cli/chunks/adapter-2HMUXHWY.js +0 -2
  352. package/dist/cli/chunks/aqe-learning-engine-M2NKRVRE.js +0 -2
  353. package/dist/cli/chunks/audit-EPB7ETMT.js +0 -3
  354. package/dist/cli/chunks/base-CCHC2DAC.js +0 -2
  355. package/dist/cli/chunks/brain-handler-FBMYEERK.js +0 -89
  356. package/dist/cli/chunks/browser-workflow-4DGHFYY3.js +0 -2
  357. package/dist/cli/chunks/chunk-5AQ7FXYG.js +0 -27
  358. package/dist/cli/chunks/chunk-KYTFIP6R.js +0 -2
  359. package/dist/cli/chunks/chunk-MYMIEQSZ.js +0 -65
  360. package/dist/cli/chunks/chunk-XXRTWG7O.js +0 -2
  361. package/dist/cli/chunks/chunk-ZSA6V5FH.js +0 -2
  362. package/dist/cli/chunks/client-2OVEDWGU.js +0 -2
  363. package/dist/cli/chunks/core-handlers-UXRRYP52.js +0 -2
  364. package/dist/cli/chunks/cross-domain-router-PV3VQVLO.js +0 -2
  365. package/dist/cli/chunks/daemon-ESUEM6VB.js +0 -10
  366. package/dist/cli/chunks/domain-transfer-TQYO3SVG.js +0 -2
  367. package/dist/cli/chunks/dream-UFUXVJQC.js +0 -2
  368. package/dist/cli/chunks/heartbeat-scheduler-MBG3SARO.js +0 -2
  369. package/dist/cli/chunks/hnsw-adapter-5HXA3QB3.js +0 -2
  370. package/dist/cli/chunks/hnsw-index-PZRQWBRG.js +0 -2
  371. package/dist/cli/chunks/hybrid-router-NQRIE2GG.js +0 -2
  372. package/dist/cli/chunks/impact-analyzer-46347ZDV.js +0 -2
  373. package/dist/cli/chunks/init-wizard-CJYP4WKO.js +0 -2
  374. package/dist/cli/chunks/kernel-22KQZ56U.js +0 -2
  375. package/dist/cli/chunks/knowledge-graph-KM3JDBGR.js +0 -2
  376. package/dist/cli/chunks/llm-router-service-IFO6GRRO.js +0 -2
  377. package/dist/cli/chunks/load-test-TTKCYAPB.js +0 -2
  378. package/dist/cli/chunks/memory-backend-ELHCX2ZT.js +0 -2
  379. package/dist/cli/chunks/memory-handlers-3SKYQZTL.js +0 -2
  380. package/dist/cli/chunks/pattern-null-store-TMXAYD43.js +0 -2
  381. package/dist/cli/chunks/protocol-executor-BPLR5EJC.js +0 -2
  382. package/dist/cli/chunks/provider-manager-4MMD5QKL.js +0 -2
  383. package/dist/cli/chunks/qe-reasoning-bank-P7KNT3WZ.js +0 -2
  384. package/dist/cli/chunks/queen-coordinator-NBZZ4MGC.js +0 -2
  385. package/dist/cli/chunks/router-2RXR6J2Q.js +0 -2
  386. package/dist/cli/chunks/routing-feedback-AVAA76TK.js +0 -2
  387. package/dist/cli/chunks/rvf-native-adapter-X2YDJA55.js +0 -2
  388. package/dist/cli/chunks/safe-db-4PRU65BK.js +0 -2
  389. package/dist/cli/chunks/schedule-2AST5CHW.js +0 -2
  390. package/dist/cli/chunks/scheduler-SW6II7OU.js +0 -2
  391. package/dist/cli/chunks/sqlite-persistence-OB5NEGAK.js +0 -2
  392. package/dist/cli/chunks/status-handler-HFPWSCBY.js +0 -45
  393. package/dist/cli/chunks/unified-memory-X7OJYGSD.js +0 -2
  394. package/dist/cli/chunks/unified-memory-hnsw-O6HOD5YL.js +0 -2
  395. package/dist/cli/chunks/unified-persistence-C332CER2.js +0 -2
  396. package/dist/cli/chunks/visual-security-MPUG5HPI.js +0 -2
  397. package/dist/cli/chunks/witness-chain-Q4BZHPDF.js +0 -2
  398. package/dist/cli/chunks/workflow-orchestrator-4NDWECYK.js +0 -2
@@ -1,89 +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.11.4");process.exit(0)}
2
- import{a as A,b as L,c as F,d as R,e as Y,f as T,g as P,h as C,i as j,j as X,k as V,l as ge,m as $,n as Z,o as ye,p as _,q as J,r as U,s as W}from"./chunk-U34OZXD6.js";import{h as pe}from"./chunk-5AQ7FXYG.js";import"./chunk-TPMBFARK.js";import"./chunk-LW5DHT3Z.js";import"./chunk-XXRTWG7O.js";import"./chunk-6GYGAW53.js";import"./chunk-LLUPRGOR.js";import{b as x,d as Q}from"./chunk-VJGHRWMH.js";import{a as fe,b as me,c as ue,d as k,f as We}from"./chunk-IB3ZPLFA.js";import"./chunk-NSPCZPTB.js";import"./chunk-PEIQDQXN.js";import{a as O,b as Ue}from"./chunk-TCWR6TDN.js";import"./chunk-YUHM72VQ.js";import"./chunk-PQUXFSN6.js";import"./chunk-7AWK43JN.js";import"./chunk-VCUCD3B5.js";import"./chunk-QJ5NCYJ3.js";import"./chunk-TQ373GGI.js";import"./chunk-7QTB5XIQ.js";import"./chunk-7ADD2ZQL.js";import"./chunk-Y4AXOHW4.js";import B from"path";import o from"chalk";Ue();Q();import{existsSync as z,mkdirSync as ze,writeFileSync as He,readFileSync as ee}from"fs";import{join as E,resolve as ne}from"path";var Ke={rl_q_values:"includeQValues",dream_insights:"includeDreamInsights",dream_cycles:"includeDreamInsights",witness_chain:"includeWitnessChain",vectors:"includeVectors"};function Ge(e,n){let r=Ke[e.tableName];return!(r&&n[r]===!1)}var Qe=1e4;function Ye(e,n,r,t){if(!Ge(n,r))return Z(E(t,n.fileName),[]),{count:0,rows:[]};let[a,s]=n.domainColumn?$(r.domains,n.domainColumn):[void 0,[]];if(X(e,n.tableName,a,s)>=Qe){let d=n.blobColumns,c=d&&d.length>0?p=>T(p,d):void 0;return{count:ye(E(t,n.fileName),ge(e,n.tableName,a,s),c)}}let i=V(e,n.tableName,a,s);return n.blobColumns&&n.blobColumns.length>0&&(i=i.map(d=>T(d,n.blobColumns))),Z(E(t,n.fileName),i),{count:i.length,rows:i}}function be(e){let n=[];for(let r of R){let t=E(e,r.fileName);z(t)?n.push(C(ee(t,"utf-8"))):n.push(C(""))}return C(n.join(":"))}function he(e,n,r="memory.db"){let t=ne(n.outputPath);z(t)||ze(t,{recursive:!0});let a=0,s={},l=new Set;for(let u of R){let p=Ye(e,u,n,t);if(s[u.tableName]=p.count,a+=p.count,u.tableName==="qe_patterns"){if(p.rows)for(let f of p.rows)f.qe_domain&&l.add(f.qe_domain);else if(p.count>0){let[f,w]=u.domainColumn?$(n.domains,u.domainColumn):[void 0,[]],y=`SELECT DISTINCT qe_domain FROM qe_patterns ${f?`WHERE ${f} AND qe_domain IS NOT NULL`:"WHERE qe_domain IS NOT NULL"}`;try{let g=e.prepare(y).all(...w||[]);for(let v of g)l.add(v.qe_domain)}catch{}}}}let i=n.includeVectors!==!1?X(e,"vectors"):0,d=be(t),c={version:"3.0",exportedAt:new Date().toISOString(),sourceDb:r,stats:{patternCount:s.qe_patterns||0,vectorCount:i,qValueCount:s.rl_q_values||0,dreamInsightCount:s.dream_insights||0,witnessChainLength:s.witness_chain||0,totalRecords:a},domains:[...l].sort(),checksum:d,tableRecordCounts:s};return He(E(t,"manifest.json"),JSON.stringify(c,null,2),"utf-8"),c}var Xe=new Set(["qe_patterns","rl_q_values","dream_insights","witness_chain"]);function Ze(e){return e==="1.0"?R.filter(n=>Xe.has(n.tableName)):e==="3.0"?R:(console.warn(`[brain-import] Unknown manifest version '${e}'. Attempting full import \u2014 some files may be missing.`),R)}function we(e,n,r){let t=ne(n),a=E(t,"manifest.json");if(!z(a))throw new Error(`Manifest not found at ${a}`);let s=x(ee(a,"utf-8")),l=be(t);if(l!==s.checksum)throw new Error(`Checksum mismatch: expected ${s.checksum}, got ${l}. The export may have been tampered with or corrupted.`);let i=Ze(s.version);if(r.dryRun){let f=0;for(let w of i){let m=_(E(t,w.fileName),x);f+=m.length}return{imported:f,skipped:0,conflicts:0}}W(e);let d=0,c=0,u=0;return e.transaction(()=>{for(let f of i){let w=E(t,f.fileName),m=_(w,x);f.blobColumns&&f.blobColumns.length>0&&(m=m.map(y=>P(y,f.blobColumns)));for(let y of m){let g;if(f.dedupColumns&&f.dedupColumns.length>0)g=U(e,f.tableName,y,f.dedupColumns);else{let v=A[f.tableName]||"id",b=F[f.tableName],I=L[f.tableName];g=J(e,f.tableName,y,v,r.mergeStrategy,b,I)}d+=g.imported,c+=g.skipped,u+=g.conflicts}}})(),{imported:d,skipped:c,conflicts:u}}function ve(e){let n=ne(e),r=E(n,"manifest.json");if(!z(r))throw new Error(`Manifest not found at ${r}`);return x(ee(r,"utf-8"))}We();import{existsSync as H,statSync as en,unlinkSync as Re,writeFileSync as nn}from"fs";import{resolve as te}from"path";function Se(e,n,r="memory.db"){if(!k())throw new Error("@ruvector/rvf-node is not available. Install it or use --format jsonl instead.");let t=te(n.outputPath),a=n.dimension??384;H(t)&&Re(t);let s=`${t}.idmap.json`;H(s)&&Re(s);let l=fe(t,a);try{let i={},d=new Set,c=0;for(let S of R){let[h,ce]=S.domainColumn?$(n.domains,S.domainColumn):[void 0,[]],D=V(e,S.tableName,h,ce);if(S.tableName==="qe_patterns")for(let q of D)q.qe_domain&&d.add(q.qe_domain);let G=Y[S.tableName];G&&G.length>0&&(D=D.map(q=>T(q,G))),i[S.tableName]=D,c+=D.length}let u=0,p=[];if(j(e,"qe_pattern_embeddings")){let S=e.prepare("SELECT pattern_id, embedding, dimension FROM qe_pattern_embeddings").all();for(let h of S)h.embedding&&h.dimension===a&&p.push({id:`pe:${h.pattern_id}`,vector:new Float32Array(h.embedding.buffer,h.embedding.byteOffset,a),metadata:{tableName:"qe_pattern_embeddings"}})}if(j(e,"captured_experiences")){let S=e.prepare("SELECT id, embedding, embedding_dimension, domain, quality FROM captured_experiences WHERE embedding IS NOT NULL").all();for(let h of S)h.embedding_dimension===a&&p.push({id:`exp:${h.id}`,vector:new Float32Array(h.embedding.buffer,h.embedding.byteOffset,a),metadata:{tableName:"captured_experiences",domain:h.domain,confidence:h.quality}})}if(j(e,"sona_patterns")){let S=e.prepare("SELECT id, state_embedding, domain, confidence FROM sona_patterns WHERE state_embedding IS NOT NULL").all();for(let h of S)h.state_embedding.byteLength/4===a&&p.push({id:`sona:${h.id}`,vector:new Float32Array(h.state_embedding.buffer,h.state_embedding.byteOffset,a),metadata:{tableName:"sona_patterns",domain:h.domain,confidence:h.confidence}})}p.length>0&&(u=l.ingest(p).accepted);let f={version:"3.0",format:"rvf",exportedAt:new Date().toISOString(),sourceDb:r,domains:[...d].sort(),tables:i},w=JSON.stringify(f),m=C(w),y=Buffer.from(w);l.embedKernel(y);let g=n.sign?l.sign(y)??void 0:void 0,v=g?n.signerKeyId??"default":void 0,b=l.fileId(),I=b?{fileId:b,parentId:l.parentId(),lineageDepth:l.lineageDepth()}:void 0,N=l.status(),M={version:"3.0",format:"rvf",exportedAt:f.exportedAt,sourceDb:r,stats:{patternCount:(i.qe_patterns||[]).length,embeddingCount:u,qValueCount:(i.rl_q_values||[]).length,dreamInsightCount:(i.dream_insights||[]).length,witnessChainLength:(i.witness_chain||[]).length,totalRecords:c},domains:f.domains,checksum:m,rvfStatus:{totalVectors:N.totalVectors,totalSegments:N.totalSegments,fileSizeBytes:N.fileSizeBytes},...g?{signature:g,signerKeyId:v}:{},...I?{lineage:I}:{}};if(g)try{l.freeze()}catch{}let Je=`${t}.manifest.json`;return nn(Je,JSON.stringify(M,null,2),"utf-8"),M}finally{l.close()}}var tn={patterns:"qe_patterns",qValues:"rl_q_values",dreamInsights:"dream_insights",witnessChain:"witness_chain"};function xe(e,n,r){if(!k())throw new Error("@ruvector/rvf-node is not available. Install it or use JSONL format.");let t=te(n);if(!H(t))throw new Error(`RVF file not found: ${t}`);let a=me(t);try{let s=a.verifyWitness();if(!s.valid&&(s.totalEntries>0||s.errors.length>0)){let m=s.errors.length>0?s.errors.join("; "):"unknown integrity error";throw new Error(`RVF witness verification failed: ${m}`)}let l=a.extractKernel();if(!l||!l.image)throw new Error("No brain data found in RVF file (missing kernel segment)");let i;try{i=JSON.parse(l.image.toString("utf-8"))}catch(m){throw new Error(`Failed to parse brain kernel data as JSON: ${m instanceof Error?m.message:m}`)}if(r.dryRun){let m=0;if(i.tables)for(let y of Object.values(i.tables))m+=y?.length??0;else m=(i.patterns?.length??0)+(i.qValues?.length??0)+(i.dreamInsights?.length??0)+(i.witnessChain?.length??0);return{imported:m,skipped:0,conflicts:0,embeddingsRestored:0}}W(e);let d=0,c=0,u=0,p=0,f={};if(i.tables)Object.assign(f,i.tables);else for(let[m,y]of Object.entries(tn)){let g=i[m];Array.isArray(g)&&(f[y]=g)}if(e.transaction(()=>{for(let m of R){let y=f[m.tableName];if(!y||!Array.isArray(y))continue;let g=Y[m.tableName];if(g&&g.length>0){y=y.map(v=>P(v,g));for(let v of y)for(let b of g)v[b]instanceof Buffer&&p++}for(let v of y){let b;if(m.dedupColumns&&m.dedupColumns.length>0)b=U(e,m.tableName,v,m.dedupColumns);else{let I=A[m.tableName]||"id",N=F[m.tableName],M=L[m.tableName];b=J(e,m.tableName,v,I,r.mergeStrategy,N,M)}d+=b.imported,c+=b.skipped,u+=b.conflicts}}})(),u>0)try{a.compact()}catch{}return{imported:d,skipped:c,conflicts:u,embeddingsRestored:p}}finally{a.close()}}function K(e){if(!k())throw new Error("@ruvector/rvf-node is not available.");let n=te(e);if(!H(n))throw new Error(`RVF file not found: ${n}`);let r=ue(n);try{let t=r.extractKernel();if(!t||!t.image)throw new Error("No brain data found in RVF file");let a=t.image.toString("utf-8"),s;try{s=JSON.parse(a)}catch(w){throw new Error(`Failed to parse brain kernel data as JSON: ${w instanceof Error?w.message:w}`)}let l=r.status(),i=en(n).size,d=s.tables,c=d?d.qe_patterns?.length??0:s.patterns?.length??0,u=d?d.rl_q_values?.length??0:s.qValues?.length??0,p=d?d.dream_insights?.length??0:s.dreamInsights?.length??0,f=d?d.witness_chain?.length??0:s.witnessChain?.length??0;return{version:"3.0",format:"rvf",exportedAt:s.exportedAt??"unknown",sourceDb:s.sourceDb??"unknown",stats:{patternCount:c,embeddingCount:l.totalVectors,qValueCount:u,dreamInsightCount:p,witnessChainLength:f},domains:s.domains??[],checksum:C(a),rvfStatus:{totalVectors:l.totalVectors,totalSegments:l.totalSegments,fileSizeBytes:i}}}finally{r.close()}}function re(){return k()}Q();import{existsSync as ae,readFileSync as rn,statSync as on}from"fs";import{join as oe,resolve as Ce}from"path";function Ie(e,n,r={}){let t=Ce(e),a=Ce(n),s=Ee(t),l=Ee(a),i=Be(t,s),d=Be(a,l),c=s==="jsonl"&&l==="jsonl",u=ln({pathA:t,pathB:a,manifestA:i,manifestB:d,recordLevel:c,tableFilter:r.tableFilter,maxIdsPerBucket:r.maxIdsPerBucket??500}),p=new Set(i.domains),f=new Set(d.domains),w=i.domains.filter(b=>!f.has(b)),m=d.domains.filter(b=>!p.has(b)),y=i.checksum===d.checksum,g=i.version===d.version,v=y&&g&&u.every(b=>b.delta===0&&(b.added?.length??0)===0&&(b.removed?.length??0)===0&&(b.changed?.length??0)===0);return{pathA:t,pathB:a,formatA:s,formatB:l,manifestA:i,manifestB:d,checksumMatch:y,versionMatch:g,identical:v,recordLevel:c,tableDiffs:u,domainsOnlyInA:w,domainsOnlyInB:m}}function Ee(e){if(!ae(e))throw new Error(`Path not found: ${e}`);if(e.endsWith(".rvf"))return"rvf";if(on(e).isFile())throw new Error(`Unsupported brain export: ${e} (expected a .rvf file or a JSONL directory)`);return"jsonl"}function Be(e,n){return n==="rvf"?sn(e):an(e)}function an(e){let n=oe(e,"manifest.json");if(!ae(n))throw new Error(`Manifest not found at ${n}`);let r=x(rn(n,"utf-8"));return Oe(r,"jsonl")}function sn(e){let n=K(e);return Oe(n,"rvf")}function Oe(e,n){return{format:n,version:e.version??"unknown",exportedAt:e.exportedAt??"unknown",sourceDb:e.sourceDb??"unknown",checksum:e.checksum??"",totalRecords:e.stats?.totalRecords??0,domains:e.domains??[],tableRecordCounts:e.tableRecordCounts??{}}}function ln(e){let n=e.tableFilter?R.filter(t=>t.tableName===e.tableFilter):R;if(e.tableFilter&&n.length===0)throw new Error(`Unknown table: ${e.tableFilter}`);let r=[];for(let t of n){let a=e.manifestA.tableRecordCounts[t.tableName]??0,s=e.manifestB.tableRecordCounts[t.tableName]??0,l=s-a,i,d,c;if(e.recordLevel&&dn(t)){let u=cn(oe(e.pathA,t.fileName),oe(e.pathB,t.fileName),t,e.maxIdsPerBucket);i=u.added,d=u.removed,c=u.changed}r.push({tableName:t.tableName,countA:a,countB:s,delta:l,...i!==void 0?{added:i}:{},...d!==void 0?{removed:d}:{},...c!==void 0?{changed:c}:{}})}return r}function dn(e){return!0}function cn(e,n,r,t){let a=_e(e,r),s=_e(n,r),l=[],i=[],d=[];for(let[c,u]of a){let p=s.get(c);if(p===void 0)i.length<t&&i.push(c);else if(p!==u){if(r.dedupColumns&&r.dedupColumns.length>0)continue;d.length<t&&d.push(c)}}for(let c of s.keys())a.has(c)||l.length<t&&l.push(c);return l.sort(),i.sort(),d.sort(),{added:l,removed:i,changed:d}}function _e(e,n){let r=new Map;if(!ae(e))return r;let t=_(e,x);for(let a of t){let s=fn(a,n);if(s===void 0)continue;let l=mn(a);r.set(s,un(l))}return r}function fn(e,n){if(n.dedupColumns&&n.dedupColumns.length>0){let a=[];for(let s of n.dedupColumns){let l=e[s];if(l==null)return;a.push(String(l))}return a.join("")}let r=A[n.tableName]??"id",t=e[r];if(t!=null)return String(t)}function mn(e){let n=Object.keys(e).sort(),r={};for(let t of n)r[t]=e[t];return JSON.stringify(r)}function un(e){return C(e)}Q();import{existsSync as ie,statSync as pn}from"fs";import{join as Ae,resolve as gn}from"path";var yn=20,bn="qe_patterns";function Ne(e,n={}){let r=gn(e);vn(r);let t=n.table??bn,a=R.find(g=>g.tableName===t);if(!a)throw new Error(`Unknown table: ${t}`);let s=Ae(r,a.fileName);if(!ie(s))throw new Error(`Table file not found: ${a.fileName} (expected in ${r}). Was this export generated with --format jsonl?`);let l=_(s,x),i=a.domainColumn,d=Math.max(1,n.limit??yn),c=n.query?n.query.toLowerCase():void 0,u=n.domains&&n.domains.length>0?new Set(n.domains):void 0,p=n.since,f=n.until,w=n.patternType,m=0,y=[];for(let g of l)hn(g,{domainColumn:i,domains:u,patternType:w,since:p,until:f,queryLower:c})&&(m++,y.length<d&&y.push(wn(g,a.tableName,i)));return{table:t,inputPath:r,totalScanned:l.length,totalMatched:m,limit:d,hits:y,truncated:m>d}}function hn(e,n){if(n.domains){if(!n.domainColumn)return!1;let r=e[n.domainColumn];if(typeof r!="string"||!n.domains.has(r))return!1}if(n.patternType!==void 0&&e.pattern_type!==n.patternType)return!1;if(n.since!==void 0||n.until!==void 0){let r=De(e);if(r===void 0||n.since!==void 0&&r<n.since||n.until!==void 0&&r>n.until)return!1}if(n.queryLower!==void 0){let r=typeof e.name=="string"?e.name.toLowerCase():"",t=typeof e.description=="string"?e.description.toLowerCase():"";if(!r.includes(n.queryLower)&&!t.includes(n.queryLower))return!1}return!0}function De(e){for(let n of["updated_at","created_at","timestamp"]){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function wn(e,n,r){let t=(typeof e.id=="string"||typeof e.id=="number"?String(e.id):void 0)??`${n}:?`,a={name:typeof e.name=="string"?e.name:void 0,description:typeof e.description=="string"?e.description:void 0,domain:r&&typeof e[r]=="string"?e[r]:void 0,patternType:typeof e.pattern_type=="string"?e.pattern_type:void 0,confidence:typeof e.confidence=="number"?e.confidence:void 0,updatedAt:De(e)};return{id:t,display:a,row:e}}function vn(e){if(!ie(e))throw new Error(`Path not found: ${e}`);if(pn(e).isFile())throw e.endsWith(".rvf")?new Error("Brain search does not support RVF exports. Re-export with --format jsonl, or use `aqe brain info` for RVF summaries."):new Error(`Unsupported brain export: ${e} (expected a JSONL directory)`);let r=Ae(e,"manifest.json");if(!ie(r))throw new Error(`Manifest not found at ${r}. Is this a brain export directory?`)}function ke(e,n){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return{created:0,skipped:0};e.exec(`
3
- CREATE TEMP TABLE IF NOT EXISTS _covered_patterns (
4
- pattern_id TEXT PRIMARY KEY
5
- )
6
- `),e.exec("DELETE FROM _covered_patterns"),e.exec(`
7
- INSERT INTO _covered_patterns (pattern_id)
8
- SELECT DISTINCT json_extract(action_data, '$.patternId')
9
- FROM witness_chain
10
- WHERE action_type = 'PATTERN_CREATE'
11
- AND json_extract(action_data, '$.patternId') IS NOT NULL
12
- `),e.exec(`
13
- INSERT OR IGNORE INTO _covered_patterns (pattern_id)
14
- SELECT DISTINCT json_extract(action_data, '$.pattern_id')
15
- FROM witness_chain
16
- WHERE action_type = 'PATTERN_CREATE'
17
- AND json_extract(action_data, '$.pattern_id') IS NOT NULL
18
- `);let t=e.prepare(`SELECT p.id, p.pattern_type, p.qe_domain, p.name, p.created_at
19
- FROM qe_patterns p
20
- LEFT JOIN _covered_patterns c ON p.id = c.pattern_id
21
- WHERE c.pattern_id IS NULL
22
- ORDER BY p.created_at ASC`).all(),s=e.prepare("SELECT COUNT(*) as count FROM qe_patterns").get().count-t.length,l=0;for(let i of t)n.append("PATTERN_CREATE",{patternId:i.id,patternType:i.pattern_type,qeDomain:i.qe_domain,name:i.name,originalCreatedAt:i.created_at,backfilled:!0},"system:backfill"),l++;return e.exec("DROP TABLE IF EXISTS _covered_patterns"),{created:l,skipped:s}}async function Te(e,n){if(Rn(n.format)==="rvf"){let a=O(e,{readonly:!0});try{return Se(a,{outputPath:n.outputPath,domains:n.domains},e)}finally{a.close()}}let t=O(e,{readonly:!0});try{return he(t,n,e)}finally{t.close()}}async function $e(e,n,r){if(Pe(n,r.format)==="rvf"){let s=O(e);try{return xe(s,n,{mergeStrategy:r.mergeStrategy,dryRun:r.dryRun})}finally{s.close()}}let a=O(e);try{return we(a,n,r)}finally{a.close()}}async function Me(e,n){return Pe(e,n)==="rvf"?K(e):ve(e)}async function qe(e,n,r={}){return Ie(e,n,r)}async function Le(e,n={}){return Ne(e,n)}async function Fe(e){let n=O(e);try{let r=pe(n);return await r.initialize(),ke(n,r)}finally{n.close()}}function Rn(e){if(e==="jsonl")return"jsonl";if(e==="rvf"){if(!re())throw new Error("RVF format requested but @ruvector/rvf-node is not available on this platform. Use --format jsonl instead.");return"rvf"}return re()?"rvf":"jsonl"}function Pe(e,n){return n==="rvf"?"rvf":n==="jsonl"?"jsonl":e.endsWith(".rvf")?"rvf":"jsonl"}var de=class{name="brain";description="Export, import, and inspect QE brain state";cleanupAndExit;ensureInitialized;constructor(n,r){this.cleanupAndExit=n,this.ensureInitialized=r}register(n,r){let t=n.command("brain").description(this.description);t.command("export").description("Export brain state to a portable directory").requiredOption("-o, --output <path>","Output directory path").option("--format <format>","Export format: rvf (default) or jsonl","rvf").option("--db <path>","Source database path").action(async a=>{await this.executeExport(a)}),t.command("import").description("Import brain state from an export directory").requiredOption("-i, --input <path>","Path to brain export directory").option("--strategy <strategy>","Merge strategy","skip-conflicts").option("--dry-run","Preview import without writing",!1).option("--db <path>","Target database path").action(async a=>{await this.executeImport(a)}),t.command("info").description("Show manifest info for a brain export").requiredOption("-i, --input <path>","Path to brain export directory").action(async a=>{await this.executeInfo(a)}),t.command("witness-backfill").description("Create witness chain entries for patterns that predate the witness chain").option("--db <path>","Database path").action(async a=>{await this.executeWitnessBackfill(a)}),t.command("diff").description("Compare two brain exports (JSONL directory or .rvf file)").argument("<a>","Path to first brain export").argument("<b>","Path to second brain export").option("--table <name>","Restrict comparison to a single table").option("--verbose","Show the IDs of added/removed/changed records",!1).option("--json","Emit the diff as JSON to stdout",!1).action(async(a,s,l)=>{await this.executeDiff(a,s,l)}),t.command("search").description("Search a JSONL brain export with filters").requiredOption("-i, --input <path>","Path to brain export directory (JSONL)").option("--table <name>","Table to search (default: qe_patterns)").option("--domain <name...>","Restrict to one or more domains").option("--pattern-type <type>","Restrict to a specific pattern_type (qe_patterns only)").option("--since <iso>","Include rows with timestamp \u2265 <iso>").option("--until <iso>","Include rows with timestamp \u2264 <iso>").option("-q, --query <text>","Substring match across name + description (case-insensitive)").option("-l, --limit <n>","Maximum results to return","20").option("--json","Emit results as JSON to stdout",!1).action(async a=>{await this.executeSearch(a)})}async executeExport(n){try{console.log(o.blue(`
23
- Exporting brain state (format: ${n.format})...
24
- `));let r=await se(n.db),t=await Te(r,{outputPath:B.resolve(n.output),format:n.format});if(console.log(o.green(" Export complete.")),console.log(` Format: ${o.cyan("format"in t?t.format??"jsonl":"jsonl")}`),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"embeddingCount"in t.stats?console.log(` Vectors: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`),"rvfStatus"in t){let a=t.rvfStatus;console.log(` RVF Size: ${o.cyan(je(a.fileSizeBytes))}`),console.log(` Segments: ${o.cyan(a.totalSegments)}`)}console.log(` Checksum: ${o.gray(t.checksum)}`),console.log(` Output: ${o.cyan(B.resolve(n.output))}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
25
- Brain export failed:`),r),await this.cleanupAndExit(1)}}async executeImport(n){try{n.dryRun?console.log(o.yellow(`
26
- Dry-run mode \u2014 no data will be written.
27
- `)):console.log(o.blue(`
28
- Importing brain state...
29
- `));let r=await se(n.db),t=await $e(r,B.resolve(n.input),{mergeStrategy:n.strategy,dryRun:n.dryRun});console.log(o.green(" Import complete.")),console.log(` Imported: ${o.cyan(t.imported)}`),console.log(` Skipped: ${o.yellow(t.skipped)}`),console.log(` Conflicts: ${o.red(t.conflicts)}`),"embeddingsRestored"in t&&console.log(` Embeddings: ${o.cyan(t.embeddingsRestored)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
30
- Brain import failed:`),r),await this.cleanupAndExit(1)}}async executeInfo(n){try{console.log(o.blue(`
31
- Brain Export Info
32
- `));let r=B.resolve(n.input),t=await Me(r),a="format"in t?t.format??"jsonl":"jsonl";if(console.log(` Version: ${o.cyan(t.version)}`),console.log(` Format: ${o.cyan(a)}`),console.log(` Exported: ${o.cyan(t.exportedAt)}`),console.log(` Source DB: ${o.cyan(t.sourceDb)}`),console.log(o.blue(`
33
- Learning Data:`)),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"qValueCount"in t.stats&&console.log(` Q-Values: ${o.cyan(t.stats.qValueCount)}`),"dreamInsightCount"in t.stats){let i=t.stats.dreamInsightCount,c=("tableRecordCounts"in t?t.tableRecordCounts:void 0)?.dream_cycles,u=c!==void 0?` (${c} cycles)`:"";console.log(` Dream Insights: ${o.cyan(i)}${o.gray(u)}`)}"witnessChainLength"in t.stats&&console.log(` Witness Chain: ${o.cyan(t.stats.witnessChainLength)} entries`),"embeddingCount"in t.stats?console.log(` Embeddings: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`);let s="tableRecordCounts"in t?t.tableRecordCounts:void 0;if(s){let i=Object.entries(s).filter(([d,c])=>c>0&&!["qe_patterns","rl_q_values","dream_insights","dream_cycles","witness_chain","vectors","qe_pattern_embeddings"].includes(d));if(i.length>0)for(let[d,c]of i){let p=`${d.replace(/_/g," ").replace(/\b\w/g,f=>f.toUpperCase())}:`.padEnd(15);console.log(` ${p}${o.cyan(c)}`)}}let l="totalRecords"in t.stats?t.stats.totalRecords:void 0;if(l!==void 0&&(console.log(o.blue(`
34
- Summary:`)),console.log(` Total Records: ${o.cyan(l)}`)),"domains"in t&&Array.isArray(t.domains)&&t.domains.length>0&&(l||console.log(o.blue(`
35
- Summary:`)),console.log(` Domains: ${o.cyan(t.domains.join(", "))}`)),"rvfStatus"in t){let i=t.rvfStatus;console.log(o.blue(`
36
- RVF Details:`)),console.log(` File Size: ${o.cyan(je(i.fileSizeBytes))}`),console.log(` Vectors: ${o.cyan(i.totalVectors)}`),console.log(` Segments: ${o.cyan(i.totalSegments)}`)}if("lineage"in t){let i=t.lineage;i&&(console.log(o.blue(`
37
- Lineage:`)),console.log(` File ID: ${o.cyan(i.fileId)}`),console.log(` Parent ID: ${o.cyan(i.parentId??"none (root)")}`),console.log(` Depth: ${o.cyan(i.lineageDepth)}`))}if("signature"in t){let i=t.signature,d=t.signerKeyId;console.log(o.blue(`
38
- Signature:`)),i?(console.log(` Status: ${o.green("Signed")}`),console.log(` Key ID: ${o.cyan(d??"unknown")}`),console.log(` Signature: ${o.gray(i.slice(0,32)+"...")}`)):console.log(` Status: ${o.yellow("Unsigned")}`)}console.log(`
39
- Checksum: ${o.gray(t.checksum)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
40
- Failed to read brain info:`),r),await this.cleanupAndExit(1)}}async executeDiff(n,r,t){try{let a=await qe(B.resolve(n),B.resolve(r),{tableFilter:t.table});if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
41
- `),await this.cleanupAndExit(a.identical?0:1);return}Cn(a,t.verbose),await this.cleanupAndExit(a.identical?0:1)}catch(a){console.error(o.red(`
42
- Brain diff failed:`),a),await this.cleanupAndExit(2)}}async executeSearch(n){try{let r=Sn(n.limit),t=xn(n.domain),a=await Le(B.resolve(n.input),{table:n.table,domains:t,patternType:n.patternType,since:n.since,until:n.until,query:n.query,limit:r});if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
43
- `),await this.cleanupAndExit(a.totalMatched>0?0:3);return}_n(a),await this.cleanupAndExit(a.totalMatched>0?0:3)}catch(r){console.error(o.red(`
44
- Brain search failed:`),r),await this.cleanupAndExit(2)}}async executeWitnessBackfill(n){try{console.log(o.blue(`
45
- Running witness chain backfill...
46
- `));let r=await se(n.db),t=await Fe(r);console.log(o.green(" Backfill complete.")),console.log(` Created: ${o.cyan(t.created)} new witness entries`),console.log(` Skipped: ${o.cyan(t.skipped)} (already witnessed)`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
47
- Witness backfill failed:`),r),await this.cleanupAndExit(1)}}getHelp(){return`
48
- Export, import, and inspect QE brain state.
49
-
50
- Formats:
51
- rvf \u2014 Single portable .rvf file (default, requires @ruvector/rvf-node)
52
- jsonl \u2014 JSONL directory format (fallback when native not available)
53
-
54
- Usage:
55
- aqe brain export -o brain.rvf [--format rvf] [--db <path>]
56
- aqe brain export -o ./brain-dir --format jsonl [--db <path>]
57
- aqe brain import -i brain.rvf [--strategy skip-conflicts] [--dry-run] [--db <path>]
58
- aqe brain info -i brain.rvf
59
-
60
- Subcommands:
61
- export Export brain state to a portable .rvf file or JSONL directory
62
- import Import a brain export into the local database
63
- info Show manifest metadata for an existing brain export
64
- diff Compare two brain exports (manifest always; record-level for JSONL)
65
- search Filtered search over a JSONL brain export
66
-
67
- Examples:
68
- aqe brain export -o .agentic-qe/brain.rvf
69
- aqe brain export -o .agentic-qe/brain.rvf --format rvf
70
- aqe brain export -o ./brain-export --format jsonl
71
- aqe brain import -i .agentic-qe/brain.rvf --strategy latest-wins
72
- aqe brain import -i .agentic-qe/brain.rvf --dry-run
73
- aqe brain info -i .agentic-qe/brain.rvf
74
- aqe brain diff ./brain-a ./brain-b --verbose
75
- aqe brain search -i ./brain-export --query oauth --domain test-generation
76
- aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
77
- `}};async function se(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-X7OJYGSD.js");return B.join(n(),".agentic-qe","memory.db")}function je(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Sn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function xn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let s=a.trim();s&&r.push(s)}return r.length>0?r:void 0}function Cn(e,n){console.log(o.blue(`
78
- Brain Diff
79
- `)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+Ve(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
80
- Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
81
- Note: record-level diff is only available when both sides are JSONL exports.
82
- Per-table counts shown below; re-export with --format jsonl for added/removed/changed IDs.`)),console.log(o.blue(`
83
- Tables:`));let r=e.tableDiffs.filter(En);if(r.length===0)console.log(o.gray(" (no differences)"));else for(let t of r)console.log(` ${t.tableName.padEnd(28)} ${o.cyan(String(t.countA).padStart(7))} \u2192 ${o.cyan(String(t.countB).padStart(7))} ${Ve(t.delta)}`+Bn(t,n)),n&&(t.added&&t.added.length>0&&le("added",t.added),t.removed&&t.removed.length>0&&le("removed",t.removed),t.changed&&t.changed.length>0&&le("changed",t.changed));console.log(""),e.identical?console.log(o.green(` Result: identical
84
- `)):console.log(o.yellow(` Result: differences found
85
- `))}function En(e){return!!(e.delta!==0||e.added&&e.added.length>0||e.removed&&e.removed.length>0||e.changed&&e.changed.length>0)}function Ve(e){return e===0?o.gray("(\xB10)"):e>0?o.green(`(+${e})`):o.red(`(${e})`)}function Bn(e,n){let r=[];return e.added&&e.added.length>0&&r.push(o.green(`+${e.added.length}`)),e.removed&&e.removed.length>0&&r.push(o.red(`-${e.removed.length}`)),e.changed&&e.changed.length>0&&r.push(o.yellow(`~${e.changed.length}`)),r.length===0?"":n?" "+r.join(" "):" "+o.gray("[")+r.join(" ")+o.gray("]")}function le(e,n){let r=n.slice(0,10).join(", "),t=n.length>10?o.gray(` \u2026(+${n.length-10} more)`):"";console.log(` ${o.gray(e+":")} ${r}${t}`)}function _n(e){if(console.log(o.blue(`
86
- Brain Search
87
- `)),console.log(` Input: ${o.cyan(e.inputPath)}`),console.log(` Table: ${o.cyan(e.table)}`),console.log(` Scanned: ${o.cyan(e.totalScanned)} Matched: ${o.cyan(e.totalMatched)} Shown: ${o.cyan(e.hits.length)}`+(e.truncated?o.yellow(` (truncated to limit ${e.limit})`):"")),e.hits.length===0){console.log(o.yellow(`
88
- No matching rows.
89
- `));return}console.log("");for(let n of e.hits){let r=o.cyan(n.id)+(n.display.patternType?o.gray(` ${n.display.patternType}`):"")+(n.display.domain?o.gray(` [${n.display.domain}]`):"")+(n.display.confidence!==void 0?o.gray(` conf=${n.display.confidence.toFixed(2)}`):"");if(console.log(` ${r}`),n.display.name&&console.log(` ${o.bold(n.display.name)}`),n.display.description){let t=n.display.description.length>200?n.display.description.slice(0,200)+"\u2026":n.display.description;console.log(` ${o.gray(t)}`)}n.display.updatedAt&&console.log(` ${o.gray(n.display.updatedAt)}`),console.log("")}}function st(e,n){return new de(e,n)}export{de as BrainHandler,st as createBrainHandler};
@@ -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.11.4");process.exit(0)}
2
- import{a}from"./chunk-ZFCVT43J.js";import"./chunk-ZSA6V5FH.js";import"./chunk-IQBZBUP5.js";import"./chunk-TPMBFARK.js";import"./chunk-LW5DHT3Z.js";import"./chunk-XXRTWG7O.js";import"./chunk-6GYGAW53.js";import"./chunk-LLUPRGOR.js";import"./chunk-VJGHRWMH.js";import"./chunk-NSPCZPTB.js";import"./chunk-PEIQDQXN.js";import"./chunk-BMQDELPA.js";import"./chunk-ICCTQ5LO.js";import"./chunk-TCWR6TDN.js";import"./chunk-YUHM72VQ.js";import"./chunk-PQUXFSN6.js";import"./chunk-7AWK43JN.js";import"./chunk-VCUCD3B5.js";import"./chunk-QJ5NCYJ3.js";import"./chunk-TQ373GGI.js";import"./chunk-7QTB5XIQ.js";import"./chunk-7ADD2ZQL.js";import"./chunk-Y4AXOHW4.js";export{a as BrowserWorkflowTool};
@@ -1,27 +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.11.4");process.exit(0)}
2
- import{i as p,m as b}from"./chunk-TPMBFARK.js";b();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function N(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function u(s,t){return s==="shake256"?N(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}externalDb;db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
- CREATE TABLE IF NOT EXISTS witness_chain (
4
- id INTEGER PRIMARY KEY AUTOINCREMENT,
5
- prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
6
- action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
7
- hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT
8
- );
9
- CREATE INDEX IF NOT EXISTS idx_witness_action_type ON witness_chain(action_type);
10
- CREATE INDEX IF NOT EXISTS idx_witness_timestamp ON witness_chain(timestamp);
11
- CREATE INDEX IF NOT EXISTS idx_witness_actor ON witness_chain(actor);
12
- `),this.addColumnIfMissing("hash_algo","TEXT DEFAULT 'sha256'"),this.addColumnIfMissing("signature","TEXT"),this.addColumnIfMissing("signer_key_id","TEXT"),this.db.exec(`
13
- CREATE TABLE IF NOT EXISTS witness_chain_archive (
14
- id INTEGER PRIMARY KEY,
15
- prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
16
- action_data TEXT, timestamp TEXT NOT NULL, actor TEXT NOT NULL,
17
- hash_algo TEXT DEFAULT 'sha256', signature TEXT, signer_key_id TEXT,
18
- archived_at TEXT NOT NULL
19
- );
20
- `)}addColumnIfMissing(t,i){if(!this.db)return;this.db.prepare("SELECT name FROM pragma_table_info('witness_chain')").all().some(r=>r.name===t)||this.db.exec(`ALTER TABLE witness_chain ADD COLUMN ${t} ${i}`)}append(t,i,e){if(!this.db)throw new Error("WitnessChain not initialized");let r=new Date().toISOString(),o=JSON.stringify(i),a="shake256",n=N(o),h=this.db.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),c=h?u(a,f(h)):g,l=null,_=null;if(this.keyManager){let R=Buffer.from(c+n+t+r+e,"utf-8"),T=this.keyManager.sign(R);l=T.signature.toString("hex"),_=T.keyId}return{id:this.db.prepare(`INSERT INTO witness_chain
21
- (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id)
22
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(c,n,t,o,r,e,a,l,_).lastInsertRowid,prev_hash:c,action_hash:n,action_type:t,action_data:o,timestamp:r,actor:e,hash_algo:a,signature:l,signer_key_id:_}}verify(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=this.db.prepare("SELECT * FROM witness_chain ORDER BY id ASC").all();if(i.length===0)return{valid:!0,entriesChecked:0};let e=0,r=t?.checkSignatures===!0&&this.keyManager!==null;for(let a=0;a<i.length;a++){let n=i[a],h=n.hash_algo||"sha256";if(n.action_hash!==u(h,n.action_data))return{valid:!1,brokenAt:n.id,entriesChecked:a+1,signatureFailures:e};if(a===0){if(n.prev_hash!==g)return{valid:!1,brokenAt:n.id,entriesChecked:1,signatureFailures:e}}else{let c=u(h,f(i[a-1]));if(n.prev_hash!==c)return{valid:!1,brokenAt:n.id,entriesChecked:a+1,signatureFailures:e}}if(r&&n.signature&&n.signer_key_id){let c=Buffer.from(n.prev_hash+n.action_hash+n.action_type+n.timestamp+n.actor,"utf-8");this.keyManager.verify(Buffer.from(c),Buffer.from(n.signature,"hex"),n.signer_key_id)||e++}}return{valid:e===0,entriesChecked:i.length,signatureFailures:e,...e>0?{brokenAt:i[0].id}:{}}}getEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=[],e=[];t?.action_type&&(i.push("action_type = ?"),e.push(t.action_type)),t?.since&&(i.push("timestamp >= ?"),e.push(t.since)),t?.until&&(i.push("timestamp <= ?"),e.push(t.until)),t?.actor&&(i.push("actor = ?"),e.push(t.actor));let r=i.length>0?`WHERE ${i.join(" AND ")}`:"",o=t?.limit!=null,a=t?.offset!=null,n=o||a?"LIMIT ?":"",h=a?"OFFSET ?":"";return o?e.push(t.limit):a&&e.push(-1),a&&e.push(t.offset),this.db.prepare(`SELECT * FROM witness_chain ${r} ORDER BY id ASC ${n} ${h}`).all(...e)}getPatternLineage(t){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare(`SELECT * FROM witness_chain
23
- WHERE json_extract(action_data, '$.patternId') = ? OR json_extract(action_data, '$.pattern_id') = ?
24
- ORDER BY id ASC`).all(t,t)}getActorHistory(t,i){if(!this.db)throw new Error("WitnessChain not initialized");return i?this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? AND timestamp >= ? ORDER BY id ASC").all(t,i):this.db.prepare("SELECT * FROM witness_chain WHERE actor = ? ORDER BY id ASC").all(t)}archiveEntries(t){if(!this.db)throw new Error("WitnessChain not initialized");let i=new Date().toISOString(),r=this.db.prepare(`INSERT INTO witness_chain_archive
25
- (id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, archived_at)
26
- SELECT id, prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo, signature, signer_key_id, ?
27
- FROM witness_chain WHERE timestamp < ? AND id > 1 AND id NOT IN (SELECT id FROM witness_chain_archive)`).run(i,t).changes;return r>0&&this.db.prepare("DELETE FROM witness_chain WHERE timestamp < ? AND id > 1").run(t),{archived:r}}crossVerifyWithRvf(t){let i=this.verify(),e=t.status(),r=e.witnessValid===!0,o=typeof e.witnessEntries=="number"?e.witnessEntries:0;return{sqliteValid:i.valid,rvfValid:r,rvfEntries:o,bothValid:i.valid&&r}}getChainLength(){if(!this.db)throw new Error("WitnessChain not initialized");return this.db.prepare("SELECT COUNT(*) as count FROM witness_chain").get().count}},E=null;async function L(){return E||(E=new d,await E.initialize()),E}function I(s,t){return new d(s,t)}function v(){E=null}export{g as a,m as b,N as c,u as d,f as e,d as f,L as g,I as h,v as i};
@@ -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.11.4");process.exit(0)}
2
- import{i as K,m as ot}from"./chunk-TPMBFARK.js";import{a as rt}from"./chunk-XXRTWG7O.js";import{c as U}from"./chunk-6GYGAW53.js";import{a as j,c as et}from"./chunk-PEIQDQXN.js";import{a as G,d as at}from"./chunk-7AWK43JN.js";import{a as nt,b as it}from"./chunk-7QTB5XIQ.js";import{c as H,e as V,g as w}from"./chunk-Y4AXOHW4.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-KWZOWBYS.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
@@ -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.11.4");process.exit(0)}
2
- import{d as B,e as j,f as re,g as W}from"./chunk-IF3HPQNV.js";import{a as ne}from"./chunk-HT6WAYIR.js";import{g as nt,h as it}from"./chunk-HJO4RNOW.js";import{b as Ce,c as tt}from"./chunk-LLUPRGOR.js";import{a as De,d as Fe,e as rt,f as Oe}from"./chunk-IB3ZPLFA.js";import{a as ie}from"./chunk-TSWF3AGQ.js";import{b as P,c as w}from"./chunk-O7PVZ32A.js";import{a as v,b as Te,c as xe}from"./chunk-PEIQDQXN.js";import{i as C}from"./chunk-BMQDELPA.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-7ADD2ZQL.js";import{a as Re,d as J,f as et,g as Ae}from"./chunk-Y4AXOHW4.js";var V=J(E=>{var ft=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function qe(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)ue(n,i)&&r.push(i);return r}E._objectKeys=qe;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=qe(n),i=r.length,s=0;s<i;s++)if(le(n[r[s]]))return!0}}return!1}E.hasUndefined=le;function Ue(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
- `)}var Pt=(function(n){ft(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Ue(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Ue(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=J(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=V();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=R._deepClone(r));var i=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=Y;function O(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,d=u.length,h=void 0,f=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(f=u[l],f&&f.indexOf("~")!=-1&&(f=R.unescapePathComponent(f)),i&&(f=="__proto__"||f=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&h===void 0&&(o[f]===void 0?h=u.slice(0,l).join("/"):l==d-1&&(h=e.path),h!==void 0&&p(e,0,n,h)),l++,Array.isArray(o)){if(f==="-")f=o.length;else{if(t&&!R.isInteger(f))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);R.isInteger(f)&&(f=~~f)}if(l>=d){if(t&&e.op==="add"&&f>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=wt[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=d){var a=L[e.op].call(e,o,f,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[f],t&&l<d&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=O;function Qe(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=O(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}g.applyPatch=Qe;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=ze([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=K;function ze(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Qe(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=ze;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var $e=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var S=V(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,i=At(n);if(!i)i=new Et(n),me.set(n,i);else{var s=Tt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=S._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=S._objectKeys(e),a=S._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],d=n[l];if(S.hasOwnProperty(e,l)&&!(e[l]===void 0&&d!==void 0&&Array.isArray(e)===!1)){var h=e[l];typeof d=="object"&&d!=null&&typeof h=="object"&&h!=null&&Array.isArray(d)===Array.isArray(h)?pe(d,h,t,r+"/"+S.escapePathComponent(l),i):d!==h&&(c=!0,i&&t.push({op:"test",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(d)}),t.push({op:"replace",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(h)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(d)}),t.push({op:"remove",path:r+"/"+S.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!S.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+S.escapePathComponent(l),value:S._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var Je=J(I=>{var Ot=de();Object.assign(I,Ot);var It=$e();Object.assign(I,It);var Z=V();I.JsonPatchError=Z.PatchError;I.deepClone=Z._deepClone;I.escapePathComponent=Z.escapePathComponent;I.unescapePathComponent=Z.unescapePathComponent});tt();xe();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-OB5NEGAK.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let d=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,d)=>l+d*d,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let d=this.sqliteStore.getPattern(l.id),h=d?.embedding;if(!h||h.length!==u.length)continue;let f=0,p=0;for(let b=0;b<u.length;b++)f+=u[b]*h[b],p+=h[b]*h[b];if(p=Math.sqrt(p),p===0)continue;let m=f/(o*p),y=this.calculateReuseInfo(d,m);s.push({pattern:d,score:m,matchType:"vector",similarity:m,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let d=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),P(void 0)}catch(r){return w(new Error(`recordUsage failed: ${v(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=j&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};Oe();xe();F();function at(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ie(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Ne=1e4,He=2166136261;function Me(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var _e="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=_e[i>>4]+_e[i&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=oe[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Ne,this.baseSeed=e?.seed??He,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=Me(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=lt(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 ut([r,i])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Ne,this.baseSeed=e?.seed??He,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=Me(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ct(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+=oe[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 ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Le(n){return new ae(n)}function ke(n){return q()?new se(n):null}var $=et(Je(),1),_t=`
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 Be(n,e){let t=$.compare(n,e),r=$.compare(e,n);return{forward:t,reverse:r}}function Nt(n,e){let t=JSON.parse(JSON.stringify(n));return $.applyPatch(t,e).newDocument}function je(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var ee=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(_t),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:C(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:c}=Be(t,r),u={id:C(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:c,metadata:i};return this.insertEvent(u),this.enforceRetention(e),u}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:c,reverse:u}=Be(a,s),o={id:C(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:u,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(je)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(je)}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=Nt(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
- WHERE pattern_id = ? AND version != 0 AND id IN (
45
- SELECT id FROM pattern_deltas
46
- WHERE pattern_id = ? AND version != 0
47
- ORDER BY version ASC
48
- LIMIT ?
49
- )`).run(e,e,s)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ge=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(d=>d.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(d=>d.version===0||d.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function We(n){return H()?new ge(n):null}F();var Mt=128,Lt=8,kt=1e4,ye=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let 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 l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Xe(n){return new ye(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ge=1-_;function qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function Qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(Qt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=qt(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ge)return new Float32Array(e);let r=Ge/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(A(e));if(t<_)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)}},ve=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.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 u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:d}=c.shift(),h=Math.tanh(.3*(o+.1)),f=l+d/2,p=new Float32Array(r);p[0]=h*Math.cos(f),p[1]=h*Math.sin(f);let m=s.get(u);if(m&&m.features.length>0){let N=h*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*N}let y=T.project(p);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:m?.parentId}});let b=i.get(u)??[];for(let N=0;N<b.length;N++){let x=d/Math.max(1,b.length);c.push({id:b[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ve(n){return zt()?new ve(n):null}function zt(){return D().useHyperbolicHnsw}F();var Pe=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ve(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=T.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=T.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 Ye(n){return new Pe(n)}var we=null;function Ke(){return we||(we=Le({dimensions:1e4})),we}var Se;function $t(){return Se===void 0&&(Se=ke()),Se}var U=null,be=0;function Ze(n){return(!U||be!==n)&&(U=Xe({dimension:n,maxPatterns:1e4}),be=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:j,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ee=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-6OJJDZHL.js"),{HnswAdapter:c}=await import("./hnsw-adapter-5HXA3QB3.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-PZRQWBRG.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=We()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=W(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ke().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(s))}try{let s=$t();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(s))}if(te()&&e.embedding)try{Ze(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(s))}if(H()&&this.deltaTracker)try{let s={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,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ze(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let p=f.metadata.id,m=await this.get(p);if(m&&this.matchesFilters(m,t)){let y=this.calculateReuseInfo(m,f.similarity);s.push({pattern:m,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",v(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let p of f){let m=await this.get(p.key);if(m&&this.matchesFilters(m,t)){let y=this.calculateReuseInfo(m,p.score);s.push({pattern:m,score:p.score,matchType:"vector",similarity:p.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(m=>[m.id,m.ftsScore])),p=new Set(s.map(m=>m.pattern.id));for(let m of s){let y=f.get(m.pattern.id);y!==void 0&&(m.score=.75*m.score+.25*y)}for(let m of h){if(p.has(m.id))continue;let y=await this.get(m.id);if(y&&this.matchesFilters(y,t)){let b=this.calculateReuseInfo(y,m.ftsScore);s.push({pattern:y,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:b.canReuse,estimatedTokenSavings:b.estimatedTokenSavings,reuseConfidence:b.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(p=>p.pattern.id));for(let p of h)f.has(p.pattern.id)||s.push(p)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),p=c-f,m=Math.pow(.5,p/a),y=h.pattern.usageCount>0?m:.5;h.score=h.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&s.length>0)try{this.nullStore||(this.nullStore=new ie(u));let h=this.nullStore.getNullSummaries(s.map(f=>f.pattern.id));for(let f of s){let p=h.get(f.pattern.id);p&&(f.nullSummary=p,f.score=ie.applyNullDiscount(f.score,p,t.contextFingerprint))}}catch(h){console.debug("[PatternStore] null discount skipped:",v(h))}s.sort((h,f)=>f.score-h.score);let o=s;t.filter&&(o=Ie(s,t.filter));let l=o.slice(0,i),d=performance.now()-r;return this.recordSearchLatency(d),P(l)}catch(a){return w(Te(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ke(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(f=>this.hdcCache.has(f)).map(f=>({id:f,similarity:u.similarity(o.vector,this.hdcCache.get(f))}));l.sort((f,p)=>p.similarity-f.similarity);let d=l.map(f=>f.id),h=c.filter(f=>!this.hdcCache.has(f));c=[...d,...h]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let d=o.name.toLowerCase(),h=o.description.toLowerCase();d.includes(s)&&(l+=.5),h.includes(s)&&(s.length/h.length>.3?l+=.5:l+=.3);for(let f of o.context.tags)if(f.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let d=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,d=t,h=e.successRate,f=Math.min(e.reuseCount/10,1),p=o?d*.4+h*.4+f*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}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){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),d={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},m={id:d.id,name:d.name,confidence:d.confidence,qualityScore:d.qualityScore,usageCount:d.usageCount,successRate:d.successRate,tier:d.tier};this.deltaTracker.recordDelta(e,p,m,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(p))}let h=re(d);return h.meetsUsageCriteria&&h.meetsQualityCriteria&&h.meetsCoherenceCriteria&&d.tier==="short-term"?await this.promote(e):this.patternCache.set(e,d),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,d=s.qualityScore<.2,h=s.usageCount===0&&o>1440*60*1e3;(l&&d||h)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,be=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ye({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(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function zr(n,e){try{if(D().useRVFPatternStore&&Fe()){let{existsSync:r}=Re("fs"),{join:i}=Re("path"),s=process.env.AQE_PROJECT_ROOT??Ce(),a=i(s,".agentic-qe"),c=i(a,"patterns.rvf");if(r(a)){let u={...X,...e},o=!1;try{let{getSharedRvfAdapter:l}=(it(),Ae(nt)),d=l(a,u.embeddingDimension);if(d){o=!0;let h=new Q(()=>d,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),h}}catch{}if(!o){let l=new Q((d,h)=>{let{openRvfStore:f}=(Oe(),Ae(rt)),p=()=>{try{return f(d)}catch{return null}},m=p();if(m){if(m.dimension()!==h){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${h})`)}return m}try{return De(d,h)}catch(y){if(m=p(),m&&m.dimension()===h)return m;throw y}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ee(n,e)}export{zr as a};
50
- /*! Bundled license information:
51
-
52
- fast-json-patch/commonjs/helpers.js:
53
- (*!
54
- * https://github.com/Starcounter-Jack/JSON-Patch
55
- * (c) 2017-2022 Joachim Wester
56
- * MIT licensed
57
- *)
58
-
59
- fast-json-patch/commonjs/duplex.js:
60
- (*!
61
- * https://github.com/Starcounter-Jack/JSON-Patch
62
- * (c) 2017-2021 Joachim Wester
63
- * MIT license
64
- *)
65
- */
@@ -1,2 +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.11.4");process.exit(0)}
2
- import{a as e,b as g,e as r}from"./chunk-6GYGAW53.js";import{c as o}from"./chunk-Y4AXOHW4.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
@@ -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.11.4");process.exit(0)}
2
- import{a as R}from"./chunk-IQBZBUP5.js";import{m as C}from"./chunk-TPMBFARK.js";import{b as S}from"./chunk-LLUPRGOR.js";import{a as b,c as T}from"./chunk-PEIQDQXN.js";import{i as h}from"./chunk-BMQDELPA.js";import{a as M}from"./chunk-ICCTQ5LO.js";C();T();import*as f from"path";import*as c from"fs";function x(){return process.env.AQE_MEMORY_BACKEND==="memory"}var s=null,d=null,g=null;function O(o){g=o}async function k(){return s||d||(d=(async()=>{if(x()){let r=new M;return await r.initialize(),s=r,r}let o=S(),e=f.join(o,".agentic-qe");c.existsSync(e)||c.mkdirSync(e,{recursive:!0});let t=new R({sqlite:{path:f.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await t.initialize(),s=t,t})(),d)}function q(){if(g)try{g()}catch{}s&&(s.dispose().catch(()=>{}),s=null),d=null}async function I(o){return o?.memory?o.memory:k()}var m=null,l=null;function L(){let o=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();return o?o!=="false"&&o!=="0"&&o!=="no"&&o!=="off":!1}function E(o){m=o,l=null}async function w(){return L()?null:m||l||(l=(async()=>{let{createLLMRouterService:o}=await import("./llm-router-service-IFO6GRRO.js"),e=await o();return e?(m=e.router,m):null})(),l)}function H(){m=null,l=null}async function N(o){return o?.llmRouter?o.llmRouter:await w()??void 0}var v={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},P=class{logger=v;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,t){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:t,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let t=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let r=e,{properties:i,required:n}=this.config.schema;if(n)for(let a of n)a in r||t.push(`Missing required field: ${a}`);for(let[a,u]of Object.entries(r)){let p=i[a];if(!p)continue;let y=this.validateType(a,u,p);y&&t.push(y)}return{valid:t.length===0,errors:t}}validateType(e,t,r){if(t==null)return null;let i=Array.isArray(t)?"array":typeof t;if(r.type==="array"&&!Array.isArray(t))return`${e} must be an array`;if(r.type!=="array"&&i!==r.type)return`${e} must be of type ${r.type}, got ${i}`;if(r.enum&&!r.enum.includes(t))return`${e} must be one of: ${r.enum.join(", ")}`;if(r.type==="number"){let n=t;if(r.minimum!==void 0&&n<r.minimum)return`${e} must be >= ${r.minimum}`;if(r.maximum!==void 0&&n>r.maximum)return`${e} must be <= ${r.maximum}`}if(r.type==="string"){let n=t;if(r.minLength!==void 0&&n.length<r.minLength)return`${e} must be at least ${r.minLength} characters`;if(r.maxLength!==void 0&&n.length>r.maxLength)return`${e} must be at most ${r.maxLength} characters`}return null}async invoke(e,t={}){let r=Date.now(),i=h();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(r,i)};let a={requestId:i,startTime:r,streaming:t.streaming,onStream:t.onStream,abortSignal:t.abortSignal,demoMode:t.demoMode,memory:t.memory,llmRouter:t.llmRouter};try{let u=await this.execute(e,a);return{...u,metadata:{...u.metadata,...this.createMetadata(r,i)}}}catch(u){return{success:!1,error:b(u),metadata:this.createMetadata(r,i)}}}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{x as a,O as b,k as c,q as d,I as e,E as f,w as g,H as h,N as i,v as j,P as k};
@@ -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.11.4");process.exit(0)}
2
- import{c as a,d as b,e as c}from"./chunk-Q7ORVHJB.js";import"./chunk-O5NEJIHB.js";import"./chunk-PEIQDQXN.js";import"./chunk-Y4AXOHW4.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
@@ -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.11.4");process.exit(0)}
2
- import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l}from"./chunk-JDFPAJGB.js";import"./chunk-ADFKY3X2.js";import"./chunk-VO6YJGB4.js";import"./chunk-EONKMHKO.js";import"./chunk-SFDUT5WM.js";import"./chunk-XHRLBJTM.js";import"./chunk-TCVEKRPI.js";import"./chunk-A4OMK3FO.js";import"./chunk-ZFCVT43J.js";import"./chunk-GOQ4P2PB.js";import"./chunk-UQ72K44T.js";import"./chunk-4JFH3MVA.js";import"./chunk-VQU7DMEY.js";import"./chunk-EZRHSHOQ.js";import"./chunk-FSGMRQFC.js";import"./chunk-B5XUWHKQ.js";import"./chunk-4RHNPRAP.js";import"./chunk-X64BEXUY.js";import"./chunk-RFQBDMAP.js";import"./chunk-KUZMVH6N.js";import"./chunk-U34OZXD6.js";import"./chunk-JCTCM6IR.js";import"./chunk-5P7Q5YNC.js";import"./chunk-P6S6ZVB5.js";import"./chunk-CNF3ZWLM.js";import"./chunk-6W3QHS45.js";import"./chunk-7IKWF2AD.js";import"./chunk-HH6NCBSP.js";import"./chunk-3E7D3A35.js";import"./chunk-TU6YN43Q.js";import"./chunk-MCT4CD5M.js";import"./chunk-NV3TXXOW.js";import"./chunk-3FJZMQJ7.js";import"./chunk-WQZ2WRO4.js";import"./chunk-NFJT7XXR.js";import"./chunk-N2BJN6AO.js";import"./chunk-6JUOH6L4.js";import"./chunk-AYGEWPN4.js";import"./chunk-MALOUGSF.js";import"./chunk-Q7ORVHJB.js";import"./chunk-O5NEJIHB.js";import"./chunk-LKURMUBU.js";import"./chunk-XQ6DW5FV.js";import"./chunk-WMIRAD3J.js";import"./chunk-4BFCLSDN.js";import"./chunk-3SRPFBU7.js";import"./chunk-QEVX4GWF.js";import"./chunk-KYTFIP6R.js";import"./chunk-G3TFNY4T.js";import"./chunk-NBBLPDJX.js";import"./chunk-5VSQAGA2.js";import"./chunk-QMC5MTBV.js";import"./chunk-63QUN3JK.js";import"./chunk-Z2REKBD6.js";import"./chunk-DRMHVY4T.js";import"./chunk-UJMTKXPI.js";import"./chunk-ZKCKOQJI.js";import"./chunk-FRFVN6AA.js";import"./chunk-GRQ36XUH.js";import"./chunk-WNMDWP5A.js";import"./chunk-3SBUL72V.js";import"./chunk-RCPD6F4R.js";import"./chunk-5Z4FBCBK.js";import"./chunk-MWFJC5HR.js";import"./chunk-37ZDGJ3H.js";import"./chunk-JNQN5DNS.js";import"./chunk-ZSA6V5FH.js";import"./chunk-IQBZBUP5.js";import"./chunk-UCYTY4LG.js";import"./chunk-BRLUNIR4.js";import"./chunk-4YT5YN5G.js";import"./chunk-T76RFXQX.js";import"./chunk-HWBMYR5W.js";import"./chunk-QSDIY3E2.js";import"./chunk-MYMIEQSZ.js";import"./chunk-DNOU2HVQ.js";import"./chunk-2WPSMQIL.js";import"./chunk-IF3HPQNV.js";import"./chunk-HT6WAYIR.js";import"./chunk-HJO4RNOW.js";import"./chunk-5AQ7FXYG.js";import"./chunk-YNK6SUPU.js";import"./chunk-PFWJQPUC.js";import"./chunk-JFLSQH2X.js";import"./chunk-YKSWC7I4.js";import"./chunk-54B6P2WS.js";import"./chunk-TPMBFARK.js";import"./chunk-LW5DHT3Z.js";import"./chunk-XXRTWG7O.js";import"./chunk-6GYGAW53.js";import"./chunk-LLUPRGOR.js";import"./chunk-VJGHRWMH.js";import"./chunk-IB3ZPLFA.js";import"./chunk-TSWF3AGQ.js";import"./chunk-NSPCZPTB.js";import"./chunk-O7PVZ32A.js";import"./chunk-PEIQDQXN.js";import"./chunk-BMQDELPA.js";import"./chunk-ICCTQ5LO.js";import"./chunk-TCWR6TDN.js";import"./chunk-YUHM72VQ.js";import"./chunk-PQUXFSN6.js";import"./chunk-7AWK43JN.js";import"./chunk-VCUCD3B5.js";import"./chunk-QJ5NCYJ3.js";import"./chunk-TQ373GGI.js";import"./chunk-7QTB5XIQ.js";import"./chunk-7ADD2ZQL.js";import"./chunk-Y4AXOHW4.js";export{c as adoptExternalFleet,e as assignAgentLevel,k as disposeFleet,f as getAgentLevel,g as getAllAgentLevels,a as getFleetState,d as getFleetTopology,l as handleAQEHealth,j as handleFleetHealth,h as handleFleetInit,i as handleFleetStatus,b as isFleetInitialized};
@@ -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.11.4");process.exit(0)}
2
- import{a,b}from"./chunk-CNF3ZWLM.js";import"./chunk-NFJT7XXR.js";import"./chunk-O7PVZ32A.js";import"./chunk-BMQDELPA.js";import"./chunk-Y4AXOHW4.js";export{a as CrossDomainEventRouter,b as createCrossDomainRouter};