agentic-qe 3.9.31 → 3.9.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +88 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-CDQOF5TF.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-AQXZYWZY.js → agent-booster-wasm-WKS3E6KT.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-7N4ZPXCY.js → agent-handler-LYCAWE7S.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-FLKF2JVX.js → agent-memory-branch-XF7IOMRK.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +2 -0
  10. package/dist/cli/chunks/{audit-B4V4IKTA.js → audit-D2AY3HFP.js} +2 -2
  11. package/dist/cli/chunks/base-UGH6TVO4.js +2 -0
  12. package/dist/cli/chunks/{hnswlib-node-WENGW3YX.js → better-sqlite3-K2VWFDKT.js} +2 -2
  13. package/dist/cli/chunks/{brain-handler-OOXJ2KYY.js → brain-handler-NNW4TAO2.js} +3 -3
  14. package/dist/cli/chunks/{branch-enumerator-LFKFW3A4.js → branch-enumerator-OM5HNZKV.js} +2 -2
  15. package/dist/cli/chunks/{browser-F72IES2I.js → browser-Y2FU2NV4.js} +2 -2
  16. package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +2 -0
  17. package/dist/cli/chunks/{chunk-35SFAIXE.js → chunk-2L5GAOST.js} +2 -2
  18. package/dist/cli/chunks/{chunk-MAJ5QFVY.js → chunk-2XC4XVCI.js} +1 -1
  19. package/dist/cli/chunks/{chunk-QEJBJST4.js → chunk-2Z2IQBIJ.js} +1 -1
  20. package/dist/cli/chunks/{chunk-AKFRM4IO.js → chunk-33PGBYTC.js} +2 -2
  21. package/dist/cli/chunks/{chunk-W7XVEWKQ.js → chunk-3MHWBCSC.js} +1 -1
  22. package/dist/cli/chunks/{chunk-NBKM7NKX.js → chunk-3R4CMTWF.js} +2 -2
  23. package/dist/cli/chunks/{chunk-4N736EES.js → chunk-45N22VAB.js} +2 -2
  24. package/dist/cli/chunks/{chunk-3VKB4HVT.js → chunk-4H4PEZUX.js} +2 -2
  25. package/dist/cli/chunks/{chunk-CFLA2GBS.js → chunk-4VAZSCTZ.js} +2 -2
  26. package/dist/cli/chunks/{chunk-JF3U456G.js → chunk-5A6LBGRU.js} +2 -2
  27. package/dist/cli/chunks/{chunk-TYUIQSSF.js → chunk-5DSANX6S.js} +2 -2
  28. package/dist/cli/chunks/chunk-5R5WOLZM.js +5 -0
  29. package/dist/cli/chunks/{chunk-K6MFAVXK.js → chunk-5WR42V5O.js} +2 -2
  30. package/dist/cli/chunks/{chunk-PUSZ4NBY.js → chunk-5XY6SULI.js} +2 -2
  31. package/dist/cli/chunks/{chunk-VOOJDHLI.js → chunk-62UXGD5J.js} +3 -3
  32. package/dist/cli/chunks/{chunk-REJEFTWX.js → chunk-667I4RTC.js} +1 -1
  33. package/dist/cli/chunks/{chunk-KXRDQQGN.js → chunk-6EKXBWJD.js} +2 -2
  34. package/dist/cli/chunks/{chunk-CNKOIHF6.js → chunk-6R6QCGNU.js} +2 -2
  35. package/dist/cli/chunks/{chunk-YEZJE2ZW.js → chunk-6SYP7QX6.js} +4 -4
  36. package/dist/cli/chunks/{chunk-TLCCM2AF.js → chunk-6YGFAJ3X.js} +1 -1
  37. package/dist/cli/chunks/{chunk-KJAIE7SL.js → chunk-6ZG6TBWF.js} +4 -4
  38. package/dist/cli/chunks/{chunk-NLUBN642.js → chunk-7AISRWBS.js} +2 -2
  39. package/dist/cli/chunks/{chunk-LF5RO6WO.js → chunk-7IDPVSTF.js} +1 -1
  40. package/dist/cli/chunks/{chunk-VUL5HIKR.js → chunk-7PTW3M67.js} +2 -2
  41. package/dist/cli/chunks/{chunk-QGLWFZVQ.js → chunk-A4UNK5SY.js} +2 -2
  42. package/dist/cli/chunks/{chunk-JRIDPOEZ.js → chunk-A6VI5BZU.js} +4 -4
  43. package/dist/cli/chunks/{chunk-7OVVBBOZ.js → chunk-BBPOTFIY.js} +2 -2
  44. package/dist/cli/chunks/{chunk-AKJWBJDK.js → chunk-BDXEL3GM.js} +2 -2
  45. package/dist/cli/chunks/{chunk-GJSH4UZ3.js → chunk-BGRC4676.js} +3 -3
  46. package/dist/cli/chunks/{chunk-PSF6YQQM.js → chunk-BQML7B4W.js} +3 -3
  47. package/dist/cli/chunks/{chunk-VAIOZDG5.js → chunk-BV3SGEV7.js} +1 -1
  48. package/dist/cli/chunks/{chunk-XNJ6DIEW.js → chunk-DBE2LIYG.js} +2 -2
  49. package/dist/cli/chunks/{chunk-AQN6PDHI.js → chunk-DFY7F4TE.js} +1 -1
  50. package/dist/cli/chunks/{chunk-IRRGUXAU.js → chunk-EFEJLZDN.js} +1 -1
  51. package/dist/cli/chunks/{chunk-5G2L4XRU.js → chunk-ESNBKAT6.js} +2 -2
  52. package/dist/cli/chunks/{chunk-7UHRT5AX.js → chunk-EVSUZKD5.js} +2 -2
  53. package/dist/cli/chunks/{chunk-FUHPLXJX.js → chunk-FFBF5BLQ.js} +1 -1
  54. package/dist/cli/chunks/{chunk-N6P7ENG7.js → chunk-FIONYUVH.js} +2 -2
  55. package/dist/cli/chunks/{chunk-TJGIIGKL.js → chunk-FNQCWEVJ.js} +2 -2
  56. package/dist/cli/chunks/{chunk-NTVJKQ5S.js → chunk-FV2MU6CY.js} +2 -2
  57. package/dist/cli/chunks/{chunk-M6RVKGIP.js → chunk-FWEYOD3S.js} +2 -2
  58. package/dist/cli/chunks/{chunk-EAIPJSKH.js → chunk-G6AJMFWL.js} +3 -3
  59. package/dist/cli/chunks/{chunk-L7DNPOAQ.js → chunk-G6VVOUUF.js} +2 -2
  60. package/dist/cli/chunks/{chunk-BYHUGO73.js → chunk-G77CYF7H.js} +3 -3
  61. package/dist/cli/chunks/{chunk-EJXRBAQF.js → chunk-H7YKTJMY.js} +2 -2
  62. package/dist/cli/chunks/{chunk-CUSLB7MB.js → chunk-HGWQC7PR.js} +2 -2
  63. package/dist/cli/chunks/{chunk-XE4YKDIM.js → chunk-HHBFI3YA.js} +2 -2
  64. package/dist/cli/chunks/{chunk-PTOTOBOU.js → chunk-HPQZSXED.js} +1 -1
  65. package/dist/cli/chunks/{chunk-YN7HCVUP.js → chunk-HR6NX6DW.js} +2 -2
  66. package/dist/cli/chunks/{chunk-QITO7E7Y.js → chunk-I6Q6BPVH.js} +1 -1
  67. package/dist/cli/chunks/{chunk-L63KB63A.js → chunk-IGEZVFOM.js} +2 -2
  68. package/dist/cli/chunks/{chunk-ENCFLC44.js → chunk-IGQPGXP7.js} +2 -2
  69. package/dist/cli/chunks/{chunk-YMN4C32S.js → chunk-IJQJV7BC.js} +3 -3
  70. package/dist/cli/chunks/chunk-JDW6GN3A.js +2 -0
  71. package/dist/cli/chunks/{chunk-LRWRFKQH.js → chunk-JRYNHFZA.js} +1 -1
  72. package/dist/cli/chunks/{chunk-7V7TP242.js → chunk-KHZRNJ3A.js} +1 -1
  73. package/dist/cli/chunks/{chunk-PYYNY7RJ.js → chunk-LHDTXTS7.js} +1 -1
  74. package/dist/cli/chunks/{chunk-ONMJJ2C3.js → chunk-LI2IOJMM.js} +1 -1
  75. package/dist/cli/chunks/{heartbeat-scheduler-OH3SS7MH.js → chunk-LR5VW3OS.js} +2 -2
  76. package/dist/cli/chunks/{chunk-XY3WUGD3.js → chunk-LTSNDM5N.js} +2 -2
  77. package/dist/cli/chunks/{chunk-CQWZNVIM.js → chunk-M5PYPGBC.js} +2 -2
  78. package/dist/cli/chunks/{chunk-RTGNWRQI.js → chunk-MEHNT37H.js} +2 -2
  79. package/dist/cli/chunks/{chunk-ZG4EKPGV.js → chunk-MERMCKPG.js} +1 -1
  80. package/dist/cli/chunks/{chunk-JKKV5KKS.js → chunk-MIHQIAVK.js} +2 -2
  81. package/dist/cli/chunks/{chunk-RDJWUKIR.js → chunk-MMVSERJQ.js} +2 -2
  82. package/dist/cli/chunks/{chunk-5WWQLPB4.js → chunk-MQQANXFS.js} +2 -2
  83. package/dist/cli/chunks/{chunk-I3TFGMOQ.js → chunk-MTOHV22P.js} +1 -1
  84. package/dist/cli/chunks/{chunk-7RPEBKQZ.js → chunk-NVZHCAEB.js} +2 -2
  85. package/dist/cli/chunks/{chunk-52D3CYE5.js → chunk-NW5FYGDE.js} +2 -2
  86. package/dist/cli/chunks/{chunk-UIRTXM7C.js → chunk-NZRJWK5H.js} +61 -121
  87. package/dist/cli/chunks/chunk-O5NEZCTB.js +2 -0
  88. package/dist/cli/chunks/{chunk-YQJBE6NX.js → chunk-O5UGJ3OI.js} +2 -2
  89. package/dist/cli/chunks/{chunk-WB6TI6Q3.js → chunk-OK2TFTXP.js} +2 -2
  90. package/dist/cli/chunks/{chunk-NNF3GCGF.js → chunk-OKEHGXIS.js} +2 -2
  91. package/dist/cli/chunks/{chunk-5AMAJCZS.js → chunk-OKRY4LNE.js} +3 -3
  92. package/dist/cli/chunks/{chunk-NZQYNUGM.js → chunk-OMOGD2NN.js} +2 -2
  93. package/dist/cli/chunks/{chunk-X2FLWV5C.js → chunk-ONNTJXU7.js} +2 -2
  94. package/dist/cli/chunks/{chunk-MYCVU3D3.js → chunk-OPOGZAN5.js} +2 -2
  95. package/dist/cli/chunks/{chunk-ZBJRNCWX.js → chunk-PG5F2VHA.js} +2 -2
  96. package/dist/cli/chunks/{chunk-JMLOEW7Y.js → chunk-PHRMWRXA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-N6SIKSCO.js → chunk-PIXUX2NR.js} +2 -2
  98. package/dist/cli/chunks/{chunk-IY4P35N3.js → chunk-PLGMPG7S.js} +2 -2
  99. package/dist/cli/chunks/{chunk-K37CNLQZ.js → chunk-PPS6VN24.js} +1 -1
  100. package/dist/cli/chunks/{chunk-XMMWYQJK.js → chunk-PQAYCK2U.js} +2 -2
  101. package/dist/cli/chunks/{chunk-SL4TAJOE.js → chunk-PS6ISBED.js} +2 -2
  102. package/dist/cli/chunks/{chunk-OXOXNAEZ.js → chunk-QPYNQSWD.js} +2 -2
  103. package/dist/cli/chunks/{chunk-62KYX5NH.js → chunk-QRTZ67BC.js} +2 -2
  104. package/dist/cli/chunks/{chunk-DUF733Z7.js → chunk-REW3W3ZW.js} +1 -1
  105. package/dist/cli/chunks/{chunk-T4DDCMKG.js → chunk-RHXYZ6AZ.js} +127 -127
  106. package/dist/cli/chunks/{chunk-VLAGWLHF.js → chunk-RZXAXWBD.js} +2 -2
  107. package/dist/cli/chunks/{chunk-XTWYCMAM.js → chunk-S4M7U6CZ.js} +2 -2
  108. package/dist/cli/chunks/{chunk-ROEIR3OD.js → chunk-SJETAUZA.js} +1 -1
  109. package/dist/cli/chunks/{chunk-47QIAHUJ.js → chunk-SLH7LFVY.js} +2 -2
  110. package/dist/cli/chunks/{chunk-XGBIXRKD.js → chunk-SRJ5N7LD.js} +2 -2
  111. package/dist/cli/chunks/{chunk-EKYPQ5DX.js → chunk-T5ADVYPH.js} +1 -1
  112. package/dist/cli/chunks/{chunk-7MXQV7RB.js → chunk-THYGFSTA.js} +2 -2
  113. package/dist/cli/chunks/{chunk-462MZLJB.js → chunk-TX2DBLTL.js} +1 -1
  114. package/dist/cli/chunks/{chunk-TVHWI77X.js → chunk-UJMGNO6L.js} +1 -1
  115. package/dist/cli/chunks/{chunk-YLEMSN46.js → chunk-UUQ3SOKM.js} +1 -1
  116. package/dist/cli/chunks/{chunk-ZWSRIJ2T.js → chunk-V5RLGPEW.js} +2 -2
  117. package/dist/cli/chunks/{chunk-CYUGE5ZQ.js → chunk-V6HM2BKJ.js} +1 -1
  118. package/dist/cli/chunks/{chunk-UIIEZMSM.js → chunk-V7I6FTLG.js} +1 -1
  119. package/dist/cli/chunks/{chunk-5M4F3PAL.js → chunk-V7ZBPSVG.js} +1 -1
  120. package/dist/cli/chunks/{chunk-VSKABN3B.js → chunk-VJL7DNUU.js} +2 -2
  121. package/dist/cli/chunks/{chunk-2NLZXG6V.js → chunk-VKCWWR6C.js} +1 -1
  122. package/dist/cli/chunks/chunk-VKNCMGOJ.js +29 -0
  123. package/dist/cli/chunks/{chunk-L4JTTPU7.js → chunk-W2VTHUDK.js} +2 -2
  124. package/dist/cli/chunks/{chunk-FOAWHNOP.js → chunk-W3JB3G7C.js} +2 -2
  125. package/dist/cli/chunks/{chunk-A424Z7LA.js → chunk-WQ4MT74X.js} +1 -1
  126. package/dist/cli/chunks/{chunk-GQFAVT2I.js → chunk-WTNM7NA4.js} +1 -1
  127. package/dist/cli/chunks/chunk-XB3SIYGU.js +62 -0
  128. package/dist/cli/chunks/{chunk-HHEIQHLQ.js → chunk-XCUNQ3FK.js} +2 -2
  129. package/dist/cli/chunks/{chunk-BMS7WFDB.js → chunk-XHQFVTFD.js} +1 -1
  130. package/dist/cli/chunks/{chunk-QMSDKKYG.js → chunk-YBUUAFKR.js} +1 -1
  131. package/dist/cli/chunks/{chunk-G2U7Q6V6.js → chunk-YJV6TTCW.js} +2 -2
  132. package/dist/cli/chunks/{chunk-GN7FUCJH.js → chunk-YUSGT2CU.js} +1 -1
  133. package/dist/cli/chunks/{chunk-JJRZOLDY.js → chunk-YUTSN5BK.js} +2 -2
  134. package/dist/cli/chunks/{chunk-G3YKCZWQ.js → chunk-YVMJTBXB.js} +3 -3
  135. package/dist/cli/chunks/chunk-YVQ4PR4H.js +2 -0
  136. package/dist/cli/chunks/{chunk-UNXUSYRL.js → chunk-Z2EDNMCQ.js} +2 -2
  137. package/dist/cli/chunks/{chunk-DMF4Z2M6.js → chunk-ZESMMAKZ.js} +2 -2
  138. package/dist/cli/chunks/{chunk-VA45HLBF.js → chunk-ZIVOT3B7.js} +2 -2
  139. package/dist/cli/chunks/{ci-LRTJSZHT.js → ci-NSF6OHB4.js} +2 -2
  140. package/dist/cli/chunks/{ci-output-LISCHUKD.js → ci-output-ZPDJ42U3.js} +2 -2
  141. package/dist/cli/chunks/{circuit-breaker-7PMP25KZ.js → circuit-breaker-Y2RUJDYG.js} +2 -2
  142. package/dist/cli/chunks/{claude-flow-setup-DOW4QVMC.js → claude-flow-setup-OH6G6KM2.js} +2 -2
  143. package/dist/cli/chunks/client-QQGRKAY7.js +2 -0
  144. package/dist/cli/chunks/{cline-installer-2NXQGW73.js → cline-installer-IHH4F27G.js} +2 -2
  145. package/dist/cli/chunks/{code-3X6RWAS7.js → code-SFAHWFTX.js} +2 -2
  146. package/dist/cli/chunks/{code-index-extractor-4ABP5WCP.js → code-index-extractor-GXECMOM2.js} +2 -2
  147. package/dist/cli/chunks/{codex-installer-V7PII6GL.js → codex-installer-UPMSAFCQ.js} +2 -2
  148. package/dist/cli/chunks/{completions-Y7LNQ63I.js → completions-5TX6LDHY.js} +2 -2
  149. package/dist/cli/chunks/{complexity-analyzer-XLYMAM6I.js → complexity-analyzer-J2ZR3XZB.js} +2 -2
  150. package/dist/cli/chunks/{continuedev-installer-GOT4TKNT.js → continuedev-installer-GWYZKB5A.js} +2 -2
  151. package/dist/cli/chunks/{copilot-installer-D6BAQVIO.js → copilot-installer-DQZMQWI7.js} +2 -2
  152. package/dist/cli/chunks/{cost-tracker-VT7C5Q52.js → cost-tracker-V7KIGCLZ.js} +2 -2
  153. package/dist/cli/chunks/{coverage-C62MRP4M.js → coverage-3X6LA2GZ.js} +3 -3
  154. package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +2 -0
  155. package/dist/cli/chunks/{cursor-installer-WAWSS2K2.js → cursor-installer-ENDG4JIU.js} +2 -2
  156. package/dist/cli/chunks/daemon-4XVAO7GT.js +16 -0
  157. package/dist/cli/chunks/daemon-TC65CQFK.js +10 -0
  158. package/dist/cli/chunks/{dag-attention-scheduler-SZIZWPV7.js → dag-attention-scheduler-JOSCDRZC.js} +2 -2
  159. package/dist/cli/chunks/{detect-AJX6NJEP.js → detect-KWZX3OMK.js} +2 -2
  160. package/dist/cli/chunks/{dist-node-E5X47QTY.js → dist-node-R4U2PJ47.js} +2 -2
  161. package/dist/cli/chunks/{domain-handler-FN3PIP45.js → domain-handler-BMYYZO2L.js} +2 -2
  162. package/dist/cli/chunks/{domain-transfer-N3TOJEMT.js → domain-transfer-MSDBBDLC.js} +2 -2
  163. package/dist/cli/chunks/dream-OCZK42FM.js +2 -0
  164. package/dist/cli/chunks/{embed-and-insert-pattern-PJI5TZKR.js → embed-and-insert-pattern-MFINPOLS.js} +2 -2
  165. package/dist/cli/chunks/{eval-OS54TDQU.js → eval-OER6UNUY.js} +2 -2
  166. package/dist/cli/chunks/{experience-capture-middleware-FBM4ANZW.js → experience-capture-middleware-F5I77ECG.js} +3 -3
  167. package/dist/cli/chunks/{fast-paths-2CVAAPQO.js → fast-paths-P3KT5DUQ.js} +2 -2
  168. package/dist/cli/chunks/{feature-flags-A5KFWVFC.js → feature-flags-5EBWQ5WU.js} +2 -2
  169. package/dist/cli/chunks/{feature-flags-GEXTW6OT.js → feature-flags-DYFZSQLV.js} +2 -2
  170. package/dist/cli/chunks/{file-discovery-KWLVC7KN.js → file-discovery-MOBVABSM.js} +2 -2
  171. package/dist/cli/chunks/{fleet-MNKH356S.js → fleet-J3R3NQNC.js} +3 -3
  172. package/dist/cli/chunks/{gnn-wrapper-ALTWYFVZ.js → gnn-wrapper-QD76SULF.js} +2 -2
  173. package/dist/cli/chunks/{heartbeat-handler-MBMEPEGW.js → heartbeat-handler-AJEWTPZ4.js} +4 -4
  174. package/dist/cli/chunks/heartbeat-scheduler-EAVZR6TJ.js +2 -0
  175. package/dist/cli/chunks/hnsw-adapter-BY4XB7FB.js +2 -0
  176. package/dist/cli/chunks/hnsw-index-657CZRG7.js +2 -0
  177. package/dist/cli/chunks/{hnsw-legacy-bridge-WTD5PR5V.js → hnsw-legacy-bridge-5VRM5N7K.js} +2 -2
  178. package/dist/cli/chunks/{better-sqlite3-NYOVLWBG.js → hnswlib-node-BWUH4OQT.js} +2 -2
  179. package/dist/cli/chunks/{hooks-ELHGEBFK.js → hooks-7PMVKQOE.js} +10 -10
  180. package/dist/cli/chunks/{hybrid-router-D6ZMIZCE.js → hybrid-router-2K2LW45J.js} +2 -2
  181. package/dist/cli/chunks/{hypergraph-engine-JOQ6TERZ.js → hypergraph-engine-2CQ735JO.js} +2 -2
  182. package/dist/cli/chunks/{hypergraph-handler-HX45YWWN.js → hypergraph-handler-AQ53GVIW.js} +3 -3
  183. package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +2 -0
  184. package/dist/cli/chunks/{init-handler-TNVU6NQ6.js → init-handler-ZOVJPAWO.js} +6 -6
  185. package/dist/cli/chunks/init-wizard-HOH577MH.js +2 -0
  186. package/dist/cli/chunks/kernel-JDYBG5GE.js +2 -0
  187. package/dist/cli/chunks/{kilocode-installer-YC5RJIY4.js → kilocode-installer-GWQCNLKI.js} +2 -2
  188. package/dist/cli/chunks/{kiro-installer-EAB26M55.js → kiro-installer-6KVES4MO.js} +2 -2
  189. package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +2 -0
  190. package/dist/cli/chunks/{learning-A2OB7D2B.js → learning-6XMNWXRT.js} +3 -3
  191. package/dist/cli/chunks/{llm-router-KEG6PA7C.js → llm-router-GS4AZJJC.js} +4 -4
  192. package/dist/cli/chunks/{load-D6ZDLVA3.js → load-FEMEQNE6.js} +2 -2
  193. package/dist/cli/chunks/load-test-3MEJ43U2.js +2 -0
  194. package/dist/cli/chunks/{mcp-ERJHZ6FN.js → mcp-6V2H7EXU.js} +2 -2
  195. package/dist/cli/chunks/{memory-GSRIJIVR.js → memory-YLGPOB2H.js} +5 -5
  196. package/dist/cli/chunks/memory-backend-2A47ZRGO.js +2 -0
  197. package/dist/cli/chunks/memory-handlers-UBTBC7D2.js +2 -0
  198. package/dist/cli/chunks/{multi-model-executor-GK3V7ERC.js → multi-model-executor-SL2EKAH2.js} +2 -2
  199. package/dist/cli/chunks/{opencode-installer-6TTN26RG.js → opencode-installer-ADOJVGNA.js} +2 -2
  200. package/dist/cli/chunks/{orchestrator-YVTSM6QW.js → orchestrator-O4IWW2VU.js} +5 -5
  201. package/dist/cli/chunks/{pipeline-EWLJCY5G.js → pipeline-5BD5YQNQ.js} +2 -2
  202. package/dist/cli/chunks/{platform-2ULHQQME.js → platform-HXSUOOJH.js} +2 -2
  203. package/dist/cli/chunks/{plugin-PYN2KOXA.js → plugin-HOLH5CUH.js} +2 -2
  204. package/dist/cli/chunks/{prime-radiant-advanced-wasm-IULCTOGZ.js → prime-radiant-advanced-wasm-PJTL7OLS.js} +2 -2
  205. package/dist/cli/chunks/protocol-executor-3FR7FBVM.js +2 -0
  206. package/dist/cli/chunks/{protocol-handler-FZYI2SBP.js → protocol-handler-K27YGLC7.js} +2 -2
  207. package/dist/cli/chunks/{prove-DN7S74SP.js → prove-MHCLHQQ6.js} +2 -2
  208. package/dist/cli/chunks/{provider-manager-FT3MCROB.js → provider-manager-3645PPXX.js} +2 -2
  209. package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +2 -0
  210. package/dist/cli/chunks/{quality-ITBU6LGC.js → quality-NDE6EDOY.js} +2 -2
  211. package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +2 -0
  212. package/dist/cli/chunks/{real-embeddings-PZUZ5RXJ.js → real-embeddings-VD3EVV3U.js} +2 -2
  213. package/dist/cli/chunks/{roocode-installer-2LMVZOUZ.js → roocode-installer-63Y45UUG.js} +2 -2
  214. package/dist/cli/chunks/router-23HRN2Z6.js +2 -0
  215. package/dist/cli/chunks/routing-feedback-R6A4B6ZG.js +2 -0
  216. package/dist/cli/chunks/{routing-handler-5RB73UCF.js → routing-handler-76XISU2E.js} +2 -2
  217. package/dist/cli/chunks/{ruvector-commands-VBN4APMG.js → ruvector-commands-AEKOZZHZ.js} +2 -2
  218. package/dist/cli/chunks/{rvf-dual-writer-BNY4AUWT.js → rvf-dual-writer-4DMUIZQF.js} +2 -2
  219. package/dist/cli/chunks/{rvf-migration-adapter-73MKPBGV.js → rvf-migration-adapter-YUTXFOZ3.js} +2 -2
  220. package/dist/cli/chunks/{rvf-migration-coordinator-SGVB7ZAZ.js → rvf-migration-coordinator-XJ5N2W37.js} +2 -2
  221. package/dist/cli/chunks/rvf-native-adapter-QINEJZM7.js +2 -0
  222. package/dist/cli/chunks/safe-db-YXMCSKFH.js +2 -0
  223. package/dist/cli/chunks/schedule-XVFD27P5.js +2 -0
  224. package/dist/cli/chunks/scheduler-NWH2IDEU.js +2 -0
  225. package/dist/cli/chunks/{security-XUH4H7R3.js → security-6YS6GQGO.js} +3 -3
  226. package/dist/cli/chunks/shared-rvf-adapter-FTZY35WI.js +2 -0
  227. package/dist/cli/chunks/{shared-rvf-dual-writer-GML4EDYF.js → shared-rvf-dual-writer-MH2Y65HA.js} +2 -2
  228. package/dist/cli/chunks/sqlite-persistence-BR6YJF5P.js +2 -0
  229. package/dist/cli/chunks/{status-handler-XI7GJF6Z.js → status-handler-57JQMPY5.js} +2 -2
  230. package/dist/cli/chunks/{structural-health-WPCYKOXV.js → structural-health-34D5VWRD.js} +2 -2
  231. package/dist/cli/chunks/sync-HJD2US5P.js +2 -0
  232. package/dist/cli/chunks/sync-TTQ6ZB5D.js +17 -0
  233. package/dist/cli/chunks/{task-handler-FZB55IEG.js → task-handler-4RF57637.js} +2 -2
  234. package/dist/cli/chunks/{task-handlers-EXZGFH7F.js → task-handlers-BRSK7HDE.js} +3 -3
  235. package/dist/cli/chunks/{test-XYRN4OVU.js → test-GMUW2VR3.js} +4 -4
  236. package/dist/cli/chunks/{test-scheduling-FLVOPGOT.js → test-scheduling-7LF24IFV.js} +3 -3
  237. package/dist/cli/chunks/{token-bootstrap-FDCFVRHM.js → token-bootstrap-VYT4RTHU.js} +2 -2
  238. package/dist/cli/chunks/{token-usage-MHNZF3DM.js → token-usage-NFNCPQGW.js} +2 -2
  239. package/dist/cli/chunks/{transformers-4CRVTMWY.js → transformers-GGD5GIEY.js} +2 -2
  240. package/dist/cli/chunks/{tree-sitter-wasm-parser-CI3V4AND.js → tree-sitter-wasm-parser-GKYG6NKT.js} +2 -2
  241. package/dist/cli/chunks/{types-RKCD4BNL.js → types-WJ3ZTRD5.js} +2 -2
  242. package/dist/cli/chunks/unified-memory-AT3Z4CY7.js +2 -0
  243. package/dist/cli/chunks/unified-memory-hnsw-6FOIGINN.js +2 -0
  244. package/dist/cli/chunks/unified-persistence-TCJB7MQS.js +2 -0
  245. package/dist/cli/chunks/{upgrade-463W7VKH.js → upgrade-IMBT4F6K.js} +2 -2
  246. package/dist/cli/chunks/{validate-LENSMEAY.js → validate-76OVF45Z.js} +2 -2
  247. package/dist/cli/chunks/{validate-swarm-4FEBNAWA.js → validate-swarm-HH2ZYWXA.js} +2 -2
  248. package/dist/cli/chunks/{vibium-TXNVIVWJ.js → vibium-74WQNDBX.js} +2 -2
  249. package/dist/cli/chunks/visual-security-IBAUX2K5.js +2 -0
  250. package/dist/cli/chunks/{web-tree-sitter-BZEGWID4.js → web-tree-sitter-W6RGE4SL.js} +2 -2
  251. package/dist/cli/chunks/{windsurf-installer-7AFXJTPU.js → windsurf-installer-7DMSFCA2.js} +2 -2
  252. package/dist/cli/chunks/{witness-chain-G6SUZOZG.js → witness-chain-BLZ4ZKAD.js} +2 -2
  253. package/dist/cli/chunks/witness-chain-GNNF23XU.js +2 -0
  254. package/dist/cli/chunks/{workflow-EVQPO6FH.js → workflow-RNSDKRZ4.js} +4 -4
  255. package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +2 -0
  256. package/dist/cli/chunks/{wrappers-HR6RUDI2.js → wrappers-J7RXMIOY.js} +2 -2
  257. package/dist/domains/learning-optimization/services/learning-coordinator.js +37 -17
  258. package/dist/kernel/hybrid-backend.d.ts +17 -7
  259. package/dist/kernel/hybrid-backend.js +24 -10
  260. package/dist/kernel/interfaces.d.ts +21 -6
  261. package/dist/kernel/memory-backend.d.ts +5 -5
  262. package/dist/kernel/memory-backend.js +14 -7
  263. package/dist/mcp/bundle.js +447 -447
  264. package/dist/mcp/handlers/core-handlers.js +21 -0
  265. package/dist/workers/interfaces.d.ts +26 -0
  266. package/dist/workers/worker-manager.d.ts +15 -12
  267. package/dist/workers/worker-manager.js +11 -0
  268. package/dist/workers/workers/learning-consolidation.js +116 -89
  269. package/package.json +3 -1
  270. package/dist/cli/chunks/adapter-CI2GZYME.js +0 -2
  271. package/dist/cli/chunks/aqe-learning-engine-KNQKALLI.js +0 -2
  272. package/dist/cli/chunks/base-P7PRMQWY.js +0 -2
  273. package/dist/cli/chunks/browser-workflow-QUP4A763.js +0 -2
  274. package/dist/cli/chunks/chunk-5Z6PYYWK.js +0 -2
  275. package/dist/cli/chunks/chunk-RBDAHW2M.js +0 -2
  276. package/dist/cli/chunks/client-XF6SJO2C.js +0 -2
  277. package/dist/cli/chunks/cross-domain-router-J2OFPM6R.js +0 -2
  278. package/dist/cli/chunks/daemon-CP2ETHRF.js +0 -19
  279. package/dist/cli/chunks/dream-D5LD5SOZ.js +0 -2
  280. package/dist/cli/chunks/hnsw-adapter-M2MMM3N6.js +0 -2
  281. package/dist/cli/chunks/hnsw-index-JO7KNF7M.js +0 -2
  282. package/dist/cli/chunks/impact-analyzer-ROQL4J7P.js +0 -2
  283. package/dist/cli/chunks/init-wizard-4BDFZX4M.js +0 -2
  284. package/dist/cli/chunks/kernel-37Y63WKR.js +0 -2
  285. package/dist/cli/chunks/knowledge-graph-V3DX6ZCX.js +0 -2
  286. package/dist/cli/chunks/load-test-HPBA2CMT.js +0 -2
  287. package/dist/cli/chunks/memory-backend-DODDBB46.js +0 -2
  288. package/dist/cli/chunks/memory-handlers-MFLCRS7V.js +0 -2
  289. package/dist/cli/chunks/protocol-executor-D56OYMCJ.js +0 -2
  290. package/dist/cli/chunks/qe-reasoning-bank-KXROIEK7.js +0 -2
  291. package/dist/cli/chunks/queen-coordinator-XOGATERL.js +0 -2
  292. package/dist/cli/chunks/router-3EHNUCOM.js +0 -2
  293. package/dist/cli/chunks/routing-feedback-ZHKGET22.js +0 -2
  294. package/dist/cli/chunks/rvf-native-adapter-4YC5IQUW.js +0 -2
  295. package/dist/cli/chunks/safe-db-PLJRHQIC.js +0 -2
  296. package/dist/cli/chunks/schedule-7DGELVJE.js +0 -2
  297. package/dist/cli/chunks/scheduler-VWASEC2J.js +0 -2
  298. package/dist/cli/chunks/shared-rvf-adapter-DCVDY2XW.js +0 -2
  299. package/dist/cli/chunks/sqlite-persistence-CTEBGVOW.js +0 -2
  300. package/dist/cli/chunks/sync-SFKTCRZC.js +0 -23
  301. package/dist/cli/chunks/unified-memory-YDKXKW3D.js +0 -2
  302. package/dist/cli/chunks/unified-memory-hnsw-6N7YZCLR.js +0 -2
  303. package/dist/cli/chunks/unified-persistence-UTWLPUQI.js +0 -2
  304. package/dist/cli/chunks/visual-security-DGXSOFKD.js +0 -2
  305. package/dist/cli/chunks/witness-chain-VP4MF6EU.js +0 -2
  306. package/dist/cli/chunks/workflow-orchestrator-VXSYAKQY.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as l}from"./chunk-EKYPQ5DX.js";import{a as m}from"./chunk-IRRGUXAU.js";import{i as a}from"./chunk-GQFAVT2I.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as l}from"./chunk-T5ADVYPH.js";import{a as m}from"./chunk-EFEJLZDN.js";import{i as a}from"./chunk-WTNM7NA4.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y as b};
