agentic-qe 3.13.1 → 3.13.2

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 (330) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +29 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-I4SNWMCM.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-4VM3DE42.js → agent-booster-wasm-PZYYTKSS.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-ZDLMZQQX.js → agent-handler-DNN7GXUN.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-P72MDHHV.js → agent-memory-branch-LVCBBCQY.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-WI47XKXI.js +2 -0
  10. package/dist/cli/chunks/{arena-GCRBQ26R.js → arena-422HSTPE.js} +2 -2
  11. package/dist/cli/chunks/{arena-55FZGKEV.js → arena-OCEOLMCH.js} +4 -4
  12. package/dist/cli/chunks/{audit-VYAYVLIV.js → audit-5O45K34M.js} +3 -3
  13. package/dist/cli/chunks/base-VJ6VDLD7.js +2 -0
  14. package/dist/cli/chunks/{hnswlib-node-GMRPPMDM.js → better-sqlite3-Y36THYK2.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-IUKMRGWO.js → brain-handler-7VHXYN3P.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-TUI3RWLX.js → branch-enumerator-PZKOD6S6.js} +2 -2
  17. package/dist/cli/chunks/{browser-NBQTZYX2.js → browser-M74UO4WJ.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-WRYHQQDU.js +2 -0
  19. package/dist/cli/chunks/{chunk-5BB5DUL4.js → chunk-24S5IUSI.js} +2 -2
  20. package/dist/cli/chunks/{chunk-E4D47QTF.js → chunk-2DG44UZ5.js} +2 -2
  21. package/dist/cli/chunks/{chunk-KNWDXI3I.js → chunk-2QJPAQE5.js} +2 -2
  22. package/dist/cli/chunks/{chunk-2G2QWV7B.js → chunk-4DKL4H5L.js} +2 -2
  23. package/dist/cli/chunks/{chunk-IBSBOHUX.js → chunk-4FYTWD4Q.js} +2 -2
  24. package/dist/cli/chunks/{chunk-6XZXMEK4.js → chunk-4HFNY3Z2.js} +2 -2
  25. package/dist/cli/chunks/{chunk-DTRFZD7N.js → chunk-4PM5VORA.js} +2 -2
  26. package/dist/cli/chunks/{chunk-WINA3XUT.js → chunk-4SFOQSXU.js} +2 -2
  27. package/dist/cli/chunks/{chunk-JOTNKZ7A.js → chunk-4STE6VLR.js} +10 -10
  28. package/dist/cli/chunks/{chunk-XN2CD5S6.js → chunk-54BCLRRJ.js} +2 -2
  29. package/dist/cli/chunks/{chunk-LTKNCYMO.js → chunk-5AAG7JTB.js} +2 -2
  30. package/dist/cli/chunks/{chunk-IZO6TPGX.js → chunk-5EFNZEOB.js} +2 -2
  31. package/dist/cli/chunks/{chunk-YLAEIS6F.js → chunk-5GGGZYFA.js} +1 -1
  32. package/dist/cli/chunks/{chunk-FQXQJMSF.js → chunk-5KMBZTDI.js} +2 -2
  33. package/dist/cli/chunks/{chunk-UHKXKWMD.js → chunk-5XYVRTI6.js} +2 -2
  34. package/dist/cli/chunks/{chunk-HFI5PHG5.js → chunk-62D27BDO.js} +3 -3
  35. package/dist/cli/chunks/{chunk-EVDYFGVH.js → chunk-6DMB6WK5.js} +2 -2
  36. package/dist/cli/chunks/{chunk-TQ2MA3SR.js → chunk-6R7TX5L4.js} +1 -1
  37. package/dist/cli/chunks/chunk-6UGYFYS4.js +2 -0
  38. package/dist/cli/chunks/{chunk-H7YZ2YF2.js → chunk-6XHDH3IJ.js} +2 -2
  39. package/dist/cli/chunks/{chunk-XOQQGZFY.js → chunk-73HALJY5.js} +1 -1
  40. package/dist/cli/chunks/{chunk-QLOOW23R.js → chunk-7TCVVVFA.js} +3 -3
  41. package/dist/cli/chunks/{chunk-LJQ27PUE.js → chunk-A2OD5Z4B.js} +1 -1
  42. package/dist/cli/chunks/{chunk-OE4B6LDZ.js → chunk-AJ7A52GF.js} +1 -1
  43. package/dist/cli/chunks/{chunk-RZ6CO3RZ.js → chunk-AP2BBV2D.js} +2 -2
  44. package/dist/cli/chunks/{chunk-EAKHU5YX.js → chunk-AS2HVJ42.js} +3 -3
  45. package/dist/cli/chunks/{chunk-2CQAWYYE.js → chunk-ASIGTVFQ.js} +1 -1
  46. package/dist/cli/chunks/{chunk-UKBDH27A.js → chunk-B7KZMPF2.js} +1 -1
  47. package/dist/cli/chunks/{chunk-7D7XFZZI.js → chunk-BFKXHXWW.js} +2 -2
  48. package/dist/cli/chunks/{chunk-NHV4PTG6.js → chunk-BO2RBAPF.js} +2 -2
  49. package/dist/cli/chunks/{chunk-ELMUHNXN.js → chunk-BSQ32ZS5.js} +2 -2
  50. package/dist/cli/chunks/{chunk-XSCOEY4C.js → chunk-CKTFKA7Q.js} +2 -2
  51. package/dist/cli/chunks/{chunk-LSKQUUUN.js → chunk-CLBBFKXV.js} +2 -2
  52. package/dist/cli/chunks/{chunk-YRVUYM62.js → chunk-COOMXCCP.js} +2 -2
  53. package/dist/cli/chunks/{chunk-3Y6CHW67.js → chunk-DAHNHVND.js} +1 -1
  54. package/dist/cli/chunks/{chunk-OCKTPTQ7.js → chunk-DCQQJLUY.js} +2 -2
  55. package/dist/cli/chunks/{chunk-NP4CP3LR.js → chunk-DIPOFCBX.js} +2 -2
  56. package/dist/cli/chunks/{chunk-YMMVCOPF.js → chunk-DL2HDULJ.js} +5 -5
  57. package/dist/cli/chunks/{chunk-UJ6TMZC6.js → chunk-DQXSDWRP.js} +2 -2
  58. package/dist/cli/chunks/{chunk-GTPZVLL6.js → chunk-E6JJ4ZRQ.js} +1 -1
  59. package/dist/cli/chunks/{chunk-55WDVSCM.js → chunk-E6PYV3DB.js} +2 -2
  60. package/dist/cli/chunks/{chunk-J45DX3IK.js → chunk-EABGQVTV.js} +1 -1
  61. package/dist/cli/chunks/{chunk-AOMXMFDH.js → chunk-EFHMS7TJ.js} +2 -2
  62. package/dist/cli/chunks/{chunk-BOCEOLLJ.js → chunk-ELVUERQW.js} +2 -2
  63. package/dist/cli/chunks/{chunk-MPD7RR4P.js → chunk-EU7NUUL6.js} +1 -1
  64. package/dist/cli/chunks/{chunk-M3T6FB54.js → chunk-F6UMLI5Y.js} +2 -2
  65. package/dist/cli/chunks/{chunk-ZCLFAOVT.js → chunk-FECBWGCA.js} +2 -2
  66. package/dist/cli/chunks/{chunk-S6F3IJMK.js → chunk-FFMUTX26.js} +1 -1
  67. package/dist/cli/chunks/{chunk-2OM3TDC4.js → chunk-FJ2L6P7O.js} +1 -1
  68. package/dist/cli/chunks/{chunk-ZLCATRXI.js → chunk-FMYNKZ2S.js} +2 -2
  69. package/dist/cli/chunks/{chunk-4WGSMODQ.js → chunk-FXXXLDB3.js} +1 -1
  70. package/dist/cli/chunks/{chunk-FM272B4O.js → chunk-FZEWEG6Q.js} +2 -2
  71. package/dist/cli/chunks/{chunk-PKMCZFET.js → chunk-G4LZ5SBC.js} +2 -2
  72. package/dist/cli/chunks/{chunk-IV2VCR75.js → chunk-GHJRLC3C.js} +5 -5
  73. package/dist/cli/chunks/{chunk-4QMWWYNU.js → chunk-GKKD22CC.js} +2 -2
  74. package/dist/cli/chunks/{chunk-3F4XH4ZA.js → chunk-GMKJWOXZ.js} +1 -1
  75. package/dist/cli/chunks/{chunk-3KGCBAUH.js → chunk-GMKQJEKX.js} +2 -2
  76. package/dist/cli/chunks/{chunk-IJP42OGW.js → chunk-GZ775E5O.js} +2 -2
  77. package/dist/cli/chunks/{chunk-GJEEPKAT.js → chunk-H6C2YTPX.js} +2 -2
  78. package/dist/cli/chunks/{chunk-QG6BXSNJ.js → chunk-HANBJ37Z.js} +2 -2
  79. package/dist/cli/chunks/{chunk-6C3MZLYW.js → chunk-HANJESCY.js} +2 -2
  80. package/dist/cli/chunks/{chunk-THFLRJT6.js → chunk-HD6PZHLC.js} +3 -3
  81. package/dist/cli/chunks/{chunk-SPJQJWGK.js → chunk-HHUKHEW5.js} +2 -2
  82. package/dist/cli/chunks/{chunk-WWP2VXYJ.js → chunk-HQCJYUKC.js} +2 -2
  83. package/dist/cli/chunks/{chunk-AYYDO52G.js → chunk-IIZ3HBPV.js} +2 -2
  84. package/dist/cli/chunks/{chunk-P4Y3G6OB.js → chunk-IV77BQ2R.js} +2 -2
  85. package/dist/cli/chunks/{chunk-CWP4RMOM.js → chunk-J722Z7VO.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GOV2MHLV.js → chunk-JDRYENTD.js} +2 -2
  87. package/dist/cli/chunks/{chunk-LVHMXGDI.js → chunk-JKVUSXT4.js} +3 -3
  88. package/dist/cli/chunks/{chunk-RSCGBHLM.js → chunk-JMRUHQEL.js} +2 -2
  89. package/dist/cli/chunks/{chunk-IMQKEFW6.js → chunk-JPO4AC5Q.js} +1 -1
  90. package/dist/cli/chunks/{chunk-ZHEKGB4A.js → chunk-JPPHM3I6.js} +2 -2
  91. package/dist/cli/chunks/{chunk-EGMGOWCE.js → chunk-K3MNTU4O.js} +2 -2
  92. package/dist/cli/chunks/{chunk-UHGMS2PJ.js → chunk-K47EWX3M.js} +1 -1
  93. package/dist/cli/chunks/{chunk-ORDH4VPL.js → chunk-KAHMXURL.js} +1 -1
  94. package/dist/cli/chunks/{chunk-VLUJWI56.js → chunk-KHVW6DQS.js} +1 -1
  95. package/dist/cli/chunks/{chunk-FDUSWM6O.js → chunk-KKPWS3XJ.js} +18 -18
  96. package/dist/cli/chunks/{chunk-MY47CR27.js → chunk-KRRGOJ6K.js} +2 -2
  97. package/dist/cli/chunks/chunk-LEOSNZR2.js +2 -0
  98. package/dist/cli/chunks/{chunk-PIOO2M4W.js → chunk-LG6UUM55.js} +2 -2
  99. package/dist/cli/chunks/{chunk-V32MDID3.js → chunk-LJWIBYTR.js} +2 -2
  100. package/dist/cli/chunks/{chunk-YQCAXYBF.js → chunk-LQDQTLWV.js} +2 -2
  101. package/dist/cli/chunks/{chunk-23MT7OBY.js → chunk-LXYVWAFN.js} +2 -2
  102. package/dist/cli/chunks/{chunk-WWCH5SSF.js → chunk-LZNJ7HXB.js} +2 -2
  103. package/dist/cli/chunks/{chunk-IJA4WS7B.js → chunk-M4JZOCV3.js} +1 -1
  104. package/dist/cli/chunks/{chunk-XFUF654L.js → chunk-MBTVAIFF.js} +1 -1
  105. package/dist/cli/chunks/{chunk-L7IOTWWY.js → chunk-MNDPSIEI.js} +1 -1
  106. package/dist/cli/chunks/{chunk-ZH6ZBDVV.js → chunk-MUSLUG6Y.js} +1 -1
  107. package/dist/cli/chunks/{chunk-UMCEEXQN.js → chunk-MVJ5UQI3.js} +1 -1
  108. package/dist/cli/chunks/{chunk-MX5ZDKRR.js → chunk-N2AGOQCL.js} +2 -2
  109. package/dist/cli/chunks/{chunk-S6VNPKHO.js → chunk-N4O2RWSL.js} +1 -1
  110. package/dist/cli/chunks/{chunk-JELNVHBF.js → chunk-NBRKZOPM.js} +1 -1
  111. package/dist/cli/chunks/{chunk-LSZZQ7H6.js → chunk-NIE3SGZM.js} +1 -1
  112. package/dist/cli/chunks/{chunk-USUFTHHT.js → chunk-NNIKJZA4.js} +3 -3
  113. package/dist/cli/chunks/{chunk-JAPOMPFD.js → chunk-NTKIDOIW.js} +2 -2
  114. package/dist/cli/chunks/{chunk-CWXDL7AH.js → chunk-ODE7Z667.js} +1 -1
  115. package/dist/cli/chunks/{chunk-A2MG3YXO.js → chunk-OYWZYG6Q.js} +1 -1
  116. package/dist/cli/chunks/{chunk-6QKQFHS7.js → chunk-P33EORZZ.js} +2 -2
  117. package/dist/cli/chunks/{chunk-Y734CWHJ.js → chunk-PILZKQX7.js} +2 -2
  118. package/dist/cli/chunks/{chunk-MAYZTGJ2.js → chunk-PJOH5Z5I.js} +2 -2
  119. package/dist/cli/chunks/{chunk-2XZ4BHWS.js → chunk-PNQWEOE2.js} +1 -1
  120. package/dist/cli/chunks/{chunk-ZYPESQ4M.js → chunk-PRQPUOSH.js} +2 -2
  121. package/dist/cli/chunks/{chunk-ZXX2VFMA.js → chunk-PT6NTWGT.js} +2 -2
  122. package/dist/cli/chunks/{chunk-AY7S7AWN.js → chunk-Q45FBGVV.js} +1 -1
  123. package/dist/cli/chunks/{chunk-GASOBSNB.js → chunk-Q625ISQI.js} +4 -4
  124. package/dist/cli/chunks/{chunk-SS6K4FBH.js → chunk-QS6TI7NR.js} +2 -2
  125. package/dist/cli/chunks/{chunk-TDGE52HJ.js → chunk-QVD3LU27.js} +1 -1
  126. package/dist/cli/chunks/{chunk-2D2XFUKI.js → chunk-QZACODX6.js} +2 -2
  127. package/dist/cli/chunks/{chunk-YBPCBFEE.js → chunk-REBNPQI7.js} +2 -2
  128. package/dist/cli/chunks/{chunk-MUFYDKVC.js → chunk-RF2DMPX2.js} +2 -2
  129. package/dist/cli/chunks/{chunk-HUMQU4ES.js → chunk-RI2V2U2N.js} +2 -2
  130. package/dist/cli/chunks/{chunk-YVKMHXQK.js → chunk-RJYAUJDC.js} +3 -3
  131. package/dist/cli/chunks/{chunk-VAJT6QWX.js → chunk-RWHHOQIC.js} +1 -1
  132. package/dist/cli/chunks/{chunk-INYS35DV.js → chunk-RWUK5VMZ.js} +2 -2
  133. package/dist/cli/chunks/{chunk-ZIBW7CB4.js → chunk-SOOI2HJB.js} +1 -1
  134. package/dist/cli/chunks/{chunk-OPQY2333.js → chunk-T2XXTEZV.js} +2 -2
  135. package/dist/cli/chunks/{chunk-TBQTGQ75.js → chunk-T55XIENI.js} +2 -2
  136. package/dist/cli/chunks/{chunk-ARTLSAXO.js → chunk-T726SRYP.js} +2 -2
  137. package/dist/cli/chunks/{chunk-3K4YC3GC.js → chunk-TLG56A27.js} +2 -2
  138. package/dist/cli/chunks/{chunk-KW5NBORV.js → chunk-TTWWCWAR.js} +2 -2
  139. package/dist/cli/chunks/{chunk-AHTOWWSE.js → chunk-TVWX7NYD.js} +1 -1
  140. package/dist/cli/chunks/{chunk-UCQ66N6M.js → chunk-U2FCUBBW.js} +2 -2
  141. package/dist/cli/chunks/{chunk-FQUUMC57.js → chunk-UIQVVS7K.js} +2 -2
  142. package/dist/cli/chunks/{chunk-LTWT4GZD.js → chunk-UPGJZA3D.js} +4 -4
  143. package/dist/cli/chunks/{chunk-MCIO7BDK.js → chunk-UVLWT6QM.js} +1 -1
  144. package/dist/cli/chunks/{chunk-CE6LYEHT.js → chunk-VKU5BUUC.js} +1 -1
  145. package/dist/cli/chunks/{chunk-7WEHZCSK.js → chunk-VOYUCJLK.js} +2 -2
  146. package/dist/cli/chunks/{chunk-FRAGSKXQ.js → chunk-WMK2ZNLM.js} +3 -3
  147. package/dist/cli/chunks/{chunk-SXADKQJN.js → chunk-WTSVP6OK.js} +2 -2
  148. package/dist/cli/chunks/{chunk-MXKHIZVM.js → chunk-XS2S3ECA.js} +3 -3
  149. package/dist/cli/chunks/{chunk-N7WAZ2Y6.js → chunk-XXQLFPIK.js} +1 -1
  150. package/dist/cli/chunks/{chunk-J4T6D2OQ.js → chunk-XZOTFJHU.js} +2 -2
  151. package/dist/cli/chunks/{chunk-BF5BKSDU.js → chunk-YTHUTBBH.js} +2 -2
  152. package/dist/cli/chunks/{chunk-SHWXADCI.js → chunk-YWJ2GPD4.js} +2 -2
  153. package/dist/cli/chunks/{chunk-WZROSTQZ.js → chunk-YXTDCP6H.js} +1 -1
  154. package/dist/cli/chunks/{chunk-2ISLQU3G.js → chunk-YZUMCXH6.js} +1 -1
  155. package/dist/cli/chunks/{chunk-HYIRFJDB.js → chunk-ZIT5VF43.js} +2 -2
  156. package/dist/cli/chunks/{chunk-DVPGQG4W.js → chunk-ZY5FB3JV.js} +2 -2
  157. package/dist/cli/chunks/{ci-HHL5WQXQ.js → ci-EOFZKCSH.js} +2 -2
  158. package/dist/cli/chunks/{ci-output-HVOJC2KN.js → ci-output-TAJFQWDP.js} +2 -2
  159. package/dist/cli/chunks/{circuit-breaker-HRXMIY2G.js → circuit-breaker-QA7YJ3IF.js} +2 -2
  160. package/dist/cli/chunks/{claude-flow-setup-3I7WVMZN.js → claude-flow-setup-4RNAIALK.js} +2 -2
  161. package/dist/cli/chunks/client-N2WAM5IK.js +2 -0
  162. package/dist/cli/chunks/{cline-installer-NBREL4QT.js → cline-installer-K25NUUA4.js} +2 -2
  163. package/dist/cli/chunks/{code-TX4E2RWU.js → code-JM4D3I2W.js} +2 -2
  164. package/dist/cli/chunks/{code-index-extractor-YELOFLSL.js → code-index-extractor-6B6TJ2B5.js} +2 -2
  165. package/dist/cli/chunks/{codex-installer-HEX3KFRB.js → codex-installer-GRUENCIO.js} +2 -2
  166. package/dist/cli/chunks/{completions-72GGFRGG.js → completions-LADTXGCC.js} +2 -2
  167. package/dist/cli/chunks/{complexity-analyzer-WRAKDYUK.js → complexity-analyzer-IQITOJH5.js} +2 -2
  168. package/dist/cli/chunks/{continuedev-installer-UGYKSKTI.js → continuedev-installer-H6NAXFZK.js} +2 -2
  169. package/dist/cli/chunks/{copilot-installer-RPCRUKIJ.js → copilot-installer-W7HCQKOS.js} +2 -2
  170. package/dist/cli/chunks/core-handlers-VSX474R3.js +2 -0
  171. package/dist/cli/chunks/{cost-tracker-CNHJ7G4M.js → cost-tracker-MC7KEENQ.js} +2 -2
  172. package/dist/cli/chunks/{coverage-RHIQ4XEX.js → coverage-NOOKPFYQ.js} +3 -3
  173. package/dist/cli/chunks/cross-domain-router-VNE7QKX4.js +2 -0
  174. package/dist/cli/chunks/{cursor-installer-KSRVA4V2.js → cursor-installer-GOZ64GZJ.js} +2 -2
  175. package/dist/cli/chunks/{daemon-IT4AAFBW.js → daemon-G4ABQMFJ.js} +3 -3
  176. package/dist/cli/chunks/{daemon-QBXSJABV.js → daemon-V23WTCJJ.js} +4 -4
  177. package/dist/cli/chunks/{dag-attention-scheduler-F7WCQTLY.js → dag-attention-scheduler-YKOO6ZWL.js} +2 -2
  178. package/dist/cli/chunks/{detect-2IYU332U.js → detect-SNEMKQGJ.js} +2 -2
  179. package/dist/cli/chunks/{dist-node-CIYNYCYN.js → dist-node-VBNEM6K6.js} +2 -2
  180. package/dist/cli/chunks/{domain-handler-QRYQO2QK.js → domain-handler-2G5XEERC.js} +2 -2
  181. package/dist/cli/chunks/{domain-transfer-2OQDOD3G.js → domain-transfer-HSEUUM7E.js} +2 -2
  182. package/dist/cli/chunks/dream-A5LVJU7T.js +2 -0
  183. package/dist/cli/chunks/{embed-and-insert-pattern-P2IFC7JL.js → embed-and-insert-pattern-H6MU5HK4.js} +2 -2
  184. package/dist/cli/chunks/{eval-SBPK37IB.js → eval-XYVDJXJF.js} +2 -2
  185. package/dist/cli/chunks/{experience-capture-middleware-3GMFND3F.js → experience-capture-middleware-BZQJVXTE.js} +3 -3
  186. package/dist/cli/chunks/{fast-paths-4OYYII2F.js → fast-paths-76WWBJ4H.js} +2 -2
  187. package/dist/cli/chunks/{feature-flags-BM6QTMMC.js → feature-flags-7E5YZ4P5.js} +2 -2
  188. package/dist/cli/chunks/{feature-flags-NFCAYUWO.js → feature-flags-SCQ35J6M.js} +2 -2
  189. package/dist/cli/chunks/{file-discovery-2M3ZUAGC.js → file-discovery-LU5MAXWA.js} +2 -2
  190. package/dist/cli/chunks/{fleet-QMGGVIDV.js → fleet-M3TH65SV.js} +3 -3
  191. package/dist/cli/chunks/{gnn-wrapper-WGMAGZMO.js → gnn-wrapper-OYUJEJD2.js} +2 -2
  192. package/dist/cli/chunks/{heartbeat-handler-5RSMEZGG.js → heartbeat-handler-II4NSOXK.js} +4 -4
  193. package/dist/cli/chunks/heartbeat-scheduler-CFZ6DNQY.js +2 -0
  194. package/dist/cli/chunks/hnsw-adapter-I4Y2T4HO.js +2 -0
  195. package/dist/cli/chunks/hnsw-index-SBR5VYGN.js +2 -0
  196. package/dist/cli/chunks/{hnsw-legacy-bridge-TYPQ2T6P.js → hnsw-legacy-bridge-322R2UAB.js} +2 -2
  197. package/dist/cli/chunks/{better-sqlite3-JDDFYVCX.js → hnswlib-node-OVLAHTPU.js} +2 -2
  198. package/dist/cli/chunks/{hooks-NUC5P3OJ.js → hooks-2A27XCUJ.js} +37 -37
  199. package/dist/cli/chunks/hybrid-router-E6YM74NQ.js +2 -0
  200. package/dist/cli/chunks/{hypergraph-engine-OIB7WK54.js → hypergraph-engine-ERA527UR.js} +2 -2
  201. package/dist/cli/chunks/{hypergraph-handler-XX2N75QC.js → hypergraph-handler-7XL4OL6W.js} +3 -3
  202. package/dist/cli/chunks/impact-analyzer-GHYFSSMJ.js +2 -0
  203. package/dist/cli/chunks/{init-handler-AKSTJMZY.js → init-handler-WN6KQ5WY.js} +6 -6
  204. package/dist/cli/chunks/init-wizard-KAN5KOGD.js +2 -0
  205. package/dist/cli/chunks/kernel-LET4HEEF.js +2 -0
  206. package/dist/cli/chunks/{kilocode-installer-375V5ZZB.js → kilocode-installer-5UCCFZ7V.js} +2 -2
  207. package/dist/cli/chunks/{kiro-installer-GKY5GB5Q.js → kiro-installer-77DPEP3K.js} +2 -2
  208. package/dist/cli/chunks/knowledge-graph-P3UJWNQS.js +2 -0
  209. package/dist/cli/chunks/{learning-2CQE3QP6.js → learning-A5GKUD73.js} +3 -3
  210. package/dist/cli/chunks/{llm-router-FTQNRF45.js → llm-router-SINJNEGP.js} +4 -4
  211. package/dist/cli/chunks/llm-router-service-BOBENURJ.js +2 -0
  212. package/dist/cli/chunks/{load-3DBAO5ZG.js → load-Q56GLXHJ.js} +2 -2
  213. package/dist/cli/chunks/load-test-4VDCVB7S.js +2 -0
  214. package/dist/cli/chunks/{mcp-AWR6TDXM.js → mcp-VBDU2WLY.js} +2 -2
  215. package/dist/cli/chunks/{memory-GI4LCNXY.js → memory-IGWBRDIT.js} +5 -5
  216. package/dist/cli/chunks/memory-backend-RRFAYQYS.js +2 -0
  217. package/dist/cli/chunks/{memory-handlers-MALKG7GP.js → memory-handlers-IITHQ7KV.js} +2 -2
  218. package/dist/cli/chunks/{multi-model-executor-SWFT5U72.js → multi-model-executor-2QUEY4CC.js} +2 -2
  219. package/dist/cli/chunks/{opencode-installer-EYXGYJX5.js → opencode-installer-FZJ5N2B3.js} +2 -2
  220. package/dist/cli/chunks/{orchestrator-MP3EAZVC.js → orchestrator-BGLDS47V.js} +5 -5
  221. package/dist/cli/chunks/pattern-null-store-V7DEZEF2.js +2 -0
  222. package/dist/cli/chunks/{pattern-usage-recorder-25P3R3W7.js → pattern-usage-recorder-4MFN4WKV.js} +2 -2
  223. package/dist/cli/chunks/{pipeline-LSAFL25D.js → pipeline-GZHAORGP.js} +2 -2
  224. package/dist/cli/chunks/{platform-IJ6DJ2PG.js → platform-TZEX4YZQ.js} +2 -2
  225. package/dist/cli/chunks/{plugin-OXOZRZW2.js → plugin-VEYUFCNY.js} +2 -2
  226. package/dist/cli/chunks/{prime-radiant-advanced-wasm-HJNJQQ3R.js → prime-radiant-advanced-wasm-OA5DLXJJ.js} +2 -2
  227. package/dist/cli/chunks/protocol-executor-I3C2ZETP.js +2 -0
  228. package/dist/cli/chunks/{protocol-handler-TCMUH2HL.js → protocol-handler-MVJ5N4X5.js} +2 -2
  229. package/dist/cli/chunks/{prove-ADXQ2GOX.js → prove-VKF7YCUA.js} +2 -2
  230. package/dist/cli/chunks/provider-manager-HB4YVQDI.js +2 -0
  231. package/dist/cli/chunks/qe-reasoning-bank-RDLBAXJY.js +2 -0
  232. package/dist/cli/chunks/{quality-EWP36ORX.js → quality-NLB5LVGM.js} +2 -2
  233. package/dist/cli/chunks/{quality-gate-3BIG7PVU.js → quality-gate-OM6A7FQM.js} +3 -3
  234. package/dist/cli/chunks/queen-coordinator-QRWRNUDR.js +2 -0
  235. package/dist/cli/chunks/{real-embeddings-D4NBT7W5.js → real-embeddings-NONEKGAV.js} +2 -2
  236. package/dist/cli/chunks/{roocode-installer-DOPWH6YV.js → roocode-installer-ORXQQO3F.js} +2 -2
  237. package/dist/cli/chunks/router-WDF7KV4M.js +2 -0
  238. package/dist/cli/chunks/routing-feedback-DHYB4ZNL.js +2 -0
  239. package/dist/cli/chunks/{routing-handler-5ADEFOHS.js → routing-handler-LGMIBVDS.js} +2 -2
  240. package/dist/cli/chunks/{ruvector-commands-PLMEIHSN.js → ruvector-commands-4GZMU4BZ.js} +2 -2
  241. package/dist/cli/chunks/{rvf-dual-writer-EQWKVNQB.js → rvf-dual-writer-45HKI22F.js} +2 -2
  242. package/dist/cli/chunks/{rvf-migration-adapter-2OWFUUCG.js → rvf-migration-adapter-RHYIXI3I.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-coordinator-URAETAPU.js → rvf-migration-coordinator-ANTAYKNN.js} +2 -2
  244. package/dist/cli/chunks/rvf-native-adapter-7W53TYTH.js +2 -0
  245. package/dist/cli/chunks/{rvf-store-integrity-4AWPW4TF.js → rvf-store-integrity-CPQUTFST.js} +2 -2
  246. package/dist/cli/chunks/safe-db-4HBFO7OQ.js +2 -0
  247. package/dist/cli/chunks/schedule-M2OSBJZM.js +2 -0
  248. package/dist/cli/chunks/scheduler-JWV5MSGE.js +2 -0
  249. package/dist/cli/chunks/{security-HDLZVM62.js → security-BM6LMCBI.js} +3 -3
  250. package/dist/cli/chunks/{shared-rvf-adapter-YQT7PF7X.js → shared-rvf-adapter-3HGARKJX.js} +2 -2
  251. package/dist/cli/chunks/{shared-rvf-dual-writer-N5D3NSJ7.js → shared-rvf-dual-writer-UQ4O46ZI.js} +2 -2
  252. package/dist/cli/chunks/sqlite-persistence-QA4JRQZ2.js +2 -0
  253. package/dist/cli/chunks/{status-handler-KLYRJ2MR.js → status-handler-TGRAM5PC.js} +2 -2
  254. package/dist/cli/chunks/{structural-health-6LKVRP6Y.js → structural-health-RXETMBB3.js} +2 -2
  255. package/dist/cli/chunks/{sync-7VMFPBVB.js → sync-B4KEYFCP.js} +2 -2
  256. package/dist/cli/chunks/{sync-YYOW6L6W.js → sync-JTBZIACA.js} +2 -2
  257. package/dist/cli/chunks/{task-handler-RKQDGFN2.js → task-handler-D7VXHWPG.js} +2 -2
  258. package/dist/cli/chunks/{task-handlers-6YJ4QTEP.js → task-handlers-XF6VVPTR.js} +3 -3
  259. package/dist/cli/chunks/{test-ASPUIUJH.js → test-BKEIMBSX.js} +4 -4
  260. package/dist/cli/chunks/{test-scheduling-I7ABQBBU.js → test-scheduling-A4OHR7KW.js} +3 -3
  261. package/dist/cli/chunks/{token-bootstrap-2XZBTODN.js → token-bootstrap-LIDDAOAK.js} +2 -2
  262. package/dist/cli/chunks/{token-usage-TMUE6PTF.js → token-usage-BJUFIU4V.js} +2 -2
  263. package/dist/cli/chunks/{transformers-FDHHH4SL.js → transformers-YYUQCGMV.js} +2 -2
  264. package/dist/cli/chunks/{tree-sitter-wasm-parser-G7PGZA5C.js → tree-sitter-wasm-parser-DFXYTJ23.js} +2 -2
  265. package/dist/cli/chunks/{types-JGT57UFP.js → types-Z75HK5HH.js} +2 -2
  266. package/dist/cli/chunks/unified-memory-BEUZQTTC.js +2 -0
  267. package/dist/cli/chunks/unified-memory-hnsw-FHLSAEX4.js +2 -0
  268. package/dist/cli/chunks/unified-persistence-TVEQGCSB.js +2 -0
  269. package/dist/cli/chunks/{upgrade-V6UQODJF.js → upgrade-NETNZZH3.js} +2 -2
  270. package/dist/cli/chunks/{validate-UBZAE5RW.js → validate-U2WQ7P6T.js} +2 -2
  271. package/dist/cli/chunks/{validate-swarm-TSO2MI5X.js → validate-swarm-DKD7H2E3.js} +2 -2
  272. package/dist/cli/chunks/{vibium-7G3VYSQA.js → vibium-FOQ73JBW.js} +2 -2
  273. package/dist/cli/chunks/visual-security-AYV46OUO.js +2 -0
  274. package/dist/cli/chunks/{web-tree-sitter-MIYJSF2L.js → web-tree-sitter-PQXWMQO6.js} +2 -2
  275. package/dist/cli/chunks/{windsurf-installer-5TLZSQIJ.js → windsurf-installer-CTFSFOBX.js} +2 -2
  276. package/dist/cli/chunks/{witness-chain-LTV7H2HM.js → witness-chain-NCRHNFQM.js} +2 -2
  277. package/dist/cli/chunks/witness-chain-RU356H6R.js +2 -0
  278. package/dist/cli/chunks/{witness-key-manager-PAJ2J4AL.js → witness-key-manager-WGCSSB23.js} +2 -2
  279. package/dist/cli/chunks/{workflow-DL3ESR2H.js → workflow-FE5QGP2U.js} +4 -4
  280. package/dist/cli/chunks/workflow-orchestrator-N2DQTC3X.js +2 -0
  281. package/dist/cli/chunks/{wrappers-5HSU665E.js → wrappers-AHL5K2LO.js} +2 -2
  282. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +9 -0
  283. package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
  284. package/dist/cli/commands/hooks.d.ts +2 -2
  285. package/dist/cli/commands/hooks.js +8 -2
  286. package/dist/coordination/handlers/coverage-collection.js +6 -2
  287. package/dist/coordination/queen-coordinator.js +4 -3
  288. package/dist/integrations/ruvector/rvf-store-integrity.js +5 -1
  289. package/dist/integrations/ruvector/shared-rvf-adapter.js +5 -5
  290. package/dist/mcp/bundle.js +46 -46
  291. package/package.json +1 -1
  292. package/dist/cli/chunks/adapter-VRZNL53W.js +0 -2
  293. package/dist/cli/chunks/aqe-learning-engine-XCNMNERX.js +0 -2
  294. package/dist/cli/chunks/base-VZZNR4UR.js +0 -2
  295. package/dist/cli/chunks/browser-workflow-5DZNIFUY.js +0 -2
  296. package/dist/cli/chunks/chunk-BBLWZT5I.js +0 -2
  297. package/dist/cli/chunks/chunk-QES4QHQW.js +0 -2
  298. package/dist/cli/chunks/client-EY2IYQDL.js +0 -2
  299. package/dist/cli/chunks/core-handlers-G4GLA4DT.js +0 -2
  300. package/dist/cli/chunks/cross-domain-router-P3K4IH5H.js +0 -2
  301. package/dist/cli/chunks/dream-IT4ZQGEO.js +0 -2
  302. package/dist/cli/chunks/heartbeat-scheduler-UUWSPHF2.js +0 -2
  303. package/dist/cli/chunks/hnsw-adapter-YUJVSFPD.js +0 -2
  304. package/dist/cli/chunks/hnsw-index-FQZ47RSJ.js +0 -2
  305. package/dist/cli/chunks/hybrid-router-T5MF73NF.js +0 -2
  306. package/dist/cli/chunks/impact-analyzer-AEGELYMD.js +0 -2
  307. package/dist/cli/chunks/init-wizard-WKX3OGWM.js +0 -2
  308. package/dist/cli/chunks/kernel-5CVWFIGR.js +0 -2
  309. package/dist/cli/chunks/knowledge-graph-EGPMNDMT.js +0 -2
  310. package/dist/cli/chunks/llm-router-service-H4LXOARB.js +0 -2
  311. package/dist/cli/chunks/load-test-OOOGITSN.js +0 -2
  312. package/dist/cli/chunks/memory-backend-O2YOT4LW.js +0 -2
  313. package/dist/cli/chunks/pattern-null-store-WBOHE2XL.js +0 -2
  314. package/dist/cli/chunks/protocol-executor-JCNTPW5J.js +0 -2
  315. package/dist/cli/chunks/provider-manager-LPGQ5GOO.js +0 -2
  316. package/dist/cli/chunks/qe-reasoning-bank-FWVYVSPP.js +0 -2
  317. package/dist/cli/chunks/queen-coordinator-UXNALRVD.js +0 -2
  318. package/dist/cli/chunks/router-C6LUIQYY.js +0 -2
  319. package/dist/cli/chunks/routing-feedback-KMSGGDVD.js +0 -2
  320. package/dist/cli/chunks/rvf-native-adapter-K54BELUE.js +0 -2
  321. package/dist/cli/chunks/safe-db-NGOZWF2D.js +0 -2
  322. package/dist/cli/chunks/schedule-B3Y5P64E.js +0 -2
  323. package/dist/cli/chunks/scheduler-Z6QVRMTB.js +0 -2
  324. package/dist/cli/chunks/sqlite-persistence-PLOUGATS.js +0 -2
  325. package/dist/cli/chunks/unified-memory-P5YVLMFI.js +0 -2
  326. package/dist/cli/chunks/unified-memory-hnsw-7HI43A2O.js +0 -2
  327. package/dist/cli/chunks/unified-persistence-U26YP3N3.js +0 -2
  328. package/dist/cli/chunks/visual-security-6FCDY5FF.js +0 -2
  329. package/dist/cli/chunks/witness-chain-I3K3WQID.js +0 -2
  330. package/dist/cli/chunks/workflow-orchestrator-MAALP4WA.js +0 -2
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{d as J,e as B,f as te,g as j}from"./chunk-2OM3TDC4.js";import{a as ne}from"./chunk-CWXDL7AH.js";import{b as _e}from"./chunk-MUFYDKVC.js";import{a as ie}from"./chunk-E4D47QTF.js";import{b as De,c as nt}from"./chunk-YBPCBFEE.js";import{a as re,b as Fe,d as Oe,f as it}from"./chunk-55WDVSCM.js";import{c as Ie}from"./chunk-QES4QHQW.js";import{b as P,c as w}from"./chunk-GTPZVLL6.js";import{a as v,b as xe,c as Ce}from"./chunk-AYYDO52G.js";import{i as C}from"./chunk-ZIBW7CB4.js";import{B as Q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-IJP42OGW.js";import{a as Te,d as $,f as rt}from"./chunk-OE4B6LDZ.js";var G=$(E=>{var ft=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function ze(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)ue(n,s)&&r.push(s);return r}E._objectKeys=ze;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=ze(n),s=r.length,i=0;i<s;i++)if(le(n[r[i]]))return!0}}return!1}E.hasUndefined=le;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
3
- `)}var Pt=(function(n){ft(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=$(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,m=void 0;for(typeof t=="function"?m=t:m=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&m(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=wt[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}g.applyOperation=O;function $e(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}g.applyPatch=$e;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Y;function Je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$e(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof g.JsonPatchError)return s;throw s}}g.validate=Je;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var Be=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,s=At(n);if(!s)s=new Et(n),me.set(n,s);else{var i=Tt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?pe(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var je=$(I=>{var Ot=de();Object.assign(I,Ot);var It=Be();Object.assign(I,It);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});nt();Ce();var q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-PLOUGATS.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,m=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],m+=d[S]*d[S];if(m=Math.sqrt(m),m===0)continue;let p=h/(o*m),y=this.calculateReuseInfo(f,p);i.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};it();Ce();F();function at(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Me=1e4,Le=2166136261;function ke(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var He="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=He[s>>4]+He[s&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=oe[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ke(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=lt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ut([r,s])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ke(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:ct(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=oe[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new ne(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ue(n){return new ae(n)}function Qe(n){return Q()?new se(n):null}var ye=rt(je(),1),ge=ye.default??ye,_t=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{d as J,e as B,f as te,g as j}from"./chunk-FJ2L6P7O.js";import{a as ne}from"./chunk-ODE7Z667.js";import{b as _e}from"./chunk-RF2DMPX2.js";import{a as ie}from"./chunk-2DG44UZ5.js";import{b as De,c as nt}from"./chunk-REBNPQI7.js";import{a as re,b as Fe,d as Oe,f as it}from"./chunk-E6PYV3DB.js";import{c as Ie}from"./chunk-LEOSNZR2.js";import{b as P,c as w}from"./chunk-E6JJ4ZRQ.js";import{a as v,b as xe,c as Ce}from"./chunk-IIZ3HBPV.js";import{i as C}from"./chunk-SOOI2HJB.js";import{B as Q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-GZ775E5O.js";import{a as Te,d as $,f as rt}from"./chunk-AJ7A52GF.js";var G=$(E=>{var ft=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var mt=Object.prototype.hasOwnProperty;function ue(n,e){return mt.call(n,e)}E.hasOwnProperty=ue;function ze(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)ue(n,s)&&r.push(s);return r}E._objectKeys=ze;function pt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=pt;function gt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=gt;function ce(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ce;function yt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=yt;function he(n,e){var t;for(var r in n)if(ue(n,r)){if(n[r]===e)return ce(r)+"/";if(typeof n[r]=="object"&&(t=he(n[r],e),t!=""))return ce(r)+"/"+t}return""}E._getPathRecursive=he;function vt(n,e){if(n===e)return"/";var t=he(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=vt;function le(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(le(n[e]))return!0}else if(typeof n=="object"){for(var r=ze(n),s=r.length,i=0;i<s;i++)if(le(n[r[i]]))return!0}}return!1}E.hasUndefined=le;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
3
+ `)}var Pt=(function(n){ft(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=Pt});var de=$(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=G();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},wt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}g.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,m=void 0;for(typeof t=="function"?m=t:m=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&m(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=wt[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}g.applyOperation=O;function $e(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}g.applyPatch=$e;function St(n,e,t){var r=O(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=St;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=Je([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=Y;function Je(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$e(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof g.JsonPatchError)return s;throw s}}g.validate=Je;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}g._areEquals=z});var Be=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),bt=de(),me=new WeakMap,Et=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Rt=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function At(n){return me.get(n)}function Tt(n,e){return n.observers.get(e)}function xt(n,e){n.observers.delete(e.callback)}function Ct(n,e){e.unobserve()}k.unobserve=Ct;function Dt(n,e){var t=[],r,s=At(n);if(!s)s=new Et(n),me.set(n,s);else{var i=Tt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){fe(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){fe(r),clearTimeout(r.next),xt(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new Rt(e,r)),r}k.observe=Dt;function fe(n,e){e===void 0&&(e=!1);var t=me.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&bt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=fe;function pe(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?pe(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ft(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=Ft});var je=$(I=>{var Ot=de();Object.assign(I,Ot);var It=Be();Object.assign(I,It);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});nt();Ce();var q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-QA4JRQZ2.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,m=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],m+=d[S]*d[S];if(m=Math.sqrt(m),m===0)continue;let p=h/(o*m),y=this.calculateReuseInfo(f,p);i.push({pattern:f,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};it();Ce();F();function at(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ot(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=at(n,e.field);return ot(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var Me=1e4,Le=2166136261;function ke(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var oe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;oe[n]=e}var He="0123456789abcdef";function ct(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=He[s>>4]+He[s&15]}return t}function lt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ut(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function ht(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=oe[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function dt(n,e,t){return 1-ht(n,e,t)}var se=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=ke(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=lt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ut([r,s])}similarity(e,t){return dt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},ae=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Me,this.baseSeed=e?.seed??Le,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=ke(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:ct(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=oe[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new ne(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ue(n){return new ae(n)}function Qe(n){return Q()?new se(n):null}var ye=rt(je(),1),ge=ye.default??ye,_t=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{d as J,e as B,f as te,g as j}from"./chunk-2OM3TDC4.js";import{a as ne}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,i)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ve=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return H()?new ve(n):null}F();var Mt=128,Lt=8,kt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ve(n){return new Pe(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ye=1-_;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),s=Math.max(_,1-A(e)),i=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(_,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),s=Math.sqrt(A(t));if(s<_)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ye)return new Float32Array(e);let r=Ye/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},we=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,m=new Float32Array(r);m[0]=d*Math.cos(h),m[1]=d*Math.sin(h);let p=i.get(u);if(p&&p.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*N}let y=T.project(m);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=s.get(u)??[];for(let N=0;N<S.length;N++){let x=f/Math.max(1,S.length);c.push({id:S[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ke(n){return zt()?new we(n):null}function zt(){return D().useHyperbolicHnsw}F();var Se=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ke(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ze(n){return new Se(n)}var be=null;function et(){return be||(be=Ue({dimensions:1e4})),be}var Ee;function $t(){return Ee===void 0&&(Ee=Qe()),Ee}var U=null,Re=0;function tt(n){return(!U||Re!==n)&&(U=Ve({dimension:n,maxPatterns:1e4}),Re=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ae=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-TYPQ2T6P.js"),{HnswAdapter:c}=await import("./hnsw-adapter-YUJVSFPD.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-FQZ47RSJ.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=et().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=$t();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{tt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=tt(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let m=h.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,h.similarity);i.push({pattern:p,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let m of h){let p=await this.get(m.key);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,m.score);i.push({pattern:p,score:m.score,matchType:"vector",similarity:m.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(p=>[p.id,p.ftsScore])),m=new Set(i.map(p=>p.pattern.id));for(let p of i){let y=h.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of d){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);i.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(m=>m.pattern.id));for(let m of d)h.has(m.pattern.id)||i.push(m)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),m=c-h,p=Math.pow(.5,m/a),y=d.pattern.usageCount>0?p:.5;d.score=d.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ie(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let m=d.get(h.pattern.id);m&&(h.nullSummary=m,h.score=ie.applyNullDiscount(h.score,m,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&i&&this.hdcCache.size>0)try{let u=et(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,m)=>m.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),m=o?f*.4+d*.4+h*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(H()&&this.deltaTracker)try{let y={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=te(h);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Re=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ze({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Jr(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Te("fs"),{join:s}=Te("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let l=_e(a,u.embeddingDimension);if(l){o=!0;let f=new q(()=>l,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),f}}catch{}if(!o){let l=new q((f,d)=>{let h=()=>{try{return Fe(f)}catch{return null}},m=h();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return re(f,d)}catch(p){if(m=h(),m&&m.dimension()===d)return m;if(Ie(f,p instanceof Error?p.message:String(p)))return re(f,d);throw p}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ae(n,e)}export{Jr as a};
49
+ )`).run(e,e,i)}}};F();var Ht={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ve=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ht,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ge(n){return H()?new ve(n):null}F();var Mt=128,Lt=8,kt=1e4,Pe=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Mt,this.beta=e?.beta??Lt,this.maxPatterns=e?.maxPatterns??kt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ve(n){return new Pe(n)}F();var Ut={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,Ye=1-_;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function qt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(qt(e,t)),s=Math.max(_,1-A(e)),i=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(_,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),s=Math.sqrt(A(t));if(s<_)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ye)return new Float32Array(e);let r=Ye/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},we=class{config;points=new Map;constructor(e){if(this.config={...Ut,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,m=new Float32Array(r);m[0]=d*Math.cos(h),m[1]=d*Math.sin(h);let p=i.get(u);if(p&&p.features.length>0){let N=d*.1;for(let x=2;x<r&&x-2<p.features.length;x++)m[x]=p.features[x-2]*N}let y=T.project(m);t.set(u,y),this.points.set(u,{id:u,coordinates:y,metadata:{depth:o,parentId:p?.parentId}});let S=s.get(u)??[];for(let N=0;N<S.length;N++){let x=f/Math.max(1,S.length);c.push({id:S[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ke(n){return zt()?new we(n):null}function zt(){return D().useHyperbolicHnsw}F();var Se=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Ke(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ze(n){return new Se(n)}var be=null;function et(){return be||(be=Ue({dimensions:1e4})),be}var Ee;function $t(){return Ee===void 0&&(Ee=Qe()),Ee}var U=null,Re=0;function tt(n){return(!U||Re!==n)&&(U=Ve({dimension:n,maxPatterns:1e4}),Re=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Ae=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-322R2UAB.js"),{HnswAdapter:c}=await import("./hnsw-adapter-I4Y2T4HO.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-SBR5VYGN.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ge()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(Q())try{let a=et().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=$t();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{tt(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=tt(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let m=h.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,h.similarity);i.push({pattern:p,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let m of h){let p=await this.get(m.key);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,m.score);i.push({pattern:p,score:m.score,matchType:"vector",similarity:m.score,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(p=>[p.id,p.ftsScore])),m=new Set(i.map(p=>p.pattern.id));for(let p of i){let y=h.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of d){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let S=this.calculateReuseInfo(y,p.ftsScore);i.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(m=>m.pattern.id));for(let m of d)h.has(m.pattern.id)||i.push(m)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),m=c-h,p=Math.pow(.5,m/a),y=d.pattern.usageCount>0?p:.5;d.score=d.score*(.7+.3*y)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ie(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let m=d.get(h.pattern.id);m&&(h.nullSummary=m,h.score=ie.applyNullDiscount(h.score,m,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(Q()&&i&&this.hdcCache.size>0)try{let u=et(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,m)=>m.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),m=o?f*.4+d*.4+h*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(y))}if(H()&&this.deltaTracker)try{let y={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,y,S,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(y))}let m=te(h);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Re=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ze({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function Jr(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Te("fs"),{join:s}=Te("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let l=_e(a,u.embeddingDimension);if(l){o=!0;let f=new q(()=>l,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),f}}catch{}if(!o){let l=new q((f,d)=>{let h=()=>{try{return Fe(f)}catch{return null}},m=h();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return re(f,d)}catch(p){if(m=h(),m&&m.dimension()===d)return m;if(Ie(f,p instanceof Error?p.message:String(p)))return re(f,d);throw p}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Ae(n,e)}export{Jr as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{e as l,l as i}from"./chunk-RSCGBHLM.js";import{a as r,c as g}from"./chunk-AYYDO52G.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-I7ABQBBU.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{e as l,l as i}from"./chunk-JMRUHQEL.js";import{a as r,c as g}from"./chunk-IIZ3HBPV.js";g();var c=class extends i{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){try{let{runTestPipeline:n}=await import("./test-scheduling-A4OHR7KW.js"),d=await l(o),t=await n({cwd:s.cwd||process.cwd(),memory:d,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),u=t.phaseResults.reduce((e,a)=>e+a.totalTests,0),f=t.phaseResults.reduce((e,a)=>e+a.passed,0),p=t.phaseResults.reduce((e,a)=>e+a.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${u} tests (${f} passed, ${p} failed) in ${t.totalDurationMs}ms`}}}catch(n){return{success:!1,error:r(n)}}}};export{c as a};
@@ -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.13.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{a as h}from"./chunk-BBLWZT5I.js";import{c as m}from"./chunk-ELMUHNXN.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{a as h}from"./chunk-6UGYFYS4.js";import{c as m}from"./chunk-BSQ32ZS5.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{c as f}from"./chunk-OE4B6LDZ.js";import*as o from"fs";import*as n from"path";function u(){t=null}function g(c=process.cwd()){if(t)return t;if(process.env.AQE_PROJECT_ROOT)return t=process.env.AQE_PROJECT_ROOT,t;let l=c,a=n.parse(l).root,e=l,i=null,s=null,r=null;for(;e!==a;)o.existsSync(n.join(e,".agentic-qe"))&&i===null&&(i=e),o.existsSync(n.join(e,".git"))&&s===null&&(s=e),o.existsSync(n.join(e,"package.json"))&&(r=e),e=n.dirname(e);return i?t=i:s?t=s:r?t=r:t=process.cwd(),t}var t,p=f(()=>{"use strict";t=null});export{u as a,g as b,p as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{c as f}from"./chunk-AJ7A52GF.js";import*as o from"fs";import*as n from"path";function u(){t=null}function g(c=process.cwd()){if(t)return t;if(process.env.AQE_PROJECT_ROOT)return t=process.env.AQE_PROJECT_ROOT,t;let l=c,a=n.parse(l).root,e=l,i=null,s=null,r=null;for(;e!==a;)o.existsSync(n.join(e,".agentic-qe"))&&i===null&&(i=e),o.existsSync(n.join(e,".git"))&&s===null&&(s=e),o.existsSync(n.join(e,"package.json"))&&(r=e),e=n.dirname(e);return i?t=i:s?t=s:r?t=r:t=process.cwd(),t}var t,p=f(()=>{"use strict";t=null});export{u as a,g as b,p as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{b as m,c as y}from"./chunk-YBPCBFEE.js";import{e as S,f as A}from"./chunk-55WDVSCM.js";import{a as R,b as g,c as v}from"./chunk-QES4QHQW.js";import{a as p,g as b}from"./chunk-OE4B6LDZ.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{b as m,c as y}from"./chunk-REBNPQI7.js";import{e as S,f as A}from"./chunk-E6PYV3DB.js";import{a as R,b as g,c as v}from"./chunk-LEOSNZR2.js";import{a as p,g as b}from"./chunk-AJ7A52GF.js";y();var s=null,f=!1;function w(t){s=t,f=t!==null}var E=(()=>{let t=process.env.AQE_RVF_SIZE_GUARD_BYTES,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0?r:256*1024*1024})(),C=(()=>{let t=process.env.AQE_RVF_DEAD_RATIO_THRESHOLD,r=t?Number(t):NaN;return Number.isFinite(r)&&r>0&&r<=1?r:.3})();function _(t=".agentic-qe",r=384){if(f)return s;f=!0;try{let{isRvfNativeAvailable:e,createRvfStore:o,openRvfStore:i}=(A(),b(S));if(!e())return console.warn("[RVF] Native bindings unavailable \u2014 agent branching and dream COW disabled. Install @ruvector/rvf-node to enable."),null;let l=p("path"),c=l.isAbsolute(t)?t:l.join(process.env.AQE_PROJECT_ROOT??m(),t),u=l.join(c,"patterns.rvf");return s=$(i,o,u,r),N(s,u),s}catch(e){return console.warn("[RVF] Shared adapter init failed:",e instanceof Error?e.message:e),null}}function $(t,r,e,o){let i=()=>{try{return{adapter:t(e),err:null}}catch(n){return{adapter:null,err:n}}},l=n=>{let a=n instanceof Error?n.message:String(n);return a.includes("LockHeld")||a.includes("0x0300")},{adapter:c,err:u}=i();if(!c&&l(u))try{let n=p("fs"),a=`${e}.lock`;n.existsSync(a)&&g(e)?console.warn(`[RVF] ${e} is locked by a live process (pid ${R(e)}) \u2014 not breaking the lock; degrading to SQLite for this run.`):n.existsSync(a)&&(n.unlinkSync(a),console.warn(`[RVF] Removed stale lock file at ${a} (prior process exited without closing). Retrying open. If you see this repeatedly under live concurrency, file an issue.`),{adapter:c,err:u}=i())}catch(n){process.env.DEBUG&&console.debug("[RVF] stale-lock recovery failed:",n instanceof Error?n.message:n)}if(c){let n=c.dimension();if(n===o)return c;console.warn(`[RVF] patterns.rvf dimension mismatch: file=${n} requested=${o} \u2014 closing and degrading. Delete the .rvf file to recreate at the requested dim.`);try{c.close()}catch{}throw new Error(`RVF dimension mismatch (file=${n}, requested=${o})`)}try{return r(e,o)}catch(n){try{let a=t(e);if(a.dimension()!==o){try{a.close()}catch{}throw new Error(`RVF dimension mismatch after race (file=${a.dimension()}, requested=${o})`)}return a}catch{if(v(e,n instanceof Error?n.message:String(n)))return r(e,o);throw n instanceof Error?n:new Error(String(n))}}}function h(t,r){if(r?.force)return{shouldCompact:!0,trigger:"force"};let e=r?.sizeGuardBytes??E,o=r?.deadRatioThreshold??C;return t.fileSizeBytes>=e?{shouldCompact:!0,trigger:"size-guard"}:(t.deadSpaceRatio??0)>=o?{shouldCompact:!0,trigger:"dead-ratio"}:{shouldCompact:!1,trigger:"none"}}function k(t){if(!s)return null;let r;try{r=s.status()}catch{return null}let e=h(r,t);if(!e.shouldCompact)return null;let o=r.fileSizeBytes,i;try{i=s.compact()}catch{return null}return i?((i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] compacted patterns.rvf: reclaimed ${d(i.bytesReclaimed)} (${i.segmentsCompacted} segments, fileSize ${d(o)} \u2192 ${d(Math.max(0,o-i.bytesReclaimed))}, trigger: ${e.trigger})`),i):null}function N(t,r){try{let e=t.status(),o=h(e);if(!o.shouldCompact)return null;let i=t.compact();return i&&(i.bytesReclaimed>0||i.segmentsCompacted>0)&&console.log(`[RVF] boot-time compact (${r}): reclaimed ${d(i.bytesReclaimed)} from ${i.segmentsCompacted} segments (trigger: ${o.trigger})`),i}catch(e){return process.env.DEBUG&&console.debug("[RVF] boot-time compact guard skipped:",e instanceof Error?e.message:e),null}}function d(t){if(!Number.isFinite(t)||t<0)return`${t}B`;let r=["B","KB","MB","GB","TB"],e=0,o=t;for(;o>=1024&&e<r.length-1;)o/=1024,e++;return`${o.toFixed(e===0?0:1)}${r[e]}`}function T(){if(s){try{s.close()}catch{}s=null}f=!1}export{w as a,_ as b,h as c,k as d,N as e,T as f};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{a as P}from"./chunk-XFUF654L.js";import{b as w}from"./chunk-S6VNPKHO.js";import{e as S}from"./chunk-2OM3TDC4.js";import{a as H}from"./chunk-BBLWZT5I.js";import{c as A}from"./chunk-ELMUHNXN.js";import{b as E,d as q}from"./chunk-ZLCATRXI.js";import{S as $,j as T}from"./chunk-IJP42OGW.js";q();var W=["oracle:test-exec","judge:llm","proxy:structural"],d="proxy:structural";function j(n){return n&&W.includes(n)?n:d}function m(n,e={}){switch(j(n)){case"oracle:test-exec":return!0;case"judge:llm":return e.allowJudgeTier===!0;default:return!1}}import{createHash as O}from"node:crypto";function D(n,e){let t=n.length;if(t===0)return-1/0;let r=e?.iters??2e3,a=e?.alpha??.05,s=(e?.seed??2654435761)>>>0,o=()=>(s=Math.imul(s,1664525)+1013904223>>>0,s/4294967296),c=new Array(r);for(let u=0;u<r;u++){let l=0;for(let h=0;h<t;h++)l+=n[Math.floor(o()*t)];c[u]=l/t}c.sort((u,l)=>u-l);let i=Math.min(Math.floor(a*r),r-1);return c[i]}function L(n,e){let t=Math.min(n.length,e.length),r=new Array(t);for(let a=0;a<t;a++)r[a]=n[a]-e[a];return r}var U=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.candidateHeldOut>n.baselineHeldOut?w(n.candidateAnchorMean,n.baselineAnchorMean,n.anchorTol)?{promote:!0,reason:"held-out gain, no anchor regression, oracle-tier evidence"}:{promote:!1,reason:`anchor regression: ${n.candidateAnchorMean} < ${n.baselineAnchorMean} - ${n.anchorTol}`}:{promote:!1,reason:`held-out ${n.candidateHeldOut} did not beat baseline ${n.baselineHeldOut}`}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},C=8,x=1e-6,N=n=>n.reduce((e,t)=>e+t,0)/n.length,V=n=>{let e=U(n);if(!e.promote)return e;let t=n.candidateHeldOutSamples,r=n.baselineHeldOutSamples;if(!t||!r||t.length===0||t.length!==r.length)return{promote:!1,reason:"significance gate: missing/mismatched paired held-out samples (need equal-length candidate & baseline per-task vectors)"};if(t.length<C)return{promote:!1,reason:`significance gate: only ${t.length} paired samples (< ${C}) \u2014 a bootstrap CI is not meaningful; fail closed rather than certify noise`};if(Math.abs(N(t)-n.candidateHeldOut)>x||Math.abs(N(r)-n.baselineHeldOut)>x)return{promote:!1,reason:"significance gate: sealed sample means do not match the sealed held-out scalars \u2014 inconsistent/forged evaluation"};let a=D(L(t,r));return a>0?{promote:!0,reason:`${e.reason}; paired gain significant (CI low ${a.toFixed(4)} > 0)`}:{promote:!1,reason:`significance gate: paired held-out gain not significant (95% CI lower bound ${a.toFixed(4)} \u2264 0)`}},se=Object.freeze({"accept/v1":U,"accept/v1+sig":V});function _(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(_).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${_(e[r])}`).join(",")}}`}var Q="aqe:promotion-path-rule:v1+sig",J=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.reward===void 0||n.rewardThreshold===void 0||!(n.reward>=n.rewardThreshold)?{promote:!1,reason:`reward ${n.reward} below threshold ${n.rewardThreshold}`}:n.occurrences===void 0||n.occurrenceThreshold===void 0||!(n.occurrences>=n.occurrenceThreshold)?{promote:!1,reason:`occurrences ${n.occurrences} below threshold ${n.occurrenceThreshold}`}:n.successRate===void 0||n.successRateThreshold===void 0||!(n.successRate>=n.successRateThreshold)?{promote:!1,reason:`success rate ${n.successRate} below threshold ${n.successRateThreshold}`}:n.withinActivityWindow!==!0?{promote:!1,reason:"pattern outside promotion activity window (stale)"}:{promote:!0,reason:"tier allowed; reward/occurrence/success-rate thresholds met; within activity window"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},G=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.insightConfidence===void 0||n.insightConfidenceThreshold===void 0||!(n.insightConfidence>=n.insightConfidenceThreshold)?{promote:!1,reason:`insight confidence ${n.insightConfidence} below threshold ${n.insightConfidenceThreshold}`}:n.insightActionable!==!0?{promote:!1,reason:"insight produced no actionable reorganization"}:{promote:!0,reason:"tier allowed; insight confidence meets threshold; actionable"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to apply`},M=Object.freeze({"pattern-promote/v1":J,"dream-apply/v1":G});function b(n){return O("sha256").update(_(n)).digest("hex")}function y(n){if(!(n in M))throw new Error(`Unknown promotion-path rule version '${n}' \u2014 cannot fingerprint an unregistered rule.`);return O("sha256").update(Q).update("\0").update(n).digest("hex")}function R(n,e){let t=M[n];if(!t)throw new Error(`Unknown promotion-path rule version '${n}' \u2014 refusing to re-execute an unregistered rule.`);return t(e)}function I(n,e={}){let t=[],r=b(n.sealed)===n.sealedHash;r||t.push("sealIntact");let a=!1;try{let c=y(n.ruleVersion);a=n.ruleFingerprint===c&&(e.pinnedRuleFingerprint===void 0||n.ruleFingerprint===e.pinnedRuleFingerprint)}catch{a=!1}a||t.push("gateUnchanged");let s=!1;r&&a&&(s=(R(n.ruleVersion,n.sealed).promote?"promote":"reject")===n.recordedVerdict),s||t.push("gateReExecutes");let o=t.length===0;return{valid:o,checks:{sealIntact:r,gateUnchanged:a,gateReExecutes:s},failures:t,reason:o?"promotion verified: sealed inputs intact, rule unchanged, frozen rule re-execution reproduces the recorded verdict":`promotion INVALID (failed: ${t.join(", ")}) \u2014 the recorded verdict is not reproducible under the frozen rule`}}H();$();var p=A.create("pattern-lifecycle"),z={promotionRewardThreshold:.7,promotionMinOccurrences:S,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{},allowJudgeTierPromotion:!1},k=5,B=.9,X=2;function Y(n,e){return e<k||!Number.isFinite(n)?0:Math.min(Math.max(n,0),1)}var v=class{constructor(e,t={}){this.db=e;this.config={...z,...t},this.asymmetricEngine=new P(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{a as P}from"./chunk-MBTVAIFF.js";import{b as w}from"./chunk-N4O2RWSL.js";import{e as S}from"./chunk-FJ2L6P7O.js";import{a as H}from"./chunk-6UGYFYS4.js";import{c as A}from"./chunk-BSQ32ZS5.js";import{b as E,d as q}from"./chunk-FMYNKZ2S.js";import{S as $,j as T}from"./chunk-GZ775E5O.js";q();var W=["oracle:test-exec","judge:llm","proxy:structural"],d="proxy:structural";function j(n){return n&&W.includes(n)?n:d}function m(n,e={}){switch(j(n)){case"oracle:test-exec":return!0;case"judge:llm":return e.allowJudgeTier===!0;default:return!1}}import{createHash as O}from"node:crypto";function D(n,e){let t=n.length;if(t===0)return-1/0;let r=e?.iters??2e3,a=e?.alpha??.05,s=(e?.seed??2654435761)>>>0,o=()=>(s=Math.imul(s,1664525)+1013904223>>>0,s/4294967296),c=new Array(r);for(let u=0;u<r;u++){let l=0;for(let h=0;h<t;h++)l+=n[Math.floor(o()*t)];c[u]=l/t}c.sort((u,l)=>u-l);let i=Math.min(Math.floor(a*r),r-1);return c[i]}function L(n,e){let t=Math.min(n.length,e.length),r=new Array(t);for(let a=0;a<t;a++)r[a]=n[a]-e[a];return r}var U=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.candidateHeldOut>n.baselineHeldOut?w(n.candidateAnchorMean,n.baselineAnchorMean,n.anchorTol)?{promote:!0,reason:"held-out gain, no anchor regression, oracle-tier evidence"}:{promote:!1,reason:`anchor regression: ${n.candidateAnchorMean} < ${n.baselineAnchorMean} - ${n.anchorTol}`}:{promote:!1,reason:`held-out ${n.candidateHeldOut} did not beat baseline ${n.baselineHeldOut}`}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},C=8,x=1e-6,N=n=>n.reduce((e,t)=>e+t,0)/n.length,V=n=>{let e=U(n);if(!e.promote)return e;let t=n.candidateHeldOutSamples,r=n.baselineHeldOutSamples;if(!t||!r||t.length===0||t.length!==r.length)return{promote:!1,reason:"significance gate: missing/mismatched paired held-out samples (need equal-length candidate & baseline per-task vectors)"};if(t.length<C)return{promote:!1,reason:`significance gate: only ${t.length} paired samples (< ${C}) \u2014 a bootstrap CI is not meaningful; fail closed rather than certify noise`};if(Math.abs(N(t)-n.candidateHeldOut)>x||Math.abs(N(r)-n.baselineHeldOut)>x)return{promote:!1,reason:"significance gate: sealed sample means do not match the sealed held-out scalars \u2014 inconsistent/forged evaluation"};let a=D(L(t,r));return a>0?{promote:!0,reason:`${e.reason}; paired gain significant (CI low ${a.toFixed(4)} > 0)`}:{promote:!1,reason:`significance gate: paired held-out gain not significant (95% CI lower bound ${a.toFixed(4)} \u2264 0)`}},se=Object.freeze({"accept/v1":U,"accept/v1+sig":V});function _(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(_).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${_(e[r])}`).join(",")}}`}var Q="aqe:promotion-path-rule:v1+sig",J=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.reward===void 0||n.rewardThreshold===void 0||!(n.reward>=n.rewardThreshold)?{promote:!1,reason:`reward ${n.reward} below threshold ${n.rewardThreshold}`}:n.occurrences===void 0||n.occurrenceThreshold===void 0||!(n.occurrences>=n.occurrenceThreshold)?{promote:!1,reason:`occurrences ${n.occurrences} below threshold ${n.occurrenceThreshold}`}:n.successRate===void 0||n.successRateThreshold===void 0||!(n.successRate>=n.successRateThreshold)?{promote:!1,reason:`success rate ${n.successRate} below threshold ${n.successRateThreshold}`}:n.withinActivityWindow!==!0?{promote:!1,reason:"pattern outside promotion activity window (stale)"}:{promote:!0,reason:"tier allowed; reward/occurrence/success-rate thresholds met; within activity window"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to promote`},G=n=>m(n.provenanceTier,{allowJudgeTier:n.allowJudgeTier})?n.insightConfidence===void 0||n.insightConfidenceThreshold===void 0||!(n.insightConfidence>=n.insightConfidenceThreshold)?{promote:!1,reason:`insight confidence ${n.insightConfidence} below threshold ${n.insightConfidenceThreshold}`}:n.insightActionable!==!0?{promote:!1,reason:"insight produced no actionable reorganization"}:{promote:!0,reason:"tier allowed; insight confidence meets threshold; actionable"}:{promote:!1,reason:`provenance tier '${n.provenanceTier}' not allowed to apply`},M=Object.freeze({"pattern-promote/v1":J,"dream-apply/v1":G});function b(n){return O("sha256").update(_(n)).digest("hex")}function y(n){if(!(n in M))throw new Error(`Unknown promotion-path rule version '${n}' \u2014 cannot fingerprint an unregistered rule.`);return O("sha256").update(Q).update("\0").update(n).digest("hex")}function R(n,e){let t=M[n];if(!t)throw new Error(`Unknown promotion-path rule version '${n}' \u2014 refusing to re-execute an unregistered rule.`);return t(e)}function I(n,e={}){let t=[],r=b(n.sealed)===n.sealedHash;r||t.push("sealIntact");let a=!1;try{let c=y(n.ruleVersion);a=n.ruleFingerprint===c&&(e.pinnedRuleFingerprint===void 0||n.ruleFingerprint===e.pinnedRuleFingerprint)}catch{a=!1}a||t.push("gateUnchanged");let s=!1;r&&a&&(s=(R(n.ruleVersion,n.sealed).promote?"promote":"reject")===n.recordedVerdict),s||t.push("gateReExecutes");let o=t.length===0;return{valid:o,checks:{sealIntact:r,gateUnchanged:a,gateReExecutes:s},failures:t,reason:o?"promotion verified: sealed inputs intact, rule unchanged, frozen rule re-execution reproduces the recorded verdict":`promotion INVALID (failed: ${t.join(", ")}) \u2014 the recorded verdict is not reproducible under the frozen rule`}}H();$();var p=A.create("pattern-lifecycle"),z={promotionRewardThreshold:.7,promotionMinOccurrences:S,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{},allowJudgeTierPromotion:!1},k=5,B=.9,X=2;function Y(n,e){return e<k||!Number.isFinite(n)?0:Math.min(Math.max(n,0),1)}var v=class{constructor(e,t={}){this.db=e;this.config={...z,...t},this.asymmetricEngine=new P(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
3
3
  SELECT deprecated_at FROM qe_patterns LIMIT 1
4
4
  `).get()}catch(e){p.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
5
5
  ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
2
- import{a as U,b as G}from"./chunk-YRVUYM62.js";import{h as N}from"./chunk-HFI5PHG5.js";import{a as W}from"./chunk-GASOBSNB.js";import{e as F}from"./chunk-2OM3TDC4.js";import{b as v,c as x}from"./chunk-2G2QWV7B.js";import{a as re}from"./chunk-BBLWZT5I.js";import{c as O}from"./chunk-ELMUHNXN.js";import{b as k,d as q}from"./chunk-ZLCATRXI.js";import{b,c as E}from"./chunk-GTPZVLL6.js";import{a as y,c as I}from"./chunk-AYYDO52G.js";import{i as z}from"./chunk-ZIBW7CB4.js";import{S as ae,b as _}from"./chunk-IJP42OGW.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-P5YVLMFI.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
+ import{a as U,b as G}from"./chunk-COOMXCCP.js";import{h as N}from"./chunk-62D27BDO.js";import{a as W}from"./chunk-Q625ISQI.js";import{e as F}from"./chunk-FJ2L6P7O.js";import{b as v,c as x}from"./chunk-4DKL4H5L.js";import{a as re}from"./chunk-6UGYFYS4.js";import{c as O}from"./chunk-BSQ32ZS5.js";import{b as k,d as q}from"./chunk-FMYNKZ2S.js";import{b,c as E}from"./chunk-E6JJ4ZRQ.js";import{a as y,c as I}from"./chunk-IIZ3HBPV.js";import{i as z}from"./chunk-SOOI2HJB.js";import{S as ae,b as _}from"./chunk-GZ775E5O.js";import{randomUUID as Y}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var B=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",B,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let o=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(o?.[1])return o[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),o=["--no-install",B,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&o.push("--result",i),n!==void 0&&o.push("--quality",String(n)),a("npx",o,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",B,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-BEUZQTTC.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(s=>s.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
3
3
  INSERT OR REPLACE INTO qe_trajectories
4
4
  (id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
5
5
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -9,4 +9,4 @@ Steps:
9
9
  ${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
10
10
  `)}
11
11
 
12
- Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-N5D3NSJ7.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-LTV7H2HM.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-LTV7H2HM.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-U26YP3N3.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-U26YP3N3.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-WBOHE2XL.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-NFCAYUWO.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-2OQDOD3G.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
12
+ Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){T.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:F},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-UQ4O46ZI.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-NCRHNFQM.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-NCRHNFQM.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-TVEQGCSB.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),o=i(a),s=t(o);this.experienceCapture.setWitnessChain(s)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}try{let{getUnifiedPersistence:e}=await import("./unified-persistence-TVEQGCSB.js"),t=e();if(t.isInitialized()){let{PatternNullStore:i}=await import("./pattern-null-store-V7DEZEF2.js"),n=new i(t.getDatabase());this.experienceCapture.setNullRecorder(r=>n.recordNull(r))}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Null recorder wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-SCQ35J6M.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-HSEUUM7E.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let o=r.byDomain?.[a]??0,s=r.totalPatterns??0;return{domain:a,successRate:s>0?o/s:.5,avgConfidence:r.avgConfidence??.5,patternCount:o,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain,contextFingerprint:e.domain?`${e.domain}:router`:void 0});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,contextFingerprint:t.contextFingerprint,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(s=>s.similarity>=.5&&s.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(s=>{let u=s.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(s.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(s=>s.pattern)],o=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((s,u)=>s+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+o,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(d){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(d))}let a=`${i??"unknown"}:${t??"unknown"}`,o;try{let d=await this.searchPatternsForTask(e,{domain:i,contextFingerprint:a});d.success&&d.value.length>0&&(o=d.value.map(g=>g.pattern.id))}catch{}let s;this.experienceCapture&&(s=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0,appliedPatterns:o}));let u={id:s||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(u.id,u),u.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),o=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],s=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(o,{cwd:e,ignore:s,onlyFiles:!0}),d=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&d.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&d.add("javascript"),m.endsWith(".py")&&d.add("python"),m.endsWith(".go")&&d.add("go"),m.endsWith(".rs")&&d.add("rust");let w=a(e,"package.json");if(n(w))try{let m=k(r(w,"utf-8")),p={...m.dependencies,...m.devDependencies};p.react&&g.add("react"),p.vue&&g.add("vue"),p.vitest&&g.add("vitest"),p.jest&&g.add("jest"),p.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(d),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),o=h(i.map(c=>c.tokenMetrics.costUsd)),s=h(n.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),d=h(n.map(c=>c.tokenMetrics.savingsUsd));if(s>o*1.1&&d<=u*1.05){let c=Math.min(1,(s-o)/(o||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((s/(o||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:A(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:A(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let p=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-p),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:A(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),j=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(j>C*1.2&&C>0){let c=Math.min(1,(j-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${j.toFixed(0)}ms`,confidence:A(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function A(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.1");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.2");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};