agentic-qe 3.11.5 → 3.12.0

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 (369) hide show
  1. package/.claude/helpers/.helpers-version +1 -0
  2. package/.claude/helpers/auto-memory-hook.mjs +35 -3
  3. package/.claude/helpers/brain-checkpoint.cjs +16 -1
  4. package/.claude/helpers/helpers.manifest.json +12 -0
  5. package/.claude/helpers/hook-handler.cjs +26 -5
  6. package/.claude/helpers/intelligence.cjs +14 -1
  7. package/.claude/hooks/aqe-hook.cjs +14 -1
  8. package/.claude/skills/skills-manifest.json +1 -1
  9. package/CHANGELOG.md +52 -0
  10. package/assets/skills/skills-manifest.json +1 -1
  11. package/dist/adapters/a2a/auth/routes.js +59 -28
  12. package/dist/cli/bundle.js +6 -6
  13. package/dist/cli/chunks/adapter-6IWRIHF3.js +2 -0
  14. package/dist/cli/chunks/{agent-booster-wasm-CSTBLNYZ.js → agent-booster-wasm-IO54X6IQ.js} +2 -2
  15. package/dist/cli/chunks/{agent-handler-M4W4GTXN.js → agent-handler-A57SZUCW.js} +2 -2
  16. package/dist/cli/chunks/{agent-memory-branch-VGXFYLSQ.js → agent-memory-branch-BX7LRFGN.js} +2 -2
  17. package/dist/cli/chunks/aqe-learning-engine-FSF5U67K.js +2 -0
  18. package/dist/cli/chunks/{arena-FKSD3LLM.js → arena-UTC4YY6Y.js} +4 -4
  19. package/dist/cli/chunks/{arena-IQBRGWAG.js → arena-Y3XTX6O7.js} +2 -2
  20. package/dist/cli/chunks/{audit-7NSGRR4Z.js → audit-L4RL2AOY.js} +3 -3
  21. package/dist/cli/chunks/base-2CKCJU3O.js +2 -0
  22. package/dist/cli/chunks/{hnswlib-node-E6NSZPP2.js → better-sqlite3-LRDXKYOJ.js} +2 -2
  23. package/dist/cli/chunks/{brain-handler-M6A3UB66.js → brain-handler-OHDPI5TQ.js} +3 -3
  24. package/dist/cli/chunks/{branch-enumerator-2JGKY4BB.js → branch-enumerator-ZRXE2CQ7.js} +2 -2
  25. package/dist/cli/chunks/{browser-J43WQPJL.js → browser-NT33FG76.js} +2 -2
  26. package/dist/cli/chunks/browser-workflow-UGYJE64S.js +2 -0
  27. package/dist/cli/chunks/{chunk-JDSHUECG.js → chunk-27JCWG5J.js} +2 -2
  28. package/dist/cli/chunks/{chunk-B2VBDMDI.js → chunk-2ALNNXFF.js} +2 -2
  29. package/dist/cli/chunks/{chunk-SK754ZSH.js → chunk-2AOOIAW3.js} +4 -4
  30. package/dist/cli/chunks/{chunk-ZG5UAEEO.js → chunk-2AR4B3DI.js} +2 -2
  31. package/dist/cli/chunks/{chunk-GODAWJMZ.js → chunk-2KHDGC7N.js} +2 -2
  32. package/dist/cli/chunks/{chunk-YZSTZUGJ.js → chunk-2UMCB7AH.js} +1 -1
  33. package/dist/cli/chunks/{chunk-Q5TR6ETB.js → chunk-335GHVJV.js} +3 -3
  34. package/dist/cli/chunks/{chunk-UBI2EOS3.js → chunk-36MPDANH.js} +1 -1
  35. package/dist/cli/chunks/{chunk-C4EZNOWK.js → chunk-3AFNXU45.js} +1 -1
  36. package/dist/cli/chunks/{chunk-7YSBATSN.js → chunk-3B4XXFKD.js} +2 -2
  37. package/dist/cli/chunks/{chunk-DPL762HU.js → chunk-4GU656WM.js} +1 -1
  38. package/dist/cli/chunks/{chunk-I3NWKPXJ.js → chunk-4SALW7OT.js} +2 -2
  39. package/dist/cli/chunks/{chunk-7BCRULCP.js → chunk-5FR5GBUT.js} +2 -2
  40. package/dist/cli/chunks/{chunk-4XJ2A3HY.js → chunk-5VBPIJUZ.js} +4 -4
  41. package/dist/cli/chunks/chunk-5XFX25AJ.js +4 -0
  42. package/dist/cli/chunks/{chunk-UORTQXJ2.js → chunk-5YGESYBC.js} +1 -1
  43. package/dist/cli/chunks/{chunk-ABU64UWB.js → chunk-62RELCU6.js} +1 -1
  44. package/dist/cli/chunks/{chunk-2XQHG56O.js → chunk-64M3FFM4.js} +2 -2
  45. package/dist/cli/chunks/{chunk-K4I7UIU5.js → chunk-6JNNZGI2.js} +1 -1
  46. package/dist/cli/chunks/{chunk-XT4TDLOB.js → chunk-6X3RJBA3.js} +2 -2
  47. package/dist/cli/chunks/{chunk-JATLFS6A.js → chunk-72VZGAMJ.js} +1 -1
  48. package/dist/cli/chunks/{chunk-AGJOGUP5.js → chunk-7F7U2HUH.js} +1 -1
  49. package/dist/cli/chunks/{chunk-ZPP57WQU.js → chunk-7HJHXSYT.js} +2 -2
  50. package/dist/cli/chunks/{chunk-6T65OKUM.js → chunk-7WX3MKRS.js} +2 -2
  51. package/dist/cli/chunks/{chunk-5WMU7XCF.js → chunk-7ZIVDGSN.js} +1 -1
  52. package/dist/cli/chunks/{chunk-M6FW56MV.js → chunk-AAATFEIL.js} +2 -2
  53. package/dist/cli/chunks/{chunk-2XPMATEK.js → chunk-AEX75YGI.js} +2 -2
  54. package/dist/cli/chunks/chunk-BA6U7NSR.js +2 -0
  55. package/dist/cli/chunks/{chunk-4QOI5JS7.js → chunk-BB4OVXWF.js} +1 -1
  56. package/dist/cli/chunks/{chunk-K4C25BWV.js → chunk-BBC526PL.js} +2 -2
  57. package/dist/cli/chunks/{chunk-354367AP.js → chunk-BGRJZH5Q.js} +2 -2
  58. package/dist/cli/chunks/{chunk-7KXPNNMR.js → chunk-BUYPRUNY.js} +2 -2
  59. package/dist/cli/chunks/{chunk-O7J54OHN.js → chunk-BZPF6GTL.js} +1 -1
  60. package/dist/cli/chunks/{chunk-NCSXLMDL.js → chunk-C4SZSPXY.js} +2 -2
  61. package/dist/cli/chunks/{chunk-YBPLJRVT.js → chunk-C6GYLCTX.js} +2 -2
  62. package/dist/cli/chunks/{chunk-53YOYZW5.js → chunk-CC5G3K4X.js} +2 -2
  63. package/dist/cli/chunks/{chunk-UBY322ED.js → chunk-CHO54B34.js} +2 -2
  64. package/dist/cli/chunks/{chunk-EK3HPH6A.js → chunk-CMGYUCM7.js} +1 -1
  65. package/dist/cli/chunks/{chunk-W72FJA2H.js → chunk-CSEEGX5T.js} +2 -2
  66. package/dist/cli/chunks/{chunk-OS2HHJTM.js → chunk-CVGXB7IX.js} +2 -2
  67. package/dist/cli/chunks/{chunk-SE3JFUKP.js → chunk-DQDFACYW.js} +1 -1
  68. package/dist/cli/chunks/chunk-DR7PCO3S.js +153 -0
  69. package/dist/cli/chunks/{chunk-4MHN7JWC.js → chunk-DTOE3NYW.js} +2 -2
  70. package/dist/cli/chunks/{chunk-FGD6HINU.js → chunk-DXOMRWDC.js} +1 -1
  71. package/dist/cli/chunks/{chunk-3V36WMIO.js → chunk-EGH3H7QO.js} +1 -1
  72. package/dist/cli/chunks/{chunk-52U5BFZP.js → chunk-EM2JIIAQ.js} +2 -2
  73. package/dist/cli/chunks/{chunk-ZLBY25MB.js → chunk-ESDGCTC4.js} +1 -1
  74. package/dist/cli/chunks/{chunk-MTBGOWJA.js → chunk-EZE2HRQB.js} +2 -2
  75. package/dist/cli/chunks/{chunk-KVVJVMDM.js → chunk-FEEMJDUF.js} +2 -2
  76. package/dist/cli/chunks/{chunk-JBKZ5TUM.js → chunk-FI5SSLEF.js} +2 -2
  77. package/dist/cli/chunks/{chunk-J5XDKVI7.js → chunk-FKPUPQQT.js} +2 -2
  78. package/dist/cli/chunks/{chunk-URP75DL4.js → chunk-FOPS6DRZ.js} +1 -1
  79. package/dist/cli/chunks/{chunk-GW6XWMX2.js → chunk-FU5RNEXV.js} +2 -2
  80. package/dist/cli/chunks/{chunk-3JF5A72M.js → chunk-FZIHOMGY.js} +2 -2
  81. package/dist/cli/chunks/{chunk-AOQYORVA.js → chunk-FZRU73M4.js} +2 -2
  82. package/dist/cli/chunks/{chunk-MEIU7457.js → chunk-G5JQLUUO.js} +2 -2
  83. package/dist/cli/chunks/{chunk-MHMQ6MCT.js → chunk-G6LR7FK7.js} +2 -2
  84. package/dist/cli/chunks/{chunk-J6PFPY7V.js → chunk-G6RKUEGL.js} +2 -2
  85. package/dist/cli/chunks/{chunk-EEKG35K5.js → chunk-GCF42L7M.js} +3 -3
  86. package/dist/cli/chunks/{chunk-OS62Y77J.js → chunk-GGMQOEZZ.js} +2 -2
  87. package/dist/cli/chunks/{chunk-QKK7VBVB.js → chunk-HAEUPIKW.js} +2 -2
  88. package/dist/cli/chunks/{chunk-4RTWPR3X.js → chunk-HDJMD6UH.js} +1 -1
  89. package/dist/cli/chunks/{chunk-EDOGRFAG.js → chunk-HW62TB4T.js} +1 -1
  90. package/dist/cli/chunks/{chunk-LOE2JETO.js → chunk-I6WHYRWB.js} +2 -2
  91. package/dist/cli/chunks/{chunk-VMFAANWX.js → chunk-ICK3B24H.js} +2 -2
  92. package/dist/cli/chunks/{chunk-C5C4W572.js → chunk-IDLNLSQI.js} +2 -2
  93. package/dist/cli/chunks/{chunk-PVDXNQPL.js → chunk-IJUYHIKN.js} +2 -2
  94. package/dist/cli/chunks/{chunk-3WR35GFF.js → chunk-IKVNYK7Y.js} +2 -2
  95. package/dist/cli/chunks/{chunk-62OTU2AP.js → chunk-JOBCMNTP.js} +2 -2
  96. package/dist/cli/chunks/{chunk-BJLA2IX7.js → chunk-JYX7AZHE.js} +2 -2
  97. package/dist/cli/chunks/{chunk-6Q57K4YD.js → chunk-JYXSVSH2.js} +2 -2
  98. package/dist/cli/chunks/{chunk-CKOF27L7.js → chunk-K5SN66B4.js} +2 -2
  99. package/dist/cli/chunks/{chunk-PW72M2FE.js → chunk-KDLYTJ5C.js} +2 -2
  100. package/dist/cli/chunks/{chunk-4LODYRNV.js → chunk-KI5BP4X5.js} +2 -2
  101. package/dist/cli/chunks/{chunk-CDJP6COA.js → chunk-KJWQ7ENF.js} +2 -2
  102. package/dist/cli/chunks/{chunk-FII3WCCY.js → chunk-KN5GOEYK.js} +2 -2
  103. package/dist/cli/chunks/{chunk-7DTMENY6.js → chunk-KZ37VHMJ.js} +2 -2
  104. package/dist/cli/chunks/{chunk-I3ANRYQ6.js → chunk-KZMRU7DL.js} +2 -2
  105. package/dist/cli/chunks/{chunk-YFCULQBP.js → chunk-L5ZLOW3K.js} +2 -2
  106. package/dist/cli/chunks/{chunk-37ZUF5NX.js → chunk-LMJUQWR7.js} +1 -1
  107. package/dist/cli/chunks/{chunk-HJWT4KME.js → chunk-MBF3Q7FQ.js} +1 -1
  108. package/dist/cli/chunks/chunk-MDT3LIXS.js +2 -0
  109. package/dist/cli/chunks/{chunk-3LY7OCSO.js → chunk-MJPYNGZ7.js} +1 -1
  110. package/dist/cli/chunks/{chunk-SO6G4IX3.js → chunk-MK3J7JVZ.js} +2 -2
  111. package/dist/cli/chunks/{chunk-VN2HHBZN.js → chunk-MUAHFGIX.js} +2 -2
  112. package/dist/cli/chunks/{chunk-6R3YOAKO.js → chunk-MUV56BPK.js} +2 -2
  113. package/dist/cli/chunks/{chunk-XLT3FYS7.js → chunk-NLHISTL2.js} +2 -2
  114. package/dist/cli/chunks/{chunk-26WEI3P4.js → chunk-NNGCUJWQ.js} +2 -2
  115. package/dist/cli/chunks/{chunk-W7TYKPLY.js → chunk-NW7G57NR.js} +2 -2
  116. package/dist/cli/chunks/{chunk-Y6DWJKHU.js → chunk-O3C5RRDQ.js} +3 -3
  117. package/dist/cli/chunks/{chunk-TEIWJ3GJ.js → chunk-OHSVDMF7.js} +1 -1
  118. package/dist/cli/chunks/{chunk-KP3R2M2G.js → chunk-OPIWFXME.js} +1 -1
  119. package/dist/cli/chunks/{chunk-FGSIID5C.js → chunk-P52YORQG.js} +2 -2
  120. package/dist/cli/chunks/chunk-PM566XEO.js +2 -0
  121. package/dist/cli/chunks/chunk-POKMJTD2.js +2 -0
  122. package/dist/cli/chunks/{chunk-HC6KTVFR.js → chunk-PQMLIVGV.js} +2 -2
  123. package/dist/cli/chunks/{chunk-RJN2RM76.js → chunk-PT3FTGKZ.js} +2 -2
  124. package/dist/cli/chunks/{chunk-ZXEWTZFR.js → chunk-Q5YRPS4P.js} +1 -1
  125. package/dist/cli/chunks/{chunk-AL5VJJN4.js → chunk-QJ6H2HQQ.js} +1 -1
  126. package/dist/cli/chunks/{chunk-AXKWV5NF.js → chunk-RG552ROA.js} +3 -3
  127. package/dist/cli/chunks/{chunk-RKXZLTWR.js → chunk-RHC7TFPU.js} +2 -2
  128. package/dist/cli/chunks/{chunk-RFLHPLET.js → chunk-RMFRFING.js} +1 -1
  129. package/dist/cli/chunks/{chunk-WMZ2QGGS.js → chunk-RQN4HWGV.js} +2 -2
  130. package/dist/cli/chunks/{chunk-3I4TCMOJ.js → chunk-RYUSZ43T.js} +1 -1
  131. package/dist/cli/chunks/{chunk-BTLUWH4R.js → chunk-RZDNCTOA.js} +2 -2
  132. package/dist/cli/chunks/chunk-SCMXIBI7.js +2 -0
  133. package/dist/cli/chunks/{chunk-FMNXHVIN.js → chunk-SPEUF7ZL.js} +2 -2
  134. package/dist/cli/chunks/{chunk-IU5RSN6M.js → chunk-SSXAW3ER.js} +2 -2
  135. package/dist/cli/chunks/{chunk-WPSK237F.js → chunk-TC2JE5OK.js} +3 -3
  136. package/dist/cli/chunks/{chunk-DFRRWOEX.js → chunk-TED4KOSK.js} +2 -2
  137. package/dist/cli/chunks/{chunk-SUL3I6QZ.js → chunk-TJ6N4CCX.js} +2 -2
  138. package/dist/cli/chunks/{chunk-Y25PO65W.js → chunk-TJEJ4UVX.js} +2 -2
  139. package/dist/cli/chunks/{chunk-G2ZIJZJ7.js → chunk-TO5PQSDD.js} +2 -2
  140. package/dist/cli/chunks/{chunk-MMEXHZUC.js → chunk-TR5GOGH3.js} +5 -5
  141. package/dist/cli/chunks/{chunk-OGNTCZKK.js → chunk-UGJQJSPB.js} +1 -1
  142. package/dist/cli/chunks/{chunk-AF6P5RWY.js → chunk-USB44IHJ.js} +2 -2
  143. package/dist/cli/chunks/{chunk-DLBVADWQ.js → chunk-UUOXV3NS.js} +42 -42
  144. package/dist/cli/chunks/chunk-UVVKFBF7.js +2 -0
  145. package/dist/cli/chunks/{chunk-FIPKIIMS.js → chunk-V2MD5EDD.js} +2 -2
  146. package/dist/cli/chunks/{chunk-DVW66FPU.js → chunk-VA7TEOPM.js} +1 -1
  147. package/dist/cli/chunks/{chunk-MCHEUSY4.js → chunk-VMP4M5PB.js} +1 -1
  148. package/dist/cli/chunks/{chunk-4Y3LGBKJ.js → chunk-VS4GMNJK.js} +3 -3
  149. package/dist/cli/chunks/{chunk-XKQY2Z3Q.js → chunk-VWJSWXHG.js} +1 -1
  150. package/dist/cli/chunks/{chunk-LPR2R3AN.js → chunk-VZ67ZDB3.js} +3 -3
  151. package/dist/cli/chunks/{chunk-TTJJ4DQE.js → chunk-W2OMW6UU.js} +2 -2
  152. package/dist/cli/chunks/{chunk-62UM7Q5N.js → chunk-W766S4SK.js} +1 -1
  153. package/dist/cli/chunks/{chunk-7P6X4BFO.js → chunk-WJYTLRA5.js} +3 -3
  154. package/dist/cli/chunks/{chunk-AOXJFDH5.js → chunk-WNASEUBW.js} +10 -10
  155. package/dist/cli/chunks/{chunk-YGVDP6X7.js → chunk-WT4ZDDFM.js} +1 -1
  156. package/dist/cli/chunks/{chunk-IBDQWKI3.js → chunk-XEYW3V5I.js} +2 -2
  157. package/dist/cli/chunks/{chunk-BLPWJQTY.js → chunk-XIFPIVZI.js} +2 -2
  158. package/dist/cli/chunks/{chunk-D45QLJEL.js → chunk-Y2MCIIJD.js} +1 -1
  159. package/dist/cli/chunks/{chunk-WHHQIL4F.js → chunk-YKOTOCO6.js} +2 -2
  160. package/dist/cli/chunks/{chunk-TRNBQFFG.js → chunk-Z3W3R4CW.js} +2 -2
  161. package/dist/cli/chunks/{chunk-KQVIWE3W.js → chunk-ZT2WHCVM.js} +2 -2
  162. package/dist/cli/chunks/{chunk-TBT3OFRW.js → chunk-ZVPAFX4I.js} +2 -2
  163. package/dist/cli/chunks/{chunk-VMWRMINE.js → chunk-ZWC6CM4R.js} +1 -1
  164. package/dist/cli/chunks/{ci-CBNVLOOQ.js → ci-RJH5LAL3.js} +2 -2
  165. package/dist/cli/chunks/{ci-output-I4HY2FYJ.js → ci-output-62SGMGB2.js} +2 -2
  166. package/dist/cli/chunks/{circuit-breaker-5VRBKGWL.js → circuit-breaker-QXTS5ZAW.js} +2 -2
  167. package/dist/cli/chunks/{claude-flow-setup-XPJPKHIO.js → claude-flow-setup-BBCCT5WV.js} +2 -2
  168. package/dist/cli/chunks/client-E2XUBCLK.js +2 -0
  169. package/dist/cli/chunks/{cline-installer-OFRDUUWZ.js → cline-installer-IZCUJJ3I.js} +2 -2
  170. package/dist/cli/chunks/{code-QIZQVB3E.js → code-AWNVOZ7S.js} +2 -2
  171. package/dist/cli/chunks/{code-index-extractor-LMUUWEX4.js → code-index-extractor-MX65BKMI.js} +2 -2
  172. package/dist/cli/chunks/{codex-installer-N2MKIZ2S.js → codex-installer-EQT6JVLM.js} +2 -2
  173. package/dist/cli/chunks/{completions-Y36S3C5J.js → completions-WOJAM45W.js} +2 -2
  174. package/dist/cli/chunks/{complexity-analyzer-73YS3WUD.js → complexity-analyzer-3DJB7V3K.js} +2 -2
  175. package/dist/cli/chunks/{continuedev-installer-SAOTP6J3.js → continuedev-installer-P4KWUTCJ.js} +2 -2
  176. package/dist/cli/chunks/{copilot-installer-A4HXF6HE.js → copilot-installer-FFZWTMWQ.js} +2 -2
  177. package/dist/cli/chunks/core-handlers-46Z5VOO6.js +2 -0
  178. package/dist/cli/chunks/{cost-tracker-P26XUVZS.js → cost-tracker-CYBOV3NI.js} +2 -2
  179. package/dist/cli/chunks/{coverage-HVNHSMVJ.js → coverage-GTZJBSC4.js} +3 -3
  180. package/dist/cli/chunks/cross-domain-router-SXQ3HFRY.js +2 -0
  181. package/dist/cli/chunks/{cursor-installer-46BQFTYZ.js → cursor-installer-WZIVXGGB.js} +2 -2
  182. package/dist/cli/chunks/{daemon-YE7K2AZF.js → daemon-JWMHEJEN.js} +4 -4
  183. package/dist/cli/chunks/{daemon-Y54O3FLT.js → daemon-MSFN2LXY.js} +3 -3
  184. package/dist/cli/chunks/{dag-attention-scheduler-ETA7YY52.js → dag-attention-scheduler-4TWOTTQE.js} +2 -2
  185. package/dist/cli/chunks/{detect-5WLQ2J3E.js → detect-YZ6AGQPB.js} +2 -2
  186. package/dist/cli/chunks/{dist-node-45WW6I7J.js → dist-node-3EM2XH54.js} +2 -2
  187. package/dist/cli/chunks/{domain-handler-J7DQV74M.js → domain-handler-4XU5BINU.js} +2 -2
  188. package/dist/cli/chunks/{domain-transfer-GD2EGQVR.js → domain-transfer-HUFC7I52.js} +2 -2
  189. package/dist/cli/chunks/dream-R6MQQQ3N.js +2 -0
  190. package/dist/cli/chunks/{embed-and-insert-pattern-JELNEA2D.js → embed-and-insert-pattern-J5ZFM6YX.js} +2 -2
  191. package/dist/cli/chunks/{eval-A4PA5G2U.js → eval-XYOA3EH2.js} +2 -2
  192. package/dist/cli/chunks/{experience-capture-middleware-MLHTYWTA.js → experience-capture-middleware-E3RYQB6Z.js} +3 -3
  193. package/dist/cli/chunks/{fast-paths-QYDTITRV.js → fast-paths-DKIYN2YS.js} +2 -2
  194. package/dist/cli/chunks/{feature-flags-MQYYRHIK.js → feature-flags-S2RNZATS.js} +2 -2
  195. package/dist/cli/chunks/{feature-flags-H4MSY26Z.js → feature-flags-ZB63Z7N5.js} +2 -2
  196. package/dist/cli/chunks/{file-discovery-RMFVJNGL.js → file-discovery-USJJLYQU.js} +2 -2
  197. package/dist/cli/chunks/{fleet-7KZQOTAC.js → fleet-4MUPHSF5.js} +3 -3
  198. package/dist/cli/chunks/{gnn-wrapper-NMZFTGVH.js → gnn-wrapper-PYOQZKX6.js} +2 -2
  199. package/dist/cli/chunks/{heartbeat-handler-7BQDK7MG.js → heartbeat-handler-HLO5XCG7.js} +4 -4
  200. package/dist/cli/chunks/heartbeat-scheduler-OSDPJT6A.js +2 -0
  201. package/dist/cli/chunks/hnsw-adapter-KMGSHBIN.js +2 -0
  202. package/dist/cli/chunks/hnsw-index-IMFRAOPE.js +2 -0
  203. package/dist/cli/chunks/{hnsw-legacy-bridge-TPPGBPKF.js → hnsw-legacy-bridge-FZEH2KLM.js} +2 -2
  204. package/dist/cli/chunks/{better-sqlite3-2KR4LQRU.js → hnswlib-node-VS6L5VUG.js} +2 -2
  205. package/dist/cli/chunks/{hooks-CYZIUYSH.js → hooks-R2757K57.js} +10 -10
  206. package/dist/cli/chunks/hybrid-router-57QSWSWC.js +2 -0
  207. package/dist/cli/chunks/{hypergraph-engine-WC6DMTYQ.js → hypergraph-engine-EAV3GJ5D.js} +2 -2
  208. package/dist/cli/chunks/{hypergraph-handler-GTGA3TXJ.js → hypergraph-handler-5ERXAVGH.js} +3 -3
  209. package/dist/cli/chunks/impact-analyzer-OC4MPBGA.js +2 -0
  210. package/dist/cli/chunks/{init-handler-N3Z72JNI.js → init-handler-RXUSEMG7.js} +6 -6
  211. package/dist/cli/chunks/init-wizard-CDBRL4PO.js +2 -0
  212. package/dist/cli/chunks/kernel-CQ7R3AAV.js +2 -0
  213. package/dist/cli/chunks/{kilocode-installer-FUX4V6II.js → kilocode-installer-ZUBVBHGT.js} +2 -2
  214. package/dist/cli/chunks/{kiro-installer-ZSNZT7ZR.js → kiro-installer-TRTRQDGL.js} +2 -2
  215. package/dist/cli/chunks/knowledge-graph-UXNH7RY4.js +2 -0
  216. package/dist/cli/chunks/{learning-UQY64COU.js → learning-UYXWAU5D.js} +3 -3
  217. package/dist/cli/chunks/{llm-router-CMHGGX6N.js → llm-router-TB5OJPEV.js} +4 -4
  218. package/dist/cli/chunks/llm-router-service-UV34YXBE.js +2 -0
  219. package/dist/cli/chunks/{load-E6WH4QN2.js → load-ELPSUIPV.js} +2 -2
  220. package/dist/cli/chunks/load-test-2VEN3PQZ.js +2 -0
  221. package/dist/cli/chunks/{mcp-UM5VTW6N.js → mcp-UX7TK3XV.js} +2 -2
  222. package/dist/cli/chunks/{memory-7Q3XDUE5.js → memory-W3LG6H6N.js} +5 -5
  223. package/dist/cli/chunks/memory-backend-TZL5U6F3.js +2 -0
  224. package/dist/cli/chunks/memory-handlers-BNXAYS2P.js +2 -0
  225. package/dist/cli/chunks/{multi-model-executor-LZENWVRR.js → multi-model-executor-227LWZRY.js} +2 -2
  226. package/dist/cli/chunks/{opencode-installer-O2JAIPLF.js → opencode-installer-F4WKVWDL.js} +2 -2
  227. package/dist/cli/chunks/{orchestrator-DKZWXDRI.js → orchestrator-V4DBMGK6.js} +5 -5
  228. package/dist/cli/chunks/pattern-null-store-KLX2RNHM.js +2 -0
  229. package/dist/cli/chunks/{pattern-usage-recorder-CLUL4M55.js → pattern-usage-recorder-BY3HEWSU.js} +2 -2
  230. package/dist/cli/chunks/{pipeline-2VDLTR5J.js → pipeline-3F5RIESX.js} +2 -2
  231. package/dist/cli/chunks/{platform-4N4Q5XYX.js → platform-KCGXTZO3.js} +2 -2
  232. package/dist/cli/chunks/{plugin-GY5AU5CS.js → plugin-2H552KOV.js} +2 -2
  233. package/dist/cli/chunks/{prime-radiant-advanced-wasm-TQ4DKDZS.js → prime-radiant-advanced-wasm-EFKVL7VN.js} +2 -2
  234. package/dist/cli/chunks/protocol-executor-5HJKW6MC.js +2 -0
  235. package/dist/cli/chunks/{protocol-handler-T3LZ3WRG.js → protocol-handler-ELGYV7D2.js} +2 -2
  236. package/dist/cli/chunks/{prove-OV7S5J4W.js → prove-AYJCQYNI.js} +2 -2
  237. package/dist/cli/chunks/provider-manager-TRZSBXD3.js +2 -0
  238. package/dist/cli/chunks/qe-reasoning-bank-RCEYSLVV.js +2 -0
  239. package/dist/cli/chunks/{quality-AXD4NLQA.js → quality-HH7L5A7V.js} +2 -2
  240. package/dist/cli/chunks/quality-gate-NAQLXE4C.js +7 -0
  241. package/dist/cli/chunks/queen-coordinator-6JFZD54W.js +2 -0
  242. package/dist/cli/chunks/{real-embeddings-2PUCC7FG.js → real-embeddings-IO3F4ZFR.js} +2 -2
  243. package/dist/cli/chunks/{roocode-installer-WJ5ARGLW.js → roocode-installer-X4TU5HO4.js} +2 -2
  244. package/dist/cli/chunks/router-KRLC46NS.js +2 -0
  245. package/dist/cli/chunks/routing-feedback-WW26H6SA.js +2 -0
  246. package/dist/cli/chunks/{routing-handler-CU6657SZ.js → routing-handler-ZJKGDDMT.js} +2 -2
  247. package/dist/cli/chunks/{ruvector-commands-IIF6VSFW.js → ruvector-commands-NXCSUBN2.js} +2 -2
  248. package/dist/cli/chunks/{rvf-dual-writer-YMQI7XO2.js → rvf-dual-writer-JMA74SKP.js} +2 -2
  249. package/dist/cli/chunks/{rvf-migration-adapter-HDE3PR2W.js → rvf-migration-adapter-BNTGH2KU.js} +2 -2
  250. package/dist/cli/chunks/{rvf-migration-coordinator-MQV5OA7K.js → rvf-migration-coordinator-7T2HHUOH.js} +2 -2
  251. package/dist/cli/chunks/rvf-native-adapter-OVQKPQUH.js +2 -0
  252. package/dist/cli/chunks/safe-db-UQOCQIH2.js +2 -0
  253. package/dist/cli/chunks/schedule-EUX7ZQUK.js +2 -0
  254. package/dist/cli/chunks/scheduler-MALHQKNR.js +2 -0
  255. package/dist/cli/chunks/{security-UM3IGDSM.js → security-XSK2QHB3.js} +3 -3
  256. package/dist/cli/chunks/{shared-rvf-adapter-I3SOJ6M4.js → shared-rvf-adapter-WLRKI7RY.js} +2 -2
  257. package/dist/cli/chunks/{shared-rvf-dual-writer-KQGC2UO7.js → shared-rvf-dual-writer-SZW3J7ZK.js} +2 -2
  258. package/dist/cli/chunks/sqlite-persistence-OBCLRP4L.js +2 -0
  259. package/dist/cli/chunks/{status-handler-OX4CJZME.js → status-handler-HGCKYJX2.js} +2 -2
  260. package/dist/cli/chunks/{structural-health-PYUMVBXJ.js → structural-health-4SJCFX63.js} +2 -2
  261. package/dist/cli/chunks/{sync-2TED3YTY.js → sync-7WAVNZGL.js} +2 -2
  262. package/dist/cli/chunks/{sync-VALFNTA6.js → sync-ATR4DUSA.js} +2 -2
  263. package/dist/cli/chunks/{task-handler-VPGAJVPC.js → task-handler-O6REL34Y.js} +2 -2
  264. package/dist/cli/chunks/{task-handlers-IB4UAMU6.js → task-handlers-WFV2ZYWW.js} +3 -3
  265. package/dist/cli/chunks/{test-OMRJOZB6.js → test-4LXUVHEU.js} +4 -4
  266. package/dist/cli/chunks/{test-scheduling-ZL3YFPBU.js → test-scheduling-OTN3DMKY.js} +3 -3
  267. package/dist/cli/chunks/{token-bootstrap-DNWZI7SH.js → token-bootstrap-VA7T4P42.js} +2 -2
  268. package/dist/cli/chunks/{token-usage-IYO7RGFF.js → token-usage-TLT6OXXR.js} +2 -2
  269. package/dist/cli/chunks/{transformers-53ALC34T.js → transformers-JI7LZRQ3.js} +2 -2
  270. package/dist/cli/chunks/{tree-sitter-wasm-parser-WUKJ2I2Q.js → tree-sitter-wasm-parser-QNIMHB4K.js} +2 -2
  271. package/dist/cli/chunks/{types-47FTEPMV.js → types-DJNWOAC6.js} +2 -2
  272. package/dist/cli/chunks/unified-memory-A5BS3LGX.js +2 -0
  273. package/dist/cli/chunks/unified-memory-hnsw-WJLJO5MY.js +2 -0
  274. package/dist/cli/chunks/unified-persistence-CFC2BKI5.js +2 -0
  275. package/dist/cli/chunks/{upgrade-QPLMJA5Z.js → upgrade-VEW4FL23.js} +2 -2
  276. package/dist/cli/chunks/{validate-3GVKZOVF.js → validate-O3P6PF7B.js} +2 -2
  277. package/dist/cli/chunks/{validate-swarm-XCRTLVM6.js → validate-swarm-M2HXHZVC.js} +2 -2
  278. package/dist/cli/chunks/{vibium-CH4VPKVZ.js → vibium-GOU55LUO.js} +2 -2
  279. package/dist/cli/chunks/visual-security-VPB6KVYJ.js +2 -0
  280. package/dist/cli/chunks/{web-tree-sitter-JDBNAZTV.js → web-tree-sitter-MXOI4GH3.js} +2 -2
  281. package/dist/cli/chunks/{windsurf-installer-3MNPVJBP.js → windsurf-installer-6GKT53IH.js} +2 -2
  282. package/dist/cli/chunks/{witness-chain-HR5UBV5J.js → witness-chain-OXGQGL26.js} +2 -2
  283. package/dist/cli/chunks/witness-chain-ZZAUAXDY.js +2 -0
  284. package/dist/cli/chunks/{witness-key-manager-G5SQTIBZ.js → witness-key-manager-PGFSQXUJ.js} +2 -2
  285. package/dist/cli/chunks/{workflow-43EMD5FY.js → workflow-ENBWRMBA.js} +4 -4
  286. package/dist/cli/chunks/workflow-orchestrator-S4LBFTYD.js +2 -0
  287. package/dist/cli/chunks/{wrappers-3N7AYNM3.js → wrappers-MHLNYANQ.js} +2 -2
  288. package/dist/cli/commands/quality-gate.d.ts +24 -0
  289. package/dist/cli/commands/quality-gate.js +135 -0
  290. package/dist/cli/index.js +5 -0
  291. package/dist/coordination/mincut/dream-integration.d.ts +11 -0
  292. package/dist/coordination/mincut/dream-integration.js +39 -12
  293. package/dist/integrations/ruvector/feature-flags.js +7 -0
  294. package/dist/learning/pattern-lifecycle.d.ts +16 -0
  295. package/dist/learning/pattern-lifecycle.js +77 -1
  296. package/dist/learning/provenance-tier.d.ts +52 -0
  297. package/dist/learning/provenance-tier.js +64 -0
  298. package/dist/learning/qe-flywheel/corpus-scorer.d.ts +55 -0
  299. package/dist/learning/qe-flywheel/corpus-scorer.js +293 -0
  300. package/dist/learning/qe-flywheel/coupled-anchor.d.ts +91 -0
  301. package/dist/learning/qe-flywheel/coupled-anchor.js +181 -0
  302. package/dist/learning/qe-flywheel/generation.d.ts +121 -0
  303. package/dist/learning/qe-flywheel/generation.js +167 -0
  304. package/dist/learning/qe-flywheel/policy.d.ts +37 -0
  305. package/dist/learning/qe-flywheel/policy.js +66 -0
  306. package/dist/learning/qe-flywheel/receipt-store.d.ts +31 -0
  307. package/dist/learning/qe-flywheel/receipt-store.js +89 -0
  308. package/dist/learning/qe-flywheel/receipt.d.ts +62 -0
  309. package/dist/learning/qe-flywheel/receipt.js +97 -0
  310. package/dist/mcp/bundle.js +396 -390
  311. package/dist/mcp/tools/quality-assessment/gate.d.ts +38 -0
  312. package/dist/mcp/tools/quality-assessment/gate.js +86 -0
  313. package/dist/mcp/tools/registry.d.ts +1 -0
  314. package/dist/mcp/tools/registry.js +3 -0
  315. package/dist/shared/safe-db.js +23 -4
  316. package/dist/validation/anchor-set.d.ts +74 -0
  317. package/dist/validation/anchor-set.js +78 -0
  318. package/dist/validation/frontier-judge.d.ts +99 -0
  319. package/dist/validation/frontier-judge.js +234 -0
  320. package/dist/validation/gate-reexecute.d.ts +165 -0
  321. package/dist/validation/gate-reexecute.js +255 -0
  322. package/dist/validation/quality-gate-runner.d.ts +49 -0
  323. package/dist/validation/quality-gate-runner.js +62 -0
  324. package/dist/validation/quality-verdict.d.ts +94 -0
  325. package/dist/validation/quality-verdict.js +120 -0
  326. package/package.json +1 -1
  327. package/dist/cli/chunks/adapter-KNM5R47J.js +0 -2
  328. package/dist/cli/chunks/aqe-learning-engine-MXPJLVR3.js +0 -2
  329. package/dist/cli/chunks/base-X4EXQ2AS.js +0 -2
  330. package/dist/cli/chunks/browser-workflow-4HX6RP5F.js +0 -2
  331. package/dist/cli/chunks/chunk-FHTYEAQ3.js +0 -2
  332. package/dist/cli/chunks/chunk-MIU5RUBJ.js +0 -149
  333. package/dist/cli/chunks/chunk-V6NAB5UZ.js +0 -2
  334. package/dist/cli/chunks/chunk-YR2JKBZO.js +0 -2
  335. package/dist/cli/chunks/chunk-ZMPAM4DY.js +0 -2
  336. package/dist/cli/chunks/client-AHXNCOHK.js +0 -2
  337. package/dist/cli/chunks/core-handlers-EEFLLMAZ.js +0 -2
  338. package/dist/cli/chunks/cross-domain-router-LT3H4SNJ.js +0 -2
  339. package/dist/cli/chunks/dream-4K3BK4IG.js +0 -2
  340. package/dist/cli/chunks/heartbeat-scheduler-IMPPGQUK.js +0 -2
  341. package/dist/cli/chunks/hnsw-adapter-EIAA6R2L.js +0 -2
  342. package/dist/cli/chunks/hnsw-index-ZXXP6AXZ.js +0 -2
  343. package/dist/cli/chunks/hybrid-router-LXWG4MLH.js +0 -2
  344. package/dist/cli/chunks/impact-analyzer-TP5LRFYH.js +0 -2
  345. package/dist/cli/chunks/init-wizard-AIOA5KOY.js +0 -2
  346. package/dist/cli/chunks/kernel-SQALRU6Q.js +0 -2
  347. package/dist/cli/chunks/knowledge-graph-JFVT6SNN.js +0 -2
  348. package/dist/cli/chunks/llm-router-service-XHFKTH3I.js +0 -2
  349. package/dist/cli/chunks/load-test-JEIFJKNN.js +0 -2
  350. package/dist/cli/chunks/memory-backend-NT7I37CP.js +0 -2
  351. package/dist/cli/chunks/memory-handlers-746D7NE7.js +0 -2
  352. package/dist/cli/chunks/pattern-null-store-6QU6WHDW.js +0 -2
  353. package/dist/cli/chunks/protocol-executor-GT2MZYUU.js +0 -2
  354. package/dist/cli/chunks/provider-manager-OATJ7R3D.js +0 -2
  355. package/dist/cli/chunks/qe-reasoning-bank-IJXNQ67O.js +0 -2
  356. package/dist/cli/chunks/queen-coordinator-6RBHWCUG.js +0 -2
  357. package/dist/cli/chunks/router-XKQRT5JK.js +0 -2
  358. package/dist/cli/chunks/routing-feedback-ACPSD4LW.js +0 -2
  359. package/dist/cli/chunks/rvf-native-adapter-SIWRKE33.js +0 -2
  360. package/dist/cli/chunks/safe-db-LCPUYMX4.js +0 -2
  361. package/dist/cli/chunks/schedule-HIQJCWXG.js +0 -2
  362. package/dist/cli/chunks/scheduler-QE5EJ5LE.js +0 -2
  363. package/dist/cli/chunks/sqlite-persistence-EU54UTMH.js +0 -2
  364. package/dist/cli/chunks/unified-memory-CJLMC2I4.js +0 -2
  365. package/dist/cli/chunks/unified-memory-hnsw-FDGR4D2J.js +0 -2
  366. package/dist/cli/chunks/unified-persistence-UFH5GLDN.js +0 -2
  367. package/dist/cli/chunks/visual-security-4ARJ7J2Y.js +0 -2
  368. package/dist/cli/chunks/witness-chain-73QC33ED.js +0 -2
  369. package/dist/cli/chunks/workflow-orchestrator-RKMMPXNA.js +0 -2
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
- import{d as J,e as B,f as te,g as j}from"./chunk-MCHEUSY4.js";import{a as re}from"./chunk-YGVDP6X7.js";import{g as it,h as st}from"./chunk-JBKZ5TUM.js";import{b as De,c as rt}from"./chunk-YFCULQBP.js";import{a as Fe,d as Oe,e as nt,f as Ie}from"./chunk-RJN2RM76.js";import{a as ne}from"./chunk-OS62Y77J.js";import{b as P,c as w}from"./chunk-5WMU7XCF.js";import{a as v,b as xe,c as Ce}from"./chunk-RKXZLTWR.js";import{i as C}from"./chunk-K4I7UIU5.js";import{B as q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-GODAWJMZ.js";import{a as Ae,d as $,f as tt,g as Te}from"./chunk-C4EZNOWK.js";var G=$(E=>{var mt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var pt=Object.prototype.hasOwnProperty;function le(n,e){return pt.call(n,e)}E.hasOwnProperty=le;function Qe(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)le(n,s)&&r.push(s);return r}E._objectKeys=Qe;function gt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=gt;function yt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=yt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=oe;function vt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=vt;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""}E._getPathRecursive=ue;function Pt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Pt;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=Qe(n),s=r.length,i=0;i<s;i++)if(ce(n[r[i]]))return!0}}return!1}E.hasUndefined=ce;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
3
- `)}var wt=(function(n){mt(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=wt});var he=$(y=>{Object.defineProperty(y,"__esModule",{value:!0});var R=G();y.JsonPatchError=R.PatchError;y.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},St={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}y.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new y.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,p=void 0;for(typeof t=="function"?p=t:p=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&p(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new y.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new y.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=St[e.op].call(e,o,h,n);if(a.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new y.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}y.applyOperation=O;function ze(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new y.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}y.applyPatch=ze;function bt(n,e,t){var r=O(n,e);if(r.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}y.applyReducer=bt;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new y.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new y.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 y.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 y.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 y.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new y.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new y.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 y.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=$e([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new y.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new y.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}y.validator=Y;function $e(n,e,t){try{if(!Array.isArray(n))throw new y.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)ze(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof y.JsonPatchError)return s;throw s}}y.validate=$e;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}y._areEquals=z});var Je=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),Et=he(),fe=new WeakMap,Rt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),At=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Tt(n){return fe.get(n)}function xt(n,e){return n.observers.get(e)}function Ct(n,e){n.observers.delete(e.callback)}function Dt(n,e){e.unobserve()}k.unobserve=Dt;function Ft(n,e){var t=[],r,s=Tt(n);if(!s)s=new Rt(n),fe.set(n,s);else{var i=xt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){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),Ct(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new At(e,r)),r}k.observe=Ft;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);me(t.value,n.object,n.patches,"",e),n.patches.length&&Et.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 me(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?me(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ot(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=Ot});var Be=$(I=>{var It=he();Object.assign(I,It);var Nt=Je();Object.assign(I,Nt);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});rt();Ce();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-EU54UTMH.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,p=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],p+=d[S]*d[S];if(p=Math.sqrt(p),p===0)continue;let m=h/(o*p),g=this.calculateReuseInfo(f,m);i.push({pattern:f,score:m,matchType:"vector",similarity:m,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};Ie();Ce();F();function ot(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ct(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=ot(n,e.field);return ct(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var He=1e4,Me=2166136261;function Le(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 _e="0123456789abcdef";function lt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=_e[s>>4]+_e[s&15]}return t}function ut(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 ht(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function dt(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=ae[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function ft(n,e,t){return 1-dt(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??He,this.baseSeed=e?.seed??Me,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=Le(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=ut(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ht([r,s])}similarity(e,t){return ft(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new re(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??He,this.baseSeed=e?.seed??Me,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=Le(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:lt(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=ae[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new re(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function ke(n){return new se(n)}function Ue(n){return q()?new ie(n):null}var ge=tt(Be(),1),pe=ge.default??ge,_t=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.0");process.exit(0)}
2
+ import{d as J,e as B,f as te,g as j}from"./chunk-VMP4M5PB.js";import{a as re}from"./chunk-WT4ZDDFM.js";import{g as it,h as st}from"./chunk-FI5SSLEF.js";import{b as De,c as rt}from"./chunk-L5ZLOW3K.js";import{a as Fe,d as Oe,e as nt,f as Ie}from"./chunk-PT3FTGKZ.js";import{a as ne}from"./chunk-GGMQOEZZ.js";import{b as P,c as w}from"./chunk-7ZIVDGSN.js";import{a as v,b as xe,c as Ce}from"./chunk-RHC7TFPU.js";import{i as C}from"./chunk-6JNNZGI2.js";import{B as q,D as H,G as ee,P as M,S as F,b as D}from"./chunk-2KHDGC7N.js";import{a as Ae,d as $,f as tt,g as Te}from"./chunk-3AFNXU45.js";var G=$(E=>{var mt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,s){r.__proto__=s}||function(r,s){for(var i in s)s.hasOwnProperty(i)&&(r[i]=s[i])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var pt=Object.prototype.hasOwnProperty;function le(n,e){return pt.call(n,e)}E.hasOwnProperty=le;function Qe(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var s in n)le(n,s)&&r.push(s);return r}E._objectKeys=Qe;function gt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=gt;function yt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=yt;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=oe;function vt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=vt;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""}E._getPathRecursive=ue;function Pt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Pt;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=Qe(n),s=r.length,i=0;i<s;i++)if(ce(n[r[i]]))return!0}}return!1}E.hasUndefined=ce;function qe(n,e){var t=[n];for(var r in e){var s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(r+": "+s)}return t.join(`
3
+ `)}var wt=(function(n){mt(e,n);function e(t,r,s,i,a){var c=this.constructor,u=n.call(this,qe(t,{name:r,index:s,operation:i,tree:a}))||this;return u.name=r,u.index=s,u.operation=i,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=qe(t,{name:r,index:s,operation:i,tree:a}),u}return e})(Error);E.PatchError=wt});var he=$(y=>{Object.defineProperty(y,"__esModule",{value:!0});var R=G();y.JsonPatchError=R.PatchError;y.deepClone=R._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=V(t,this.path);r&&(r=R._deepClone(r));var s=O(t,{op:"remove",path:this.from}).removed;return O(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=V(t,this.from);return O(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},St={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function V(n,e){if(e=="")return n;var t={op:"_get",path:e};return O(n,t),t.value}y.getValueByPointer=V;function O(n,e,t,r,s,i){if(t===void 0&&(t=!1),r===void 0&&(r=!0),s===void 0&&(s=!0),i===void 0&&(i=0),t&&(typeof t=="function"?t(e,0,n,e.path):Y(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=V(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new y.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,n);return a}}else{r||(n=R._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,f=u.length,d=void 0,h=void 0,p=void 0;for(typeof t=="function"?p=t:p=Y;;){if(h=u[l],h&&h.indexOf("~")!=-1&&(h=R.unescapePathComponent(h)),s&&(h=="__proto__"||h=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&d===void 0&&(o[h]===void 0?d=u.slice(0,l).join("/"):l==f-1&&(d=e.path),d!==void 0&&p(e,0,n,d)),l++,Array.isArray(o)){if(h==="-")h=o.length;else{if(t&&!R.isInteger(h))throw new y.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,n);R.isInteger(h)&&(h=~~h)}if(l>=f){if(t&&e.op==="add"&&h>o.length)throw new y.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,n);var a=St[e.op].call(e,o,h,n);if(a.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}}else if(l>=f){var a=L[e.op].call(e,o,h,n);if(a.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",i,e,n);return a}if(o=o[h],t&&l<f&&(!o||typeof o!="object"))throw new y.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,n)}}}y.applyOperation=O;function ze(n,e,t,r,s){if(r===void 0&&(r=!0),s===void 0&&(s=!0),t&&!Array.isArray(e))throw new y.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var i=new Array(e.length),a=0,c=e.length;a<c;a++)i[a]=O(n,e[a],t,!0,s,a),n=i[a].newDocument;return i.newDocument=n,i}y.applyPatch=ze;function bt(n,e,t){var r=O(n,e);if(r.test===!1)throw new y.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}y.applyReducer=bt;function Y(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new y.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new y.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 y.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 y.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 y.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new y.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,i=r.split("/").length;if(s!==i+1&&s!==i)throw new y.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 y.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=$e([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new y.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new y.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}y.validator=Y;function $e(n,e,t){try{if(!Array.isArray(n))throw new y.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)ze(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||Y;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof y.JsonPatchError)return s;throw s}}y.validate=$e;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,i,a;if(t&&r){if(i=n.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!z(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}y._areEquals=z});var Je=$(k=>{Object.defineProperty(k,"__esModule",{value:!0});var b=G(),Et=he(),fe=new WeakMap,Rt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),At=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Tt(n){return fe.get(n)}function xt(n,e){return n.observers.get(e)}function Ct(n,e){n.observers.delete(e.callback)}function Dt(n,e){e.unobserve()}k.unobserve=Dt;function Ft(n,e){var t=[],r,s=Tt(n);if(!s)s=new Rt(n),fe.set(n,s);else{var i=xt(s,e);r=i&&i.observer}if(r)return r;if(r={},s.value=b._deepClone(n),e){r.callback=e,r.next=null;var a=function(){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),Ct(s,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},s.observers.set(e,new At(e,r)),r}k.observe=Ft;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);me(t.value,n.object,n.patches,"",e),n.patches.length&&Et.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 me(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=b._objectKeys(e),a=b._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],f=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof f=="object"&&f!=null&&typeof d=="object"&&d!=null&&Array.isArray(f)===Array.isArray(d)?me(f,d,t,r+"/"+b.escapePathComponent(l),s):f!==d&&(c=!0,s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),u=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&i.length==a.length))for(var o=0;o<i.length;o++){var l=i[o];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Ot(n,e,t){t===void 0&&(t=!1);var r=[];return me(n,e,r,"",t),r}k.compare=Ot});var Be=$(I=>{var It=he();Object.assign(I,It);var Nt=Je();Object.assign(I,Nt);var K=G();I.JsonPatchError=K.PatchError;I.deepClone=K._deepClone;I.escapePathComponent=K.escapePathComponent;I.unescapePathComponent=K.unescapePathComponent});rt();Ce();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??W,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=v(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-OBCLRP4L.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:s}=await import("node:fs"),i=`${this.rvfPath}.idmap.json`;if(!s(i))return;let a=JSON.parse(r(i,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${v(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,v(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,v(r))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:J({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),s=t.limit??10,i=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,s*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.score);i.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",v(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&i.length===0)try{let c=this.sqliteStore.getPatterns({limit:s*4}),u=e,o=Math.sqrt(u.reduce((l,f)=>l+f*f,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let f=this.sqliteStore.getPattern(l.id),d=f?.embedding;if(!d||d.length!==u.length)continue;let h=0,p=0;for(let S=0;S<u.length;S++)h+=u[S]*d[S],p+=d[S]*d[S];if(p=Math.sqrt(p),p===0)continue;let m=h/(o*p),g=this.calculateReuseInfo(f,m);i.push({pattern:f,score:m,matchType:"vector",similarity:m,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:s*2}),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);i.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,s*2),u=new Set(i.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let f=this.calculateReuseInfo(l,o.ftsScore);i.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}}catch{}i.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,P(i.slice(0,s))}async recordUsage(e,t,r,s){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,s),P(void 0)}catch(i){return w(new Error(`recordUsage failed: ${v(i)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return w(new Error(`promote failed: ${v(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,v(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${v(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},s={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let i=this.sqliteStore.getStats();t=i.totalPatterns,r=i.byDomain,s={shortTerm:i.byTier["short-term"]??0,longTerm:i.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:s,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let s of r)s.confidence<this.config.minConfidence&&s.usageCount>3?(await this.delete(s.id),e++):s.tier==="short-term"&&s.successfulUses>=B&&(await this.promote(s.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",v(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,s=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:s,estimatedTokenSavings:s?500:0,reuseConfidence:s?t*e.successRate:0}}};Ie();Ce();F();function ot(n,e){let r=[n.pattern,n];for(let s of r){let i=e.split("."),a=s;for(let c of i){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function ct(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let i=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return i>=a&&i<=c}return!1}let[r,s]=t;return n>=r&&n<=s}default:return!1}}function X(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>X(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>X(n,r))}case"NOT":return e.child?!X(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=ot(n,e.field);return ct(t,e.operator,e.value)}default:return!0}}function Ne(n,e){return e?n.filter(t=>X(t,e)):n}F();F();var He=1e4,Me=2166136261;function Le(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 _e="0123456789abcdef";function lt(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let s=n[r];t+=_e[s>>4]+_e[s&15]}return t}function ut(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 ht(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let s=1;s<n.length;s++)if(n[s].length!==e)throw new Error(`Vector length mismatch at index ${s}: expected ${e}, got ${n[s].length}`);let t=new Uint8Array(e),r=n.length/2;for(let s=0;s<e;s++){let i=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][s]&u&&c++;c>=r&&(i|=u)}t[s]=i}return t}function dt(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let i=0;i<n.length;i++)r+=ae[n[i]^e[i]];let s=t??n.length*8;return s>0?r/s:0}function ft(n,e,t){return 1-dt(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??He,this.baseSeed=e?.seed??Me,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=Le(e)^this.baseSeed,s=this.generateSeededVector(r);return this.tokenCache.set(e,s),new Uint8Array(s)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=ut(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let s=this.fingerprintPattern(t);return ht([r,s])}similarity(e,t){return ft(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new re(e),s=0;for(;s<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-s);for(let u=0;u<c;u++)t[s++]=a>>>u*8&255}let i=this.dimensions%8;return i>0&&(t[this.byteLen-1]&=(1<<i)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??He,this.baseSeed=e?.seed??Me,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=Le(t)^this.baseSeed,s=this.generateVector(r);return{vector:s,dimensions:this.dimensions,hash:lt(s)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let s=0;s<e.length;s++)r[s]=e[s]^t[s];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let s=0;s<e.length;s++)r+=ae[e[s]^t[s]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),s=new re(e),i=0;for(;i<t;){let c=s.next(),u=t-i,o=u<4?u:4;for(let l=0;l<o;l++)r[i++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function ke(n){return new se(n)}function Ue(n){return q()?new ie(n):null}var ge=tt(Be(),1),pe=ge.default??ge,_t=`
4
4
  CREATE TABLE IF NOT EXISTS pattern_deltas (
5
5
  id TEXT PRIMARY KEY,
6
6
  pattern_id TEXT NOT NULL,
@@ -46,7 +46,7 @@ import{d as J,e as B,f as te,g as j}from"./chunk-MCHEUSY4.js";import{a as re}fro
46
46
  WHERE pattern_id = ? AND version != 0
47
47
  ORDER BY version ASC
48
48
  LIMIT ?
49
- )`).run(e,e,i)}}};F();var Mt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ye=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Mt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Xe(n){return H()?new ye(n):null}F();var Lt=128,kt=8,Ut=1e4,ve=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Lt,this.beta=e?.beta??kt,this.maxPatterns=e?.maxPatterns??Ut,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ge(n){return new ve(n)}F();var qt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},N=1e-5,Ve=1-N;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function zt(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(zt(e,t)),s=Math.max(N,1-A(e)),i=Math.max(N,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(N,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(N,1-A(e)),s=Math.sqrt(A(t));if(s<N)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ve)return new Float32Array(e);let r=Ve/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<N)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},Pe=class{config;points=new Map;constructor(e){if(this.config={...qt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,p=new Float32Array(r);p[0]=d*Math.cos(h),p[1]=d*Math.sin(h);let m=i.get(u);if(m&&m.features.length>0){let _=d*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*_}let g=T.project(p);t.set(u,g),this.points.set(u,{id:u,coordinates:g,metadata:{depth:o,parentId:m?.parentId}});let S=s.get(u)??[];for(let _=0;_<S.length;_++){let x=f/Math.max(1,S.length);c.push({id:S[_],depth:o+1,angOff:l+_*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ye(n){return $t()?new Pe(n):null}function $t(){return D().useHyperbolicHnsw}F();var we=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=Ye(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ke(n){return new we(n)}var Se=null;function Ze(){return Se||(Se=ke({dimensions:1e4})),Se}var be;function Jt(){return be===void 0&&(be=Ue()),be}var U=null,Ee=0;function et(n){return(!U||Ee!==n)&&(U=Ge({dimension:n,maxPatterns:1e4}),Ee=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Re=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-TPPGBPKF.js"),{HnswAdapter:c}=await import("./hnsw-adapter-EIAA6R2L.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-ZXXP6AXZ.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Xe()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ze().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=Jt();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{et(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=et(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let p=h.metadata.id,m=await this.get(p);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,h.similarity);i.push({pattern:m,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let p of h){let m=await this.get(p.key);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,p.score);i.push({pattern:m,score:p.score,matchType:"vector",similarity:p.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(m=>[m.id,m.ftsScore])),p=new Set(i.map(m=>m.pattern.id));for(let m of i){let g=h.get(m.pattern.id);g!==void 0&&(m.score=.75*m.score+.25*g)}for(let m of d){if(p.has(m.id))continue;let g=await this.get(m.id);if(g&&this.matchesFilters(g,t)){let S=this.calculateReuseInfo(g,m.ftsScore);i.push({pattern:g,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(p=>p.pattern.id));for(let p of d)h.has(p.pattern.id)||i.push(p)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),p=c-h,m=Math.pow(.5,p/a),g=d.pattern.usageCount>0?m:.5;d.score=d.score*(.7+.3*g)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ne(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let p=d.get(h.pattern.id);p&&(h.nullSummary=p,h.score=ne.applyNullDiscount(h.score,p,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&i&&this.hdcCache.size>0)try{let u=Ze(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,p)=>p.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),p=o?f*.4+d*.4+h*.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,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(g){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(g))}if(H()&&this.deltaTracker)try{let g={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,g,S,{success:t})}catch(g){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(g))}let p=te(h);return p.meetsUsageCriteria&&p.meetsQualityCriteria&&p.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Ee=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ke({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function $r(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Ae("fs"),{join:s}=Ae("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let{getSharedRvfAdapter:l}=(st(),Te(it)),f=l(a,u.embeddingDimension);if(f){o=!0;let d=new Q(()=>f,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}catch{}if(!o){let l=new Q((f,d)=>{let{openRvfStore:h}=(Ie(),Te(nt)),p=()=>{try{return h(f)}catch{return null}},m=p();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return Fe(f,d)}catch(g){if(m=p(),m&&m.dimension()===d)return m;throw g}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Re(n,e)}export{$r as a};
49
+ )`).run(e,e,i)}}};F();var Mt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},ye=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Mt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let s=this.computeSparseChanges(new Array(t.length).fill(0),t),i={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:s,metadata:r,compressedSize:s.length},a={patternId:e,version:0,fullVector:[...t],timestamp:i.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(i),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(i),i}recordDelta(e,t,r,s){let i=this.versions.get(e);if(i===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=i+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:s,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let s=[...r].reverse();return t!==void 0&&t>0?s.slice(0,t):s}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let s=this.versions.get(e);if(t<0||t>s)return null;let i=this.snapshots.get(e)||[],a=null;for(let o=i.length-1;o>=0;o--)if(i[o].version<=t){a=i[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,s=this.history.get(e);if(!s||s.length<=r)return 0;let i=s.length-r,a=s.slice(0,i),c=s.slice(i),u=a.findIndex(f=>f.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(f=>f.version===0||f.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let a=i<e.length?e[i]:0,c=i<t.length?t[i]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:i,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Xe(n){return H()?new ye(n):null}F();var Lt=128,kt=8,Ut=1e4,ve=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Lt,this.beta=e?.beta??kt,this.maxPatterns=e?.maxPatterns??Ut,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let s=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:s,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let s=this.softmax(r),i=0,a=s[0];for(let l=1;l<s.length;l++)s[l]>a&&(a=s[l],i=l);let c=this.patterns[i],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let s=new Float32Array(this.patterns.length),i=-1/0;for(let o=0;o<this.patterns.length;o++)s[o]=this.beta*r[o],s[o]>i&&(i=s[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(s[o]-i);let c=1/this.beta*(i+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let i=0;i<e.length;i++)e[i]>r&&(r=e[i]);let s=0;for(let i=0;i<e.length;i++)t[i]=Math.exp(e[i]-r),s+=t[i];if(s>0)for(let i=0;i<t.length;i++)t[i]/=s;return t}dotProduct(e,t){let r=0;for(let s=0;s<e.length;s++)r+=e[s]*t[s];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),s=Math.sqrt(this.dotProduct(e,e)),i=Math.sqrt(this.dotProduct(t,t));return s===0||i===0?0:r/(s*i)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let s=0;s<e.length;s++)r[s]=e[s]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function Ge(n){return new ve(n)}F();var qt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},N=1e-5,Ve=1-N;function Qt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function zt(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(zt(e,t)),s=Math.max(N,1-A(e)),i=Math.max(N,1-A(t));return Math.acosh(Math.max(1,1+2*r/(s*i)))}static mobiusAdd(e,t){let r=Qt(e,t),s=A(e),i=A(t),a=Math.max(N,1+2*r+s*i),c=1+2*r+i,u=1-s,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(N,1-A(e)),s=Math.sqrt(A(t));if(s<N)return new Float32Array(e);let i=Math.tanh(r*s/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=i/s*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=Ve)return new Float32Array(e);let r=Ve/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return s}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<N)return new Float32Array(e.length);let r=Math.tanh(t)/t,s=new Float32Array(e.length);for(let i=0;i<e.length;i++)s[i]=e[i]*r;return n.project(s)}},Pe=class{config;points=new Map;constructor(e){if(this.config={...qt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),s=[];for(let i of this.points.values())s.push({id:i.id,distance:T.poincareDistance(r,i.coordinates),point:i});return s.sort((i,a)=>i.distance-a.distance),s.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,s=new Map,i=new Map,a=[];for(let u of e)if(i.set(u.id,u),!u.parentId)a.push(u.id);else{let o=s.get(u.parentId);o||(o=[],s.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:f}=c.shift(),d=Math.tanh(.3*(o+.1)),h=l+f/2,p=new Float32Array(r);p[0]=d*Math.cos(h),p[1]=d*Math.sin(h);let m=i.get(u);if(m&&m.features.length>0){let _=d*.1;for(let x=2;x<r&&x-2<m.features.length;x++)p[x]=m.features[x-2]*_}let g=T.project(p);t.set(u,g),this.points.set(u,{id:u,coordinates:g,metadata:{depth:o,parentId:m?.parentId}});let S=s.get(u)??[];for(let _=0;_<S.length;_++){let x=f/Math.max(1,S.length);c.push({id:S[_],depth:o+1,angOff:l+_*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Ye(n){return $t()?new Pe(n):null}function $t(){return D().useHyperbolicHnsw}F();var we=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=Ye(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let s=t instanceof Float32Array?t:new Float32Array(t),i=T.euclideanToHyperbolic(s);this.index.insert(e,i,r)}catch(s){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,s instanceof Error?s.message:s)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),s=T.euclideanToHyperbolic(r);return this.index.search(s,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ke(n){return new we(n)}var Se=null;function Ze(){return Se||(Se=ke({dimensions:1e4})),Se}var be;function Jt(){return be===void 0&&(be=Ue()),be}var U=null,Ee=0;function et(n){return(!U||Ee!==n)&&(U=Ge({dimension:n,maxPatterns:1e4}),Ee=n),U}var W={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:B,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},Re=class{constructor(e,t={}){this.memory=e;this.config={...W,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new Z(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-FZEH2KLM.js"),{HnswAdapter:c}=await import("./hnsw-adapter-KMGSHBIN.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-IMFRAOPE.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,s=this.hnswIndex.initialize(),i=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([s,i]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",v(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,s=0;for(let{patternId:i,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){s++;continue}let c=this.patternCache.get(i);if(!c){s++;continue}try{await this.hnswIndex.insert(i,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{s++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${s})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",v(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Xe()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",v(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let s=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{let i=this.sqliteStore.storePattern(e,e.embedding);i&&i!==e.id&&(this.unindexPattern(e),e.id=i,this.indexPattern(e))}catch(i){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,v(i))}if(e.embedding){let i=await this.ensureHNSW();if(i)try{await i.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ze().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(i){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,v(i))}try{let i=Jt();if(i){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=i.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(i){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,v(i))}if(ee()&&e.embedding)try{et(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(i){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,v(i))}if(H()&&this.deltaTracker)try{let i={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,i)}catch(i){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,v(i))}if(e.embedding)try{let i=this.getVectorDeltaTracker();i&&(s?.embedding?i.recordDelta(e.id,s.embedding,e.embedding):i.getVersion(e.id)<0&&i.recordGenesis(e.id,e.embedding))}catch(i){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,v(i))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),s={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},i=await this.store(s);return i.success?P(s):w(i.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),s=t.limit||10,i=[];try{if(Array.isArray(e)&&ee())try{let d=et(e.length);if(d.getPatternCount()>0){let h=d.recall(new Float32Array(e));if(h&&h.similarity>.98){let p=h.metadata.id,m=await this.get(p);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,h.similarity);i.push({pattern:m,score:h.similarity,matchType:"vector",similarity:h.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(d){console.debug("[PatternStore] Hopfield recall failed:",v(d))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let d=await this.ensureHNSW();if(d){let h=await d.search(e,s*2);for(let p of h){let m=await this.get(p.key);if(m&&this.matchesFilters(m,t)){let g=this.calculateReuseInfo(m,p.score);i.push({pattern:m,score:p.score,matchType:"vector",similarity:p.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(e,s*2);if(d.length>0){let h=new Map(d.map(m=>[m.id,m.ftsScore])),p=new Set(i.map(m=>m.pattern.id));for(let m of i){let g=h.get(m.pattern.id);g!==void 0&&(m.score=.75*m.score+.25*g)}for(let m of d){if(p.has(m.id))continue;let g=await this.get(m.id);if(g&&this.matchesFilters(g,t)){let S=this.calculateReuseInfo(g,m.ftsScore);i.push({pattern:g,score:.5*m.ftsScore,matchType:"exact",similarity:m.ftsScore,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch{}if(typeof e=="string"||i.length<s){let d=await this.searchByText(typeof e=="string"?e:"",t,s-i.length),h=new Set(i.map(p=>p.pattern.id));for(let p of d)h.has(p.pattern.id)||i.push(p)}let a=720*60*60*1e3,c=Date.now();for(let d of i){let h=d.pattern.lastUsedAt?.getTime()??d.pattern.createdAt.getTime(),p=c-h,m=Math.pow(.5,p/a),g=d.pattern.usageCount>0?m:.5;d.score=d.score*(.7+.3*g)}let u=this.sqliteStore?.getDatabase();if(u&&i.length>0)try{this.nullStore||(this.nullStore=new ne(u));let d=this.nullStore.getNullSummaries(i.map(h=>h.pattern.id));for(let h of i){let p=d.get(h.pattern.id);p&&(h.nullSummary=p,h.score=ne.applyNullDiscount(h.score,p,t.contextFingerprint))}}catch(d){console.debug("[PatternStore] null discount skipped:",v(d))}i.sort((d,h)=>h.score-d.score);let o=i;t.filter&&(o=Ne(i,t.filter));let l=o.slice(0,s),f=performance.now()-r;return this.recordSearchLatency(f),P(l)}catch(a){return w(xe(a))}}async searchByText(e,t,r){let s=[],i=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&i&&this.hdcCache.size>0)try{let u=Ze(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(h=>this.hdcCache.has(h)).map(h=>({id:h,similarity:u.similarity(o.vector,this.hdcCache.get(h))}));l.sort((h,p)=>p.similarity-h.similarity);let f=l.map(h=>h.id),d=c.filter(h=>!this.hdcCache.has(h));c=[...f,...d]}catch{}for(let u of c){if(s.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(i){let f=o.name.toLowerCase(),d=o.description.toLowerCase();f.includes(i)&&(l+=.5),d.includes(i)&&(i.length/d.length>.3?l+=.5:l+=.3);for(let h of o.context.tags)if(h.toLowerCase().includes(i)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!i){let f=this.calculateReuseInfo(o,l);s.push({pattern:o,score:l||o.qualityScore,matchType:i?"exact":"context",similarity:l||o.qualityScore,canReuse:f.canReuse,estimatedTokenSavings:f.estimatedTokenSavings,reuseConfidence:f.reuseConfidence})}}return s}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,s=t>=r.minSimilarityForReuse,i=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&s&&i&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,f=t,d=e.successRate,h=Math.min(e.reuseCount/10,1),p=o?f*.4+d*.4+h*.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,r,s){let i=await this.get(e);if(!i)return w(new Error(`Pattern not found: ${e}`));let a=new Date,c=i.usageCount+1,u=i.successfulUses+(t?1:0),o=u/c,l=t?.02:-.01,f=Math.max(.1,Math.min(1,i.confidence+l)),d=J({confidence:f,usageCount:c,successRate:o}),h={...i,usageCount:c,successfulUses:u,successRate:o,confidence:f,qualityScore:d,lastUsedAt:a};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,s)}catch(g){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,v(g))}if(H()&&this.deltaTracker)try{let g={id:i.id,name:i.name,confidence:i.confidence,qualityScore:i.qualityScore,usageCount:i.usageCount,successRate:i.successRate,tier:i.tier},S={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,g,S,{success:t})}catch(g){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,v(g))}let p=te(h);return p.meetsUsageCriteria&&p.meetsQualityCriteria&&p.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(s){console.debug("[PatternStore] SQLite promotion error:",s instanceof Error?s.message:s)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,s=0,i=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,s+=o.qualityScore,i+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?s/a:0,avgSuccessRate:a>0?i/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],s=[];for(let i of this.patternCache.values()){let a=te(i);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){s.push(i.id);continue}if(i.tier==="short-term"){let u=i.createdAt instanceof Date?i.createdAt.getTime():new Date(i.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,f=i.qualityScore<.2,d=i.usageCount===0&&o>1440*60*1e3;(l&&f||d)&&r.push(i.id)}}for(let i of s)(await this.promote(i)).success&&t++;for(let i of r)(await this.delete(i)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let s=Math.ceil(r.length*.1),i=0;for(let a of r){if(i>=s)break;a.tier==="short-term"&&(await this.delete(a.id),i++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Ee=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ke({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(s){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,s instanceof Error?s.message:s)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),s=[];for(let i of r){let a=await this.get(i.patternId);if(!a)continue;let c=Math.exp(-i.distance),u=this.calculateReuseInfo(a,c);s.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return P(s)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function $r(n,e){try{if(D().useRVFPatternStore&&Oe()){let{existsSync:r}=Ae("fs"),{join:s}=Ae("path"),i=process.env.AQE_PROJECT_ROOT??De(),a=s(i,".agentic-qe"),c=s(a,"patterns.rvf");if(r(a)){let u={...W,...e},o=!1;try{let{getSharedRvfAdapter:l}=(st(),Te(it)),f=l(a,u.embeddingDimension);if(f){o=!0;let d=new Q(()=>f,{rvfPath:c,base:u,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}catch{}if(!o){let l=new Q((f,d)=>{let{openRvfStore:h}=(Ie(),Te(nt)),p=()=>{try{return h(f)}catch{return null}},m=p();if(m){if(m.dimension()!==d){try{m.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m.dimension()}, requested=${d})`)}return m}try{return Fe(f,d)}catch(g){if(m=p(),m&&m.dimension()===d)return m;throw g}},{rvfPath:c,base:u});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Re(n,e)}export{$r as a};
50
50
  /*! Bundled license information:
51
51
 
52
52
  fast-json-patch/commonjs/helpers.js:
@@ -0,0 +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.12.0");process.exit(0)}
2
+ import{a as m}from"./chunk-PM566XEO.js";import{f as c}from"./chunk-BA6U7NSR.js";import{m as R}from"./chunk-C4SZSPXY.js";import{b as f}from"./chunk-L5ZLOW3K.js";import h from"node:path";async function p(e){if(e.checklist.requirements.length===0)throw new Error("RequirementChecklist must have a non-empty, constant denominator (ADR-117).");if(!(e.oracle!=null&&e.oracle.baselinePassed&&e.oracle.passed)){let u=e.oracle==null?"oracle did not run":e.oracle.baselinePassed?"mutation score below threshold":"tests did not execute against the reference implementation";return{verdict:"fail",mechanical:"fail",specCoverage:null,unmet:[],attempts:0,reason:`mechanical gate failed: ${u}`}}if(!await e.judge.preflight())return{verdict:"inconclusive",mechanical:"pass",specCoverage:null,unmet:[],attempts:0,reason:"judge preflight failed: judge tooling did not run \u2014 refusing to report success"};let s=[],i=null,r=[],o=0;for(let u=0;u<2;u++){o++;let a=await e.judge.grade(e.artifact,e.checklist);if(a.ran&&(s.push(a),(i==null||a.coverage>i)&&(i=a.coverage,r=a.unmet),a.coverage>=1))return{verdict:"pass",mechanical:"pass",specCoverage:a.coverage,unmet:[],attempts:o,reason:`spec gate passed at coverage ${a.coverage.toFixed(3)} on attempt ${o}`}}return s.length>=2?{verdict:"fail",mechanical:"pass",specCoverage:i,unmet:r,attempts:o,reason:`spec gate failed: ${s.length} real opinions, best coverage ${(i??0).toFixed(3)} < 1 (${r.length} unmet)`}:{verdict:"inconclusive",mechanical:"pass",specCoverage:i,unmet:r,attempts:o,reason:`spec gate inconclusive: only ${s.length} real opinion(s) obtainable (need 2 to fail) \u2014 retry later, record neither pass nor fail`}}R();var T="verification/anchors/qe-anchor-v1.json";async function I(e){let t=A(e.checklistId,e.anchorPath);return p({oracle:e.oracleResult,artifact:e.artifact,checklist:t,judge:e.judge})}function A(e,t){let n=y(t),s=m(n),i=s.items.find(r=>r.id===e);if(!i){let r=s.items.map(o=>o.id).join(", ");throw new Error(`Unknown checklist id "${e}" in anchor ${n}. Available: ${r}`)}return{id:i.id,requirements:i.requirements}}function U(e){return m(y(e)).items.map(n=>n.id)}function y(e){if(e&&h.isAbsolute(e))return e;let t=f();return h.resolve(t,e??T)}var C=6e4,k=15e3;function E(e){let t=e.timeoutMs??C,n=e.logger??(()=>{}),s=e.model??"frontier",i=e.ping??(async()=>{let r=await v(e.complete("Reply with exactly: OK"),Math.min(k,t),"judge preflight ping");return typeof r=="string"&&r.trim().length>0});return{async preflight(){try{let r=await i();return r||n(`frontier-judge preflight: provider (${s}) returned empty \u2014 not ready`),r}catch(r){return n(`frontier-judge preflight failed (${s}): ${b(r)}`),!1}},async grade(r,o){let u=o.requirements.length;try{let a=j(r,o),x=await v(e.complete(a),t,"judge grade"),d=q(x,u);if(d==null)return n(`frontier-judge grade: could not parse response for ${o.id}`),{ran:!1,coverage:0,unmet:[]};let g=[...d].sort((l,P)=>l-P).map(l=>o.requirements[l]);return{ran:!0,coverage:(u-g.length)/u,unmet:g}}catch(a){return n(`frontier-judge grade failed for ${o.id} (${s}): ${b(a)}`),{ran:!1,coverage:0,unmet:[]}}}}}function O(e,t={}){let n=t.model??c;return async s=>(await e.chat({messages:[{role:"user",content:s}],model:n,preferredProvider:t.preferredProvider,temperature:t.temperature??0,maxTokens:t.maxTokens??1024,timeoutMs:t.timeoutMs,skipCache:!0})).content??""}function Q(e,t={}){let n=t.model??c;return E({complete:O(e,{...t,model:n}),model:n,timeoutMs:t.timeoutMs,logger:t.logger})}function D(e){return{preflight:()=>!1,grade:()=>({ran:!1,coverage:0,unmet:[]})}}function j(e,t){let n=t.requirements.map((s,i)=>`${i+1}. ${s}`).join(`
3
+ `);return["You are a rigorous, frontier-tier quality oracle grading a software artifact","against a FIXED requirement checklist. Judge only what the artifact actually","verifies \u2014 do not give credit for requirements it merely mentions or leaves",'implicit. A requirement is "met" only if the artifact demonstrably covers it.',"",`Checklist id: ${t.id}`,"Requirements (the denominator is fixed \u2014 grade ALL of them):",n,"","--- ARTIFACT UNDER JUDGEMENT ---",e,"--- END ARTIFACT ---","","Return ONLY a single JSON object, no prose, no markdown fences, of the form:",'{"unmet": [<numbers of requirements NOT met>]}','Use the requirement numbers above. If every requirement is met, return {"unmet": []}.'].join(`
4
+ `)}function q(e,t){let n=J(e);if(n==null||!Array.isArray(n.unmet))return null;let s=new Set;for(let i of n.unmet){let r=typeof i=="number"?i:typeof i=="string"?Number(i.trim()):NaN;if(!Number.isInteger(r))continue;let o=r-1;o>=0&&o<t&&s.add(o)}return s}function J(e){if(typeof e!="string")return null;let t=e.indexOf("{");if(t===-1)return null;let n=0,s=!1,i=!1;for(let r=t;r<e.length;r++){let o=e[r];if(s){i?i=!1:o==="\\"?i=!0:o==='"'&&(s=!1);continue}if(o==='"')s=!0;else if(o==="{")n++;else if(o==="}"&&(n--,n===0))try{return JSON.parse(e.slice(t,r+1))}catch{return null}}return null}function v(e,t,n){return new Promise((s,i)=>{let r=setTimeout(()=>i(new Error(`${n} timed out after ${t}ms`)),t);e.then(o=>{clearTimeout(r),s(o)},o=>{clearTimeout(r),i(o)})})}function b(e){return e instanceof Error?e.message:String(e)}export{I as a,U as b,Q as c,D as d};
@@ -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.11.5");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.12.0");process.exit(0)}
2
2
  var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
3
3
  describe('createUser', () => {
4
4
  it('should create user with valid data', async () => {
@@ -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.11.5");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.12.0");process.exit(0)}
2
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 g=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 q,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},p=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=q(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.pollTimer.unref?.()),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
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=q(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
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(`
@@ -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.11.5");process.exit(0)}
2
- import{c as h}from"./chunk-C4EZNOWK.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
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.12.0");process.exit(0)}
2
+ import{c as h}from"./chunk-3AFNXU45.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
@@ -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.11.5");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.12.0");process.exit(0)}
2
2
  var N="ffffffff-ffff-ffff-ffff-ffffffffffff";var _="00000000-0000-0000-0000-000000000000";var y=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function k(r){return typeof r=="string"&&y.test(r)}var u=k;function q(r){if(!u(r))throw TypeError("Invalid UUID");let n;return Uint8Array.of((n=parseInt(r.slice(0,8),16))>>>24,n>>>16&255,n>>>8&255,n&255,(n=parseInt(r.slice(9,13),16))>>>8,n&255,(n=parseInt(r.slice(14,18),16))>>>8,n&255,(n=parseInt(r.slice(19,23),16))>>>8,n&255,(n=parseInt(r.slice(24,36),16))/1099511627776&255,n/4294967296&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255)}var c=q;var x=[];for(let r=0;r<256;++r)x.push((r+256).toString(16).slice(1));function l(r,n=0){return(x[r[n+0]]+x[r[n+1]]+x[r[n+2]]+x[r[n+3]]+"-"+x[r[n+4]]+x[r[n+5]]+"-"+x[r[n+6]]+x[r[n+7]]+"-"+x[r[n+8]]+x[r[n+9]]+"-"+x[r[n+10]]+x[r[n+11]]+x[r[n+12]]+x[r[n+13]]+x[r[n+14]]+x[r[n+15]]).toLowerCase()}function C(r,n=0){let f=l(r,n);if(!u(f))throw TypeError("Stringified UUID is invalid");return f}var H=C;var v=new Uint8Array(16);function m(){return crypto.getRandomValues(v)}var g={};function X(r,n,f){let e,o=r?._v6??!1;if(r){let t=Object.keys(r);t.length===1&&t[0]==="_v6"&&(r=void 0)}if(r)e=E(r.random??r.rng?.()??m(),r.msecs,r.nsecs,r.clockseq,r.node,n,f);else{let t=Date.now(),i=m();j(g,t,i),e=E(i,g.msecs,g.nsecs,o?void 0:g.clockseq,o?void 0:g.node,n,f)}return n??l(e)}function j(r,n,f){return r.msecs??=-1/0,r.nsecs??=0,n===r.msecs?(r.nsecs++,r.nsecs>=1e4&&(r.node=void 0,r.nsecs=0)):n>r.msecs?r.nsecs=0:n<r.msecs&&(r.node=void 0),r.node||(r.node=f.slice(10,16),r.node[0]|=1,r.clockseq=(f[8]<<8|f[9])&16383),r.msecs=n,r}function E(r,n,f,e,o,t,i=0){if(r.length<16)throw new Error("Random bytes length must be >= 16");if(!t)t=new Uint8Array(16),i=0;else if(i<0||i+16>t.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);n??=Date.now(),f??=0,e??=(r[8]<<8|r[9])&16383,o??=r.slice(10,16),n+=122192928e5;let d=((n&268435455)*1e4+f)%4294967296;t[i++]=d>>>24&255,t[i++]=d>>>16&255,t[i++]=d>>>8&255,t[i++]=d&255;let a=n/4294967296*1e4&268435455;t[i++]=a>>>8&255,t[i++]=a&255,t[i++]=a>>>24&15|16,t[i++]=a>>>16&255,t[i++]=e>>>8|128,t[i++]=e&255;for(let p=0;p<6;++p)t[i++]=o[p];return t}var D=X;function U(r){let n=typeof r=="string"?c(r):r,f=G(n);return typeof r=="string"?l(f):f}function G(r){return Uint8Array.of((r[6]&15)<<4|r[7]>>4&15,(r[7]&15)<<4|(r[4]&240)>>4,(r[4]&15)<<4|(r[5]&240)>>4,(r[5]&15)<<4|(r[0]&240)>>4,(r[0]&15)<<4|(r[1]&240)>>4,(r[1]&15)<<4|(r[2]&240)>>4,96|r[2]&15,r[3],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15])}import{createHash as K}from"node:crypto";function M(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),K("md5").update(r).digest()}var T=M;function O(r){r=unescape(encodeURIComponent(r));let n=new Uint8Array(r.length);for(let f=0;f<r.length;++f)n[f]=r.charCodeAt(f);return n}var w="6ba7b810-9dad-11d1-80b4-00c04fd430c8",I="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function h(r,n,f,e,o,t){let i=typeof f=="string"?O(f):f,d=typeof e=="string"?c(e):e;if(typeof e=="string"&&(e=c(e)),e?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+i.length);if(a.set(d),a.set(i,d.length),a=n(a),a[6]=a[6]&15|r,a[8]=a[8]&63|128,o){if(t??=0,t<0||t+16>o.length)throw new RangeError(`UUID byte range ${t}:${t+15} is out of buffer bounds`);for(let p=0;p<16;++p)o[t+p]=a[p];return o}return l(a)}function S(r,n,f,e){return h(48,T,r,n,f,e)}S.DNS=w;S.URL=I;var z=S;function F(r,n,f){return!n&&!r&&crypto.randomUUID?crypto.randomUUID():J(r,n,f)}function J(r,n,f){r=r||{};let e=r.random??r.rng?.()??m();if(e.length<16)throw new Error("Random bytes length must be >= 16");if(e[6]=e[6]&15|64,e[8]=e[8]&63|128,n){if(f=f||0,f<0||f+16>n.length)throw new RangeError(`UUID byte range ${f}:${f+15} is out of buffer bounds`);for(let o=0;o<16;++o)n[f+o]=e[o];return n}return l(e)}var P=F;import{createHash as Q}from"node:crypto";function W(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),Q("sha1").update(r).digest()}var V=W;function R(r,n,f,e){return h(80,V,r,n,f,e)}R.DNS=w;R.URL=I;var Y=R;function Z(r,n,f){r??={},f??=0;let e=D({...r,_v6:!0},new Uint8Array(16));if(e=U(e),n){if(f<0||f+16>n.length)throw new RangeError(`UUID byte range ${f}:${f+15} is out of buffer bounds`);for(let o=0;o<16;o++)n[f+o]=e[o];return n}return l(e)}var s=Z;function $(r){let n=typeof r=="string"?c(r):r,f=b(n);return typeof r=="string"?l(f):f}function b(r){return Uint8Array.of((r[3]&15)<<4|r[4]>>4&15,(r[4]&15)<<4|(r[5]&240)>>4,(r[5]&15)<<4|r[6]&15,r[7],(r[1]&15)<<4|(r[2]&240)>>4,(r[2]&15)<<4|(r[3]&240)>>4,16|(r[0]&240)>>4,(r[0]&15)<<4|(r[1]&240)>>4,r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15])}var A={};function B(r,n,f){let e;if(r)e=L(r.random??r.rng?.()??m(),r.msecs,r.seq,n,f);else{let o=Date.now(),t=m();r0(A,o,t),e=L(t,A.msecs,A.seq,n,f)}return n??l(e)}function r0(r,n,f){return r.msecs??=-1/0,r.seq??=0,n>r.msecs?(r.seq=f[6]<<23|f[7]<<16|f[8]<<8|f[9],r.msecs=n):(r.seq=r.seq+1|0,r.seq===0&&r.msecs++),r}function L(r,n,f,e,o=0){if(r.length<16)throw new Error("Random bytes length must be >= 16");if(!e)e=new Uint8Array(16),o=0;else if(o<0||o+16>e.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return n??=Date.now(),f??=r[6]*127<<24|r[7]<<16|r[8]<<8|r[9],e[o++]=n/1099511627776&255,e[o++]=n/4294967296&255,e[o++]=n/16777216&255,e[o++]=n/65536&255,e[o++]=n/256&255,e[o++]=n&255,e[o++]=112|f>>>28&15,e[o++]=f>>>20&255,e[o++]=128|f>>>14&63,e[o++]=f>>>6&255,e[o++]=f<<2&255|r[10]&3,e[o++]=r[11],e[o++]=r[12],e[o++]=r[13],e[o++]=r[14],e[o++]=r[15],e}var n0=B;function f0(r){if(!u(r))throw TypeError("Invalid UUID");return parseInt(r.slice(14,15),16)}var e0=f0;export{N as a,_ as b,u as c,c as d,H as e,D as f,U as g,z as h,P as i,Y as j,s as k,$ as l,n0 as m,e0 as n};
@@ -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.11.5");process.exit(0)}
2
- import{b as d,d as L}from"./chunk-NCSXLMDL.js";import{createHash as m}from"crypto";import{existsSync as g,readFileSync as R,writeFileSync as A,openSync as X,writeSync as U,closeSync as f}from"fs";var p=[`CREATE TABLE IF NOT EXISTS qe_patterns (
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.12.0");process.exit(0)}
2
+ import{b as d,d as L}from"./chunk-C4SZSPXY.js";import{createHash as m}from"crypto";import{existsSync as g,readFileSync as R,writeFileSync as A,openSync as X,writeSync as U,closeSync as f}from"fs";var p=[`CREATE TABLE IF NOT EXISTS qe_patterns (
3
3
  id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
4
4
  domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
5
5
  confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
@@ -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.11.5");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.12.0");process.exit(0)}
2
2
  import a from"chalk";import{existsSync as m,statSync as S}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)&&S(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)&&S(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 V=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,V as j};
@@ -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.11.5");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.12.0");process.exit(0)}
2
2
  var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
- import{l as d}from"./chunk-6T65OKUM.js";import{a as u,c as g}from"./chunk-RKXZLTWR.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.12.0");process.exit(0)}
2
+ import{l as d}from"./chunk-7WX3MKRS.js";import{a as u,c as g}from"./chunk-RHC7TFPU.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
- import{a as R}from"./chunk-I3NWKPXJ.js";import{m as T}from"./chunk-NCSXLMDL.js";import{b as S}from"./chunk-YFCULQBP.js";import{a as b,c as P}from"./chunk-RKXZLTWR.js";import{i as h}from"./chunk-K4I7UIU5.js";import{a as M}from"./chunk-SUL3I6QZ.js";T();P();import*as f from"path";import*as c from"fs";function C(){return process.env.AQE_MEMORY_BACKEND==="memory"}var s=null,d=null,g=null;function O(o){g=o}async function x(){return s||d||(d=(async()=>{if(C()){let r=new M;return await r.initialize(),s=r,r}let o=S(),e=f.join(o,".agentic-qe");c.existsSync(e)||c.mkdirSync(e,{recursive:!0});let t=new R({sqlite:{path:f.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await t.initialize(),s=t,t})(),d)}function E(){if(g)try{g()}catch{}s&&(s.dispose().catch(()=>{}),s=null),d=null}async function q(o){return o?.memory?o.memory:x()}var m=null,l=null;function L(){let o=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();return o?o!=="false"&&o!=="0"&&o!=="no"&&o!=="off":!1}function I(o){m=o,l=null}async function w(){return L()?null:m||l||(l=(async()=>{let{createLLMRouterService:o}=await import("./llm-router-service-XHFKTH3I.js"),e=await o();return e?(m=e.router,m):null})(),l)}function H(){m=null,l=null}async function K(o){return o?.llmRouter?o.llmRouter:await w()??void 0}async function N(o){if(o?.kernel)return o.kernel;try{let{getFleetState:e}=await import("./core-handlers-EEFLLMAZ.js");return e().kernel??void 0}catch{return}}var v={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},k=class{logger=v;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,t){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:t,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let t=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let r=e,{properties:i,required:n}=this.config.schema;if(n)for(let a of n)a in r||t.push(`Missing required field: ${a}`);for(let[a,u]of Object.entries(r)){let p=i[a];if(!p)continue;let y=this.validateType(a,u,p);y&&t.push(y)}return{valid:t.length===0,errors:t}}validateType(e,t,r){if(t==null)return null;let i=Array.isArray(t)?"array":typeof t;if(r.type==="array"&&!Array.isArray(t))return`${e} must be an array`;if(r.type!=="array"&&i!==r.type)return`${e} must be of type ${r.type}, got ${i}`;if(r.enum&&!r.enum.includes(t))return`${e} must be one of: ${r.enum.join(", ")}`;if(r.type==="number"){let n=t;if(r.minimum!==void 0&&n<r.minimum)return`${e} must be >= ${r.minimum}`;if(r.maximum!==void 0&&n>r.maximum)return`${e} must be <= ${r.maximum}`}if(r.type==="string"){let n=t;if(r.minLength!==void 0&&n.length<r.minLength)return`${e} must be at least ${r.minLength} characters`;if(r.maxLength!==void 0&&n.length>r.maxLength)return`${e} must be at most ${r.maxLength} characters`}return null}async invoke(e,t={}){let r=Date.now(),i=h();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(r,i)};let a={requestId:i,startTime:r,streaming:t.streaming,onStream:t.onStream,abortSignal:t.abortSignal,demoMode:t.demoMode,memory:t.memory,llmRouter:t.llmRouter,kernel:t.kernel};try{let u=await this.execute(e,a);return{...u,metadata:{...u.metadata,...this.createMetadata(r,i)}}}catch(u){return{success:!1,error:b(u),metadata:this.createMetadata(r,i)}}}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{C as a,O as b,x as c,E as d,q as e,I as f,w as g,H as h,K as i,N as j,v as k,k as l};
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.12.0");process.exit(0)}
2
+ import{a as R}from"./chunk-4SALW7OT.js";import{m as T}from"./chunk-C4SZSPXY.js";import{b as S}from"./chunk-L5ZLOW3K.js";import{a as b,c as P}from"./chunk-RHC7TFPU.js";import{i as h}from"./chunk-6JNNZGI2.js";import{a as M}from"./chunk-TJ6N4CCX.js";T();P();import*as f from"path";import*as c from"fs";function C(){return process.env.AQE_MEMORY_BACKEND==="memory"}var s=null,d=null,g=null;function O(o){g=o}async function x(){return s||d||(d=(async()=>{if(C()){let r=new M;return await r.initialize(),s=r,r}let o=S(),e=f.join(o,".agentic-qe");c.existsSync(e)||c.mkdirSync(e,{recursive:!0});let t=new R({sqlite:{path:f.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await t.initialize(),s=t,t})(),d)}function E(){if(g)try{g()}catch{}s&&(s.dispose().catch(()=>{}),s=null),d=null}async function q(o){return o?.memory?o.memory:x()}var m=null,l=null;function L(){let o=(process.env.AQE_LLM_ROUTER_DISABLED??"").trim().toLowerCase();return o?o!=="false"&&o!=="0"&&o!=="no"&&o!=="off":!1}function I(o){m=o,l=null}async function w(){return L()?null:m||l||(l=(async()=>{let{createLLMRouterService:o}=await import("./llm-router-service-UV34YXBE.js"),e=await o();return e?(m=e.router,m):null})(),l)}function H(){m=null,l=null}async function K(o){return o?.llmRouter?o.llmRouter:await w()??void 0}async function N(o){if(o?.kernel)return o.kernel;try{let{getFleetState:e}=await import("./core-handlers-46Z5VOO6.js");return e().kernel??void 0}catch{return}}var v={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},k=class{logger=v;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,t){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:t,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let t=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let r=e,{properties:i,required:n}=this.config.schema;if(n)for(let a of n)a in r||t.push(`Missing required field: ${a}`);for(let[a,u]of Object.entries(r)){let p=i[a];if(!p)continue;let y=this.validateType(a,u,p);y&&t.push(y)}return{valid:t.length===0,errors:t}}validateType(e,t,r){if(t==null)return null;let i=Array.isArray(t)?"array":typeof t;if(r.type==="array"&&!Array.isArray(t))return`${e} must be an array`;if(r.type!=="array"&&i!==r.type)return`${e} must be of type ${r.type}, got ${i}`;if(r.enum&&!r.enum.includes(t))return`${e} must be one of: ${r.enum.join(", ")}`;if(r.type==="number"){let n=t;if(r.minimum!==void 0&&n<r.minimum)return`${e} must be >= ${r.minimum}`;if(r.maximum!==void 0&&n>r.maximum)return`${e} must be <= ${r.maximum}`}if(r.type==="string"){let n=t;if(r.minLength!==void 0&&n.length<r.minLength)return`${e} must be at least ${r.minLength} characters`;if(r.maxLength!==void 0&&n.length>r.maxLength)return`${e} must be at most ${r.maxLength} characters`}return null}async invoke(e,t={}){let r=Date.now(),i=h();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(r,i)};let a={requestId:i,startTime:r,streaming:t.streaming,onStream:t.onStream,abortSignal:t.abortSignal,demoMode:t.demoMode,memory:t.memory,llmRouter:t.llmRouter,kernel:t.kernel};try{let u=await this.execute(e,a);return{...u,metadata:{...u.metadata,...this.createMetadata(r,i)}}}catch(u){return{success:!1,error:b(u),metadata:this.createMetadata(r,i)}}}createMetadata(e,t){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:t,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,t){e.streaming&&e.onStream&&e.onStream(t)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{C as a,O as b,x as c,E as d,q as e,I as f,w as g,H as h,K as i,N as j,v as k,k as l};
@@ -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.11.5");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.12.0");process.exit(0)}
2
2
  var n=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration","coordination"];function t(e){return{success:!0,value:e}}function r(e){return{success:!1,error:e}}export{n as a,t as b,r 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.11.5");process.exit(0)}
2
- import{a as v}from"./chunk-3WR35GFF.js";import{h as U}from"./chunk-OS2HHJTM.js";import{c as D,d as R,e as h,g as x}from"./chunk-3LY7OCSO.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-KNM5R47J.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ 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.12.0");process.exit(0)}
2
+ import{a as v}from"./chunk-IKVNYK7Y.js";import{h as U}from"./chunk-CVGXB7IX.js";import{c as D,d as R,e as h,g as x}from"./chunk-MJPYNGZ7.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-6IWRIHF3.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};