@@ -0,0 +1,5 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as R,join as H}from"path";import{existsSync as L,readFileSync as U}from"fs";var _=$(Q),z={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...z,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=R(this.options.repoRoot,".git","refs","heads");if(!L(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
+ `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=R(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=U(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
4
+ `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
5
+ `)){if(!t)continue;let[i,o]=t.split(" ");this.lastKnownHeads.set(i,o)}}catch{}}};var E={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...E,...t}}queue;options;async analyze(e,t,i){let o=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!o)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let r=o,n={line:e.overall.line-r.overall.line,branch:e.overall.branch-r.overall.branch,function:e.overall.function-r.overall.function,statement:e.overall.statement-r.overall.statement},s=n.line<-this.options.regressionThreshold||n.branch<-this.options.regressionThreshold,a=i??Object.keys(e.files),u=[],c=[];for(let d of a){let l=e.files[d],m=r.files[d];if(!l)continue;let I=m?l.line-m.line:0,M=m?l.branch-m.branch:0,D=m?l.uncoveredLines.filter(T=>!m.uncoveredLines.includes(T)):l.uncoveredLines;if((I!==0||M!==0||D.length>0)&&u.push({file:d,lineDelta:I,branchDelta:M,newUncoveredLines:D}),l.line<this.options.gapThreshold){let T=this.computeRiskScore(l,D.length);c.push({file:d,uncoveredLines:l.uncoveredLines,currentCoverage:l.line,riskScore:T})}}return(s||c.length>0)&&this.enqueueTestSuggestion(e,r,c),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:u.length,gapCount:c.length}),{regressionDetected:s,overallDelta:n,affectedFiles:u,newGaps:c}}async buildSnapshot(e){let t=await e.get("coverage:latest");if(t)return{timestamp:Date.now(),overall:{line:t.line,branch:t.branch,function:t.function,statement:t.statement},files:t.files??{}}}computeRiskScore(e,t){let o=1-Math.min(100,Math.max(0,e.line))/100,r=Math.min(t/50,1);return Math.min(1,o*.6+r*.4)}enqueueTestSuggestion(e,t,i){let o={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},r={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:o,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(r)}};import{execFile as j}from"child_process";import{promisify as B}from"util";var J=B(j),K={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...K,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],o=[],r=0;for(let[s,a]of Object.entries(t)){let u=a.filter(m=>m.conclusion==="failure").length,c=a.length>0?(a.length-u)/a.length*100:100,d=this.countConsecutiveFailures(a),l=a[0]?.conclusion??"unknown";l==="failure"&&r++,d>=this.options.flakyThreshold&&(o.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:u,successRate:Math.round(c*10)/10,lastConclusion:l,consecutiveFailures:d})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:r,flakyWorkflows:o,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await J("gh",e,{timeout:15e3});return JSON.parse(t).map(o=>({name:o.name,status:o.status,conclusion:o.conclusion??"pending",headBranch:o.headBranch,runNumber:o.number,databaseId:o.databaseId,createdAt:o.createdAt}))}catch{return[]}}groupByWorkflow(e){let t={};for(let i of e)t[i.name]||(t[i.name]=[]),t[i.name].push(i);for(let i of Object.keys(t))t[i]=t[i].slice(0,this.options.runsPerWorkflow);return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,o)=>i+o.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},o={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(o)}};var V={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...V,...e}}async suggest(e,t,i){let o=[],r=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of r){let a=t.includes(s.file),u=this.determinePriority(s,a),c=this.determineTestType(s.file),d=this.estimateEffort(s);o.push({id:`suggestion-${Date.now()}-${o.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:c,description:this.generateDescription(s,c),priority:u,estimatedEffort:d,createdAt:Date.now(),status:"pending"})}o.sort((s,a)=>{let u={high:0,medium:1,low:2};return u[s.priority]-u[a.priority]});let n=o.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let o=await i.get(`${this.options.memoryPrefix}:list`);if(!o)return!1;let r=o.findIndex(s=>s.id===e);if(r===-1)return!1;let n=o.map((s,a)=>a===r?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,o=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${o}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let r=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,r),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:r.length,lastUpdated:Date.now()})}};var Y={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...Y,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),o=new Date().toISOString().split("T")[0],r=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(o,t);await e.set(`${this.options.memoryPrefix}:report:${o}`,s),this.lastRunDate=o;let a={timestamp:Date.now(),patternsConsolidated:r,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,o=Date.now();for(let r of t){if(r.endsWith(":snapshot")||r.endsWith(":list"))continue;let n=await e.get(r);n&&typeof n.timestamp=="number"&&o-n.timestamp>this.options.maxEntryAge&&(await e.set(r,{pruned:!0,prunedAt:o}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};import{writeFileSync as q,mkdirSync as W,readdirSync as S,readFileSync as A,unlinkSync as N}from"fs";import{join as b,resolve as X}from"path";var F={notificationsDir:X(process.cwd(),".agentic-qe","notifications"),maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??F.notificationsDir,this.maxNotifications=e?.maxNotifications??F.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){W(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=S(this.notificationsDir).filter(r=>r.endsWith(".json")).sort().reverse(),o=[];for(let r of i){if(o.length>=t)break;try{let n=A(b(this.notificationsDir,r),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;o.push(s)}catch{}}return o}catch{return[]}}markRead(e){try{let t=S(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),r={...JSON.parse(A(i,"utf-8")),read:!0};return q(i,JSON.stringify(r,null,2)),!0}catch{return!1}}clear(){try{let e=S(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)N(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{W(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);q(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=S(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)N(b(this.notificationsDir,i))}catch{}}};var C={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},O=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??C.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??C.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??C.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??C.cpuThreshold,memoryThreshold:e?.memoryThreshold??C.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs))}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let o=this.queue.dequeue();if(!o)break;await this.handleQueueItem(o,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":this._commitsAnalyzed++;let o=await this.coverageDelta.buildSnapshot(t);if(o){let r=await this.coverageDelta.analyze(o,t,i.changedFiles);if(r.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${r.overallDelta.line.toFixed(1)}% (${r.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:r.overallDelta,commit:i.commitHash}}),r.newGaps.length>0){let n=await this.testSuggester.suggest(r.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break;case"coverage_delta":{let r=await this.testSuggester.getPending(t);r.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${r.length} test suggestions awaiting review`,severity:"info",metadata:{count:r.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let r={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,r);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);i&&(this._coverageHealth=Math.round((i.overall.line+i.overall.branch+i.overall.function+i.overall.statement)/4),this._lastCoverageCheck=t)}catch{}}isResourceConstrained(){if(1-ee()/te()>this.config.memoryThreshold)return!0;let t=Z().length;return(t>0?ie()[0]/t:0)>this.config.cpuThreshold}};export{x as a,O 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.9.31");process.exit(0)}
2
- import{c as r}from"./chunk-BMS7WFDB.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t 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.9.32");process.exit(0)}
2
+ import{c as r}from"./chunk-XHQFVTFD.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t 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.9.31");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-BMS7WFDB.js";var g={};o(g,{DotProductAttention:()=>u,FlashAttention:()=>m,HyperbolicAttention:()=>h,LinearAttention:()=>f,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>r,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>d,pipeline:()=>L});import{createRequire as n}from"module";var i,e,r,a,c,l,s,p,d,m,u,A,h,f,_,b,L,q=t(()=>{i=n(import.meta.url),e=i("hnswlib-node"),r=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:d,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:A,HyperbolicAttention:h,LinearAttention:f,MoEAttention:_,SonaEngine:b,pipeline:L}=e||{}});export{r as a,a as b,c,l as d,s as e,p as f,d as g,m as h,u as i,A as j,h as k,f as l,_ as m,b as n,L as o,g as p,q};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-XHQFVTFD.js";var g={};o(g,{DotProductAttention:()=>u,FlashAttention:()=>m,HyperbolicAttention:()=>h,LinearAttention:()=>f,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>r,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>d,pipeline:()=>L});import{createRequire as n}from"module";var i,e,r,a,c,l,s,p,d,m,u,A,h,f,_,b,L,q=t(()=>{i=n(import.meta.url),e=i("hnswlib-node"),r=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:d,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:A,HyperbolicAttention:h,LinearAttention:f,MoEAttention:_,SonaEngine:b,pipeline:L}=e||{}});export{r as a,a as b,c,l as d,s as e,p as f,d as g,m as h,u as i,A as j,h as k,f as l,_ as m,b as n,L as o,g as p,q};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as H}from"./chunk-YEZJE2ZW.js";import{a as C,b as D,c as U,d as _}from"./chunk-UIIEZMSM.js";import{c as X,d as K,e as Y,f as J}from"./chunk-VA45HLBF.js";import{b as k,f as j,i as G}from"./chunk-ZG4EKPGV.js";import{g as w}from"./chunk-M6RVKGIP.js";import{e as $}from"./chunk-VSKABN3B.js";import{k as z,o as me}from"./chunk-7MXQV7RB.js";import{a as B}from"./chunk-5Z6PYYWK.js";import{c as T}from"./chunk-NZQYNUGM.js";import{b as q,c as x}from"./chunk-IRRGUXAU.js";import{a as f,b as L,c as V}from"./chunk-K6MFAVXK.js";import{S as de,b as W}from"./chunk-AKFRM4IO.js";B();V();var I={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var A=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as H}from"./chunk-6SYP7QX6.js";import{a as C,b as D,c as U,d as _}from"./chunk-V7I6FTLG.js";import{c as X,d as K,e as Y,f as J}from"./chunk-ZIVOT3B7.js";import{b as k,f as j,i as G}from"./chunk-MERMCKPG.js";import{g as w}from"./chunk-FWEYOD3S.js";import{e as $}from"./chunk-VJL7DNUU.js";import{k as z,o as me}from"./chunk-THYGFSTA.js";import{a as B}from"./chunk-YVQ4PR4H.js";import{c as T}from"./chunk-OMOGD2NN.js";import{b as q,c as x}from"./chunk-EFEJLZDN.js";import{a as f,b as L,c as V}from"./chunk-5WR42V5O.js";import{S as de,b as W}from"./chunk-33PGBYTC.js";B();V();var I={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var A=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -317,4 +317,4 @@ On promotion:
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return C(e)}generateContext(e,r){return _(e,r||{})}checkAntiPatterns(e,r){return U(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-PZUZ5RXJ.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of G)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function ft(n,e,r,t){return new F(n,e,r,t)}export{I as a,A as b,R as c,re as d,N as e,Q as f,F as g,ft as h};
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return C(e)}generateContext(e,r){return _(e,r||{})}checkAntiPatterns(e,r){return U(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-VD3EVV3U.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){process.env.DEBUG&&g.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of G)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function ft(n,e,r,t){return new F(n,e,r,t)}export{I as a,A as b,R as c,re as d,N as e,Q as f,F as g,ft as h};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var s=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],c="anthropic/claude-sonnet-4.6",u="claude-sonnet-4-6";function o(n){return n.includes("claude-opus-4-7")||n.includes("claude-opus-4.7")}function i(n,e=process.env){return e.AQE_CYBER_VERIFIED==="true"?!1:s.includes(n)}function a(n,e,r,t=process.env){return!i(n,t)||!o(e)?e:r}export{c as a,u as b,o as c,i as d,a as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{i as c}from"./chunk-ZG4EKPGV.js";import{b as g,d as E}from"./chunk-WB6TI6Q3.js";import{a as p}from"./chunk-5Z6PYYWK.js";import{c as m}from"./chunk-NZQYNUGM.js";import{a as l,b as _}from"./chunk-CFLA2GBS.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{i as c}from"./chunk-MERMCKPG.js";import{b as g,d as E}from"./chunk-OK2TFTXP.js";import{a as p}from"./chunk-YVQ4PR4H.js";import{c as m}from"./chunk-OMOGD2NN.js";import{a as l,b as _}from"./chunk-4VAZSCTZ.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{b as c,d as p}from"./chunk-WB6TI6Q3.js";import{a as f}from"./chunk-BMS7WFDB.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{b as c,d as p}from"./chunk-OK2TFTXP.js";import{a as f}from"./chunk-XHQFVTFD.js";p();import{existsSync as l,readFileSync as i}from"node:fs";import{join as a}from"node:path";import{execSync as m}from"node:child_process";var s=null,d=0,g=6e4;function S(){s=null,d=0}function b(e){if(s&&Date.now()-d<g)return s;let n=w(e);return s=n,d=Date.now(),n}function w(e){let n=h(e);if(n)return n;let r=v(e);if(r)return r;let t=k(e);return t||{available:!1}}function h(e){let n=a(e,".mcp.json");if(l(n))try{let o=c(i(n,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let r=a(e,".claude","mcp.json");if(l(r))try{let o=c(i(r,"utf-8"));if(o.mcpServers?.ruflo||o.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let t=a(e,".claude","settings.json");if(l(t))try{let o=c(i(t,"utf-8")),u=o.mcpServers||o.mcp?.servers||{};if(u.ruflo||u["claude-flow"]||u["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function v(e){let n=a(e,"package.json");if(!l(n))return null;try{let r=c(i(n,"utf-8")),t={...r.dependencies,...r.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function k(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:m(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function x(){for(let e of["ruflo","@claude-flow/cli"])try{return f.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function P(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
3
3
  `)}export{S as a,b,x as c,P as d};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as ne}from"./chunk-AQN6PDHI.js";import{d as B,e as W,f as re,g as j}from"./chunk-ZG4EKPGV.js";import{c as et,d as tt}from"./chunk-N6P7ENG7.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-NTVJKQ5S.js";import{b as v,c as w}from"./chunk-IRRGUXAU.js";import{a as y,b as Ae,c as Te}from"./chunk-K6MFAVXK.js";import{i as C}from"./chunk-GQFAVT2I.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-AKFRM4IO.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-BMS7WFDB.js";var V=J(S=>{var ut=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function pt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=pt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
- `)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}m.getValueByPointer=Y;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new m.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new m.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new m.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new m.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof m.JsonPatchError)return i;throw i}}m.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Rt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-CTEBGVOW.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};De();Te();F();function nt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function it(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ot(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ne(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=at(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as ne}from"./chunk-DFY7F4TE.js";import{d as B,e as W,f as re,g as j}from"./chunk-MERMCKPG.js";import{c as et,d as tt}from"./chunk-FIONYUVH.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-FV2MU6CY.js";import{b as v,c as w}from"./chunk-EFEJLZDN.js";import{a as y,b as Ae,c as Te}from"./chunk-5WR42V5O.js";import{i as C}from"./chunk-WTNM7NA4.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-33PGBYTC.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-XHQFVTFD.js";var V=J(S=>{var ut=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function pt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=pt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}m.getValueByPointer=Y;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new m.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new m.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new m.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new m.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof m.JsonPatchError)return i;throw i}}m.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Rt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-BR6YJF5P.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};De();Te();F();function nt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function it(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ot(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ne(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=at(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{a as ne}from"./chunk-AQN6PDHI.js";import{d as B,e as W,f as re,g as j}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(kt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=je)return new Float32Array(e);let r=je/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-WTD5PR5V.js"),{HnswAdapter:c}=await import("./hnsw-adapter-M2MMM3N6.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-JO7KNF7M.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
49
+ )`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(kt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=je)return new Float32Array(e);let r=je/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-5VRM5N7K.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BY4XB7FB.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-657CZRG7.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-YQJBE6NX.js";import{b as _,d as T}from"./chunk-WB6TI6Q3.js";import{a as k,c as q}from"./chunk-K6MFAVXK.js";import{a as v,b as ee}from"./chunk-CFLA2GBS.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-O5UGJ3OI.js";import{b as _,d as T}from"./chunk-OK2TFTXP.js";import{a as k,c as q}from"./chunk-5WR42V5O.js";import{a as v,b as ee}from"./chunk-4VAZSCTZ.js";T();import{existsSync as w,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(w(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-NYOVLWBG.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-K2VWFDKT.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function G(t){let e=o(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let n=v(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-V3DX6ZCX.js"),{InMemoryBackend:n}=await import("./memory-backend-DODDBB46.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-RAQOWLG3.js"),{InMemoryBackend:n}=await import("./memory-backend-2A47ZRGO.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:d.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function H(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");f(r)||b(r,{recursive:!0});let s=o(r,"hnsw");f(s)||b(s,{recursive:!0});let i=o(r,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(d,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let p of m.patterns){let l=p.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(p)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([p,l])=>({name:p,patternCount:l.length})),loadedAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8");for(let[p,l]of a){let y=o(r,"patterns",p);f(y)||b(y,{recursive:!0});let C=o(y,"patterns.json");E(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function J(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");f(n)||b(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let u=o(n,`${a}.json`),h={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return E(c,`#!/usr/bin/env node
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as C,b as E}from"./chunk-SL4TAJOE.js";import{a as T}from"./chunk-YEZJE2ZW.js";import{a as _}from"./chunk-ZG4EKPGV.js";import{n as D,o as F}from"./chunk-7MXQV7RB.js";import{a as R,c as A}from"./chunk-K6MFAVXK.js";import{g as O}from"./chunk-BMS7WFDB.js";import{createHash as M}from"crypto";var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function S(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return"["+o.map(i=>S(i)).join(",")+"]";let e=o;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+S(e[i])).join(",")+"}"}var x=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=S({action:t,domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=w();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as C,b as E}from"./chunk-PS6ISBED.js";import{a as T}from"./chunk-6SYP7QX6.js";import{a as _}from"./chunk-MERMCKPG.js";import{n as D,o as F}from"./chunk-THYGFSTA.js";import{a as R,c as A}from"./chunk-5WR42V5O.js";import{g as O}from"./chunk-XHQFVTFD.js";import{createHash as M}from"crypto";var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function S(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return"["+o.map(i=>S(i)).join(",")+"]";let e=o;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+S(e[i])).join(",")+"}"}var x=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=S({action:t,domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=w();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=w();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  import a from"chalk";import{existsSync as m,statSync as V}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}defaultValue;description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var S=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
3
3
  Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,S as j};