agentic-qe 3.9.30 → 3.9.32

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 (345) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +208 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/bridge/captured-experience-bridge.js +31 -2
  5. package/dist/cli/bundle.js +5 -5
  6. package/dist/cli/chunks/adapter-CDQOF5TF.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-TOSXWTUQ.js → agent-booster-wasm-WKS3E6KT.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-2BU6TYZZ.js → agent-handler-LYCAWE7S.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-JFG3BXZY.js → agent-memory-branch-XF7IOMRK.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +2 -0
  11. package/dist/cli/chunks/{audit-4IGZZKUW.js → audit-D2AY3HFP.js} +2 -2
  12. package/dist/cli/chunks/base-UGH6TVO4.js +2 -0
  13. package/dist/cli/chunks/{hnswlib-node-STKRZIU3.js → better-sqlite3-K2VWFDKT.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-RIDW27HH.js → brain-handler-NNW4TAO2.js} +4 -4
  15. package/dist/cli/chunks/{branch-enumerator-GMYHLLWD.js → branch-enumerator-OM5HNZKV.js} +2 -2
  16. package/dist/cli/chunks/{browser-N76A3I2P.js → browser-Y2FU2NV4.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +2 -0
  18. package/dist/cli/chunks/{chunk-ETEHVG76.js → chunk-2L5GAOST.js} +2 -2
  19. package/dist/cli/chunks/{chunk-ECX6VXMW.js → chunk-2XC4XVCI.js} +1 -1
  20. package/dist/cli/chunks/{chunk-L7X3A36M.js → chunk-2Z2IQBIJ.js} +1 -1
  21. package/dist/cli/chunks/{chunk-UYLHIGNC.js → chunk-33PGBYTC.js} +2 -2
  22. package/dist/cli/chunks/{chunk-OOFWYDG6.js → chunk-3MHWBCSC.js} +1 -1
  23. package/dist/cli/chunks/{chunk-FI4HRS2G.js → chunk-3R4CMTWF.js} +2 -2
  24. package/dist/cli/chunks/{chunk-IP6ZTXNJ.js → chunk-45N22VAB.js} +2 -2
  25. package/dist/cli/chunks/{chunk-FG5GL26L.js → chunk-4H4PEZUX.js} +2 -2
  26. package/dist/cli/chunks/{chunk-CNNVL5W4.js → chunk-4VAZSCTZ.js} +2 -2
  27. package/dist/cli/chunks/{chunk-AWWD3EI3.js → chunk-5A6LBGRU.js} +2 -2
  28. package/dist/cli/chunks/{chunk-ER6BT4GS.js → chunk-5DSANX6S.js} +2 -2
  29. package/dist/cli/chunks/chunk-5R5WOLZM.js +5 -0
  30. package/dist/cli/chunks/{chunk-RNO6CE7I.js → chunk-5WR42V5O.js} +2 -2
  31. package/dist/cli/chunks/{chunk-UEXOMDRS.js → chunk-5XY6SULI.js} +2 -2
  32. package/dist/cli/chunks/{chunk-WVODEWH5.js → chunk-62UXGD5J.js} +14 -8
  33. package/dist/cli/chunks/{chunk-EWNJ6OAT.js → chunk-667I4RTC.js} +1 -1
  34. package/dist/cli/chunks/{chunk-ND6VCNN5.js → chunk-6EKXBWJD.js} +2 -2
  35. package/dist/cli/chunks/{chunk-Y57V4FDT.js → chunk-6R6QCGNU.js} +2 -2
  36. package/dist/cli/chunks/{chunk-VRP4GB4Y.js → chunk-6SYP7QX6.js} +4 -4
  37. package/dist/cli/chunks/{chunk-BFJLKG3D.js → chunk-6YGFAJ3X.js} +1 -1
  38. package/dist/cli/chunks/{chunk-UWWX4RK7.js → chunk-6ZG6TBWF.js} +4 -4
  39. package/dist/cli/chunks/{chunk-QSV4ROZD.js → chunk-7AISRWBS.js} +2 -2
  40. package/dist/cli/chunks/{chunk-SJCEPKZO.js → chunk-7IDPVSTF.js} +1 -1
  41. package/dist/cli/chunks/{chunk-HQIWLMDS.js → chunk-7PTW3M67.js} +2 -2
  42. package/dist/cli/chunks/{chunk-TA3QYAZ6.js → chunk-A4UNK5SY.js} +2 -2
  43. package/dist/cli/chunks/chunk-A6VI5BZU.js +95 -0
  44. package/dist/cli/chunks/{chunk-XVTZXCHI.js → chunk-BBPOTFIY.js} +2 -2
  45. package/dist/cli/chunks/{chunk-OEGFOMXP.js → chunk-BDXEL3GM.js} +2 -2
  46. package/dist/cli/chunks/{chunk-YETPSL6H.js → chunk-BGRC4676.js} +3 -3
  47. package/dist/cli/chunks/chunk-BQML7B4W.js +180 -0
  48. package/dist/cli/chunks/{chunk-DEDFPHJL.js → chunk-BV3SGEV7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-FGMHVSLV.js → chunk-DBE2LIYG.js} +2 -2
  50. package/dist/cli/chunks/{chunk-2GBBZLXT.js → chunk-DFY7F4TE.js} +1 -1
  51. package/dist/cli/chunks/{chunk-LDGNVPBZ.js → chunk-EFEJLZDN.js} +1 -1
  52. package/dist/cli/chunks/{chunk-ZKZTSYPU.js → chunk-ESNBKAT6.js} +2 -2
  53. package/dist/cli/chunks/{chunk-5F26LSG2.js → chunk-EVSUZKD5.js} +2 -2
  54. package/dist/cli/chunks/{chunk-QOJ7EAF5.js → chunk-FFBF5BLQ.js} +1 -1
  55. package/dist/cli/chunks/{chunk-3AICELMQ.js → chunk-FIONYUVH.js} +2 -2
  56. package/dist/cli/chunks/{chunk-UROPIIB2.js → chunk-FNQCWEVJ.js} +2 -2
  57. package/dist/cli/chunks/{chunk-5DJAJPBG.js → chunk-FV2MU6CY.js} +2 -2
  58. package/dist/cli/chunks/{chunk-QTS2DS42.js → chunk-FWEYOD3S.js} +2 -2
  59. package/dist/cli/chunks/{chunk-XK6YXCS7.js → chunk-G6AJMFWL.js} +3 -3
  60. package/dist/cli/chunks/{chunk-R57J3O6I.js → chunk-G6VVOUUF.js} +2 -2
  61. package/dist/cli/chunks/{chunk-2O5TT3UT.js → chunk-G77CYF7H.js} +3 -3
  62. package/dist/cli/chunks/{chunk-TULNR2AH.js → chunk-H7YKTJMY.js} +2 -2
  63. package/dist/cli/chunks/{chunk-GEXVUFK4.js → chunk-HGWQC7PR.js} +2 -2
  64. package/dist/cli/chunks/{chunk-QLNS6DGB.js → chunk-HHBFI3YA.js} +2 -2
  65. package/dist/cli/chunks/{chunk-WP6X67YI.js → chunk-HPQZSXED.js} +1 -1
  66. package/dist/cli/chunks/{chunk-HA7N45KB.js → chunk-HR6NX6DW.js} +2 -2
  67. package/dist/cli/chunks/{chunk-HB52S6IV.js → chunk-I6Q6BPVH.js} +1 -1
  68. package/dist/cli/chunks/{chunk-BM73MJLE.js → chunk-IGEZVFOM.js} +2 -2
  69. package/dist/cli/chunks/{chunk-QBDXUI2H.js → chunk-IGQPGXP7.js} +2 -2
  70. package/dist/cli/chunks/{chunk-Q26GG6WO.js → chunk-IJQJV7BC.js} +3 -3
  71. package/dist/cli/chunks/chunk-JDW6GN3A.js +2 -0
  72. package/dist/cli/chunks/{chunk-GZ3U2QT2.js → chunk-JRYNHFZA.js} +1 -1
  73. package/dist/cli/chunks/{chunk-MV3NUANS.js → chunk-KHZRNJ3A.js} +1 -1
  74. package/dist/cli/chunks/chunk-LHDTXTS7.js +2 -0
  75. package/dist/cli/chunks/{chunk-52TRKIAQ.js → chunk-LI2IOJMM.js} +1 -1
  76. package/dist/cli/chunks/{heartbeat-scheduler-CNJBAO5C.js → chunk-LR5VW3OS.js} +2 -2
  77. package/dist/cli/chunks/{chunk-2NFGUFYU.js → chunk-LTSNDM5N.js} +2 -2
  78. package/dist/cli/chunks/{chunk-3EP2YZSY.js → chunk-M5PYPGBC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-JCWHX4XV.js → chunk-MEHNT37H.js} +2 -2
  80. package/dist/cli/chunks/{chunk-QHKK2H4H.js → chunk-MERMCKPG.js} +1 -1
  81. package/dist/cli/chunks/{chunk-Q53UMLLC.js → chunk-MIHQIAVK.js} +2 -2
  82. package/dist/cli/chunks/{chunk-VOBNJWZF.js → chunk-MMVSERJQ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-37I6K7QO.js → chunk-MQQANXFS.js} +2 -2
  84. package/dist/cli/chunks/{chunk-YKFURJNP.js → chunk-MTOHV22P.js} +1 -1
  85. package/dist/cli/chunks/{chunk-MOLOWMON.js → chunk-NVZHCAEB.js} +2 -2
  86. package/dist/cli/chunks/{chunk-YXR5RYRE.js → chunk-NW5FYGDE.js} +2 -2
  87. package/dist/cli/chunks/{chunk-NMBHF7ZD.js → chunk-NZRJWK5H.js} +61 -121
  88. package/dist/cli/chunks/chunk-O5NEZCTB.js +2 -0
  89. package/dist/cli/chunks/{chunk-E7UHOKKL.js → chunk-O5UGJ3OI.js} +2 -2
  90. package/dist/cli/chunks/{chunk-Q4HJRYQB.js → chunk-OK2TFTXP.js} +2 -2
  91. package/dist/cli/chunks/{chunk-FGDEM4HU.js → chunk-OKEHGXIS.js} +2 -2
  92. package/dist/cli/chunks/{chunk-C6TNYLD7.js → chunk-OKRY4LNE.js} +3 -3
  93. package/dist/cli/chunks/{chunk-3WIU2E2Y.js → chunk-OMOGD2NN.js} +2 -2
  94. package/dist/cli/chunks/{chunk-DJRWVNHK.js → chunk-ONNTJXU7.js} +2 -2
  95. package/dist/cli/chunks/chunk-OPOGZAN5.js +14 -0
  96. package/dist/cli/chunks/{chunk-OTFJCZNY.js → chunk-PG5F2VHA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-MYF7F3ZP.js → chunk-PHRMWRXA.js} +2 -2
  98. package/dist/cli/chunks/{chunk-7D2DM23U.js → chunk-PIXUX2NR.js} +2 -2
  99. package/dist/cli/chunks/{chunk-IWC6GR24.js → chunk-PLGMPG7S.js} +2 -2
  100. package/dist/cli/chunks/{chunk-T2DIMSQF.js → chunk-PPS6VN24.js} +1 -1
  101. package/dist/cli/chunks/{chunk-AUNNGKLN.js → chunk-PQAYCK2U.js} +2 -2
  102. package/dist/cli/chunks/{chunk-FU74OETU.js → chunk-PS6ISBED.js} +2 -2
  103. package/dist/cli/chunks/{chunk-JNRRDG7O.js → chunk-QPYNQSWD.js} +2 -2
  104. package/dist/cli/chunks/{chunk-MHPK4ZPK.js → chunk-QRTZ67BC.js} +2 -2
  105. package/dist/cli/chunks/{chunk-Z3TXQOS7.js → chunk-REW3W3ZW.js} +1 -1
  106. package/dist/cli/chunks/{chunk-3PZDXE5E.js → chunk-RHXYZ6AZ.js} +127 -127
  107. package/dist/cli/chunks/{chunk-IEGAEXQX.js → chunk-RZXAXWBD.js} +2 -2
  108. package/dist/cli/chunks/{chunk-4UZQSPR4.js → chunk-S4M7U6CZ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-H27XUYWZ.js → chunk-SJETAUZA.js} +1 -1
  110. package/dist/cli/chunks/{chunk-MZ7M2CDV.js → chunk-SLH7LFVY.js} +2 -2
  111. package/dist/cli/chunks/{chunk-6EP3GHED.js → chunk-SRJ5N7LD.js} +2 -2
  112. package/dist/cli/chunks/{chunk-XDYTQPJM.js → chunk-T5ADVYPH.js} +1 -1
  113. package/dist/cli/chunks/{chunk-TYZGEVP6.js → chunk-THYGFSTA.js} +12 -6
  114. package/dist/cli/chunks/{chunk-XKH4E2IQ.js → chunk-TX2DBLTL.js} +1 -1
  115. package/dist/cli/chunks/{chunk-HJDHQBMJ.js → chunk-UJMGNO6L.js} +1 -1
  116. package/dist/cli/chunks/{chunk-MCXRS2TZ.js → chunk-UUQ3SOKM.js} +1 -1
  117. package/dist/cli/chunks/{chunk-USN2JKUW.js → chunk-V5RLGPEW.js} +2 -2
  118. package/dist/cli/chunks/chunk-V6HM2BKJ.js +2 -0
  119. package/dist/cli/chunks/{chunk-R5IW5ARI.js → chunk-V7I6FTLG.js} +1 -1
  120. package/dist/cli/chunks/{chunk-2MKSEL6F.js → chunk-V7ZBPSVG.js} +1 -1
  121. package/dist/cli/chunks/{chunk-IOINZWNA.js → chunk-VJL7DNUU.js} +29 -17
  122. package/dist/cli/chunks/{chunk-JCDEMPJS.js → chunk-VKCWWR6C.js} +1 -1
  123. package/dist/cli/chunks/chunk-VKNCMGOJ.js +29 -0
  124. package/dist/cli/chunks/{chunk-GRPEDIYG.js → chunk-W2VTHUDK.js} +2 -2
  125. package/dist/cli/chunks/{chunk-SAVITYEX.js → chunk-W3JB3G7C.js} +2 -2
  126. package/dist/cli/chunks/{chunk-WTXRPYNN.js → chunk-WQ4MT74X.js} +1 -1
  127. package/dist/cli/chunks/{chunk-GY4EGQO3.js → chunk-WTNM7NA4.js} +1 -1
  128. package/dist/cli/chunks/chunk-XB3SIYGU.js +62 -0
  129. package/dist/cli/chunks/{chunk-IHRFR5SV.js → chunk-XCUNQ3FK.js} +2 -2
  130. package/dist/cli/chunks/{chunk-ITBPDVK5.js → chunk-XHQFVTFD.js} +1 -1
  131. package/dist/cli/chunks/{chunk-KJZXBZQR.js → chunk-YBUUAFKR.js} +1 -1
  132. package/dist/cli/chunks/{chunk-KR2PGNXX.js → chunk-YJV6TTCW.js} +2 -2
  133. package/dist/cli/chunks/{chunk-BQLFOJ5G.js → chunk-YUSGT2CU.js} +1 -1
  134. package/dist/cli/chunks/{chunk-5E3YCZC5.js → chunk-YUTSN5BK.js} +2 -2
  135. package/dist/cli/chunks/{chunk-DDMFTEJP.js → chunk-YVMJTBXB.js} +3 -3
  136. package/dist/cli/chunks/chunk-YVQ4PR4H.js +2 -0
  137. package/dist/cli/chunks/{chunk-RYMHYTOK.js → chunk-Z2EDNMCQ.js} +3 -3
  138. package/dist/cli/chunks/{chunk-QNSUPXUU.js → chunk-ZESMMAKZ.js} +2 -2
  139. package/dist/cli/chunks/chunk-ZIVOT3B7.js +2 -0
  140. package/dist/cli/chunks/{ci-BYCH3NPL.js → ci-NSF6OHB4.js} +2 -2
  141. package/dist/cli/chunks/{ci-output-P7P4XH6F.js → ci-output-ZPDJ42U3.js} +2 -2
  142. package/dist/cli/chunks/{circuit-breaker-VLX556ZI.js → circuit-breaker-Y2RUJDYG.js} +2 -2
  143. package/dist/cli/chunks/{claude-flow-setup-JPR425PL.js → claude-flow-setup-OH6G6KM2.js} +2 -2
  144. package/dist/cli/chunks/client-QQGRKAY7.js +2 -0
  145. package/dist/cli/chunks/{cline-installer-FOY47NSH.js → cline-installer-IHH4F27G.js} +2 -2
  146. package/dist/cli/chunks/{code-57SN4ZDY.js → code-SFAHWFTX.js} +2 -2
  147. package/dist/cli/chunks/{code-index-extractor-GT7UFRYU.js → code-index-extractor-GXECMOM2.js} +2 -2
  148. package/dist/cli/chunks/{codex-installer-JAGWONAV.js → codex-installer-UPMSAFCQ.js} +2 -2
  149. package/dist/cli/chunks/{completions-7YLHPGSV.js → completions-5TX6LDHY.js} +2 -2
  150. package/dist/cli/chunks/{complexity-analyzer-TQUF6BEI.js → complexity-analyzer-J2ZR3XZB.js} +2 -2
  151. package/dist/cli/chunks/{continuedev-installer-TICV6IGT.js → continuedev-installer-GWYZKB5A.js} +2 -2
  152. package/dist/cli/chunks/{copilot-installer-A6PDMI52.js → copilot-installer-DQZMQWI7.js} +2 -2
  153. package/dist/cli/chunks/{cost-tracker-NZPNHNV2.js → cost-tracker-V7KIGCLZ.js} +2 -2
  154. package/dist/cli/chunks/{coverage-HBEB2LKS.js → coverage-3X6LA2GZ.js} +3 -3
  155. package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +2 -0
  156. package/dist/cli/chunks/{cursor-installer-R4FM7MGN.js → cursor-installer-ENDG4JIU.js} +2 -2
  157. package/dist/cli/chunks/daemon-4XVAO7GT.js +16 -0
  158. package/dist/cli/chunks/daemon-TC65CQFK.js +10 -0
  159. package/dist/cli/chunks/{dag-attention-scheduler-2L7VCYZ3.js → dag-attention-scheduler-JOSCDRZC.js} +2 -2
  160. package/dist/cli/chunks/{detect-EEWB4IYE.js → detect-KWZX3OMK.js} +2 -2
  161. package/dist/cli/chunks/{dist-node-7RM6BB2X.js → dist-node-R4U2PJ47.js} +2 -2
  162. package/dist/cli/chunks/{domain-handler-RVGHBDUJ.js → domain-handler-BMYYZO2L.js} +2 -2
  163. package/dist/cli/chunks/{domain-transfer-M5MERQG5.js → domain-transfer-MSDBBDLC.js} +2 -2
  164. package/dist/cli/chunks/dream-OCZK42FM.js +2 -0
  165. package/dist/cli/chunks/{embed-and-insert-pattern-MS55QS73.js → embed-and-insert-pattern-MFINPOLS.js} +2 -2
  166. package/dist/cli/chunks/{eval-MBTMI7KN.js → eval-OER6UNUY.js} +2 -2
  167. package/dist/cli/chunks/{experience-capture-middleware-Z5XB7D6A.js → experience-capture-middleware-F5I77ECG.js} +3 -3
  168. package/dist/cli/chunks/{fast-paths-FSWLHI4I.js → fast-paths-P3KT5DUQ.js} +2 -2
  169. package/dist/cli/chunks/{feature-flags-QUPNH2J5.js → feature-flags-5EBWQ5WU.js} +2 -2
  170. package/dist/cli/chunks/{feature-flags-ATYOPR5D.js → feature-flags-DYFZSQLV.js} +2 -2
  171. package/dist/cli/chunks/{file-discovery-SOJJEQ2E.js → file-discovery-MOBVABSM.js} +2 -2
  172. package/dist/cli/chunks/{fleet-PWBTDWVG.js → fleet-J3R3NQNC.js} +3 -3
  173. package/dist/cli/chunks/{gnn-wrapper-2N67VQOQ.js → gnn-wrapper-QD76SULF.js} +2 -2
  174. package/dist/cli/chunks/{heartbeat-handler-5PSG2UPO.js → heartbeat-handler-AJEWTPZ4.js} +4 -4
  175. package/dist/cli/chunks/heartbeat-scheduler-EAVZR6TJ.js +2 -0
  176. package/dist/cli/chunks/hnsw-adapter-BY4XB7FB.js +2 -0
  177. package/dist/cli/chunks/hnsw-index-657CZRG7.js +2 -0
  178. package/dist/cli/chunks/{hnsw-legacy-bridge-YIXH5T4U.js → hnsw-legacy-bridge-5VRM5N7K.js} +2 -2
  179. package/dist/cli/chunks/{better-sqlite3-3U2AVWQ3.js → hnswlib-node-BWUH4OQT.js} +2 -2
  180. package/dist/cli/chunks/hooks-7PMVKQOE.js +248 -0
  181. package/dist/cli/chunks/{hybrid-router-RL47S47Z.js → hybrid-router-2K2LW45J.js} +2 -2
  182. package/dist/cli/chunks/{hypergraph-engine-XW2IHFWW.js → hypergraph-engine-2CQ735JO.js} +2 -2
  183. package/dist/cli/chunks/{hypergraph-handler-AQXKY4UF.js → hypergraph-handler-AQ53GVIW.js} +3 -3
  184. package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +2 -0
  185. package/dist/cli/chunks/{init-handler-KXYGJQI5.js → init-handler-ZOVJPAWO.js} +6 -6
  186. package/dist/cli/chunks/init-wizard-HOH577MH.js +2 -0
  187. package/dist/cli/chunks/kernel-JDYBG5GE.js +2 -0
  188. package/dist/cli/chunks/{kilocode-installer-VSULDGRO.js → kilocode-installer-GWQCNLKI.js} +2 -2
  189. package/dist/cli/chunks/{kiro-installer-SH4D2UXW.js → kiro-installer-6KVES4MO.js} +2 -2
  190. package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +2 -0
  191. package/dist/cli/chunks/learning-6XMNWXRT.js +117 -0
  192. package/dist/cli/chunks/{llm-router-YXXSQX5K.js → llm-router-GS4AZJJC.js} +4 -4
  193. package/dist/cli/chunks/{load-S52R2SLL.js → load-FEMEQNE6.js} +2 -2
  194. package/dist/cli/chunks/load-test-3MEJ43U2.js +2 -0
  195. package/dist/cli/chunks/{mcp-ZWMAJIU7.js → mcp-6V2H7EXU.js} +2 -2
  196. package/dist/cli/chunks/{memory-4YTWWDK7.js → memory-YLGPOB2H.js} +5 -5
  197. package/dist/cli/chunks/memory-backend-2A47ZRGO.js +2 -0
  198. package/dist/cli/chunks/memory-handlers-UBTBC7D2.js +2 -0
  199. package/dist/cli/chunks/{multi-model-executor-F3VEM2UF.js → multi-model-executor-SL2EKAH2.js} +2 -2
  200. package/dist/cli/chunks/{opencode-installer-Z2CUJQ6D.js → opencode-installer-ADOJVGNA.js} +2 -2
  201. package/dist/cli/chunks/{orchestrator-UPXR2XOF.js → orchestrator-O4IWW2VU.js} +37 -18
  202. package/dist/cli/chunks/{pipeline-6MEMAIXM.js → pipeline-5BD5YQNQ.js} +2 -2
  203. package/dist/cli/chunks/{platform-H72FLOM7.js → platform-HXSUOOJH.js} +2 -2
  204. package/dist/cli/chunks/{plugin-GIMQFDVR.js → plugin-HOLH5CUH.js} +2 -2
  205. package/dist/cli/chunks/{prime-radiant-advanced-wasm-DM5FR5SV.js → prime-radiant-advanced-wasm-PJTL7OLS.js} +2 -2
  206. package/dist/cli/chunks/protocol-executor-3FR7FBVM.js +2 -0
  207. package/dist/cli/chunks/{protocol-handler-YW3N333B.js → protocol-handler-K27YGLC7.js} +2 -2
  208. package/dist/cli/chunks/{prove-IJY524KK.js → prove-MHCLHQQ6.js} +2 -2
  209. package/dist/cli/chunks/{provider-manager-FNG6YR2V.js → provider-manager-3645PPXX.js} +2 -2
  210. package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +2 -0
  211. package/dist/cli/chunks/{quality-EZLAMSCP.js → quality-NDE6EDOY.js} +2 -2
  212. package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +2 -0
  213. package/dist/cli/chunks/{real-embeddings-MFRCC6GH.js → real-embeddings-VD3EVV3U.js} +2 -2
  214. package/dist/cli/chunks/{roocode-installer-H3ZIRGWU.js → roocode-installer-63Y45UUG.js} +2 -2
  215. package/dist/cli/chunks/router-23HRN2Z6.js +2 -0
  216. package/dist/cli/chunks/routing-feedback-R6A4B6ZG.js +2 -0
  217. package/dist/cli/chunks/{routing-handler-T2A7FYHW.js → routing-handler-76XISU2E.js} +2 -2
  218. package/dist/cli/chunks/{ruvector-commands-TCLWBP2M.js → ruvector-commands-AEKOZZHZ.js} +2 -2
  219. package/dist/cli/chunks/{rvf-dual-writer-BE3JCPYC.js → rvf-dual-writer-4DMUIZQF.js} +2 -2
  220. package/dist/cli/chunks/{rvf-migration-adapter-MLUX5YGR.js → rvf-migration-adapter-YUTXFOZ3.js} +2 -2
  221. package/dist/cli/chunks/{rvf-migration-coordinator-OAQXTASZ.js → rvf-migration-coordinator-XJ5N2W37.js} +2 -2
  222. package/dist/cli/chunks/rvf-native-adapter-QINEJZM7.js +2 -0
  223. package/dist/cli/chunks/safe-db-YXMCSKFH.js +2 -0
  224. package/dist/cli/chunks/schedule-XVFD27P5.js +2 -0
  225. package/dist/cli/chunks/scheduler-NWH2IDEU.js +2 -0
  226. package/dist/cli/chunks/{security-SHWJWJ4M.js → security-6YS6GQGO.js} +3 -3
  227. package/dist/cli/chunks/shared-rvf-adapter-FTZY35WI.js +2 -0
  228. package/dist/cli/chunks/{shared-rvf-dual-writer-BKSR2FFK.js → shared-rvf-dual-writer-MH2Y65HA.js} +2 -2
  229. package/dist/cli/chunks/sqlite-persistence-BR6YJF5P.js +2 -0
  230. package/dist/cli/chunks/{status-handler-QK5KMKYC.js → status-handler-57JQMPY5.js} +2 -2
  231. package/dist/cli/chunks/{structural-health-3BRNCAYQ.js → structural-health-34D5VWRD.js} +2 -2
  232. package/dist/cli/chunks/sync-HJD2US5P.js +2 -0
  233. package/dist/cli/chunks/sync-TTQ6ZB5D.js +17 -0
  234. package/dist/cli/chunks/{task-handler-VH2CLUIA.js → task-handler-4RF57637.js} +2 -2
  235. package/dist/cli/chunks/{task-handlers-BUZNV2VX.js → task-handlers-BRSK7HDE.js} +3 -3
  236. package/dist/cli/chunks/{test-K24JQQZ2.js → test-GMUW2VR3.js} +4 -4
  237. package/dist/cli/chunks/{test-scheduling-MHXRV5VI.js → test-scheduling-7LF24IFV.js} +3 -3
  238. package/dist/cli/chunks/{token-bootstrap-3NZDLG52.js → token-bootstrap-VYT4RTHU.js} +2 -2
  239. package/dist/cli/chunks/{token-usage-C4BGA2O7.js → token-usage-NFNCPQGW.js} +2 -2
  240. package/dist/cli/chunks/{transformers-ZIIFB2V4.js → transformers-GGD5GIEY.js} +2 -2
  241. package/dist/cli/chunks/{tree-sitter-wasm-parser-GES2AV7A.js → tree-sitter-wasm-parser-GKYG6NKT.js} +2 -2
  242. package/dist/cli/chunks/{types-L3MO5VNC.js → types-WJ3ZTRD5.js} +2 -2
  243. package/dist/cli/chunks/unified-memory-AT3Z4CY7.js +2 -0
  244. package/dist/cli/chunks/unified-memory-hnsw-6FOIGINN.js +2 -0
  245. package/dist/cli/chunks/unified-persistence-TCJB7MQS.js +2 -0
  246. package/dist/cli/chunks/{upgrade-EKJYS5S5.js → upgrade-IMBT4F6K.js} +2 -2
  247. package/dist/cli/chunks/{validate-WYWWB5PQ.js → validate-76OVF45Z.js} +2 -2
  248. package/dist/cli/chunks/{validate-swarm-SBSWKJ3H.js → validate-swarm-HH2ZYWXA.js} +2 -2
  249. package/dist/cli/chunks/{vibium-VEMTLNFV.js → vibium-74WQNDBX.js} +2 -2
  250. package/dist/cli/chunks/visual-security-IBAUX2K5.js +2 -0
  251. package/dist/cli/chunks/{web-tree-sitter-STW2WR2J.js → web-tree-sitter-W6RGE4SL.js} +2 -2
  252. package/dist/cli/chunks/{windsurf-installer-6ZXMJASZ.js → windsurf-installer-7DMSFCA2.js} +2 -2
  253. package/dist/cli/chunks/{witness-chain-PTULB4MR.js → witness-chain-BLZ4ZKAD.js} +2 -2
  254. package/dist/cli/chunks/witness-chain-GNNF23XU.js +2 -0
  255. package/dist/cli/chunks/{workflow-TEBAAHNR.js → workflow-RNSDKRZ4.js} +4 -4
  256. package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +2 -0
  257. package/dist/cli/chunks/{wrappers-DVMVRKXK.js → wrappers-J7RXMIOY.js} +2 -2
  258. package/dist/cli/commands/hooks-handlers/editing-hooks.js +9 -3
  259. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +16 -24
  260. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +1 -1
  261. package/dist/cli/commands/hooks-handlers/hooks-shared.js +8 -1
  262. package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -3
  263. package/dist/cli/commands/hooks-handlers/task-hooks.js +37 -46
  264. package/dist/cli/commands/learning.js +194 -0
  265. package/dist/domains/learning-optimization/services/learning-coordinator.js +37 -17
  266. package/dist/init/phases/10-workers.js +20 -1
  267. package/dist/kernel/hybrid-backend.d.ts +17 -7
  268. package/dist/kernel/hybrid-backend.js +24 -10
  269. package/dist/kernel/interfaces.d.ts +33 -6
  270. package/dist/kernel/kernel.d.ts +1 -0
  271. package/dist/kernel/kernel.js +57 -0
  272. package/dist/kernel/memory-backend.d.ts +5 -5
  273. package/dist/kernel/memory-backend.js +14 -7
  274. package/dist/kernel/unified-memory-schemas.d.ts +1 -1
  275. package/dist/kernel/unified-memory-schemas.js +7 -1
  276. package/dist/learning/agent-routing.d.ts +134 -1
  277. package/dist/learning/agent-routing.js +185 -2
  278. package/dist/learning/dream/dream-insights-pruner.d.ts +49 -0
  279. package/dist/learning/dream/dream-insights-pruner.js +53 -0
  280. package/dist/learning/dream/dream-scheduler.js +17 -0
  281. package/dist/learning/loop-health.d.ts +84 -0
  282. package/dist/learning/loop-health.js +91 -0
  283. package/dist/learning/pattern-usage-recorder.d.ts +58 -0
  284. package/dist/learning/pattern-usage-recorder.js +72 -0
  285. package/dist/learning/qe-reasoning-bank-types.d.ts +11 -0
  286. package/dist/learning/qe-reasoning-bank.d.ts +11 -0
  287. package/dist/learning/qe-reasoning-bank.js +86 -3
  288. package/dist/learning/routing-topology-gate.d.ts +40 -0
  289. package/dist/learning/routing-topology-gate.js +55 -0
  290. package/dist/learning/sqlite-persistence.d.ts +6 -1
  291. package/dist/learning/sqlite-persistence.js +14 -20
  292. package/dist/mcp/bundle.js +3837 -3811
  293. package/dist/mcp/handlers/core-handlers.js +21 -0
  294. package/dist/routing/routing-feedback.js +7 -3
  295. package/dist/routing/routing-outcomes-migration.d.ts +31 -0
  296. package/dist/routing/routing-outcomes-migration.js +60 -0
  297. package/dist/workers/interfaces.d.ts +26 -0
  298. package/dist/workers/worker-manager.d.ts +15 -12
  299. package/dist/workers/worker-manager.js +11 -0
  300. package/dist/workers/workers/learning-consolidation.d.ts +28 -0
  301. package/dist/workers/workers/learning-consolidation.js +302 -71
  302. package/package.json +3 -1
  303. package/dist/cli/chunks/adapter-HV42JOZD.js +0 -2
  304. package/dist/cli/chunks/aqe-learning-engine-GL22PE2V.js +0 -2
  305. package/dist/cli/chunks/base-4KQ2FGUX.js +0 -2
  306. package/dist/cli/chunks/browser-workflow-CTE7BDM4.js +0 -2
  307. package/dist/cli/chunks/chunk-3NGNSKL3.js +0 -14
  308. package/dist/cli/chunks/chunk-6HSFZ6SL.js +0 -180
  309. package/dist/cli/chunks/chunk-7Z3GBQNV.js +0 -2
  310. package/dist/cli/chunks/chunk-AQJ6XS34.js +0 -2
  311. package/dist/cli/chunks/chunk-H2IMXQCJ.js +0 -2
  312. package/dist/cli/chunks/chunk-SPCANEJY.js +0 -95
  313. package/dist/cli/chunks/client-FRVNMXQO.js +0 -2
  314. package/dist/cli/chunks/cross-domain-router-BVCPAWG2.js +0 -2
  315. package/dist/cli/chunks/daemon-PHIZPZIE.js +0 -19
  316. package/dist/cli/chunks/dream-77ODIFIF.js +0 -2
  317. package/dist/cli/chunks/hnsw-adapter-CQGQS3V7.js +0 -2
  318. package/dist/cli/chunks/hnsw-index-2ACF6FOJ.js +0 -2
  319. package/dist/cli/chunks/hooks-YROFO6PE.js +0 -259
  320. package/dist/cli/chunks/impact-analyzer-LWEGK23B.js +0 -2
  321. package/dist/cli/chunks/init-wizard-7BS3QMWR.js +0 -2
  322. package/dist/cli/chunks/kernel-TX67WXSI.js +0 -2
  323. package/dist/cli/chunks/knowledge-graph-TDSP2UE2.js +0 -2
  324. package/dist/cli/chunks/learning-RRWV3SEL.js +0 -107
  325. package/dist/cli/chunks/load-test-GEBBBUMV.js +0 -2
  326. package/dist/cli/chunks/memory-backend-WQS2MLW2.js +0 -2
  327. package/dist/cli/chunks/memory-handlers-RTY5MBA5.js +0 -2
  328. package/dist/cli/chunks/protocol-executor-DT7XHMLL.js +0 -2
  329. package/dist/cli/chunks/qe-reasoning-bank-LDNETZVA.js +0 -2
  330. package/dist/cli/chunks/queen-coordinator-AF7HCQSM.js +0 -2
  331. package/dist/cli/chunks/router-OWQ5EI72.js +0 -2
  332. package/dist/cli/chunks/routing-feedback-B43DEQMK.js +0 -2
  333. package/dist/cli/chunks/rvf-native-adapter-XBJDXHNI.js +0 -2
  334. package/dist/cli/chunks/safe-db-RT3LEDUG.js +0 -2
  335. package/dist/cli/chunks/schedule-EHUDCKS2.js +0 -2
  336. package/dist/cli/chunks/scheduler-GEGZ4J3C.js +0 -2
  337. package/dist/cli/chunks/shared-rvf-adapter-LNBUNRAM.js +0 -2
  338. package/dist/cli/chunks/sqlite-persistence-3DGRJH3K.js +0 -2
  339. package/dist/cli/chunks/sync-5CDYOT3H.js +0 -23
  340. package/dist/cli/chunks/unified-memory-ZSBX4LYU.js +0 -2
  341. package/dist/cli/chunks/unified-memory-hnsw-Y6EKAMRP.js +0 -2
  342. package/dist/cli/chunks/unified-persistence-2PDVU2U5.js +0 -2
  343. package/dist/cli/chunks/visual-security-RHMFLKVQ.js +0 -2
  344. package/dist/cli/chunks/witness-chain-QO237QOF.js +0 -2
  345. package/dist/cli/chunks/workflow-orchestrator-RHM5MIGE.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{a as V}from"./chunk-VRP4GB4Y.js";import{a as k,b as q,c as W,d as C}from"./chunk-R5IW5ARI.js";import{b as x,f as z,i as j}from"./chunk-QHKK2H4H.js";import{d as G}from"./chunk-IOINZWNA.js";import{g as P}from"./chunk-QTS2DS42.js";import{a as M}from"./chunk-7Z3GBQNV.js";import{c as E}from"./chunk-3WIU2E2Y.js";import{b as T,c as S}from"./chunk-LDGNVPBZ.js";import{a as f,b as L,c as F}from"./chunk-RNO6CE7I.js";import{S as Y,b as B}from"./chunk-UYLHIGNC.js";M();F();var D={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var w=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as H}from"./chunk-6SYP7QX6.js";import{a as C,b as D,c as U,d as _}from"./chunk-V7I6FTLG.js";import{c as X,d as K,e as Y,f as J}from"./chunk-ZIVOT3B7.js";import{b as k,f as j,i as G}from"./chunk-MERMCKPG.js";import{g as w}from"./chunk-FWEYOD3S.js";import{e as $}from"./chunk-VJL7DNUU.js";import{k as z,o as me}from"./chunk-THYGFSTA.js";import{a as B}from"./chunk-YVQ4PR4H.js";import{c as T}from"./chunk-OMOGD2NN.js";import{b as q,c as x}from"./chunk-EFEJLZDN.js";import{a as f,b as L,c as V}from"./chunk-5WR42V5O.js";import{S as de,b as W}from"./chunk-33PGBYTC.js";B();V();var I={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var A=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -278,7 +278,7 @@ On promotion:
278
278
  - Move from short-term to long-term tier
279
279
  - Boost confidence by 10%
280
280
  - Enable for cross-domain transfer to related domains
281
- - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];var R={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};function I(a,e,r,t,i=R,s){let o=[];for(let[n,c]of Object.entries(i)){let p=0,l=[],g=a.filter(m=>c.domains.includes(m)).length,d=g>0?g/a.length*.4:0;if(p+=d*t.similarity,d>0&&l.push(`Domain match: ${(d*100).toFixed(0)}%`),e&&e.length>0){let m=e.filter(A=>c.capabilities.some(v=>v.toLowerCase().includes(A.toLowerCase()))).length,y=m>0?m/e.length*.3:0;p+=y*t.capabilities,y>0&&l.push(`Capability match: ${(y*100).toFixed(0)}%`)}else p+=.15*t.capabilities;if(p+=c.performanceScore*.3*t.performance,l.push(`Performance score: ${(c.performanceScore*100).toFixed(0)}%`),s&&c.languages&&c.languages.length>0){let m=t.language??1,y=s.toLowerCase();if(c.languages.some(v=>v.toLowerCase()===y)){let v=.15*m;p+=v,l.push(`Language match: ${s}`)}}let h=r.get(n)||0;if(h>0){let m=Math.min(.1,h*.02);p+=m,l.push(`Pattern matches: ${h}`)}o.push({agent:n,score:p,reasoning:l})}return o.sort((n,c)=>c.score-n.score),o}var _={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function U(a,e){if(a.length===e)return a;if(a.length>e){let r=a.length/e,t=new Array(e).fill(0);for(let i=0;i<e;i++){let s=Math.floor(i*r),o=Math.floor((i+1)*r),n=0;for(let c=s;c<o;c++)n+=a[c];t[i]=n/(o-s)}return N(t)}else{let r=new Array(e).fill(0),t=(a.length-1)/(e-1);for(let i=0;i<e;i++){let s=i*t,o=Math.floor(s),n=Math.min(o+1,a.length-1),c=s-o;r[i]=a[o]*(1-c)+a[n]*c}return N(r)}}function $(a,e){let r=new Array(e).fill(0),t=a.toLowerCase().trim();for(let i=0;i<3;i++)for(let s=0;s<t.length;s++){let o=t.charCodeAt(s),n=o*(s+1)*(i+1)%e;r[n]+=Math.sin(o*(i+1))/(s+1)}return N(r)}function N(a){let e=Math.sqrt(a.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<a.length;r++)a[r]/=e;return a}M();F();Y();var b=E.create("PatternPromotion");async function X(a,e){let r=z(a);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),o=[...t.success?t.value.map(c=>c.pattern):[],a].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),n=await e.coherenceService.checkCoherence(o);if(n.energy>=e.coherenceThreshold){let c={patternId:a.id,patternName:a.name,reason:"coherence_violation",energy:n.energy,existingPatternConflicts:n.contradictions?.map(p=>p.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${a.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),b.info("Pattern promotion blocked due to coherence violation",{name:a.name,energy:n.energy}),!1}}return!0}async function H(a,e){let r=await e.patternStore.promote(a);if(r.success){try{e.getSqliteStore().promotePattern(a)}catch(t){b.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(B().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let i=new Q(t),s=await e.getPattern(a);if(s){let o=await e.searchPatterns("",{domain:s.qeDomain,tier:"long-term",limit:20});if(o.success)for(let{pattern:n}of o.value)n.id!==a&&i.recordCoOccurrence(a,n.id)}}}catch(t){b.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(a);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(a,t.embedding)}catch(t){b.warn("RVF dual-write on promote failed (non-fatal)",{patternId:a,error:f(t)})}P().then(t=>t.append("PATTERN_PROMOTE",{patternId:a},"reasoning-bank")).catch(t=>{b.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),b.info("Promoted pattern to long-term",{patternId:a}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${a}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:a,newTier:"long-term"}})}else b.error("Failed to promote pattern",r.error,{patternId:a})}async function K(a){let{signal:e}=a;e?.throwIfAborted();let r=await a.patternStore.getStats(),t=0,i=0;for(let[s,o]of Object.entries(_)){e?.throwIfAborted();let n=s,c=r.byDomain[n]||0;if(c===0)continue;let p=await a.searchPatterns("",{domain:n,limit:50});if(p.success)for(let l of o){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){i++;continue}for(let{pattern:d}of p.value){e?.throwIfAborted();let h=await a.searchPatterns(d.name,{domain:l,limit:1});if(h.success&&h.value.length>0&&h.value[0].score>.8){i++;continue}let m=Math.max(.3,(d.confidence||.5)*.8);(await a.storePattern({patternType:d.patternType,qeDomain:l,name:`${d.name} (from ${n})`,description:`${d.description} [Transferred from ${n} domain]`,template:d.template,context:{...d.context,relatedDomains:[n,l],tags:[...d.context.tags,"cross-domain-transfer",`source:${n}`]},confidence:m})).success?t++:i++}}}return b.info("Cross-domain transfer complete",{transferred:t,skipped:i}),{transferred:t,skipped:i}}var J=`
281
+ - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as Z}from"crypto";var R={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},ge=.4,fe=20;function he(n){return 1/(1+Math.exp(-n))}function ye(n,e){if(!e||e.visits===0)return{score:n,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/fe,1)*ge,t=he(e.qValue);return{score:n*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function ee(n){let e=n.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,i=n.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*i,0),1),baseEpsilon:t,safetyMultiplier:i}}function te(n,e){if(e<=0||n.length<2)return;let r=Math.round(e*1e6);if(r<=0||Z(0,1e6)>=r)return;let t=Math.min(4,n.length),i=Z(1,t),o=n[i];n[i]=n[0],n[0]=o,n[0].exploration=!0,n[0].reasoning=[...n[0].reasoning,"(exploration)"]}function re(n){let e=n.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function ne(n){return`${n.taskType}|${n.priority??"normal"}|${n.domain??"any"}|${n.complexityBucket}`}function ie(n){return Math.max(0,Math.min(10,Math.round(Math.min(n.length/200,1)*10)))}function N(n,e,r,t,i=R,o,s){let a=[];for(let[c,u]of Object.entries(i)){let l=0,d=[],m=n.filter(h=>u.domains.includes(h)).length,y=m>0?m/n.length*.4:0;if(l+=y*t.similarity,y>0&&d.push(`Domain match: ${(y*100).toFixed(0)}%`),e&&e.length>0){let h=e.filter(v=>u.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,p=h>0?h/e.length*.3:0;l+=p*t.capabilities,p>0&&d.push(`Capability match: ${(p*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=u.performanceScore*.3*t.performance,d.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),o&&u.languages&&u.languages.length>0){let h=t.language??1,p=o.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===p)){let P=.15*h;l+=P,d.push(`Language match: ${o}`)}}let b=r.get(c)||0;if(b>0){let h=Math.min(.1,b*.02);l+=h,d.push(`Pattern matches: ${b}`)}let E=l;if(s){let h=s(c),p=ye(E,h);l=p.score,p.qWeight>0&&d.push(`Q-bonus (w=${p.qWeight.toFixed(2)}, v=${p.qVisits})`),a.push({agent:c,score:l,reasoning:d,staticScore:E,qWeight:p.qWeight,qValue:p.qValue,qVisits:p.qVisits})}else a.push({agent:c,score:l,reasoning:d,staticScore:E})}return a.sort((c,u)=>u.score-c.score),a}var Q={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function ae(){try{return!J()||!Y()||X().isEmpty()?!1:K().isCritical()}catch{return!1}}me();function oe(n,e){if(n.length===e)return n;if(n.length>e){let r=n.length/e,t=new Array(e).fill(0);for(let i=0;i<e;i++){let o=Math.floor(i*r),s=Math.floor((i+1)*r),a=0;for(let c=o;c<s;c++)a+=n[c];t[i]=a/(s-o)}return M(t)}else{let r=new Array(e).fill(0),t=(n.length-1)/(e-1);for(let i=0;i<e;i++){let o=i*t,s=Math.floor(o),a=Math.min(s+1,n.length-1),c=o-s;r[i]=n[s]*(1-c)+n[a]*c}return M(r)}}function se(n,e){let r=new Array(e).fill(0),t=n.toLowerCase().trim();for(let i=0;i<3;i++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(i+1)%e;r[a]+=Math.sin(s*(i+1))/(o+1)}return M(r)}function M(n){let e=Math.sqrt(n.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<n.length;r++)n[r]/=e;return n}B();V();de();var S=T.create("PatternPromotion");async function ce(n,e){let r=j(n);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],n].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:n.id,patternName:n.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${n.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),S.info("Pattern promotion blocked due to coherence violation",{name:n.name,energy:a.energy}),!1}}return!0}async function le(n,e){let r=await e.patternStore.promote(n);if(r.success){try{e.getSqliteStore().promotePattern(n)}catch(t){S.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(W().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let i=new O(t),o=await e.getPattern(n);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==n&&i.recordCoOccurrence(n,a.id)}}}catch(t){S.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(n);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(n,t.embedding)}catch(t){S.warn("RVF dual-write on promote failed (non-fatal)",{patternId:n,error:f(t)})}w().then(t=>t.append("PATTERN_PROMOTE",{patternId:n},"reasoning-bank")).catch(t=>{S.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),S.info("Promoted pattern to long-term",{patternId:n}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${n}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:n,newTier:"long-term"}})}else S.error("Failed to promote pattern",r.error,{patternId:n})}async function ue(n){let{signal:e}=n;e?.throwIfAborted();let r=await n.patternStore.getStats(),t=0,i=0;for(let[o,s]of Object.entries(Q)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let u=await n.searchPatterns("",{domain:a,limit:50});if(u.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){i++;continue}for(let{pattern:m}of u.value){e?.throwIfAborted();let y=await n.searchPatterns(m.name,{domain:l,limit:1});if(y.success&&y.value.length>0&&y.value[0].score>.8){i++;continue}let b=Math.max(.3,(m.confidence||.5)*.8);(await n.storePattern({patternType:m.patternType,qeDomain:l,name:`${m.name} (from ${a})`,description:`${m.description} [Transferred from ${a} domain]`,template:m.template,context:{...m.context,relatedDomains:[a,l],tags:[...m.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:b})).success?t++:i++}}}return S.info("Cross-domain transfer complete",{transferred:t,skipped:i}),{transferred:t,skipped:i}}var be=`
282
282
  CREATE TABLE IF NOT EXISTS pattern_citations (
283
283
  source_pattern_id TEXT NOT NULL,
284
284
  target_pattern_id TEXT NOT NULL,
@@ -289,7 +289,7 @@ On promotion:
289
289
  );
290
290
  CREATE INDEX IF NOT EXISTS idx_citations_source ON pattern_citations(source_pattern_id);
291
291
  CREATE INDEX IF NOT EXISTS idx_citations_target ON pattern_citations(target_pattern_id);
292
- `,Q=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(J),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,i]=e<r?[e,r]:[r,e];this.db.prepare(`
292
+ `,O=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(be),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,i]=e<r?[e,r]:[r,e];this.db.prepare(`
293
293
  INSERT INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
294
294
  VALUES (?, ?, 1.0, 'co-occurrence')
295
295
  ON CONFLICT(source_pattern_id, target_pattern_id)
@@ -299,16 +299,22 @@ On promotion:
299
299
  VALUES (?, ?, 2.0, 'derivation')
300
300
  ON CONFLICT(source_pattern_id, target_pattern_id)
301
301
  DO UPDATE SET weight = MAX(weight, 2.0), relationship = 'derivation'
302
- `).run(e,r)}buildGraph(){this.ensureSchema();let e=this.db.prepare("SELECT source_pattern_id, target_pattern_id, weight, relationship FROM pattern_citations").all(),r=new Set;for(let o of e)r.add(o.source_pattern_id),r.add(o.target_pattern_id);let t=Array.from(r),i=new Map;t.forEach((o,n)=>i.set(o,n));let s=[];for(let o of e){let n=i.get(o.source_pattern_id),c=i.get(o.target_pattern_id);s.push([n,c,o.weight]),o.relationship==="co-occurrence"&&s.push([c,n,o.weight])}return{nodes:t,edges:s}}bootstrapFromExistingData(){this.ensureSchema();let e=0,r=this.db.prepare(`
302
+ `).run(e,r)}buildGraph(){this.ensureSchema();let e=this.db.prepare("SELECT source_pattern_id, target_pattern_id, weight, relationship FROM pattern_citations").all(),r=new Set;for(let s of e)r.add(s.source_pattern_id),r.add(s.target_pattern_id);let t=Array.from(r),i=new Map;t.forEach((s,a)=>i.set(s,a));let o=[];for(let s of e){let a=i.get(s.source_pattern_id),c=i.get(s.target_pattern_id);o.push([a,c,s.weight]),s.relationship==="co-occurrence"&&o.push([c,a,s.weight])}return{nodes:t,edges:o}}bootstrapFromExistingData(){this.ensureSchema();let e=0,r=this.db.prepare(`
303
303
  SELECT id, qe_domain FROM qe_patterns WHERE qe_domain IS NOT NULL ORDER BY qe_domain
304
- `).all(),t=new Map;for(let p of r){let l=t.get(p.qe_domain)??[];l.push(p.id),t.set(p.qe_domain,l)}let i=this.db.prepare(`
304
+ `).all(),t=new Map;for(let u of r){let l=t.get(u.qe_domain)??[];l.push(u.id),t.set(u.qe_domain,l)}let i=this.db.prepare(`
305
305
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
306
306
  VALUES (?, ?, 1.0, 'co-occurrence')
307
- `),s=this.db.transaction(p=>{for(let[l,g]of p)i.run(l,g).changes>0&&e++}),o=[];for(let[,p]of t){let l=p.slice(0,50);for(let g=0;g<l.length;g++)for(let d=g+1;d<l.length;d++){let[h,m]=l[g]<l[d]?[l[g],l[d]]:[l[d],l[g]];o.push([h,m])}}s(o);let n=this.db.prepare(`
307
+ `),o=this.db.transaction(u=>{for(let[l,d]of u)i.run(l,d).changes>0&&e++}),s=[];for(let[,u]of t){let l=u.slice(0,50);for(let d=0;d<l.length;d++)for(let m=d+1;m<l.length;m++){let[y,b]=l[d]<l[m]?[l[d],l[m]]:[l[m],l[d]];s.push([y,b])}}o(s);let a=this.db.prepare(`
308
308
  SELECT source_pattern_id, target_pattern_id, relationship_type
309
309
  FROM pattern_relationships
310
310
  WHERE relationship_type IN ('merged', 'derived', 'superseded')
311
311
  `).all(),c=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let p of n)c.run(p.source_pattern_id,p.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var u=E.create("QEReasoningBank"),O=class{constructor(e,r,t={},i){this.memory=e;this.eventBus=r;this.coherenceService=i;this.config={...D,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=V(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=G(),this.sqliteStore.initialize().catch(e=>{u.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){u.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),await this.loadPretrainedPatterns(r),r?.throwIfAborted(),this.initialized=!0;try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let s=await this.patternStore.getStats();u.info("Cross-domain transfer already complete",{totalPatterns:s.totalPatterns})}}catch(t){if(r?.aborted)throw t;u.warn("Cross-domain seeding failed (non-fatal)",{error:t})}u.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){u.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let s=this.getSqliteStore().getAllEmbeddings().filter(({embedding:o})=>o&&o.length>0).map(({patternId:o,embedding:n})=>({id:o,vector:n instanceof Float32Array?n:new Float32Array(n)}));if(s.length>0){let{accepted:o,rejected:n}=t.ingest(s);u.info("Backfilled RVF from SQLite",{count:s.length,accepted:o}),n>0&&u.warn("RVF backfill partially rejected",{accepted:o,rejected:n})}}catch(i){u.warn("RVF backfill failed (non-fatal)",{error:f(i)})}return}for(let t of w){e?.throwIfAborted();try{await this.storePattern(t)}catch(i){if(e?.aborted)throw i;u.warn("Failed to load pattern",{name:t.name,error:i})}}u.info("Loaded foundational patterns",{count:w.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),K({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return S(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(P().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{u.warn("Witness chain PATTERN_CREATE failed",{error:f(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){u.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:f(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,i=!0;return typeof e=="string"&&(e.trim()===""?(i=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:i})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return T(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){u.warn("SQLite pattern usage persist failed",{error:f(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,P().then(s=>s.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(s=>{u.warn("Witness chain PATTERN_UPDATE failed",{error:f(s)})});let t=await this.getPattern(e.patternId),i=this.getPromotionDeps();t&&await X(t,i)&&(await H(e.patternId,i),u.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return S(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:x(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),i=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),s=i.success?i.value.map(d=>d.pattern):[],o=new Map;for(let[d,h]of Object.entries(R)){let m=s.filter(y=>h.domains.includes(y.qeDomain)).length;m>0&&o.set(d,m)}let n=I(r,e.capabilities,o,this.config.routingWeights),c=n[0],p=n.slice(1,4),l=[];if(this.config.enableGuidance&&r.length>0){let d=q(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});l.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=c.score;let g={recommendedAgent:c.agent,confidence:c.score,alternatives:p.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:s,guidance:l,reasoning:c.reasoning.join("; ")};return T(g)}catch(r){return S(L(r))}}getGuidance(e,r){return k(e)}generateContext(e,r){return C(e,r||{})}checkAntiPatterns(e,r){return W(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-MFRCC6GH.js"),t=await r(e);return t.length!==this.config.embeddingDimension?U(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&u.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return $(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let n of j)r[n]=e.byDomain[n]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,s=this.stats.learningOutcomes,o=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||s===0)try{let n=this.getSqliteStore().getAggregateOutcomeStats();t===0&&n.routingRequests>0&&(t=n.routingRequests,i=n.avgRoutingConfidence),s===0&&n.learningOutcomes>0&&(s=n.learningOutcomes,o=n.learningOutcomes>0?n.successfulOutcomes/n.learningOutcomes:n.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:s,patternSuccessRate:o,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Ge(a,e,r,t){return new O(a,e,r,t)}export{D as a,w as b,R as c,I as d,_ as e,O as f,Ge as g};
314
+ `);for(let u of a)c.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var g=T.create("QEReasoningBank"),F=class{constructor(e,r,t={},i){this.memory=e;this.eventBus=r;this.coherenceService=i;this.config={...I,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=H(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=$(),this.sqliteStore.initialize().catch(e=>{g.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){g.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),await this.loadPretrainedPatterns(r),r?.throwIfAborted(),this.initialized=!0;try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();g.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;g.warn("Cross-domain seeding failed (non-fatal)",{error:t})}g.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){g.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let o=this.getSqliteStore().getAllEmbeddings().filter(({embedding:s})=>s&&s.length>0).map(({patternId:s,embedding:a})=>({id:s,vector:a instanceof Float32Array?a:new Float32Array(a)}));if(o.length>0){let{accepted:s,rejected:a}=t.ingest(o);g.info("Backfilled RVF from SQLite",{count:o.length,accepted:s}),a>0&&g.warn("RVF backfill partially rejected",{accepted:s,rejected:a})}}catch(i){g.warn("RVF backfill failed (non-fatal)",{error:f(i)})}return}for(let t of A){e?.throwIfAborted();try{await this.storePattern(t)}catch(i){if(e?.aborted)throw i;g.warn("Failed to load pattern",{name:t.name,error:i})}}g.info("Loaded foundational patterns",{count:A.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),ue({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return x(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(w().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{g.warn("Witness chain PATTERN_CREATE failed",{error:f(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){g.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:f(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,i=!0;return typeof e=="string"&&(e.trim()===""?(i=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:i})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return q(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){g.warn("SQLite pattern usage persist failed",{error:f(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,w().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{g.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let t=await this.getPattern(e.patternId),i=this.getPromotionDeps();t&&await ce(t,i)&&(await le(e.patternId,i),g.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return x(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:k(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),i=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),o=i.success?i.value.map(p=>p.pattern):[],s=new Map;for(let[p,v]of Object.entries(R)){let P=o.filter(pe=>v.domains.includes(pe.qeDomain)).length;P>0&&s.set(p,P)}let a=ne({taskType:re(e.task),priority:"normal",domain:r[0],complexityBucket:ie(e.task)}),c=this.buildQValueLookup(a),u=N(r,e.capabilities,s,this.config.routingWeights,R,e.context?.language,c),l=1;try{let p=ae(),v=ee({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:p});l=v.safetyMultiplier,te(u,v.epsilon)}catch{}let d=u[0],m=u.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let p=D(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...p.slice(0,5))}this.stats.totalRoutingConfidence+=d.score;let b=u.reduce((p,v)=>p+(v.qWeight??0),0),E=u.length>0?b/u.length:0,h={recommendedAgent:d.agent,confidence:d.score,alternatives:m.map(p=>({agent:p.agent,score:p.score})),domains:r,patterns:o,guidance:y,reasoning:d.reasoning.join("; "),exploration:d.exploration===!0,criticality:l,qWeight:E};return q(h)}catch(r){return x(L(r))}}buildQValueLookup(e){try{let r=z();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
315
+ SELECT q_value, visits FROM rl_q_values
316
+ WHERE algorithm = 'q-learning'
317
+ AND agent_id = 'aqe-hook-router'
318
+ AND state_key = ?
319
+ AND action_key = ?
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return C(e)}generateContext(e,r){return _(e,r||{})}checkAntiPatterns(e,r){return U(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-VD3EVV3U.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of G)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function ft(n,e,r,t){return new F(n,e,r,t)}export{I as a,A as b,R as c,re as d,N as e,Q as f,F as g,ft as h};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var s=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],c="anthropic/claude-sonnet-4.6",u="claude-sonnet-4-6";function o(n){return n.includes("claude-opus-4-7")||n.includes("claude-opus-4.7")}function i(n,e=process.env){return e.AQE_CYBER_VERIFIED==="true"?!1:s.includes(n)}function a(n,e,r,t=process.env){return!i(n,t)||!o(e)?e:r}export{c as a,u as b,o as c,i as d,a as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{i as c}from"./chunk-QHKK2H4H.js";import{a as p}from"./chunk-7Z3GBQNV.js";import{c as m}from"./chunk-3WIU2E2Y.js";import{b as g,d as E}from"./chunk-Q4HJRYQB.js";import{a as l,b as _}from"./chunk-CNNVL5W4.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{i as c}from"./chunk-MERMCKPG.js";import{b as g,d as E}from"./chunk-OK2TFTXP.js";import{a as p}from"./chunk-YVQ4PR4H.js";import{c as m}from"./chunk-OMOGD2NN.js";import{a as l,b as _}from"./chunk-4VAZSCTZ.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{b as c,d as p}from"./chunk-Q4HJRYQB.js";import{a as f}from"./chunk-ITBPDVK5.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
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.9.32");process.exit(0)}
2
+ import{b as c,d as p}from"./chunk-OK2TFTXP.js";import{a as f}from"./chunk-XHQFVTFD.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
3
3
  `)}export{S as a,b,x as c,P as d};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{a as ne}from"./chunk-2GBBZLXT.js";import{d as B,e as W,f as re,g as j}from"./chunk-QHKK2H4H.js";import{c as et,d as tt}from"./chunk-3AICELMQ.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-5DJAJPBG.js";import{b as v,c as w}from"./chunk-LDGNVPBZ.js";import{a as y,b as Ae,c as Te}from"./chunk-RNO6CE7I.js";import{i as C}from"./chunk-GY4EGQO3.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-UYLHIGNC.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-ITBPDVK5.js";var V=J(S=>{var ut=S&&S.__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(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(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)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(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}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function pt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=pt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(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 gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(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=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._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=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._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}}},yt={add:function(n,e,t){return b.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 I(n,t),t.value}m.getValueByPointer=Y;function I(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 m.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 m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="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&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.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);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.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=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.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 m.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 m.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 m.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")&&b.hasUndefined(n.value))throw new m.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 m.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 m.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=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._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 m.JsonPatchError)return i;throw i}}m.validate=qe;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}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(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(){de(r),clearTimeout(r.next),Rt(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 St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.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];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();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){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=y(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-3DGRJH3K.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: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(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}:`,y(r))}return v(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?v(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 h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(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,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.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 h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(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),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(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>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(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}}};De();Te();F();function nt(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 it(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=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(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 ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(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 ot(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 ct(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+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,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=Ne(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=at(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 ot([r,i])}similarity(e,t){return lt(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}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,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=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(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+=ae[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 He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
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.9.32");process.exit(0)}
2
+ import{a as ne}from"./chunk-DFY7F4TE.js";import{d as B,e as W,f as re,g as j}from"./chunk-MERMCKPG.js";import{c as et,d as tt}from"./chunk-FIONYUVH.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-FV2MU6CY.js";import{b as v,c as w}from"./chunk-EFEJLZDN.js";import{a as y,b as Ae,c as Te}from"./chunk-5WR42V5O.js";import{i as C}from"./chunk-WTNM7NA4.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-33PGBYTC.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-XHQFVTFD.js";var V=J(S=>{var ut=S&&S.__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(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(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)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(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}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function pt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=pt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(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 gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(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=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._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=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._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}}},yt={add:function(n,e,t){return b.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 I(n,t),t.value}m.getValueByPointer=Y;function I(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 m.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 m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="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&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.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);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.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=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.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 m.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 m.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 m.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")&&b.hasUndefined(n.value))throw new m.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 m.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 m.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=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._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 m.JsonPatchError)return i;throw i}}m.validate=qe;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}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(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(){de(r),clearTimeout(r.next),Rt(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 St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.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];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();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){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=y(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-BR6YJF5P.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: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(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}:`,y(r))}return v(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?v(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 h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(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,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.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 h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(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),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(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>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(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}}};De();Te();F();function nt(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 it(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=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(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 ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(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 ot(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 ct(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+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,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=Ne(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=at(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 ot([r,i])}similarity(e,t){return lt(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}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,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=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(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+=ae[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 He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{a as ne}from"./chunk-2GBBZLXT.js";import{d as B,e as W,f as re,g as j}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...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(h=>h.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(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,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 Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,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 We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(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 kt(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(kt(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=Lt(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<=je)return new Float32Array(e);let r=je/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)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...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:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[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 Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=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=Xe(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 Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,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}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=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-YIXH5T4U.js"),{HnswAdapter:c}=await import("./hnsw-adapter-CQGQS3V7.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-2ACF6FOJ.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:",y(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:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),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:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let 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}:`,y(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=Ve().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}:`,y(s))}try{let s=qt();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}:`,y(s))}if(te()&&e.embedding)try{Ye(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}:`,y(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}:`,y(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}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(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?v(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=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(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 d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.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(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.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(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(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=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}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 h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.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,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.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}),h={...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}:`,y(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},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(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 v(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`),v(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 v(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,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&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,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({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 v([]);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 v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
49
+ )`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...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(h=>h.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(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,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 Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,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 We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(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 kt(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(kt(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=Lt(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<=je)return new Float32Array(e);let r=je/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)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...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:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[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 Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=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=Xe(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 Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,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}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=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-5VRM5N7K.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BY4XB7FB.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-657CZRG7.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:",y(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:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),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:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let 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}:`,y(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=Ve().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}:`,y(s))}try{let s=qt();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}:`,y(s))}if(te()&&e.embedding)try{Ye(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}:`,y(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}:`,y(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}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(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?v(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=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(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 d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.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(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.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(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(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=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}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 h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.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,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.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}),h={...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}:`,y(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},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(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 v(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`),v(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 v(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,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&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,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({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 v([]);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 v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-E7UHOKKL.js";import{b as _,d as T}from"./chunk-Q4HJRYQB.js";import{a as k,c as q}from"./chunk-RNO6CE7I.js";import{a as v,b as ee}from"./chunk-CNNVL5W4.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
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.9.32");process.exit(0)}
2
+ import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-O5UGJ3OI.js";import{b as _,d as T}from"./chunk-OK2TFTXP.js";import{a as k,c as q}from"./chunk-5WR42V5O.js";import{a as v,b as ee}from"./chunk-4VAZSCTZ.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-3U2AVWQ3.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-K2VWFDKT.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function G(t){let e=o(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let n=v(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-TDSP2UE2.js"),{InMemoryBackend:n}=await import("./memory-backend-WQS2MLW2.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-RAQOWLG3.js"),{InMemoryBackend:n}=await import("./memory-backend-2A47ZRGO.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function H(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");f(r)||b(r,{recursive:!0});let s=o(r,"hnsw");f(s)||b(s,{recursive:!0});let i=o(r,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(d,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let p of m.patterns){let l=p.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(p)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([p,l])=>({name:p,patternCount:l.length})),loadedAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8");for(let[p,l]of a){let y=o(r,"patterns",p);f(y)||b(y,{recursive:!0});let C=o(y,"patterns.json");E(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function J(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");f(n)||b(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let u=o(n,`${a}.json`),h={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return E(c,`#!/usr/bin/env node
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{a as C,b as E}from"./chunk-FU74OETU.js";import{a as T}from"./chunk-VRP4GB4Y.js";import{a as _}from"./chunk-QHKK2H4H.js";import{n as D,o as F}from"./chunk-TYZGEVP6.js";import{a as R,c as A}from"./chunk-RNO6CE7I.js";import{g as O}from"./chunk-ITBPDVK5.js";import{createHash as M}from"crypto";var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function S(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return"["+o.map(i=>S(i)).join(",")+"]";let e=o;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+S(e[i])).join(",")+"}"}var x=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=S({action:t,domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=w();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
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.9.32");process.exit(0)}
2
+ import{a as C,b as E}from"./chunk-PS6ISBED.js";import{a as T}from"./chunk-6SYP7QX6.js";import{a as _}from"./chunk-MERMCKPG.js";import{n as D,o as F}from"./chunk-THYGFSTA.js";import{a as R,c as A}from"./chunk-5WR42V5O.js";import{g as O}from"./chunk-XHQFVTFD.js";import{createHash as M}from"crypto";var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function S(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return"["+o.map(i=>S(i)).join(",")+"]";let e=o;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+S(e[i])).join(",")+"}"}var x=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=S({action:t,domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=w();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=w();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)