agentic-qe 3.15.15 → 3.15.16

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 (495) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +90 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/audit/witness-chain.d.ts +7 -0
  5. package/dist/audit/witness-chain.js +10 -0
  6. package/dist/cli/bundle.js +6 -6
  7. package/dist/cli/chunks/adapter-6CQ2PIP5.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-EUF4XVUC.js → agent-booster-wasm-45NWEKVS.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-MOX6PSIQ.js → agent-handler-LVHMYFEF.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-AEXKIGDG.js → agent-memory-branch-YDWOJFEQ.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-73RR52VS.js +2 -0
  12. package/dist/cli/chunks/{arena-IQ5ZZDRF.js → arena-CZKHXDDS.js} +2 -2
  13. package/dist/cli/chunks/{arena-M7GA3CVG.js → arena-ELDZH3CZ.js} +4 -4
  14. package/dist/cli/chunks/{audit-4IPBMKWB.js → audit-5MT4T47Z.js} +3 -3
  15. package/dist/cli/chunks/base-SMCMMVGP.js +2 -0
  16. package/dist/cli/chunks/{better-sqlite3-IKDKJ2IE.js → better-sqlite3-6TGYPC2B.js} +2 -2
  17. package/dist/cli/chunks/{brain-handler-5NQUDH4W.js → brain-handler-HQWZFO52.js} +3 -3
  18. package/dist/cli/chunks/{branch-enumerator-KSXELWRC.js → branch-enumerator-WVILM4SO.js} +2 -2
  19. package/dist/cli/chunks/{browser-6LACARWE.js → browser-RX5ALU3H.js} +2 -2
  20. package/dist/cli/chunks/browser-workflow-A2MEZ66K.js +2 -0
  21. package/dist/cli/chunks/{chunk-SJCKCSN3.js → chunk-24OX5TQJ.js} +1 -1
  22. package/dist/cli/chunks/{chunk-J3FP5UGL.js → chunk-24QHCVX6.js} +1 -1
  23. package/dist/cli/chunks/{chunk-BZULJMGH.js → chunk-2H4XH6FT.js} +2 -2
  24. package/dist/cli/chunks/{chunk-E3MRDIZF.js → chunk-2YZ4G6NW.js} +1 -1
  25. package/dist/cli/chunks/chunk-32BPDLRZ.js +27 -0
  26. package/dist/cli/chunks/{chunk-76P32JVU.js → chunk-32GN3JKR.js} +1 -1
  27. package/dist/cli/chunks/{chunk-W62OOK7A.js → chunk-3HD7E6HN.js} +2 -2
  28. package/dist/cli/chunks/{chunk-AJPROCDW.js → chunk-4D4DENG6.js} +2 -2
  29. package/dist/cli/chunks/{chunk-PFQCV6YS.js → chunk-4LQFBY5L.js} +6 -6
  30. package/dist/cli/chunks/{chunk-4ATQP3PR.js → chunk-4NFQLP6R.js} +1 -1
  31. package/dist/cli/chunks/{chunk-WUOOX7UG.js → chunk-525CFDUE.js} +2 -2
  32. package/dist/cli/chunks/chunk-5B5QPCNU.js +65 -0
  33. package/dist/cli/chunks/{chunk-SON6ZRH3.js → chunk-5JZRZI4S.js} +2 -2
  34. package/dist/cli/chunks/{chunk-2ZFLULL4.js → chunk-5LAVKGLH.js} +2 -2
  35. package/dist/cli/chunks/chunk-5NNNEWLS.js +755 -0
  36. package/dist/cli/chunks/{chunk-JCZCJE6X.js → chunk-5PBLPQ5T.js} +2 -2
  37. package/dist/cli/chunks/chunk-5QO3R3TU.js +6 -0
  38. package/dist/cli/chunks/{chunk-EKP2SC77.js → chunk-5SPCGMBB.js} +2 -2
  39. package/dist/cli/chunks/{chunk-3J3RNJNX.js → chunk-5V3TI2LG.js} +1 -1
  40. package/dist/cli/chunks/{chunk-UAQZI6N4.js → chunk-5VZL4UVN.js} +2 -2
  41. package/dist/cli/chunks/{chunk-MIA447GY.js → chunk-63GMRQ25.js} +1 -1
  42. package/dist/cli/chunks/{chunk-TODNOP7C.js → chunk-63ZKI4PX.js} +6 -6
  43. package/dist/cli/chunks/{chunk-TZIHDJZD.js → chunk-67Z5R7RJ.js} +2 -2
  44. package/dist/cli/chunks/{chunk-WVXJ2QIG.js → chunk-6DPYNAOK.js} +2 -2
  45. package/dist/cli/chunks/{chunk-4HKAD25N.js → chunk-6ICX3FEG.js} +3 -3
  46. package/dist/cli/chunks/{chunk-BLL2XU7A.js → chunk-6XXZDV2C.js} +2 -2
  47. package/dist/cli/chunks/{chunk-R6LHJ7ME.js → chunk-6ZBXSOX6.js} +2 -2
  48. package/dist/cli/chunks/{chunk-5PTAFGJT.js → chunk-72XSEQMW.js} +2 -2
  49. package/dist/cli/chunks/{chunk-GKSMRBHU.js → chunk-7TE5ONQQ.js} +1 -1
  50. package/dist/cli/chunks/{chunk-UJABDXST.js → chunk-A5GBXCP5.js} +2 -2
  51. package/dist/cli/chunks/{chunk-22UKJGGN.js → chunk-AAMLQ2LF.js} +3 -3
  52. package/dist/cli/chunks/chunk-AG2EWGXS.js +21 -0
  53. package/dist/cli/chunks/{chunk-SZAZQZWI.js → chunk-AGRV5B3T.js} +2 -2
  54. package/dist/cli/chunks/{chunk-XH4JMX5O.js → chunk-AJMJNQMP.js} +1 -1
  55. package/dist/cli/chunks/{chunk-ZIPAB5J6.js → chunk-AR67RJPY.js} +2 -2
  56. package/dist/cli/chunks/{chunk-GGQGCT4Y.js → chunk-ASEOFRIG.js} +2 -2
  57. package/dist/cli/chunks/{chunk-AHMWD6JG.js → chunk-BEKDKVQT.js} +2 -2
  58. package/dist/cli/chunks/{chunk-W27AJ5B4.js → chunk-BY5OF7OH.js} +2 -2
  59. package/dist/cli/chunks/{chunk-T67R2MUN.js → chunk-C5FP5GW3.js} +2 -2
  60. package/dist/cli/chunks/{chunk-XHHWABJV.js → chunk-C6D5AHBO.js} +2 -2
  61. package/dist/cli/chunks/{chunk-PXATBHWN.js → chunk-CAKMOVZ6.js} +2 -2
  62. package/dist/cli/chunks/{chunk-337Z52QM.js → chunk-CEYSYSK5.js} +2 -2
  63. package/dist/cli/chunks/{chunk-KJBPB7P5.js → chunk-CGGUM2YJ.js} +2 -2
  64. package/dist/cli/chunks/{chunk-CAOUV5GZ.js → chunk-CJSHWQXP.js} +2 -2
  65. package/dist/cli/chunks/{chunk-GCHYOPRZ.js → chunk-CRPIYUTJ.js} +2 -2
  66. package/dist/cli/chunks/{chunk-RIRZHOS2.js → chunk-D6COXLYE.js} +2 -2
  67. package/dist/cli/chunks/{chunk-O6EWL5DQ.js → chunk-DTMAS2GB.js} +2 -2
  68. package/dist/cli/chunks/{chunk-XM6ZVFM5.js → chunk-DVYHMDFR.js} +470 -411
  69. package/dist/cli/chunks/chunk-DXD6K2ZP.js +3 -0
  70. package/dist/cli/chunks/{chunk-74YG72NQ.js → chunk-E3D4GPLP.js} +3 -3
  71. package/dist/cli/chunks/{chunk-KCQNFBBR.js → chunk-EA4YQVKS.js} +1 -1
  72. package/dist/cli/chunks/{chunk-4D4CWP72.js → chunk-EGYE5UPQ.js} +2 -2
  73. package/dist/cli/chunks/{chunk-DURD37JZ.js → chunk-EK7OLYOZ.js} +2 -2
  74. package/dist/cli/chunks/{chunk-DKX4GNRU.js → chunk-F742SZAX.js} +2 -2
  75. package/dist/cli/chunks/{chunk-JCQGJGGZ.js → chunk-FBDVGRSC.js} +1 -1
  76. package/dist/cli/chunks/{chunk-LVABQNRF.js → chunk-FDDC72IA.js} +2 -2
  77. package/dist/cli/chunks/{chunk-5AFVEWMT.js → chunk-FL64OUBA.js} +2 -2
  78. package/dist/cli/chunks/{chunk-5I7357KS.js → chunk-FLNAW7C4.js} +2 -2
  79. package/dist/cli/chunks/{chunk-BQ47GQPK.js → chunk-G5RHFBAY.js} +2 -2
  80. package/dist/cli/chunks/{chunk-XIVVTYM2.js → chunk-GAHNO6JJ.js} +2 -2
  81. package/dist/cli/chunks/{chunk-X33CWRDF.js → chunk-GFWHUQSF.js} +2 -2
  82. package/dist/cli/chunks/{chunk-VMAM46HQ.js → chunk-GJYHWYXR.js} +2 -2
  83. package/dist/cli/chunks/{chunk-ZYJB6FML.js → chunk-GQ6TUIKY.js} +1 -1
  84. package/dist/cli/chunks/{chunk-E56PVVWC.js → chunk-GSKMOPL7.js} +2 -2
  85. package/dist/cli/chunks/{chunk-JUDUBQHA.js → chunk-HCH4Y6XX.js} +2 -2
  86. package/dist/cli/chunks/{chunk-QFGYH6HD.js → chunk-HGWXF45W.js} +1 -1
  87. package/dist/cli/chunks/{chunk-FTRSS64D.js → chunk-HJ6ZGVTB.js} +2 -2
  88. package/dist/cli/chunks/{chunk-6BRQPHMZ.js → chunk-HLUXXCHF.js} +1 -1
  89. package/dist/cli/chunks/{chunk-BP5T3OEV.js → chunk-HVRRLYX6.js} +4 -4
  90. package/dist/cli/chunks/{chunk-AOKKUB5F.js → chunk-I7MQIM2U.js} +1 -1
  91. package/dist/cli/chunks/{chunk-7XB3FCKM.js → chunk-IESR7TNB.js} +2 -2
  92. package/dist/cli/chunks/{chunk-OQG3UQQ7.js → chunk-IHRXZZQM.js} +1 -1
  93. package/dist/cli/chunks/{chunk-YUS6TWAL.js → chunk-IOKYCMTJ.js} +6 -6
  94. package/dist/cli/chunks/{chunk-ERN56H6S.js → chunk-IOQ6ZQ5W.js} +1 -1
  95. package/dist/cli/chunks/{chunk-GQABPCQE.js → chunk-IOYG4VFL.js} +2 -2
  96. package/dist/cli/chunks/{chunk-KLTMOXIK.js → chunk-IUBJVHNB.js} +2 -2
  97. package/dist/cli/chunks/{chunk-ZSOMUTNL.js → chunk-J442IZLE.js} +1 -1
  98. package/dist/cli/chunks/{chunk-G242G224.js → chunk-J4ELZNLY.js} +2 -2
  99. package/dist/cli/chunks/chunk-J7I6PABJ.js +153 -0
  100. package/dist/cli/chunks/chunk-JDIYMZCQ.js +2 -0
  101. package/dist/cli/chunks/{chunk-2IIXCEMS.js → chunk-JHQCRRJI.js} +2 -2
  102. package/dist/cli/chunks/{chunk-6LE362LZ.js → chunk-JQ3DYUMS.js} +2 -2
  103. package/dist/cli/chunks/{chunk-EFUJDMNC.js → chunk-KITOPKRG.js} +2 -2
  104. package/dist/cli/chunks/{chunk-M4CJCPCQ.js → chunk-KKU2QGSJ.js} +2 -2
  105. package/dist/cli/chunks/chunk-KL7OKSU2.js +4 -0
  106. package/dist/cli/chunks/{chunk-HL2ANKN3.js → chunk-KNSRL6NO.js} +2 -2
  107. package/dist/cli/chunks/{chunk-FOOW4JVS.js → chunk-KPRCB5LT.js} +2 -2
  108. package/dist/cli/chunks/{chunk-E5G4WZ2T.js → chunk-KQYJ4VQ5.js} +1 -1
  109. package/dist/cli/chunks/{chunk-RBKUU7WF.js → chunk-KU2AUFGX.js} +2 -2
  110. package/dist/cli/chunks/{chunk-UQPA33UK.js → chunk-KVF4NXGQ.js} +2 -2
  111. package/dist/cli/chunks/{chunk-BDKEAGQ2.js → chunk-KXCLACFG.js} +2 -2
  112. package/dist/cli/chunks/{chunk-K3WZICFA.js → chunk-L2DWPVNJ.js} +1 -1
  113. package/dist/cli/chunks/{chunk-6YVMX2TC.js → chunk-L6QSTQME.js} +2 -2
  114. package/dist/cli/chunks/{chunk-LJMYRTJ7.js → chunk-LE4QJREF.js} +1 -1
  115. package/dist/cli/chunks/{chunk-NWIIYHT6.js → chunk-LKTTUHLF.js} +2 -2
  116. package/dist/cli/chunks/{chunk-W5ZJG2OU.js → chunk-LQLPB2T6.js} +2 -2
  117. package/dist/cli/chunks/{chunk-JKJOB65O.js → chunk-LRSX2FJM.js} +1 -1
  118. package/dist/cli/chunks/chunk-M4FRQ4TE.js +12 -0
  119. package/dist/cli/chunks/chunk-M7WJCTG3.js +2 -0
  120. package/dist/cli/chunks/{chunk-6RBTS3NF.js → chunk-MAFQV4U4.js} +2 -2
  121. package/dist/cli/chunks/{chunk-UE2J6MA5.js → chunk-MD43XRX5.js} +1 -1
  122. package/dist/cli/chunks/{chunk-2CKERSMB.js → chunk-MI5MFHRA.js} +2 -2
  123. package/dist/cli/chunks/{chunk-T66PPF4D.js → chunk-MO55CVMT.js} +32 -32
  124. package/dist/cli/chunks/{chunk-C4KLXFJP.js → chunk-N7HL5PHH.js} +1 -1
  125. package/dist/cli/chunks/chunk-NAEWCFQT.js +14 -0
  126. package/dist/cli/chunks/{chunk-U62OUXBF.js → chunk-NDJ7P2EP.js} +1 -1
  127. package/dist/cli/chunks/{chunk-M4WMSCAE.js → chunk-NO3IV5Q5.js} +1 -1
  128. package/dist/cli/chunks/{chunk-27HE2BHC.js → chunk-NQXXI77K.js} +2 -2
  129. package/dist/cli/chunks/{chunk-NQS3BWS6.js → chunk-NVEWF4JV.js} +1 -1
  130. package/dist/cli/chunks/{chunk-EBTNMQSS.js → chunk-NZU4ACBZ.js} +2 -2
  131. package/dist/cli/chunks/chunk-O5W3FIO6.js +63 -0
  132. package/dist/cli/chunks/{chunk-BFQTLF5X.js → chunk-OAEE6JWQ.js} +2 -2
  133. package/dist/cli/chunks/{chunk-PS6UMZVK.js → chunk-OCV2XEWQ.js} +2 -2
  134. package/dist/cli/chunks/{chunk-BU4UQR36.js → chunk-P3EYRILV.js} +2 -2
  135. package/dist/cli/chunks/{chunk-LHMQIZ6B.js → chunk-PEQDY4BO.js} +2 -2
  136. package/dist/cli/chunks/{chunk-PYPS65P7.js → chunk-PF7RBAYL.js} +2 -2
  137. package/dist/cli/chunks/{chunk-UXIY4IAI.js → chunk-PHT5N7SC.js} +2 -2
  138. package/dist/cli/chunks/{chunk-GV2QE5TO.js → chunk-PINSJCM3.js} +1 -1
  139. package/dist/cli/chunks/{chunk-4X3SWKBA.js → chunk-PPUZWYUG.js} +2 -2
  140. package/dist/cli/chunks/{chunk-L32JNNKL.js → chunk-QPEOLAAS.js} +1 -1
  141. package/dist/cli/chunks/{chunk-UUBIQR6A.js → chunk-QQWBWEJS.js} +18 -18
  142. package/dist/cli/chunks/{chunk-VCXI4XC4.js → chunk-QVDCVD5D.js} +2 -2
  143. package/dist/cli/chunks/{chunk-JW74KRBC.js → chunk-RJIEG3NA.js} +2 -2
  144. package/dist/cli/chunks/{chunk-C4RTAVC6.js → chunk-RV74I3YO.js} +2 -2
  145. package/dist/cli/chunks/{chunk-5G4UFTV4.js → chunk-S75SOOZL.js} +2 -2
  146. package/dist/cli/chunks/{chunk-MV55NXTD.js → chunk-SASBO5Y5.js} +2 -2
  147. package/dist/cli/chunks/{chunk-UORB2QDU.js → chunk-SDLWKRVL.js} +2 -2
  148. package/dist/cli/chunks/{chunk-Y2OX6KGN.js → chunk-SHKOCGNK.js} +2 -2
  149. package/dist/cli/chunks/{chunk-6KCSKGVY.js → chunk-SI6DPU5D.js} +1 -1
  150. package/dist/cli/chunks/{chunk-LYJHUNBK.js → chunk-SJ6Y4725.js} +2 -2
  151. package/dist/cli/chunks/{chunk-7ACCBHRB.js → chunk-SR52XP5F.js} +1 -1
  152. package/dist/cli/chunks/{chunk-C5CXL3JP.js → chunk-SSUAAX3F.js} +2 -2
  153. package/dist/cli/chunks/{chunk-BBRROA3Z.js → chunk-SSYAQZXA.js} +2 -2
  154. package/dist/cli/chunks/{chunk-DUKE27HC.js → chunk-SUDMM5SO.js} +2 -2
  155. package/dist/cli/chunks/{chunk-H5DER3JY.js → chunk-TIUKLYAI.js} +1 -1
  156. package/dist/cli/chunks/{chunk-5C62XMJR.js → chunk-TVGI32MB.js} +33 -33
  157. package/dist/cli/chunks/{chunk-MPFPWJTH.js → chunk-U2A7NHZA.js} +2 -2
  158. package/dist/cli/chunks/{chunk-TX2CHQD7.js → chunk-UE5ZOZR2.js} +2 -2
  159. package/dist/cli/chunks/{chunk-OLZH5LRT.js → chunk-UHEOGZLX.js} +11 -11
  160. package/dist/cli/chunks/chunk-UNGBRZDK.js +12 -0
  161. package/dist/cli/chunks/{chunk-XWIAZG3C.js → chunk-V5NHZV7S.js} +2 -2
  162. package/dist/cli/chunks/{chunk-AP2W7Z3A.js → chunk-VJCIEHEF.js} +1 -1
  163. package/dist/cli/chunks/{chunk-K3XBQC3R.js → chunk-VMDFFTCK.js} +1 -1
  164. package/dist/cli/chunks/chunk-VSIKHWZ4.js +29 -0
  165. package/dist/cli/chunks/{chunk-LB2LGEDP.js → chunk-VWPM27GU.js} +2 -2
  166. package/dist/cli/chunks/{chunk-HTZSRMHW.js → chunk-VXFLJNCA.js} +2 -2
  167. package/dist/cli/chunks/{chunk-73PBAWAF.js → chunk-W5HQUIML.js} +2 -2
  168. package/dist/cli/chunks/{chunk-DEKR3CTS.js → chunk-WP4RETKG.js} +2 -2
  169. package/dist/cli/chunks/{chunk-ZWBGYJ7K.js → chunk-XIIQ5QTT.js} +2 -2
  170. package/dist/cli/chunks/{chunk-TDQWTSBS.js → chunk-XIQW7EFL.js} +2 -2
  171. package/dist/cli/chunks/{chunk-AKZO6GGG.js → chunk-XWUWX7BV.js} +4 -4
  172. package/dist/cli/chunks/{chunk-LNX74WHQ.js → chunk-Y4PFUMOU.js} +1 -1
  173. package/dist/cli/chunks/chunk-YAPLJR7K.js +2 -0
  174. package/dist/cli/chunks/{chunk-3CYNZFKH.js → chunk-YLMNVLDK.js} +1 -1
  175. package/dist/cli/chunks/{chunk-XG4F4XH4.js → chunk-YNMJEDN5.js} +2 -2
  176. package/dist/cli/chunks/{chunk-RDMRY7CT.js → chunk-YPBSUGMI.js} +1 -1
  177. package/dist/cli/chunks/{chunk-OBDONJQM.js → chunk-YRAX7SFJ.js} +2 -2
  178. package/dist/cli/chunks/{chunk-7BLZHFKD.js → chunk-YTHTQPWR.js} +1 -1
  179. package/dist/cli/chunks/{chunk-IXL5ZHWJ.js → chunk-YU2BDRSD.js} +1 -1
  180. package/dist/cli/chunks/chunk-ZB3LEFYG.js +2 -0
  181. package/dist/cli/chunks/{chunk-T4GE7MPI.js → chunk-ZFL436FN.js} +2 -2
  182. package/dist/cli/chunks/{chunk-CBK5CT6T.js → chunk-ZJH5MU2I.js} +2 -2
  183. package/dist/cli/chunks/{chunk-LTQVUAPH.js → chunk-ZQ2XW3IP.js} +2 -2
  184. package/dist/cli/chunks/chunk-ZR2TKVXQ.js +14 -0
  185. package/dist/cli/chunks/{ci-UCUJOSBW.js → ci-MFUR4CWV.js} +2 -2
  186. package/dist/cli/chunks/{ci-config-2XILD3XG.js → ci-config-PNDLQ6XV.js} +2 -2
  187. package/dist/cli/chunks/{ci-output-BL6KWOHW.js → ci-output-PFZ4M7NC.js} +2 -2
  188. package/dist/cli/chunks/{circuit-breaker-5XLIOXE5.js → circuit-breaker-5HH6NLZN.js} +2 -2
  189. package/dist/cli/chunks/{claude-flow-setup-4IMP6ACS.js → claude-flow-setup-QCKYLGLC.js} +2 -2
  190. package/dist/cli/chunks/client-MHQRTZM4.js +2 -0
  191. package/dist/cli/chunks/{cline-installer-RYLHCDK7.js → cline-installer-EASVPFXR.js} +2 -2
  192. package/dist/cli/chunks/{code-WY3GJXHX.js → code-UJXDVYRK.js} +4 -3
  193. package/dist/cli/chunks/{code-index-extractor-Y4MZBZCW.js → code-index-extractor-BZJ3UDP4.js} +2 -2
  194. package/dist/cli/chunks/{codex-installer-SCJ3T3DX.js → codex-installer-XSQZUVOZ.js} +2 -2
  195. package/dist/cli/chunks/{completions-CN2DXQFU.js → completions-OWOOJFI2.js} +2 -2
  196. package/dist/cli/chunks/{complexity-analyzer-7MDPPIBH.js → complexity-analyzer-KP5TOHDT.js} +2 -2
  197. package/dist/cli/chunks/{continuedev-installer-GCEJRK34.js → continuedev-installer-IFKQXLHM.js} +2 -2
  198. package/dist/cli/chunks/{copilot-installer-BHPDSELY.js → copilot-installer-IGJ6KGQY.js} +2 -2
  199. package/dist/cli/chunks/core-handlers-UAK3LLJE.js +2 -0
  200. package/dist/cli/chunks/{cost-tracker-VO5MFWR6.js → cost-tracker-MMDDNKZB.js} +2 -2
  201. package/dist/cli/chunks/{coverage-LYFQYNH6.js → coverage-LUH2B7NT.js} +3 -3
  202. package/dist/cli/chunks/cross-domain-router-WTRZQPNQ.js +2 -0
  203. package/dist/cli/chunks/{cursor-installer-KP4HA7TV.js → cursor-installer-4YLM5GWM.js} +2 -2
  204. package/dist/cli/chunks/daemon-CAVZ7OFV.js +18 -0
  205. package/dist/cli/chunks/{daemon-7RC7TS57.js → daemon-MZKVM4CJ.js} +3 -3
  206. package/dist/cli/chunks/{dag-attention-scheduler-NKA44RSR.js → dag-attention-scheduler-X4CYW665.js} +2 -2
  207. package/dist/cli/chunks/{detect-CMYAJWYF.js → detect-7BM2XINO.js} +2 -2
  208. package/dist/cli/chunks/{dist-node-EN3PYEGW.js → dist-node-Y5APLEYB.js} +2 -2
  209. package/dist/cli/chunks/{domain-handler-EXSZCX7A.js → domain-handler-X3ZRJNAH.js} +2 -2
  210. package/dist/cli/chunks/{domain-plugins-HCQFSNL7.js → domain-plugins-2UW5KQJB.js} +2 -2
  211. package/dist/cli/chunks/{domain-transfer-3LGSNTPO.js → domain-transfer-35W4CIBV.js} +2 -2
  212. package/dist/cli/chunks/dream-EJY24JN6.js +2 -0
  213. package/dist/cli/chunks/embed-and-insert-pattern-COG4C7ZI.js +3 -0
  214. package/dist/cli/chunks/embedding-space-SBM2MZD2.js +2 -0
  215. package/dist/cli/chunks/{eval-OQELIWJK.js → eval-4QA2SROK.js} +2 -2
  216. package/dist/cli/chunks/experience-capture-middleware-Z6BF6KYM.js +40 -0
  217. package/dist/cli/chunks/{fast-paths-UV4NDEWM.js → fast-paths-FIORX6GN.js} +2 -2
  218. package/dist/cli/chunks/{feature-flags-CKTYX67J.js → feature-flags-6LYI2T4G.js} +2 -2
  219. package/dist/cli/chunks/{feature-flags-H7H33B6C.js → feature-flags-ZOO7LMIC.js} +2 -2
  220. package/dist/cli/chunks/file-discovery-UZSFSS4V.js +2 -0
  221. package/dist/cli/chunks/{fleet-ZJBCAKRG.js → fleet-7WF53H4F.js} +3 -3
  222. package/dist/cli/chunks/{gnn-wrapper-RUE2QZRG.js → gnn-wrapper-KJ6B7BRM.js} +2 -2
  223. package/dist/cli/chunks/{heartbeat-handler-XRV327M7.js → heartbeat-handler-DEKKMOVW.js} +4 -4
  224. package/dist/cli/chunks/heartbeat-scheduler-NVR356I7.js +2 -0
  225. package/dist/cli/chunks/hnsw-adapter-LFMPLUJU.js +2 -0
  226. package/dist/cli/chunks/hnsw-index-POCPMVJH.js +2 -0
  227. package/dist/cli/chunks/{hnsw-legacy-bridge-UJID6ZZ4.js → hnsw-legacy-bridge-L27WS27N.js} +2 -2
  228. package/dist/cli/chunks/{hnswlib-node-WS43R4AX.js → hnswlib-node-4YOQC6L4.js} +2 -2
  229. package/dist/cli/chunks/{hooks-YZNJKXAJ.js → hooks-TAOKV4EJ.js} +23 -22
  230. package/dist/cli/chunks/hybrid-backend-4STAO7CV.js +2 -0
  231. package/dist/cli/chunks/{hypergraph-engine-XQJSIMTS.js → hypergraph-engine-BODRJLHL.js} +2 -2
  232. package/dist/cli/chunks/{hypergraph-handler-ZD2NYXMR.js → hypergraph-handler-RKMYJNTU.js} +3 -3
  233. package/dist/cli/chunks/impact-analyzer-3VIIISBQ.js +2 -0
  234. package/dist/cli/chunks/{init-guard-DSRUAVRT.js → init-guard-MXHSLSB2.js} +2 -2
  235. package/dist/cli/chunks/{init-handler-RJU5QMAP.js → init-handler-HUE57IFW.js} +6 -6
  236. package/dist/cli/chunks/init-wizard-PL6QN6RQ.js +2 -0
  237. package/dist/cli/chunks/kernel-CCDWT7KS.js +2 -0
  238. package/dist/cli/chunks/{kilocode-installer-BCPOCVMC.js → kilocode-installer-S333IKYQ.js} +2 -2
  239. package/dist/cli/chunks/{kiro-installer-GFCWCB2S.js → kiro-installer-WM5DLQWC.js} +2 -2
  240. package/dist/cli/chunks/knowledge-graph-KFOMEN3H.js +2 -0
  241. package/dist/cli/chunks/{learning-FZTD72CF.js → learning-LNHMQLH5.js} +3 -3
  242. package/dist/cli/chunks/{llm-router-GJVKGRJL.js → llm-router-EWFXYZZR.js} +4 -4
  243. package/dist/cli/chunks/llm-router-service-7NBE2EX6.js +2 -0
  244. package/dist/cli/chunks/{load-YKTPOYBE.js → load-FGYGWVDK.js} +2 -2
  245. package/dist/cli/chunks/load-test-UNZUWY3F.js +2 -0
  246. package/dist/cli/chunks/{mcp-LT6R2IKS.js → mcp-2FHNAAOM.js} +2 -2
  247. package/dist/cli/chunks/{memory-4HKKOLRY.js → memory-DZMQ73AB.js} +5 -5
  248. package/dist/cli/chunks/memory-backend-DFGKWA2Q.js +2 -0
  249. package/dist/cli/chunks/memory-handlers-MP426XRJ.js +2 -0
  250. package/dist/cli/chunks/{multi-model-executor-2YPM2WTK.js → multi-model-executor-6F2UAEUW.js} +2 -2
  251. package/dist/cli/chunks/{opencode-installer-WBAJMH5K.js → opencode-installer-XY3BGOTZ.js} +2 -2
  252. package/dist/cli/chunks/{orchestrator-5W5WVMVJ.js → orchestrator-B4CNKUOS.js} +5 -5
  253. package/dist/cli/chunks/pattern-null-store-SSVF5TE5.js +2 -0
  254. package/dist/cli/chunks/{pattern-usage-recorder-GXRMNPAZ.js → pattern-usage-recorder-R4GUFNMD.js} +2 -2
  255. package/dist/cli/chunks/{pipeline-2NA4DRDA.js → pipeline-FG5RKVRO.js} +2 -2
  256. package/dist/cli/chunks/{platform-BGERNQ5V.js → platform-3BT4KEVJ.js} +2 -2
  257. package/dist/cli/chunks/{plugin-L4EPVENR.js → plugin-WI4RIN7O.js} +2 -2
  258. package/dist/cli/chunks/{prime-radiant-advanced-wasm-RTQRTPTM.js → prime-radiant-advanced-wasm-7ECDNQFS.js} +2 -2
  259. package/dist/cli/chunks/project-root-BEANNYWU.js +2 -0
  260. package/dist/cli/chunks/protocol-executor-FQVIHXZ7.js +2 -0
  261. package/dist/cli/chunks/{protocol-handler-SYQXM6JK.js → protocol-handler-WNODKPGW.js} +2 -2
  262. package/dist/cli/chunks/{prove-5O7GPJCU.js → prove-5RHAEPYZ.js} +2 -2
  263. package/dist/cli/chunks/qe-reasoning-bank-5TFYSE24.js +2 -0
  264. package/dist/cli/chunks/{quality-KIIDHGNF.js → quality-WPHR7BGQ.js} +2 -2
  265. package/dist/cli/chunks/{quality-gate-H65VECD3.js → quality-gate-4RKTEZMX.js} +3 -3
  266. package/dist/cli/chunks/queen-coordinator-Y2OUL7IN.js +2 -0
  267. package/dist/cli/chunks/real-embeddings-OXLYU7JW.js +2 -0
  268. package/dist/cli/chunks/{ref-validation-CSBJOMZM.js → ref-validation-TPAWHOHH.js} +2 -2
  269. package/dist/cli/chunks/{roocode-installer-G7OVYXEN.js → roocode-installer-7AVHFNDI.js} +2 -2
  270. package/dist/cli/chunks/router-EP34O3KB.js +2 -0
  271. package/dist/cli/chunks/routing-feedback-FJCRKXNG.js +2 -0
  272. package/dist/cli/chunks/{routing-handler-ZNZPPI5Y.js → routing-handler-YKEDVJSH.js} +2 -2
  273. package/dist/cli/chunks/{ruvector-commands-C6IG3OY3.js → ruvector-commands-JUAMM354.js} +2 -2
  274. package/dist/cli/chunks/rvf-dual-writer-ILITJSFG.js +2 -0
  275. package/dist/cli/chunks/rvf-migration-adapter-XF6W4C2N.js +2 -0
  276. package/dist/cli/chunks/rvf-migration-coordinator-CMKG56AR.js +2 -0
  277. package/dist/cli/chunks/rvf-native-adapter-7YFW6S4Y.js +2 -0
  278. package/dist/cli/chunks/{rvf-store-integrity-3G6LFLT3.js → rvf-store-integrity-VJDUIRTX.js} +2 -2
  279. package/dist/cli/chunks/safe-db-TCAU4FUT.js +2 -0
  280. package/dist/cli/chunks/schedule-NB5KV435.js +2 -0
  281. package/dist/cli/chunks/scheduler-JKXGKVK6.js +2 -0
  282. package/dist/cli/chunks/{security-A3IMVLFM.js → security-ORDN3RD2.js} +3 -3
  283. package/dist/cli/chunks/{shared-rvf-adapter-VHWQ6US5.js → shared-rvf-adapter-CF4BCIO7.js} +2 -2
  284. package/dist/cli/chunks/{shared-rvf-dual-writer-JB3QS7IG.js → shared-rvf-dual-writer-C32UBR6D.js} +2 -2
  285. package/dist/cli/chunks/sqlite-persistence-IXCNZRTW.js +2 -0
  286. package/dist/cli/chunks/{standalone-memory-DDNXCSBD.js → standalone-memory-OXRJYZXN.js} +2 -2
  287. package/dist/cli/chunks/{status-handler-2HK7XPEK.js → status-handler-BCX5D4HY.js} +2 -2
  288. package/dist/cli/chunks/{structural-health-DSJVLEPV.js → structural-health-LFG7RUU6.js} +2 -2
  289. package/dist/cli/chunks/sync-OSF7C2NL.js +2 -0
  290. package/dist/cli/chunks/{sync-NTUR53PI.js → sync-YJEE2K2L.js} +2 -2
  291. package/dist/cli/chunks/task-handler-6LXKPTXJ.js +64 -0
  292. package/dist/cli/chunks/{task-handlers-VJR6EHRZ.js → task-handlers-CILP36I7.js} +4 -4
  293. package/dist/cli/chunks/{test-O6FK3FVF.js → test-SD457QJ6.js} +4 -4
  294. package/dist/cli/chunks/test-runner-process-VKD65QQU.js +2 -0
  295. package/dist/cli/chunks/{test-scheduling-Q6QEEOS6.js → test-scheduling-ISI2O4Q5.js} +3 -3
  296. package/dist/cli/chunks/token-bootstrap-VUELSBOS.js +2 -0
  297. package/dist/cli/chunks/{token-usage-YEEFWSSI.js → token-usage-XOC5KG7S.js} +2 -2
  298. package/dist/cli/chunks/{transformers-BZCHJJJT.js → transformers-LSLQAARK.js} +2 -2
  299. package/dist/cli/chunks/tree-sitter-wasm-parser-YAIPHRIL.js +2 -0
  300. package/dist/cli/chunks/{types-4AOKZYOX.js → types-5BLCGLCR.js} +2 -2
  301. package/dist/cli/chunks/unified-memory-GI76TXFV.js +2 -0
  302. package/dist/cli/chunks/unified-memory-hnsw-GXJ5BTZO.js +2 -0
  303. package/dist/cli/chunks/unified-persistence-OP7FDQPD.js +2 -0
  304. package/dist/cli/chunks/{upgrade-2MWW6BT2.js → upgrade-RQJYLK3J.js} +2 -2
  305. package/dist/cli/chunks/{validate-PAEV3GT5.js → validate-QBHWXXCK.js} +2 -2
  306. package/dist/cli/chunks/{validate-swarm-ZIXACK5K.js → validate-swarm-IKXBKFB5.js} +2 -2
  307. package/dist/cli/chunks/visual-security-GZ2MOKWB.js +2 -0
  308. package/dist/cli/chunks/{web-tree-sitter-VLTXZFAB.js → web-tree-sitter-ZF6FIE5R.js} +2 -2
  309. package/dist/cli/chunks/{windsurf-installer-VELMLOZF.js → windsurf-installer-HQGDZT5D.js} +2 -2
  310. package/dist/cli/chunks/witness-chain-DCHCAMSQ.js +2 -0
  311. package/dist/cli/chunks/witness-chain-P3XXXA62.js +2 -0
  312. package/dist/cli/chunks/witness-chain-repair-PUX2NFDL.js +2 -0
  313. package/dist/cli/chunks/{witness-chain-verifier-MIDWD4JS.js → witness-chain-verifier-PX2OQ6XT.js} +2 -2
  314. package/dist/cli/chunks/{witness-key-manager-OSVCWOB2.js → witness-key-manager-RXYQNFJB.js} +2 -2
  315. package/dist/cli/chunks/{workflow-MK7A7QCX.js → workflow-FBKCA4H6.js} +4 -4
  316. package/dist/cli/chunks/workflow-orchestrator-P2APAJAA.js +2 -0
  317. package/dist/cli/chunks/wrappers-TWSKBTWD.js +2 -0
  318. package/dist/cli/commands/code.js +4 -0
  319. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +10 -2
  320. package/dist/cli/handlers/task-handler.d.ts +5 -0
  321. package/dist/cli/handlers/task-handler.js +21 -1
  322. package/dist/cli/utils/task-result.d.ts +11 -0
  323. package/dist/cli/utils/task-result.js +39 -0
  324. package/dist/coordination/handlers/test-execution-handlers.js +92 -58
  325. package/dist/coordination/mincut/mincut-persistence.js +29 -25
  326. package/dist/domains/code-intelligence/coordinator.d.ts +4 -0
  327. package/dist/domains/code-intelligence/coordinator.js +46 -13
  328. package/dist/domains/code-intelligence/interfaces.d.ts +10 -1
  329. package/dist/domains/code-intelligence/services/semantic-analyzer.d.ts +32 -7
  330. package/dist/domains/code-intelligence/services/semantic-analyzer.js +112 -53
  331. package/dist/domains/learning-optimization/services/learning-coordinator.js +1 -1
  332. package/dist/domains/quality-assessment/coordinator.js +2 -1
  333. package/dist/domains/test-execution/coordinator.js +10 -5
  334. package/dist/domains/test-execution/interfaces.d.ts +12 -0
  335. package/dist/domains/test-execution/plugin.js +6 -2
  336. package/dist/domains/test-execution/services/retry-handler.d.ts +2 -0
  337. package/dist/domains/test-execution/services/retry-handler.js +14 -9
  338. package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
  339. package/dist/domains/test-execution/services/test-executor.js +28 -9
  340. package/dist/domains/visual-accessibility/coordinator.d.ts +15 -7
  341. package/dist/domains/visual-accessibility/coordinator.js +15 -7
  342. package/dist/domains/visual-accessibility/interfaces.d.ts +27 -3
  343. package/dist/domains/visual-accessibility/services/accessibility-contrast.d.ts +39 -0
  344. package/dist/domains/visual-accessibility/services/accessibility-contrast.js +93 -0
  345. package/dist/domains/visual-accessibility/services/accessibility-tester-browser.d.ts +18 -3
  346. package/dist/domains/visual-accessibility/services/accessibility-tester-browser.js +50 -40
  347. package/dist/domains/visual-accessibility/services/accessibility-tester-checks.d.ts +27 -0
  348. package/dist/domains/visual-accessibility/services/accessibility-tester-checks.js +137 -0
  349. package/dist/domains/visual-accessibility/services/accessibility-tester.d.ts +5 -0
  350. package/dist/domains/visual-accessibility/services/accessibility-tester.js +43 -24
  351. package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.d.ts +2 -3
  352. package/dist/domains/visual-accessibility/services/browser-swarm-coordinator.js +8 -14
  353. package/dist/feedback/coverage-learner.js +13 -9
  354. package/dist/feedback/test-outcome-tracker.js +13 -9
  355. package/dist/governance/witness-chain.d.ts +5 -0
  356. package/dist/governance/witness-chain.js +22 -6
  357. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.d.ts +22 -0
  358. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +115 -45
  359. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.d.ts +6 -0
  360. package/dist/integrations/agentic-flow/reasoning-bank/pattern-evolution.js +51 -33
  361. package/dist/integrations/agentic-flow/reasoning-bank/trajectory-tracker.js +17 -9
  362. package/dist/integrations/embeddings/cache/EmbeddingCache.d.ts +8 -0
  363. package/dist/integrations/embeddings/cache/EmbeddingCache.js +24 -10
  364. package/dist/integrations/ruvector/delta-tracker.d.ts +11 -0
  365. package/dist/integrations/ruvector/delta-tracker.js +16 -0
  366. package/dist/integrations/ruvector/sona-persistence.d.ts +10 -0
  367. package/dist/integrations/ruvector/sona-persistence.js +49 -24
  368. package/dist/kernel/unified-memory.d.ts +24 -0
  369. package/dist/kernel/unified-memory.js +63 -8
  370. package/dist/learning/aqe-learning-engine.js +1 -1
  371. package/dist/learning/embed-and-insert-pattern.js +4 -2
  372. package/dist/learning/embedder-endpoint-client.d.ts +31 -0
  373. package/dist/learning/embedder-endpoint-client.js +103 -10
  374. package/dist/learning/embedding-space.d.ts +12 -0
  375. package/dist/learning/embedding-space.js +17 -0
  376. package/dist/learning/experience-capture-middleware.js +25 -13
  377. package/dist/learning/experience-capture.js +1 -1
  378. package/dist/learning/experience-consolidation.d.ts +18 -0
  379. package/dist/learning/experience-consolidation.js +55 -8
  380. package/dist/learning/experience-space-verification.d.ts +71 -0
  381. package/dist/learning/experience-space-verification.js +147 -0
  382. package/dist/learning/pattern-lifecycle.d.ts +40 -4
  383. package/dist/learning/pattern-lifecycle.js +153 -76
  384. package/dist/learning/pattern-null-store.d.ts +5 -0
  385. package/dist/learning/pattern-null-store.js +8 -0
  386. package/dist/learning/pattern-promotion.js +6 -3
  387. package/dist/learning/pattern-store.d.ts +6 -0
  388. package/dist/learning/pattern-store.js +19 -6
  389. package/dist/learning/qe-reasoning-bank.js +2 -2
  390. package/dist/learning/real-embeddings.js +3 -1
  391. package/dist/learning/real-qe-reasoning-bank.d.ts +5 -0
  392. package/dist/learning/real-qe-reasoning-bank.js +77 -47
  393. package/dist/learning/rvf-pattern-store.js +6 -2
  394. package/dist/learning/sqlite-persistence.d.ts +6 -0
  395. package/dist/learning/sqlite-persistence.js +10 -0
  396. package/dist/mcp/bundle.js +641 -570
  397. package/dist/mcp/entry.js +4 -0
  398. package/dist/mcp/handlers/domain-handler-configs.js +2 -0
  399. package/dist/mcp/handlers/trajectory-judge.js +1 -1
  400. package/dist/mcp/protocol-server.js +1 -0
  401. package/dist/mcp/tools/visual-accessibility/index.js +8 -2
  402. package/dist/mcp/types.d.ts +6 -0
  403. package/dist/optimization/session-cache.d.ts +17 -1
  404. package/dist/optimization/session-cache.js +40 -36
  405. package/dist/planning/goap-planner.d.ts +6 -0
  406. package/dist/planning/goap-planner.js +35 -19
  407. package/dist/planning/plan-executor.js +24 -15
  408. package/dist/routing/co-execution-repository.js +12 -9
  409. package/dist/routing/routing-feedback.d.ts +8 -0
  410. package/dist/routing/routing-feedback.js +46 -24
  411. package/dist/routing/routing-outcomes-migration.js +7 -2
  412. package/dist/shared/llm/spend-ledger.d.ts +9 -0
  413. package/dist/shared/llm/spend-ledger.js +64 -39
  414. package/dist/shared/sqlite-lock-wait.d.ts +27 -0
  415. package/dist/shared/sqlite-lock-wait.js +37 -0
  416. package/dist/shared/sqlite-write-queue.d.ts +28 -0
  417. package/dist/shared/sqlite-write-queue.js +38 -0
  418. package/dist/shared/test-runner-project.d.ts +69 -0
  419. package/dist/shared/test-runner-project.js +186 -0
  420. package/dist/skills/security-visual-testing/index.d.ts +3 -1
  421. package/dist/skills/security-visual-testing/index.js +49 -35
  422. package/dist/skills/security-visual-testing/types.d.ts +19 -3
  423. package/dist/workers/workers/heartbeat-scheduler.js +5 -5
  424. package/dist/workers/workers/learning-consolidation.js +8 -7
  425. package/package.json +1 -1
  426. package/dist/cli/chunks/adapter-QU6INSKP.js +0 -2
  427. package/dist/cli/chunks/aqe-learning-engine-PAJPENJD.js +0 -2
  428. package/dist/cli/chunks/base-OTGSN6IC.js +0 -2
  429. package/dist/cli/chunks/browser-workflow-WLZGR6SB.js +0 -2
  430. package/dist/cli/chunks/chunk-2LUTPMBO.js +0 -21
  431. package/dist/cli/chunks/chunk-3HVFIITW.js +0 -2
  432. package/dist/cli/chunks/chunk-5KA5TVPR.js +0 -6
  433. package/dist/cli/chunks/chunk-6NBRMD25.js +0 -13
  434. package/dist/cli/chunks/chunk-7O45RQHF.js +0 -153
  435. package/dist/cli/chunks/chunk-EMSZVUYA.js +0 -29
  436. package/dist/cli/chunks/chunk-G6RDCCFV.js +0 -4
  437. package/dist/cli/chunks/chunk-HH4ED4F7.js +0 -744
  438. package/dist/cli/chunks/chunk-Q6I4SIUU.js +0 -65
  439. package/dist/cli/chunks/chunk-QGBGSQ2E.js +0 -14
  440. package/dist/cli/chunks/chunk-QRKTBSZT.js +0 -27
  441. package/dist/cli/chunks/chunk-SHRI7TKJ.js +0 -62
  442. package/dist/cli/chunks/chunk-UGYM4U44.js +0 -2
  443. package/dist/cli/chunks/chunk-VY4U6DPO.js +0 -12
  444. package/dist/cli/chunks/chunk-WNTA4YKE.js +0 -14
  445. package/dist/cli/chunks/chunk-XHLYGXYE.js +0 -2
  446. package/dist/cli/chunks/client-KKRNPX4F.js +0 -2
  447. package/dist/cli/chunks/core-handlers-47MPMED7.js +0 -2
  448. package/dist/cli/chunks/cross-domain-router-U6MBFHEC.js +0 -2
  449. package/dist/cli/chunks/daemon-AXLVPKVO.js +0 -18
  450. package/dist/cli/chunks/dream-76L6EEN7.js +0 -2
  451. package/dist/cli/chunks/embed-and-insert-pattern-B6MNHICW.js +0 -3
  452. package/dist/cli/chunks/experience-capture-middleware-SUFILYPW.js +0 -40
  453. package/dist/cli/chunks/file-discovery-VSFKZ3LJ.js +0 -2
  454. package/dist/cli/chunks/heartbeat-scheduler-NIK3KKEH.js +0 -2
  455. package/dist/cli/chunks/hnsw-adapter-WJG7LUJJ.js +0 -2
  456. package/dist/cli/chunks/hnsw-index-D6PRI5HC.js +0 -2
  457. package/dist/cli/chunks/hybrid-backend-RIUR3I7F.js +0 -2
  458. package/dist/cli/chunks/impact-analyzer-C36YYTJ5.js +0 -2
  459. package/dist/cli/chunks/init-wizard-JCKNGIGT.js +0 -2
  460. package/dist/cli/chunks/kernel-F7ILJTYD.js +0 -2
  461. package/dist/cli/chunks/knowledge-graph-VTXDBHB2.js +0 -2
  462. package/dist/cli/chunks/llm-router-service-TNOWQINA.js +0 -2
  463. package/dist/cli/chunks/load-test-FPVBK2EV.js +0 -2
  464. package/dist/cli/chunks/memory-backend-2QE7O67A.js +0 -2
  465. package/dist/cli/chunks/memory-handlers-X4CMVBXB.js +0 -2
  466. package/dist/cli/chunks/pattern-null-store-UI35ORHW.js +0 -2
  467. package/dist/cli/chunks/project-root-S7WDFTMU.js +0 -2
  468. package/dist/cli/chunks/protocol-executor-OPANXQVB.js +0 -2
  469. package/dist/cli/chunks/qe-reasoning-bank-3OTF4DYQ.js +0 -2
  470. package/dist/cli/chunks/queen-coordinator-WTYH4TAN.js +0 -2
  471. package/dist/cli/chunks/real-embeddings-DYIOLKQ3.js +0 -2
  472. package/dist/cli/chunks/router-DBBW4NC2.js +0 -2
  473. package/dist/cli/chunks/routing-feedback-W35QHCL4.js +0 -2
  474. package/dist/cli/chunks/rvf-dual-writer-X3NSL25Z.js +0 -2
  475. package/dist/cli/chunks/rvf-migration-adapter-TZR7GDOK.js +0 -2
  476. package/dist/cli/chunks/rvf-migration-coordinator-4ATTHGHD.js +0 -2
  477. package/dist/cli/chunks/rvf-native-adapter-HD25ZYV5.js +0 -2
  478. package/dist/cli/chunks/safe-db-ZS2QKANY.js +0 -2
  479. package/dist/cli/chunks/schedule-ZH6VNA32.js +0 -2
  480. package/dist/cli/chunks/scheduler-T6CD74B6.js +0 -2
  481. package/dist/cli/chunks/sqlite-persistence-47WU5EKZ.js +0 -2
  482. package/dist/cli/chunks/sync-3MUV6S5E.js +0 -2
  483. package/dist/cli/chunks/task-handler-74MZN2EO.js +0 -62
  484. package/dist/cli/chunks/test-runner-process-2NPW3UDQ.js +0 -2
  485. package/dist/cli/chunks/token-bootstrap-TTRCECLP.js +0 -2
  486. package/dist/cli/chunks/tree-sitter-wasm-parser-RZAND65G.js +0 -2
  487. package/dist/cli/chunks/unified-memory-FZ5K2C7W.js +0 -2
  488. package/dist/cli/chunks/unified-memory-hnsw-VREWX56M.js +0 -2
  489. package/dist/cli/chunks/unified-persistence-YZGMKX6B.js +0 -2
  490. package/dist/cli/chunks/visual-security-GXGSFBVA.js +0 -2
  491. package/dist/cli/chunks/witness-chain-MRJKVCOW.js +0 -2
  492. package/dist/cli/chunks/witness-chain-WWHJKITG.js +0 -2
  493. package/dist/cli/chunks/witness-chain-repair-5SAXPETG.js +0 -2
  494. package/dist/cli/chunks/workflow-orchestrator-SG7DV72E.js +0 -2
  495. package/dist/cli/chunks/wrappers-5QFMCKXL.js +0 -2
@@ -0,0 +1,27 @@
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.15.16");process.exit(0)}
2
+ import{c as m,d as x}from"./chunk-JDIYMZCQ.js";import{a as f}from"./chunk-YAPLJR7K.js";import{c as g}from"./chunk-G5RHFBAY.js";import{S as R,b as l}from"./chunk-L6QSTQME.js";f();R();x();import{createHash as v,randomUUID as E}from"crypto";var o=g.create("witness-chain"),d=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},h="0".repeat(64),p=class{receipts=[];lastHash=h;sprtAccumulators=new Map;appendWitness(t){let e=E(),i=Date.now(),n=this.receipts.length,s=this.lastHash+JSON.stringify(t)+i,r=v("sha256").update(s).digest("hex"),c={id:e,timestamp:i,previousHash:this.lastHash,hash:r,decision:t,chainIndex:n};return this.receipts.push(c),this.lastHash=r,this.updateSPRT(t),o.debug("Witness appended",{chainIndex:n,type:t.type,decision:t.decision,hash:r.slice(0,16)+"..."}),c}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:h};let t=h;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let n=i.previousHash+JSON.stringify(i.decision)+i.timestamp,s=v("sha256").update(n).digest("hex");if(i.hash!==s)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return o.warn("Import failed: invalid format"),!1;let i=this.receipts,n=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:h;let s=this.verifyChain();return s.valid?(o.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=n,o.warn("Import failed: chain integrity check failed",{message:s.message}),!1)}catch(e){return o.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new d(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},u=class extends p{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?o.info("Witness chain restored from SQLite",{receipts:e.length}):o.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t),i=n=>{o.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:n instanceof Error?n.message:String(n)})};try{this.persistence.insertReceiptWhenUnlocked?this.persistence.insertReceiptWhenUnlocked(e).catch(i):this.persistence.insertReceipt(e)}catch(n){i(n)}return e}};function b(a){a.exec(`
3
+ CREATE TABLE IF NOT EXISTS witness_chain_receipts (
4
+ id TEXT PRIMARY KEY,
5
+ chain_index INTEGER NOT NULL,
6
+ timestamp INTEGER NOT NULL,
7
+ previous_hash TEXT NOT NULL,
8
+ hash TEXT NOT NULL,
9
+ decision_type TEXT NOT NULL,
10
+ decision_outcome TEXT NOT NULL,
11
+ decision_context TEXT NOT NULL,
12
+ decision_evidence REAL,
13
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
14
+ )
15
+ `),a.exec(`
16
+ CREATE INDEX IF NOT EXISTS idx_witness_chain_index
17
+ ON witness_chain_receipts(chain_index)
18
+ `);let t=a.prepare(`
19
+ INSERT OR REPLACE INTO witness_chain_receipts
20
+ (id, chain_index, timestamp, previous_hash, hash,
21
+ decision_type, decision_outcome, decision_context, decision_evidence)
22
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
23
+ `),e=a.prepare(`
24
+ SELECT * FROM witness_chain_receipts ORDER BY chain_index ASC
25
+ `),i=a.prepare(`
26
+ SELECT COUNT(*) as cnt FROM witness_chain_receipts
27
+ `),n=s=>{t.run(s.id,s.chainIndex,s.timestamp,s.previousHash,s.hash,s.decision.type,s.decision.decision,JSON.stringify(s.decision.context),s.decision.evidence??null)};return{insertReceipt:n,insertReceiptWhenUnlocked(s){return m(a,()=>n(s))},loadAllReceipts(){return e.all().map(r=>{let c={};try{c=JSON.parse(r.decision_context)}catch{o.warn("Corrupt decision_context in witness receipt, using empty object",{receiptId:r.id,chainIndex:r.chain_index})}return{id:r.id,chainIndex:r.chain_index,timestamp:r.timestamp,previousHash:r.previous_hash,hash:r.hash,decision:{type:r.decision_type,decision:r.decision_outcome,context:c,evidence:r.decision_evidence??void 0}}})},getReceiptCount(){return i.get().cnt}}}function T(){return new p}function _(a){return new u(a)}function I(){return l().useWitnessChain}export{d as a,p as b,u as c,b as d,T as e,_ as f,I as g};
@@ -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.15.15");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.15.16");process.exit(0)}
2
2
  import*as y from"node:fs/promises";import*as g from"node:path";var b=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),R=new Set(["node_modules",".git","dist","build","coverage",".nyc_output","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".agentic-qe",".claude",".cache",".npm",".yarn",".next",".nuxt",".svelte-kit","out",".turbo","tmp","temp",".tmp"]);function x(e){return b.has(g.extname(e).toLowerCase())}async function $(e,c={}){let s=c.maxFiles??5e3,o=c.maxDepth??64;if(!Number.isSafeInteger(s)||s<1||!Number.isSafeInteger(o)||o<0)throw new Error("Security discovery requires a positive file limit and non-negative depth limit.");let n=[],a=[],p=[],t=g.resolve(e),k=!1,v=!1;function E(r,m){let d=m?.code;a.push({path:r,reason:typeof d=="string"&&/^[A-Z0-9_]{1,32}$/.test(d)?d:"DISCOVERY_FAILED"})}async function D(r,m){if(m>o){a.push({path:r,reason:"DEPTH_LIMIT"});return}let d;try{d=await y.readdir(r,{withFileTypes:!0})}catch(i){E(r,i),r===t&&(k=!0);return}d.sort((i,l)=>i.name<l.name?-1:i.name>l.name?1:0);for(let i of d){if(v)return;let l=g.join(r,i.name);if(i.isSymbolicLink())p.push(l);else if(i.isDirectory())R.has(i.name)?p.push(l):await D(l,m+1);else if(i.isFile()&&x(i.name)){if(n.length===s){a.push({path:l,reason:"FILE_LIMIT"}),v=!0;return}n.push(l)}}}try{let r=await y.lstat(t);r.isFile()?n.push(t):r.isDirectory()?await D(t,0):(k=!0,a.push({path:t,reason:r.isSymbolicLink()?"SYMLINK_TARGET":"NOT_REGULAR_INPUT"}))}catch(r){k=!0,E(t,r)}return{files:n,discovery:{status:k?"failed":a.length>0?"partial":"complete",policy:"aqe-security-source-files@1",issues:a,excludedPaths:p}}}import*as f from"fs/promises";import*as u from"path";var S="osv-dependency-advisories";async function w(e,c=process.env){let s=e;try{(await f.stat(e)).isDirectory()||(s=u.dirname(e))}catch{s=u.dirname(e)}let o=[s,c.AQE_PROJECT_ROOT?u.resolve(c.AQE_PROJECT_ROOT):null];for(let n of o){if(!n)continue;let a=u.join(n,"package.json");try{if((await f.stat(a)).isFile())return a}catch{}}return null}var O="direct dependencies of this package.json only; workspace members and transitive dependencies are not checked";function P(e){return`${_(e)} Scope: ${O}.`}function _(e){switch(e.status){case"complete":return e.packagesRequested===0?`No registry dependencies to check${e.localPackages.length?` (${e.localPackages.length} local package(s) excluded)`:" in package.json"}; nothing to check (complete).`:`Dependency advisories checked for all ${e.packagesChecked} package(s): ${e.vulnerabilities} advisory finding(s).`;case"incomplete":return(e.uncheckedPackages.length>0?`Dependency advisories could not be checked for ${e.uncheckedPackages.length} of ${e.packagesRequested} package(s); `:"")+(e.resolutionErrors.length>0?`${e.resolutionErrors.slice(0,3).join("; ")}; `:"")+`${e.vulnerabilities} finding(s) from the ${e.packagesChecked} checked package(s). Dependency scan is INCOMPLETE, not clean.`;case"failed":return`${e.error??`Dependency advisories could not be checked for ${e.uncheckedPackages.length} package(s)`}. Dependency vulnerabilities are UNMEASURED, not zero.`;default:return e.error??"Dependency advisory scan did not run."}}function h(e,c){let s={status:"not-run",measured:!1,...c?{manifest:c}:{},packagesRequested:0,packagesChecked:0,uncheckedPackages:[],localPackages:[],resolutionErrors:[],scope:"direct",vulnerabilities:0,error:e};return{engine:{id:S,requested:!0,required:!0,status:"failed",scope:"parent-directory",...c?{target:c}:{},analyzedFiles:0,ruleCoverage:"unknown",errors:[e],limitations:[]},vulnerabilities:[],report:{...s,message:P(s)}}}async function N(e,c){let s=await w(c);if(!s)return h("No package.json found for the dependency advisory scan.");let o;try{o=await e.scanPackageJson(s)}catch(t){return h(`Dependency advisory scan failed: ${t instanceof Error?t.message:String(t)}`,s)}if(!o.success)return h(`Dependency advisory scan did not run: ${o.error.message}`,s);let n=o.value,a=n.uncheckedPackages.map(t=>`${t.name}@${t.version}: ${t.reason}`),p={status:n.status,measured:n.measured,manifest:s,lockfile:n.lockfile??null,packagesRequested:n.packagesScanned,packagesChecked:n.packagesChecked,uncheckedPackages:n.uncheckedPackages,localPackages:n.localPackages??[],resolutionErrors:n.resolutionErrors??[],scope:"direct",vulnerabilities:n.vulnerabilities.length,scanId:n.scanId,...n.error?{error:n.error}:{}};return{engine:{id:S,requested:!0,required:!0,status:n.status==="complete"?"completed":n.status==="incomplete"?"partial":"failed",scope:"parent-directory",target:s,ruleCoverage:"unknown",errors:[...n.error?[n.error]:[],...n.resolutionErrors??[],...a.slice(0,20),...a.length>20?[`... and ${a.length-20} more unchecked package(s)`]:[]],limitations:[n.lockfile?`Direct dependencies are checked at the versions ${n.lockfile} resolves (when in sync with package.json); transitive dependencies are not checked.`:"No lockfile: only exact versions in package.json are checked; ranges are reported unchecked. Transitive dependencies are not checked.",...(n.localPackages??[]).length>0?[`${n.localPackages.length} local workspace/linked package(s) are not OSV subjects and were excluded.`]:[]]},vulnerabilities:n.vulnerabilities,report:{...p,message:P(p)}}}export{x as a,$ as b,N 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.15.15");process.exit(0)}
2
- import{b as t}from"./chunk-XH4JMX5O.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r 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.15.16");process.exit(0)}
2
+ import{b as t}from"./chunk-AJMJNQMP.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r 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.15.15");process.exit(0)}
2
- import{S as f,b as p}from"./chunk-6YVMX2TC.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{S as f,b as p}from"./chunk-L6QSTQME.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
@@ -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.15.15");process.exit(0)}
2
- import{a as I,b as _,c as X,d as M,f as ee,h as ae}from"./chunk-RBKUU7WF.js";import{a as K,e as Z}from"./chunk-Q6I4SIUU.js";import{c as te,d as re,e as ne,f as ie}from"./chunk-UXIY4IAI.js";import{b as D,g as $,j as H}from"./chunk-KCQNFBBR.js";import{b as k}from"./chunk-TODNOP7C.js";import{c as Y,i as J}from"./chunk-YUS6TWAL.js";import{r as U,v as ve}from"./chunk-T66PPF4D.js";import{s as T}from"./chunk-6NBRMD25.js";import{c as C,d as E}from"./chunk-LJMYRTJ7.js";import{a as G}from"./chunk-3HVFIITW.js";import{c as A}from"./chunk-BQ47GQPK.js";import{S as ye,b as j}from"./chunk-6YVMX2TC.js";import{a as f,b as B,e as z}from"./chunk-HL2ANKN3.js";G();z();function oe(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:g}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:g,capped:o.length>s}}var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.16");process.exit(0)}
2
+ import{a as _,b as M,c as K,d as N,f as te,h as oe}from"./chunk-KU2AUFGX.js";import{a as Y,e as ee}from"./chunk-5B5QPCNU.js";import{c as re,d as ne,e as ie,f as ae}from"./chunk-PHT5N7SC.js";import{b as I,g as H,j as X}from"./chunk-EA4YQVKS.js";import{b as k}from"./chunk-63ZKI4PX.js";import{c as J,i as Z}from"./chunk-IOKYCMTJ.js";import{B as Re,w as $}from"./chunk-MO55CVMT.js";import{c as D,d as Pe}from"./chunk-JDIYMZCQ.js";import{n as T}from"./chunk-M4FRQ4TE.js";import{c as C,d as E}from"./chunk-LE4QJREF.js";import{a as U}from"./chunk-YAPLJR7K.js";import{c as A}from"./chunk-G5RHFBAY.js";import{S as ve,b as G}from"./chunk-L6QSTQME.js";import{a as f,b as z,e as j}from"./chunk-KNSRL6NO.js";U();j();function se(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:g}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:g,capped:o.length>s}}var O={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -278,7 +278,7 @@ On promotion:
278
278
  - Move from short-term to long-term tier
279
279
  - Boost confidence by 10%
280
280
  - Enable for cross-domain transfer to related domains
281
- - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as se}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},Pe=.4,Re=20,we=3;function Se(i){return 1/(1+Math.exp(-i))}function Ee(i,e){if(!e||e.visits===0)return{score:i,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/Re,1)*Pe,t=Se(e.qValue);return{score:i*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function ce(i){let e=i.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,n=i.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*n,0),1),baseEpsilon:t,safetyMultiplier:n}}function le(i,e){if(e<=0||i.length<2)return;let r=Math.round(e*1e6);if(r<=0||se(0,1e6)>=r)return;let t=Math.min(4,i.length),n=se(1,t),a=i[n];i[n]=i[0],i[0]=a,i[0].exploration=!0,i[0].reasoning=[...i[0].reasoning,"(exploration)"]}function ue(i){let e=i.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function de(i){return`${i.taskType}|${i.priority??"normal"}|${i.domain??"any"}`}function O(i,e,r,t,n=x,a,o){let s=[];for(let[l,u]of Object.entries(n)){let c=0,g=[],d=i.filter(b=>u.domains.includes(b)).length,h=Math.min(i.length,we),y=d>0?Math.min(d/h,1)*.4:0;if(c+=y*t.similarity,y>0&&g.push(`Domain match: ${(y*100).toFixed(0)}%`),e&&e.length>0){let b=e.filter(v=>u.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,p=b>0?b/e.length*.3:0;c+=p*t.capabilities,p>0&&g.push(`Capability match: ${(p*100).toFixed(0)}%`)}else c+=.15*t.capabilities;if(c+=u.performanceScore*.3*t.performance,g.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),a&&u.languages&&u.languages.length>0){let b=t.language??1,p=a.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===p)){let P=.15*b;c+=P,g.push(`Language match: ${a}`)}}let w=r.get(l)||0;if(w>0){let b=Math.min(.1,w*.02);c+=b,g.push(`Pattern matches: ${w}`)}let S=c;if(o){let b=o(l),p=Ee(S,b);c=p.score,p.qWeight>0&&g.push(`Q-bonus (w=${p.qWeight.toFixed(2)}, v=${p.qVisits})`),s.push({agent:l,score:c,reasoning:g,staticScore:S,qWeight:p.qWeight,qValue:p.qValue,qVisits:p.qVisits})}else s.push({agent:l,score:c,reasoning:g,staticScore:S})}return s.sort((l,u)=>u.score-l.score),s}var Q={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function pe(){try{return!ie()||!ne()||te().getVerticesByType("agent").length===0?!1:re().isCritical()}catch{return!1}}ve();function me(i,e){if(i.length===e)return i;if(i.length>e){let r=i.length/e,t=new Array(e).fill(0);for(let n=0;n<e;n++){let a=Math.floor(n*r),o=Math.floor((n+1)*r),s=0;for(let l=a;l<o;l++)s+=i[l];t[n]=s/(o-a)}return F(t)}else{let r=new Array(e).fill(0),t=(i.length-1)/(e-1);for(let n=0;n<e;n++){let a=n*t,o=Math.floor(a),s=Math.min(o+1,i.length-1),l=a-o;r[n]=i[o]*(1-l)+i[s]*l}return F(r)}}function ge(i,e){let r=new Array(e).fill(0),t=i.toLowerCase().trim();for(let n=0;n<3;n++)for(let a=0;a<t.length;a++){let o=t.charCodeAt(a),s=o*(a+1)*(n+1)%e;r[s]+=Math.sin(o*(n+1))/(a+1)}return F(r)}function F(i){let e=Math.sqrt(i.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<i.length;r++)i[r]/=e;return i}G();z();ye();var R=A.create("PatternPromotion");async function fe(i,e){let r=$(i);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),o=[...t.success?t.value.map(l=>l.pattern):[],i].map(l=>({id:l.id,embedding:l.embedding||[],weight:l.confidence,metadata:{name:l.name,domain:l.qeDomain}})),s=await e.coherenceService.checkCoherence(o);if(s.energy>=e.coherenceThreshold){let l={patternId:i.id,patternName:i.name,reason:"coherence_violation",energy:s.energy,existingPatternConflicts:s.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${i.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:l}),R.info("Pattern promotion blocked due to coherence violation",{name:i.name,energy:s.energy}),!1}}return!0}async function V(i,e){let r=await e.patternStore.promote(i);if(r.success){try{e.getSqliteStore().promotePattern(i)}catch(t){R.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(j().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let n=new L(t),a=await e.getPattern(i);if(a){let o=await e.searchPatterns("",{domain:a.qeDomain,tier:"long-term",limit:20});if(o.success)for(let{pattern:s}of o.value)s.id!==i&&n.recordCoOccurrence(i,s.id)}}}catch(t){R.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(i);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(i,t.embedding)}catch(t){R.warn("RVF dual-write on promote failed (non-fatal)",{patternId:i,error:f(t)})}return k().then(t=>t.append("PATTERN_PROMOTE",{patternId:i},"reasoning-bank")).catch(t=>{R.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),R.info("Promoted pattern to long-term",{patternId:i}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${i}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:i,newTier:"long-term"}}),r}else return R.error("Failed to promote pattern",r.error,{patternId:i}),r}async function he(i){let{signal:e}=i;e?.throwIfAborted();let r=await i.patternStore.getStats(),t=0,n=0;for(let[a,o]of Object.entries(Q)){e?.throwIfAborted();let s=a,l=r.byDomain[s]||0;if(l===0)continue;let u=await i.searchPatterns("",{domain:s,limit:50});if(u.success)for(let c of o){if(e?.throwIfAborted(),(r.byDomain[c]||0)>=l){n++;continue}for(let{pattern:d}of u.value){e?.throwIfAborted();let h=await i.searchPatterns(d.name,{domain:c,limit:1});if(h.success&&h.value.length>0&&h.value[0].score>.8){n++;continue}let y=Math.max(.3,(d.confidence||.5)*.8);(await i.storePattern({patternType:d.patternType,qeDomain:c,name:`${d.name} (from ${s})`,description:`${d.description} [Transferred from ${s} domain]`,template:d.template,context:{...d.context,relatedDomains:[s,c],tags:[...d.context.tags,"cross-domain-transfer",`source:${s}`]},confidence:y})).success?t++:n++}}}return R.info("Cross-domain transfer complete",{transferred:t,skipped:n}),{transferred:t,skipped:n}}var ke=`
281
+ - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as ce}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},we=.4,Se=20,Ee=3;function ke(i){return 1/(1+Math.exp(-i))}function xe(i,e){if(!e||e.visits===0)return{score:i,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/Se,1)*we,t=ke(e.qValue);return{score:i*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function le(i){let e=i.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,n=i.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*n,0),1),baseEpsilon:t,safetyMultiplier:n}}function ue(i,e){if(e<=0||i.length<2)return;let r=Math.round(e*1e6);if(r<=0||ce(0,1e6)>=r)return;let t=Math.min(4,i.length),n=ce(1,t),a=i[n];i[n]=i[0],i[0]=a,i[0].exploration=!0,i[0].reasoning=[...i[0].reasoning,"(exploration)"]}function de(i){let e=i.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function pe(i){return`${i.taskType}|${i.priority??"normal"}|${i.domain??"any"}`}function Q(i,e,r,t,n=x,a,o){let s=[];for(let[l,u]of Object.entries(n)){let c=0,g=[],d=i.filter(b=>u.domains.includes(b)).length,h=Math.min(i.length,Ee),y=d>0?Math.min(d/h,1)*.4:0;if(c+=y*t.similarity,y>0&&g.push(`Domain match: ${(y*100).toFixed(0)}%`),e&&e.length>0){let b=e.filter(v=>u.capabilities.some(P=>P.toLowerCase().includes(v.toLowerCase()))).length,p=b>0?b/e.length*.3:0;c+=p*t.capabilities,p>0&&g.push(`Capability match: ${(p*100).toFixed(0)}%`)}else c+=.15*t.capabilities;if(c+=u.performanceScore*.3*t.performance,g.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),a&&u.languages&&u.languages.length>0){let b=t.language??1,p=a.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===p)){let P=.15*b;c+=P,g.push(`Language match: ${a}`)}}let w=r.get(l)||0;if(w>0){let b=Math.min(.1,w*.02);c+=b,g.push(`Pattern matches: ${w}`)}let S=c;if(o){let b=o(l),p=xe(S,b);c=p.score,p.qWeight>0&&g.push(`Q-bonus (w=${p.qWeight.toFixed(2)}, v=${p.qVisits})`),s.push({agent:l,score:c,reasoning:g,staticScore:S,qWeight:p.qWeight,qValue:p.qValue,qVisits:p.qVisits})}else s.push({agent:l,score:c,reasoning:g,staticScore:S})}return s.sort((l,u)=>u.score-l.score),s}var F={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function me(){try{return!ae()||!ie()||re().getVerticesByType("agent").length===0?!1:ne().isCritical()}catch{return!1}}Re();function ge(i,e){if(i.length===e)return i;if(i.length>e){let r=i.length/e,t=new Array(e).fill(0);for(let n=0;n<e;n++){let a=Math.floor(n*r),o=Math.floor((n+1)*r),s=0;for(let l=a;l<o;l++)s+=i[l];t[n]=s/(o-a)}return L(t)}else{let r=new Array(e).fill(0),t=(i.length-1)/(e-1);for(let n=0;n<e;n++){let a=n*t,o=Math.floor(a),s=Math.min(o+1,i.length-1),l=a-o;r[n]=i[o]*(1-l)+i[s]*l}return L(r)}}function fe(i,e){let r=new Array(e).fill(0),t=i.toLowerCase().trim();for(let n=0;n<3;n++)for(let a=0;a<t.length;a++){let o=t.charCodeAt(a),s=o*(a+1)*(n+1)%e;r[s]+=Math.sin(o*(n+1))/(a+1)}return L(r)}function L(i){let e=Math.sqrt(i.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<i.length;r++)i[r]/=e;return i}U();j();Pe();ve();var R=A.create("PatternPromotion");async function he(i,e){let r=H(i);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),o=[...t.success?t.value.map(l=>l.pattern):[],i].map(l=>({id:l.id,embedding:l.embedding||[],weight:l.confidence,metadata:{name:l.name,domain:l.qeDomain}})),s=await e.coherenceService.checkCoherence(o);if(s.energy>=e.coherenceThreshold){let l={patternId:i.id,patternName:i.name,reason:"coherence_violation",energy:s.energy,existingPatternConflicts:s.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${i.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:l}),R.info("Pattern promotion blocked due to coherence violation",{name:i.name,energy:s.energy}),!1}}return!0}async function W(i,e){let r=await e.patternStore.promote(i);if(r.success){try{let t=e.getSqliteStore();await D(t.getDatabase(),()=>t.promotePattern(i))}catch(t){R.warn("SQLite pattern promotion persist failed",{error:f(t)})}if(G().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let n=new V(t),a=await e.getPattern(i);if(a){let o=await e.searchPatterns("",{domain:a.qeDomain,tier:"long-term",limit:20});if(o.success)for(let{pattern:s}of o.value)s.id!==i&&await D(t,()=>n.recordCoOccurrence(i,s.id))}}}catch(t){R.warn("Citation graph update failed (non-fatal)",{error:f(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(i);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(i,t.embedding)}catch(t){R.warn("RVF dual-write on promote failed (non-fatal)",{patternId:i,error:f(t)})}return k().then(t=>t.appendWhenUnlocked("PATTERN_PROMOTE",{patternId:i},"reasoning-bank")).catch(t=>{R.warn("Witness chain PATTERN_PROMOTE failed",{error:f(t)})}),R.info("Promoted pattern to long-term",{patternId:i}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${i}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:i,newTier:"long-term"}}),r}else return R.error("Failed to promote pattern",r.error,{patternId:i}),r}async function be(i){let{signal:e}=i;e?.throwIfAborted();let r=await i.patternStore.getStats(),t=0,n=0;for(let[a,o]of Object.entries(F)){e?.throwIfAborted();let s=a,l=r.byDomain[s]||0;if(l===0)continue;let u=await i.searchPatterns("",{domain:s,limit:50});if(u.success)for(let c of o){if(e?.throwIfAborted(),(r.byDomain[c]||0)>=l){n++;continue}for(let{pattern:d}of u.value){e?.throwIfAborted();let h=await i.searchPatterns(d.name,{domain:c,limit:1});if(h.success&&h.value.length>0&&h.value[0].score>.8){n++;continue}let y=Math.max(.3,(d.confidence||.5)*.8);(await i.storePattern({patternType:d.patternType,qeDomain:c,name:`${d.name} (from ${s})`,description:`${d.description} [Transferred from ${s} domain]`,template:d.template,context:{...d.context,relatedDomains:[s,c],tags:[...d.context.tags,"cross-domain-transfer",`source:${s}`]},confidence:y})).success?t++:n++}}}return R.info("Cross-domain transfer complete",{transferred:t,skipped:n}),{transferred:t,skipped:n}}var Ae=`
282
282
  CREATE TABLE IF NOT EXISTS pattern_citations (
283
283
  source_pattern_id TEXT NOT NULL,
284
284
  target_pattern_id TEXT NOT NULL,
@@ -289,7 +289,7 @@ On promotion:
289
289
  );
290
290
  CREATE INDEX IF NOT EXISTS idx_citations_source ON pattern_citations(source_pattern_id);
291
291
  CREATE INDEX IF NOT EXISTS idx_citations_target ON pattern_citations(target_pattern_id);
292
- `,L=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(ke),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,n]=e<r?[e,r]:[r,e];this.db.prepare(`
292
+ `,V=class{constructor(e){this.db=e}db;initialized=!1;ensureSchema(){this.initialized||(this.db.exec(Ae),this.initialized=!0)}recordCoOccurrence(e,r){this.ensureSchema();let[t,n]=e<r?[e,r]:[r,e];this.db.prepare(`
293
293
  INSERT INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
294
294
  VALUES (?, ?, 1.0, 'co-occurrence')
295
295
  ON CONFLICT(source_pattern_id, target_pattern_id)
@@ -311,10 +311,10 @@ On promotion:
311
311
  `).all(),l=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let u of s)l.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var m=A.create("QEReasoningBank"),W=class{constructor(e,r,t={},n){this.memory=e;this.eventBus=r;this.coherenceService=n;this.config={...N,...t},this.embedderRecovery=new ee({retryIntervalMs:this.config.embedderRetryIntervalMs,onRecovered:()=>m.info("Embedder available again: patterns are stored and searched with vectors"),onRetryFailed:a=>m.debug("Embedder still unavailable",{error:f(a)})}),t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=Z(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;embeddingProvenance=new WeakMap;embedderRecovery;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=J(),this.sqliteStore.initialize().catch(e=>{m.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,measuredOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){m.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let a=await this.patternStore.getStats();m.info("Cross-domain transfer already complete",{totalPatterns:a.totalPatterns})}}catch(t){if(r?.aborted)throw t;m.warn("Cross-domain seeding failed (non-fatal)",{error:t})}m.info("Initialized")}lastVectorReconcile=null;getLastVectorReconcile(){return this.lastVectorReconcile}reconcileVectorIndex(){let e=this.patternStore.getAdapter?.(),r=T()?.spaceId;if(!e||!r)return null;try{let t=Number(process.env.AQE_RVF_BACKFILL_LIMIT),n=Number.isFinite(t)&&t>0?Math.floor(t):1e3,a=oe(e,this.getSqliteStore(),r,n);return a.missing>0&&m.info("Reconciled RVF index with SQLite vectors",{...a}),this.lastVectorReconcile=a,a}catch(t){return m.warn("RVF reconcile failed (non-fatal)",{error:f(t)}),null}}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){m.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let n=(()=>{let s=process.env.AQE_RVF_BACKFILL_LIMIT,l=s?Number(s):NaN;return Number.isFinite(l)&&l>0?Math.floor(l):1e3})(),o=this.getSqliteStore().getRecentEmbeddings(n).filter(({embedding:s})=>s&&s.length>0).map(({patternId:s,embedding:l})=>({id:s,vector:l instanceof Float32Array?l:new Float32Array(l)}));if(o.length>0){let{accepted:s,rejected:l}=t.ingest(o);m.info("Backfilled RVF from SQLite",{requested:o.length,accepted:s,cap:n,truncated:o.length>=n}),l>0&&m.warn("RVF backfill partially rejected",{accepted:s,rejected:l})}}catch(n){m.warn("RVF backfill failed (non-fatal)",{error:f(n)})}else t&&this.reconcileVectorIndex();return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(n){if(e?.aborted)throw n;m.warn("Failed to load pattern",{name:t.name,error:n})}}m.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),he({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let n=await this.embedForPatterns(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);n!==null&&(this.embeddingProvenance.has(n)||!!T()?.spaceId)?e={...e,embedding:n}:m.debug("No embedding runtime provenance; storing pattern without a vector",{name:e.name})}let r=await this.patternStore.create(e),t=r.success?r.value:null;if(!r.success&&r.error instanceof K&&r.error.disposition==="COMMITTED_PENDING_INDEX")try{t=await this.patternStore.get(r.error.patternId)}catch(n){m.warn("Committed pattern lookup failed",{patternId:r.error.patternId,error:f(n)})}if(t){let n=t;if(k().then(a=>a.append("PATTERN_CREATE",{patternId:n.id,domain:n.qeDomain,confidence:n.confidence,name:n.name},"reasoning-bank")).catch(a=>{m.warn("Witness chain PATTERN_CREATE failed",{error:f(a)})}),this.rvfDualWriter&&n.embedding&&n.embedding.length>0)try{this.rvfDualWriter.writePattern(n.id,n.embedding)}catch(a){m.warn("RVF dual-write failed (non-fatal)",{patternId:n.id,error:f(a)})}}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,n=!0;if(typeof e=="string")if(e.trim()==="")n=!1,t="";else{let a=await this.embedForPatterns(e);t=a&&this.embeddingProvenance.has(a)?a:e,n=Array.isArray(t)}return this.patternStore.search(t,{...r,textQuery:typeof e=="string"&&e.trim()?e:r?.textQuery,useVectorSearch:n,embeddingSpaceId:typeof e=="string"?Array.isArray(t)?this.embeddingProvenance.get(t):void 0:r?.embeddingSpaceId})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return C(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,Y(e.metrics)==="measured"&&(this.stats.measuredOutcomes++,e.success&&this.stats.successfulOutcomes++),k().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{m.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let n=await this.getPattern(e.patternId),a=this.getPromotionDeps();n&&await fe(n,a)&&(await V(e.patternId,a),m.info("Pattern promoted to long-term",{name:n.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?V(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:D(e.task);r.length===0&&r.push("test-generation");let t=await this.embedForPatterns(e.task),n=t?this.embeddingProvenance.get(t):void 0,a=await this.patternStore.search(t&&n?t:e.task,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!!n,textQuery:e.task,embeddingSpaceId:n}),o=a.success?a.value.map(p=>p.pattern):[],s=new Map;for(let[p,v]of Object.entries(x)){let P=o.filter(be=>v.domains.includes(be.qeDomain)).length;P>0&&s.set(p,P)}let l=de({taskType:ue(e.task),priority:"normal",domain:r[0]}),u=this.buildQValueLookup(l),c=O(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,u),g=1;try{let p=pe(),v=ce({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:p});g=v.safetyMultiplier,le(c,v.epsilon)}catch{}let d=c[0],h=c.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let p=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...p.slice(0,5))}this.stats.totalRoutingConfidence+=d.score;let w=c.reduce((p,v)=>p+(v.qWeight??0),0),S=c.length>0?w/c.length:0,b={recommendedAgent:d.agent,confidence:d.score,alternatives:h.map(p=>({agent:p.agent,score:p.score})),domains:r,patterns:o,guidance:y,reasoning:d.reasoning.join("; "),exploration:d.exploration===!0,criticality:g,qWeight:S};return C(ae(e.includePatternGuidance,b,a.success?a.value:[]))}catch(r){return E(B(r))}}buildQValueLookup(e){try{let r=U();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let a=t.prepare(`
314
+ `);for(let u of s)l.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var m=A.create("QEReasoningBank"),B=class{constructor(e,r,t={},n){this.memory=e;this.eventBus=r;this.coherenceService=n;this.config={...O,...t},this.embedderRecovery=new te({retryIntervalMs:this.config.embedderRetryIntervalMs,onRecovered:()=>m.info("Embedder available again: patterns are stored and searched with vectors"),onRetryFailed:a=>m.debug("Embedder still unavailable",{error:f(a)})}),t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=ee(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;embeddingProvenance=new WeakMap;embedderRecovery;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=Z(),this.sqliteStore.initialize().catch(e=>{m.warn("SQLitePatternStore init failed",{error:f(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,measuredOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){m.warn("Failed to wire SQLitePatternStore into PatternStore",{error:f(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let a=await this.patternStore.getStats();m.info("Cross-domain transfer already complete",{totalPatterns:a.totalPatterns})}}catch(t){if(r?.aborted)throw t;m.warn("Cross-domain seeding failed (non-fatal)",{error:t})}m.info("Initialized")}lastVectorReconcile=null;getLastVectorReconcile(){return this.lastVectorReconcile}reconcileVectorIndex(){let e=this.patternStore.getAdapter?.(),r=T()?.spaceId;if(!e||!r)return null;try{let t=Number(process.env.AQE_RVF_BACKFILL_LIMIT),n=Number.isFinite(t)&&t>0?Math.floor(t):1e3,a=se(e,this.getSqliteStore(),r,n);return a.missing>0&&m.info("Reconciled RVF index with SQLite vectors",{...a}),this.lastVectorReconcile=a,a}catch(t){return m.warn("RVF reconcile failed (non-fatal)",{error:f(t)}),null}}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){m.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let n=(()=>{let s=process.env.AQE_RVF_BACKFILL_LIMIT,l=s?Number(s):NaN;return Number.isFinite(l)&&l>0?Math.floor(l):1e3})(),o=this.getSqliteStore().getRecentEmbeddings(n).filter(({embedding:s})=>s&&s.length>0).map(({patternId:s,embedding:l})=>({id:s,vector:l instanceof Float32Array?l:new Float32Array(l)}));if(o.length>0){let{accepted:s,rejected:l}=t.ingest(o);m.info("Backfilled RVF from SQLite",{requested:o.length,accepted:s,cap:n,truncated:o.length>=n}),l>0&&m.warn("RVF backfill partially rejected",{accepted:s,rejected:l})}}catch(n){m.warn("RVF backfill failed (non-fatal)",{error:f(n)})}else t&&this.reconcileVectorIndex();return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(n){if(e?.aborted)throw n;m.warn("Failed to load pattern",{name:t.name,error:n})}}m.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),be({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return E(new Error("Pattern learning is disabled"));if(!e.embedding){let n=await this.embedForPatterns(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);n!==null&&(this.embeddingProvenance.has(n)||!!T()?.spaceId)?e={...e,embedding:n}:m.debug("No embedding runtime provenance; storing pattern without a vector",{name:e.name})}let r=await this.patternStore.create(e),t=r.success?r.value:null;if(!r.success&&r.error instanceof Y&&r.error.disposition==="COMMITTED_PENDING_INDEX")try{t=await this.patternStore.get(r.error.patternId)}catch(n){m.warn("Committed pattern lookup failed",{patternId:r.error.patternId,error:f(n)})}if(t){let n=t;if(k().then(a=>a.appendWhenUnlocked("PATTERN_CREATE",{patternId:n.id,domain:n.qeDomain,confidence:n.confidence,name:n.name},"reasoning-bank")).catch(a=>{m.warn("Witness chain PATTERN_CREATE failed",{error:f(a)})}),this.rvfDualWriter&&n.embedding&&n.embedding.length>0)try{this.rvfDualWriter.writePattern(n.id,n.embedding)}catch(a){m.warn("RVF dual-write failed (non-fatal)",{patternId:n.id,error:f(a)})}}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,n=!0;if(typeof e=="string")if(e.trim()==="")n=!1,t="";else{let a=await this.embedForPatterns(e);t=a&&this.embeddingProvenance.has(a)?a:e,n=Array.isArray(t)}return this.patternStore.search(t,{...r,textQuery:typeof e=="string"&&e.trim()?e:r?.textQuery,useVectorSearch:n,embeddingSpaceId:typeof e=="string"?Array.isArray(t)?this.embeddingProvenance.get(t):void 0:r?.embeddingSpaceId})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return C(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,J(e.metrics)==="measured"&&(this.stats.measuredOutcomes++,e.success&&this.stats.successfulOutcomes++),k().then(o=>o.appendWhenUnlocked("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{m.warn("Witness chain PATTERN_UPDATE failed",{error:f(o)})});let n=await this.getPattern(e.patternId),a=this.getPromotionDeps();n&&await he(n,a)&&(await W(e.patternId,a),m.info("Pattern promoted to long-term",{name:n.name}))}return r}async promotePattern(e){return this.initialized||await this.initialize(),await this.getPattern(e)?W(e,this.getPromotionDeps()):E(new Error(`Pattern not found: ${e}`))}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return E(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:I(e.task);r.length===0&&r.push("test-generation");let t=await this.embedForPatterns(e.task),n=t?this.embeddingProvenance.get(t):void 0,a=await this.patternStore.search(t&&n?t:e.task,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!!n,textQuery:e.task,embeddingSpaceId:n}),o=a.success?a.value.map(p=>p.pattern):[],s=new Map;for(let[p,v]of Object.entries(x)){let P=o.filter(ye=>v.domains.includes(ye.qeDomain)).length;P>0&&s.set(p,P)}let l=pe({taskType:de(e.task),priority:"normal",domain:r[0]}),u=this.buildQValueLookup(l),c=Q(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,u),g=1;try{let p=me(),v=le({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:p});g=v.safetyMultiplier,ue(c,v.epsilon)}catch{}let d=c[0],h=c.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let p=M(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...p.slice(0,5))}this.stats.totalRoutingConfidence+=d.score;let w=c.reduce((p,v)=>p+(v.qWeight??0),0),S=c.length>0?w/c.length:0,b={recommendedAgent:d.agent,confidence:d.score,alternatives:h.map(p=>({agent:p.agent,score:p.score})),domains:r,patterns:o,guidance:y,reasoning:d.reasoning.join("; "),exploration:d.exploration===!0,criticality:g,qWeight:S};return C(oe(e.includePatternGuidance,b,a.success?a.value:[]))}catch(r){return E(z(r))}}buildQValueLookup(e){try{let r=$();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let a=t.prepare(`
315
315
  SELECT q_value, visits FROM rl_q_values
316
316
  WHERE algorithm = 'q-learning'
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-DYIOLKQ3.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return me(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-DYIOLKQ3.js");if(t())throw r;process.env.DEBUG&&m.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return ge(e,this.config.embeddingDimension)}async embedForPatterns(e){if(!this.embedderRecovery.isAvailable())return null;try{return await this.embed(e)}catch(r){let t=f(r),n="Embedder failed: storing and searching patterns by text only";return this.embedderRecovery.markUnavailable(t)?m.warn(n,{error:t}):m.debug(n,{error:t}),null}}getEmbedderFailure(){return this.embedderRecovery.unavailableReason}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of H)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Dt(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,ue as d,O as e,Q as f,W as g,Dt as h};
320
+ `);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return _(e)}generateContext(e,r){return N(e,r||{})}checkAntiPatterns(e,r){return K(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-OXLYU7JW.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return ge(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-OXLYU7JW.js");if(t())throw r;process.env.DEBUG&&m.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return fe(e,this.config.embeddingDimension)}async embedForPatterns(e){if(!this.embedderRecovery.isAvailable())return null;try{return await this.embed(e)}catch(r){let t=f(r),n="Embedder failed: storing and searching patterns by text only";return this.embedderRecovery.markUnavailable(t)?m.warn(n,{error:t}):m.debug(n,{error:t}),null}}getEmbedderFailure(){return this.embedderRecovery.unavailableReason}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of X)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Mt(i,e,r,t){return new B(i,e,r,t)}export{O as a,q as b,x as c,de as d,Q as e,F as f,B as g,Mt as h};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");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.15.16");process.exit(0)}
2
2
  var e=!1;function o(){e=!0;let r=!1;return()=>{r||(r=!0,e=!1)}}function t(){return e}export{o as a,t as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
2
- import{d as D,e as V}from"./chunk-BQ47GQPK.js";V();import*as A from"node:fs";import B from"node:module";import*as N from"node:path";import{fileURLToPath as J}from"node:url";var b=D("TreeSitterWASM"),O={python:{wasmFile:"tree-sitter-python.wasm",nodeTypes:{functionDecl:["function_definition"],classDecl:["class_definition"],importDecl:["import_statement","import_from_statement"]}},java:{wasmFile:"tree-sitter-java.wasm",nodeTypes:{functionDecl:["method_declaration","constructor_declaration"],classDecl:["class_declaration","interface_declaration"],importDecl:["import_declaration"]}},csharp:{wasmFile:"tree-sitter-c_sharp.wasm",nodeTypes:{functionDecl:["method_declaration","constructor_declaration"],classDecl:["class_declaration","interface_declaration"],importDecl:["using_directive"]}},rust:{wasmFile:"tree-sitter-rust.wasm",nodeTypes:{functionDecl:["function_item"],classDecl:[],importDecl:["use_declaration"],implBlock:"impl_item",structDecl:"struct_item"}},swift:{wasmFile:"tree-sitter-swift.wasm",nodeTypes:{functionDecl:["function_declaration"],classDecl:["class_declaration"],importDecl:["import_declaration"],structDecl:"struct_declaration",protocolDecl:"protocol_declaration"}}},y=null,g=null,F=0,P=3,w=new Map;function I(i){let e=J(new URL(".",import.meta.url)),t=[N.resolve(e,"..","..","..","assets","grammars",i),N.resolve(e,"..","..","assets","grammars",i),N.resolve(process.cwd(),"assets","grammars",i),N.resolve(e,"..","assets","grammars",i)];for(let n of t)if(A.existsSync(n))return n;throw new Error(`Grammar file ${i} not found. Searched: ${t.join(", ")}`)}async function E(){if(F>=P)throw new Error(`web-tree-sitter failed to initialize after ${P} attempts`);if(!y)return g||(g=(async()=>{try{let i=await import("./web-tree-sitter-VLTXZFAB.js"),e=i.default??i;await(e.Parser?.init??e.init).call(e.Parser??e),y=e,F=0,b.info("web-tree-sitter WASM runtime initialized")}catch(i){F++,g=null;let e=i instanceof Error?i.message:String(i);throw b.warn(`web-tree-sitter WASM init failed (attempt ${F}/${P}): ${e}. `+(F<P?"Will retry on next parse.":"Falling back to regex permanently.")),i}})()),g}async function X(i){let e=w.get(i);if(e)return e;await E();let t=O[i];if(!t)throw new Error(`No WASM grammar config for ${i}`);try{let n=I(t.wasmFile),s=await y.Language.load(n);return w.set(i,s),b.info(`Loaded tree-sitter WASM grammar for ${i}`),s}catch(n){let s=n instanceof Error?n.message:String(n);throw b.warn(`Failed to load WASM grammar for ${i}: ${s}. Falling back to regex parser.`),n}}function u(i,e){let t=[];for(let n=0;n<i.childCount;n++){let s=i.child(n);e.includes(s.type)&&t.push(s)}return t}function h(i,e,t=10){let n=[];function s(r,o){if(!(o>t))for(let a=0;a<r.childCount;a++){let c=r.child(a);e.includes(c.type)&&n.push(c),s(c,o+1)}}return s(i,0),n}function x(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);(n.type==="modifiers"||n.type==="modifier"||n.type==="visibility_modifier")&&e.push(n.text.trim())}return e}function C(i,e){return x(i).some(t=>t.includes(e))}var Y=new Set(["if_statement","if_expression","if_let_statement","while_statement","while_expression","for_statement","for_in_statement","for_expression","enhanced_for_statement","match_expression","switch_statement","switch_expression","case_clause","match_arm","switch_entry","catch_clause","except_clause","catch_block","binary_expression","conditional_expression","ternary_expression"]),q=new Set(["&&","||","and","or"]);function _(i){if(!i)return 1;let e=1;function t(n){if(Y.has(n.type))if(n.type==="binary_expression"){let s=n.childForFieldName("operator");s&&q.has(s.text)&&e++}else e++;for(let s=0;s<n.childCount;s++)t(n.child(s))}return t(i),e}function S(i,e){if(!i)return[];let t=[];for(let n=0;n<i.childCount;n++){let s=i.child(n);switch(e){case"java":if(s.type==="field_declaration"){let r=x(s),o=s.childForFieldName("type")?.text?.trim(),a=s.childForFieldName("declarator"),c=a?.childForFieldName("name")?.text??a?.text?.split(/[=;]/)[0]?.trim()??"";c&&t.push({name:c,type:o||void 0,isPublic:r.some(l=>l.includes("public")),isReadonly:r.some(l=>l.includes("final"))})}break;case"csharp":if(s.type==="field_declaration"||s.type==="property_declaration"){let r=x(s),o=s.childForFieldName("type")?.text?.trim(),a=s.childForFieldName("name")?.text??"";a&&t.push({name:a,type:o||void 0,isPublic:r.some(c=>c.includes("public")),isReadonly:r.some(c=>c.includes("readonly"))})}break;case"rust":if(s.type==="field_declaration"){let r=s.childForFieldName("name")?.text??"",o=s.childForFieldName("type")?.text?.trim(),a=C(s,"pub");r&&t.push({name:r,type:o||void 0,isPublic:a,isReadonly:!1})}break;case"swift":if(s.type==="property_declaration"){let r=L(s),o=s.childForFieldName("name")?.text??"",a=s.childForFieldName("type")?.text?.trim(),c=r.includes("public")||r.includes("open"),l=s.text.includes("let ");o&&t.push({name:o,type:a||void 0,isPublic:c,isReadonly:l})}break;case"python":if(s.type==="expression_statement"){let r=s.child(0);if(r?.type==="assignment"){let o=r.childForFieldName("left");if(o?.type==="attribute"||o?.type==="identifier"){let a=o.text.replace("self.","");t.push({name:a,type:void 0,isPublic:!a.startsWith("_"),isReadonly:!1})}}}break}}return t}function k(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("parameters"),s=e.childForFieldName("return_type"),r=e.childForFieldName("body"),o=e.text.trimStart().startsWith("async"),a=W(e);return{name:t,parameters:z(n),returnType:s?.text?.trim()||void 0,isAsync:o,isPublic:!t.startsWith("_"),complexity:_(r),decorators:a,genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function z(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="identifier"){let s=n.text;if(s==="self"||s==="cls")continue;e.push({name:s,type:void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="typed_parameter"){let s=n.child(0)?.text??"";if(s==="self"||s==="cls")continue;let r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="default_parameter"||n.type==="typed_default_parameter"){let s=n.childForFieldName("name")?.text??n.child(0)?.text??"";if(s==="self"||s==="cls")continue;let r=n.childForFieldName("type")?.text?.trim(),o=n.childForFieldName("value")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!0,defaultValue:o||void 0})}else if(n.type==="list_splat_pattern"||n.type==="dictionary_splat_pattern"){let s=n.text;e.push({name:s,type:void 0,isOptional:!0,defaultValue:void 0})}}return e}function W(i){let e=[],t=i.parent;if(!t)return e;if(t.type==="decorated_definition")for(let n=0;n<t.childCount;n++){let s=t.child(n);s.type==="decorator"&&e.push(s.text.trim())}return e}function Q(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("body"),s=e.childForFieldName("superclasses"),r=[];if(s)for(let l=0;l<s.childCount;l++){let d=s.child(l);d.isNamed&&r.push(d.text)}let o=n?h(n,["function_definition"],2):[],a=k(o),c=W(e);return{name:t,methods:a,properties:S(n,"python"),isPublic:!t.startsWith("_"),implements:[],extends:r[0]||void 0,decorators:c,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function H(i){return i.map(e=>{if(e.type==="import_from_statement"){let n=e.childForFieldName("module_name")?.text??"",s=[];for(let r=0;r<e.childCount;r++){let o=e.child(r);e.fieldNameForChild(r)==="name"&&o.isNamed&&s.push(o.text)}return{module:n,namedImports:s,isTypeOnly:!1}}return{module:e.childForFieldName("name")?.text??"",namedImports:[],isTypeOnly:!1}})}function T(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("type"),s=e.childForFieldName("parameters"),r=e.childForFieldName("body"),a=x(e).some(d=>d.includes("public")),c=n?.text?.includes("CompletableFuture")??!1,l=M(e);return{name:t,parameters:K(s),returnType:n?.text==="void"?void 0:n?.text?.trim(),isAsync:c,isPublic:a,complexity:_(r),decorators:l,genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function K(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="formal_parameter"||n.type==="spread_parameter"){let s=n.childForFieldName("name")?.text??"",r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!1,defaultValue:void 0})}}return e}function M(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="modifiers")for(let s=0;s<n.childCount;s++){let r=n.child(s);(r.type==="marker_annotation"||r.type==="annotation")&&e.push(r.text.trim())}}return e}function Z(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("body"),r=x(e).some(p=>p.includes("public")),o=e.childForFieldName("superclass")?.text,a=e.childForFieldName("interfaces"),c=[];if(a)for(let p=0;p<a.childCount;p++){let f=a.child(p);f.isNamed&&c.push(f.text)}let l=n?u(n,["method_declaration","constructor_declaration"]):[],d=T(l),m=M(e);return{name:t,methods:d,properties:S(n,"java"),isPublic:r,implements:c,extends:o||void 0,decorators:m,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function ee(i){return i.map(e=>{let t=e.text.replace(/^\s*import\s+(static\s+)?/,"").replace(/;\s*$/,"").trim(),n=t.split("."),s=n[n.length-1];return{module:t,namedImports:s==="*"?[]:[s],isTypeOnly:!1}})}function te(i){return h(i,["method_declaration","constructor_declaration"]).map(t=>{let n=t.childForFieldName("name")?.text??"",s=t.childForFieldName("type"),r=t.childForFieldName("parameters"),o=x(t),a=o.some(d=>d.includes("public")),c=o.some(d=>d.includes("async"))||s?.text?.includes("Task")||!1,l=j(t);return{name:n,parameters:ne(r),returnType:s?.text==="void"?void 0:s?.text?.trim(),isAsync:c,isPublic:a,complexity:_(t.childForFieldName("body")),decorators:l,genericParams:[],startLine:t.startPosition.row+1,endLine:t.endPosition.row+1}})}function ne(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="parameter"){let s=n.childForFieldName("name")?.text??"",r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:r?.endsWith("?")||!1,defaultValue:void 0})}}return e}function j(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);n.type==="attribute_list"&&e.push(n.text.trim())}return e}function se(i){return h(i,["class_declaration","interface_declaration"]).map(t=>{let n=t.childForFieldName("name")?.text??"",s=t.childForFieldName("body"),o=x(t).some(p=>p.includes("public")),a=t.childForFieldName("bases"),c=[];if(a)for(let p=0;p<a.childCount;p++){let f=a.child(p);f.isNamed&&c.push(f.text)}let l=s?u(s,["method_declaration","constructor_declaration"]):[],d=T(l),m=j(t);return{name:n,methods:d,properties:S(s,"csharp"),isPublic:o,implements:c.slice(1),extends:c[0]||void 0,decorators:m,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1}})}function ie(i){return h(i,["using_directive"]).map(t=>({module:t.text.replace(/^\s*using\s+(static\s+)?/,"").replace(/;\s*$/,"").trim(),namedImports:[],isTypeOnly:!1}))}function re(i,e){let t=[],n=u(i,e.nodeTypes.functionDecl);if(t.push(...n.map(U)),e.nodeTypes.implBlock){let s=u(i,[e.nodeTypes.implBlock]);for(let r of s){let o=r.childForFieldName("body");if(o){let a=u(o,e.nodeTypes.functionDecl);t.push(...a.map(U))}}}return t}function U(i){let e=i.childForFieldName("name")?.text??"",t=i.childForFieldName("parameters"),n=i.childForFieldName("return_type"),s=i.childForFieldName("body"),r=C(i,"pub"),o=i.text.trimStart().startsWith("pub async")||i.text.trimStart().startsWith("async"),a=G(i);return{name:e,parameters:oe(t),returnType:n?.text?.trim()||void 0,isAsync:o,isPublic:r,complexity:_(s),decorators:a,genericParams:[],startLine:i.startPosition.row+1,endLine:i.endPosition.row+1}}function oe(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="parameter"){let s=n.childForFieldName("pattern"),r=n.childForFieldName("type"),o=s?.text??"",a=r?.text?.trim();e.push({name:o,type:a||void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="self_parameter")continue}return e}function G(i){let e=[],t=i.previousNamedSibling;for(;t&&t.type==="attribute_item";)e.unshift(t.text.trim()),t=t.previousNamedSibling;return e}function ae(i){let e=[],t=u(i,["struct_item","enum_item","trait_item"]);for(let n of t){let s=n.childForFieldName("name")?.text??"",r=C(n,"pub"),o=G(n),a=n.childForFieldName("body");e.push({name:s,methods:[],properties:S(a,"rust"),isPublic:r,implements:[],extends:void 0,decorators:o,startLine:n.startPosition.row+1,endLine:n.endPosition.row+1})}return e}function ce(i){return u(i,["use_declaration"]).map(t=>({module:t.childForFieldName("argument")?.text??t.text.replace(/^\s*use\s+/,"").replace(/;\s*$/,"").trim(),namedImports:[],isTypeOnly:!1}))}function $(i){return i.map(e=>{let t="",n=[],s,r=L(e),o=r.includes("public")||r.includes("open"),a=!1;for(let l=0;l<e.childCount;l++){let d=e.child(l);e.fieldNameForChild(l)==="name"&&(d.type==="simple_identifier"?t=d.text:t||(s=d.text)),d.type==="parameter"&&n.push(d),(d.type==="async"||d.text==="async")&&(a=!0)}if(!t){for(let l=0;l<e.childCount;l++)if(e.child(l).type==="simple_identifier"){t=e.child(l).text;break}}let c=null;for(let l=0;l<e.childCount;l++)if(e.child(l).type==="function_body"){c=e.child(l);break}return{name:t,parameters:le(n),returnType:s,isAsync:a,isPublic:o,complexity:_(c),decorators:[],genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function L(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="modifiers")for(let s=0;s<n.childCount;s++)e.push(n.child(s).text.trim())}return e}function le(i){return i.map(e=>{let n=e.text.split(":"),s=n[0]?.trim().split(/\s+/)??[],r=s[s.length-1]||"",o=n.slice(1).join(":").trim()||void 0;return{name:r,type:o,isOptional:o?.endsWith("?")||!1,defaultValue:void 0}})}function de(i){return u(i,["class_declaration","struct_declaration","protocol_declaration"]).map(n=>{let s=n.childForFieldName("name"),r=s?.text??"",o=L(n),a=o.includes("public")||o.includes("open"),c=[];for(let p=0;p<n.childCount;p++){let f=n.child(p);f.type==="type_identifier"&&f!==s&&c.push(f.text),(f.type==="inheritance_specifier"||f.type==="user_type")&&c.push(f.text)}let l=n.childForFieldName("body"),d=l?h(l,["function_declaration"],2):[],m=$(d);return{name:r,methods:m,properties:S(l,"swift"),isPublic:a,implements:c.slice(1),extends:c[0]||void 0,decorators:[],startLine:n.startPosition.row+1,endLine:n.endPosition.row+1}})}function ue(i){return u(i,["import_declaration"]).map(t=>{let n="";for(let s=0;s<t.childCount;s++){let r=t.child(s);(r.type==="identifier"||r.type==="simple_identifier")&&(n=r.text)}return{module:n,namedImports:[],isTypeOnly:!1}})}var v=class{language;supportedExtensions;constructor(e,t){this.language=e,this.supportedExtensions=t}async parseFile(e,t){let n=await X(this.language),s=y.Parser??y,r=new s;r.setLanguage(n);let o=r.parse(e),a=o.rootNode;try{return{...this.extractFromAST(a),language:this.language,filePath:t}}finally{o.delete(),r.delete()}}extractFromAST(e){let t=O[this.language];switch(this.language){case"python":{let n=u(e,t.nodeTypes.functionDecl),s=u(e,["decorated_definition"]).map(d=>{for(let m=0;m<d.childCount;m++)if(t.nodeTypes.functionDecl.includes(d.child(m).type))return d.child(m);return null}).filter(Boolean),r=[...n,...s],o=u(e,t.nodeTypes.classDecl),a=u(e,["decorated_definition"]).map(d=>{for(let m=0;m<d.childCount;m++)if(t.nodeTypes.classDecl.includes(d.child(m).type))return d.child(m);return null}).filter(Boolean),c=[...o,...a],l=u(e,t.nodeTypes.importDecl);return{functions:k(r),classes:Q(c),imports:H(l)}}case"java":{let n=h(e,t.nodeTypes.classDecl),s=u(e,t.nodeTypes.importDecl),o=[...u(e,t.nodeTypes.functionDecl)];for(let a of n){let c=a.childForFieldName("body");c&&o.push(...u(c,t.nodeTypes.functionDecl))}return{functions:T(o),classes:Z(n),imports:ee(s)}}case"csharp":return{functions:te(e),classes:se(e),imports:ie(e)};case"rust":return{functions:re(e,t),classes:ae(e),imports:ce(e)};case"swift":{let n=h(e,t.nodeTypes.functionDecl);return{functions:$(n),classes:de(e),imports:ue(e)}}default:return{functions:[],classes:[],imports:[]}}}},me={python:[".py"],java:[".java"],csharp:[".cs"],rust:[".rs"],swift:[".swift"]};function xe(){let i=new Map;for(let[e,t]of Object.entries(me))i.set(e,new v(e,t));return i}function pe(){if(process.env.AQE_PARSER_REGEX_ONLY==="1"||process.env.AQE_PARSER_REGEX_ONLY==="true")return!1;try{let{createRequire:i}=B;return i(import.meta.url).resolve("web-tree-sitter"),I("tree-sitter-python.wasm"),!0}catch{return!1}}var R=new Map;async function Fe(i){if(!pe())return null;try{await E();let e=R.get(i);return e||(e=await y.Language.load(I(i)),R.set(i,e)),{parse:t=>{let n=y.Parser??y,s=new n;s.setLanguage(e);let r=s.parse(t);return s.delete?.(),r}}}catch{return null}}function Ne(){y=null,g=null,F=0,w.clear()}export{v as a,xe as b,pe as c,Fe as d,Ne as e};
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.15.16");process.exit(0)}
2
+ import{d as D,e as V}from"./chunk-G5RHFBAY.js";V();import*as A from"node:fs";import B from"node:module";import*as N from"node:path";import{fileURLToPath as J}from"node:url";var b=D("TreeSitterWASM"),O={python:{wasmFile:"tree-sitter-python.wasm",nodeTypes:{functionDecl:["function_definition"],classDecl:["class_definition"],importDecl:["import_statement","import_from_statement"]}},java:{wasmFile:"tree-sitter-java.wasm",nodeTypes:{functionDecl:["method_declaration","constructor_declaration"],classDecl:["class_declaration","interface_declaration"],importDecl:["import_declaration"]}},csharp:{wasmFile:"tree-sitter-c_sharp.wasm",nodeTypes:{functionDecl:["method_declaration","constructor_declaration"],classDecl:["class_declaration","interface_declaration"],importDecl:["using_directive"]}},rust:{wasmFile:"tree-sitter-rust.wasm",nodeTypes:{functionDecl:["function_item"],classDecl:[],importDecl:["use_declaration"],implBlock:"impl_item",structDecl:"struct_item"}},swift:{wasmFile:"tree-sitter-swift.wasm",nodeTypes:{functionDecl:["function_declaration"],classDecl:["class_declaration"],importDecl:["import_declaration"],structDecl:"struct_declaration",protocolDecl:"protocol_declaration"}}},y=null,g=null,F=0,P=3,w=new Map;function I(i){let e=J(new URL(".",import.meta.url)),t=[N.resolve(e,"..","..","..","assets","grammars",i),N.resolve(e,"..","..","assets","grammars",i),N.resolve(process.cwd(),"assets","grammars",i),N.resolve(e,"..","assets","grammars",i)];for(let n of t)if(A.existsSync(n))return n;throw new Error(`Grammar file ${i} not found. Searched: ${t.join(", ")}`)}async function E(){if(F>=P)throw new Error(`web-tree-sitter failed to initialize after ${P} attempts`);if(!y)return g||(g=(async()=>{try{let i=await import("./web-tree-sitter-ZF6FIE5R.js"),e=i.default??i;await(e.Parser?.init??e.init).call(e.Parser??e),y=e,F=0,b.info("web-tree-sitter WASM runtime initialized")}catch(i){F++,g=null;let e=i instanceof Error?i.message:String(i);throw b.warn(`web-tree-sitter WASM init failed (attempt ${F}/${P}): ${e}. `+(F<P?"Will retry on next parse.":"Falling back to regex permanently.")),i}})()),g}async function X(i){let e=w.get(i);if(e)return e;await E();let t=O[i];if(!t)throw new Error(`No WASM grammar config for ${i}`);try{let n=I(t.wasmFile),s=await y.Language.load(n);return w.set(i,s),b.info(`Loaded tree-sitter WASM grammar for ${i}`),s}catch(n){let s=n instanceof Error?n.message:String(n);throw b.warn(`Failed to load WASM grammar for ${i}: ${s}. Falling back to regex parser.`),n}}function u(i,e){let t=[];for(let n=0;n<i.childCount;n++){let s=i.child(n);e.includes(s.type)&&t.push(s)}return t}function h(i,e,t=10){let n=[];function s(r,o){if(!(o>t))for(let a=0;a<r.childCount;a++){let c=r.child(a);e.includes(c.type)&&n.push(c),s(c,o+1)}}return s(i,0),n}function x(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);(n.type==="modifiers"||n.type==="modifier"||n.type==="visibility_modifier")&&e.push(n.text.trim())}return e}function C(i,e){return x(i).some(t=>t.includes(e))}var Y=new Set(["if_statement","if_expression","if_let_statement","while_statement","while_expression","for_statement","for_in_statement","for_expression","enhanced_for_statement","match_expression","switch_statement","switch_expression","case_clause","match_arm","switch_entry","catch_clause","except_clause","catch_block","binary_expression","conditional_expression","ternary_expression"]),q=new Set(["&&","||","and","or"]);function _(i){if(!i)return 1;let e=1;function t(n){if(Y.has(n.type))if(n.type==="binary_expression"){let s=n.childForFieldName("operator");s&&q.has(s.text)&&e++}else e++;for(let s=0;s<n.childCount;s++)t(n.child(s))}return t(i),e}function S(i,e){if(!i)return[];let t=[];for(let n=0;n<i.childCount;n++){let s=i.child(n);switch(e){case"java":if(s.type==="field_declaration"){let r=x(s),o=s.childForFieldName("type")?.text?.trim(),a=s.childForFieldName("declarator"),c=a?.childForFieldName("name")?.text??a?.text?.split(/[=;]/)[0]?.trim()??"";c&&t.push({name:c,type:o||void 0,isPublic:r.some(l=>l.includes("public")),isReadonly:r.some(l=>l.includes("final"))})}break;case"csharp":if(s.type==="field_declaration"||s.type==="property_declaration"){let r=x(s),o=s.childForFieldName("type")?.text?.trim(),a=s.childForFieldName("name")?.text??"";a&&t.push({name:a,type:o||void 0,isPublic:r.some(c=>c.includes("public")),isReadonly:r.some(c=>c.includes("readonly"))})}break;case"rust":if(s.type==="field_declaration"){let r=s.childForFieldName("name")?.text??"",o=s.childForFieldName("type")?.text?.trim(),a=C(s,"pub");r&&t.push({name:r,type:o||void 0,isPublic:a,isReadonly:!1})}break;case"swift":if(s.type==="property_declaration"){let r=L(s),o=s.childForFieldName("name")?.text??"",a=s.childForFieldName("type")?.text?.trim(),c=r.includes("public")||r.includes("open"),l=s.text.includes("let ");o&&t.push({name:o,type:a||void 0,isPublic:c,isReadonly:l})}break;case"python":if(s.type==="expression_statement"){let r=s.child(0);if(r?.type==="assignment"){let o=r.childForFieldName("left");if(o?.type==="attribute"||o?.type==="identifier"){let a=o.text.replace("self.","");t.push({name:a,type:void 0,isPublic:!a.startsWith("_"),isReadonly:!1})}}}break}}return t}function k(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("parameters"),s=e.childForFieldName("return_type"),r=e.childForFieldName("body"),o=e.text.trimStart().startsWith("async"),a=W(e);return{name:t,parameters:z(n),returnType:s?.text?.trim()||void 0,isAsync:o,isPublic:!t.startsWith("_"),complexity:_(r),decorators:a,genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function z(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="identifier"){let s=n.text;if(s==="self"||s==="cls")continue;e.push({name:s,type:void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="typed_parameter"){let s=n.child(0)?.text??"";if(s==="self"||s==="cls")continue;let r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="default_parameter"||n.type==="typed_default_parameter"){let s=n.childForFieldName("name")?.text??n.child(0)?.text??"";if(s==="self"||s==="cls")continue;let r=n.childForFieldName("type")?.text?.trim(),o=n.childForFieldName("value")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!0,defaultValue:o||void 0})}else if(n.type==="list_splat_pattern"||n.type==="dictionary_splat_pattern"){let s=n.text;e.push({name:s,type:void 0,isOptional:!0,defaultValue:void 0})}}return e}function W(i){let e=[],t=i.parent;if(!t)return e;if(t.type==="decorated_definition")for(let n=0;n<t.childCount;n++){let s=t.child(n);s.type==="decorator"&&e.push(s.text.trim())}return e}function Q(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("body"),s=e.childForFieldName("superclasses"),r=[];if(s)for(let l=0;l<s.childCount;l++){let d=s.child(l);d.isNamed&&r.push(d.text)}let o=n?h(n,["function_definition"],2):[],a=k(o),c=W(e);return{name:t,methods:a,properties:S(n,"python"),isPublic:!t.startsWith("_"),implements:[],extends:r[0]||void 0,decorators:c,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function H(i){return i.map(e=>{if(e.type==="import_from_statement"){let n=e.childForFieldName("module_name")?.text??"",s=[];for(let r=0;r<e.childCount;r++){let o=e.child(r);e.fieldNameForChild(r)==="name"&&o.isNamed&&s.push(o.text)}return{module:n,namedImports:s,isTypeOnly:!1}}return{module:e.childForFieldName("name")?.text??"",namedImports:[],isTypeOnly:!1}})}function T(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("type"),s=e.childForFieldName("parameters"),r=e.childForFieldName("body"),a=x(e).some(d=>d.includes("public")),c=n?.text?.includes("CompletableFuture")??!1,l=M(e);return{name:t,parameters:K(s),returnType:n?.text==="void"?void 0:n?.text?.trim(),isAsync:c,isPublic:a,complexity:_(r),decorators:l,genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function K(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="formal_parameter"||n.type==="spread_parameter"){let s=n.childForFieldName("name")?.text??"",r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:!1,defaultValue:void 0})}}return e}function M(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="modifiers")for(let s=0;s<n.childCount;s++){let r=n.child(s);(r.type==="marker_annotation"||r.type==="annotation")&&e.push(r.text.trim())}}return e}function Z(i){return i.map(e=>{let t=e.childForFieldName("name")?.text??"",n=e.childForFieldName("body"),r=x(e).some(p=>p.includes("public")),o=e.childForFieldName("superclass")?.text,a=e.childForFieldName("interfaces"),c=[];if(a)for(let p=0;p<a.childCount;p++){let f=a.child(p);f.isNamed&&c.push(f.text)}let l=n?u(n,["method_declaration","constructor_declaration"]):[],d=T(l),m=M(e);return{name:t,methods:d,properties:S(n,"java"),isPublic:r,implements:c,extends:o||void 0,decorators:m,startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function ee(i){return i.map(e=>{let t=e.text.replace(/^\s*import\s+(static\s+)?/,"").replace(/;\s*$/,"").trim(),n=t.split("."),s=n[n.length-1];return{module:t,namedImports:s==="*"?[]:[s],isTypeOnly:!1}})}function te(i){return h(i,["method_declaration","constructor_declaration"]).map(t=>{let n=t.childForFieldName("name")?.text??"",s=t.childForFieldName("type"),r=t.childForFieldName("parameters"),o=x(t),a=o.some(d=>d.includes("public")),c=o.some(d=>d.includes("async"))||s?.text?.includes("Task")||!1,l=j(t);return{name:n,parameters:ne(r),returnType:s?.text==="void"?void 0:s?.text?.trim(),isAsync:c,isPublic:a,complexity:_(t.childForFieldName("body")),decorators:l,genericParams:[],startLine:t.startPosition.row+1,endLine:t.endPosition.row+1}})}function ne(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="parameter"){let s=n.childForFieldName("name")?.text??"",r=n.childForFieldName("type")?.text?.trim();e.push({name:s,type:r||void 0,isOptional:r?.endsWith("?")||!1,defaultValue:void 0})}}return e}function j(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);n.type==="attribute_list"&&e.push(n.text.trim())}return e}function se(i){return h(i,["class_declaration","interface_declaration"]).map(t=>{let n=t.childForFieldName("name")?.text??"",s=t.childForFieldName("body"),o=x(t).some(p=>p.includes("public")),a=t.childForFieldName("bases"),c=[];if(a)for(let p=0;p<a.childCount;p++){let f=a.child(p);f.isNamed&&c.push(f.text)}let l=s?u(s,["method_declaration","constructor_declaration"]):[],d=T(l),m=j(t);return{name:n,methods:d,properties:S(s,"csharp"),isPublic:o,implements:c.slice(1),extends:c[0]||void 0,decorators:m,startLine:t.startPosition.row+1,endLine:t.endPosition.row+1}})}function ie(i){return h(i,["using_directive"]).map(t=>({module:t.text.replace(/^\s*using\s+(static\s+)?/,"").replace(/;\s*$/,"").trim(),namedImports:[],isTypeOnly:!1}))}function re(i,e){let t=[],n=u(i,e.nodeTypes.functionDecl);if(t.push(...n.map(U)),e.nodeTypes.implBlock){let s=u(i,[e.nodeTypes.implBlock]);for(let r of s){let o=r.childForFieldName("body");if(o){let a=u(o,e.nodeTypes.functionDecl);t.push(...a.map(U))}}}return t}function U(i){let e=i.childForFieldName("name")?.text??"",t=i.childForFieldName("parameters"),n=i.childForFieldName("return_type"),s=i.childForFieldName("body"),r=C(i,"pub"),o=i.text.trimStart().startsWith("pub async")||i.text.trimStart().startsWith("async"),a=G(i);return{name:e,parameters:oe(t),returnType:n?.text?.trim()||void 0,isAsync:o,isPublic:r,complexity:_(s),decorators:a,genericParams:[],startLine:i.startPosition.row+1,endLine:i.endPosition.row+1}}function oe(i){if(!i)return[];let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="parameter"){let s=n.childForFieldName("pattern"),r=n.childForFieldName("type"),o=s?.text??"",a=r?.text?.trim();e.push({name:o,type:a||void 0,isOptional:!1,defaultValue:void 0})}else if(n.type==="self_parameter")continue}return e}function G(i){let e=[],t=i.previousNamedSibling;for(;t&&t.type==="attribute_item";)e.unshift(t.text.trim()),t=t.previousNamedSibling;return e}function ae(i){let e=[],t=u(i,["struct_item","enum_item","trait_item"]);for(let n of t){let s=n.childForFieldName("name")?.text??"",r=C(n,"pub"),o=G(n),a=n.childForFieldName("body");e.push({name:s,methods:[],properties:S(a,"rust"),isPublic:r,implements:[],extends:void 0,decorators:o,startLine:n.startPosition.row+1,endLine:n.endPosition.row+1})}return e}function ce(i){return u(i,["use_declaration"]).map(t=>({module:t.childForFieldName("argument")?.text??t.text.replace(/^\s*use\s+/,"").replace(/;\s*$/,"").trim(),namedImports:[],isTypeOnly:!1}))}function $(i){return i.map(e=>{let t="",n=[],s,r=L(e),o=r.includes("public")||r.includes("open"),a=!1;for(let l=0;l<e.childCount;l++){let d=e.child(l);e.fieldNameForChild(l)==="name"&&(d.type==="simple_identifier"?t=d.text:t||(s=d.text)),d.type==="parameter"&&n.push(d),(d.type==="async"||d.text==="async")&&(a=!0)}if(!t){for(let l=0;l<e.childCount;l++)if(e.child(l).type==="simple_identifier"){t=e.child(l).text;break}}let c=null;for(let l=0;l<e.childCount;l++)if(e.child(l).type==="function_body"){c=e.child(l);break}return{name:t,parameters:le(n),returnType:s,isAsync:a,isPublic:o,complexity:_(c),decorators:[],genericParams:[],startLine:e.startPosition.row+1,endLine:e.endPosition.row+1}})}function L(i){let e=[];for(let t=0;t<i.childCount;t++){let n=i.child(t);if(n.type==="modifiers")for(let s=0;s<n.childCount;s++)e.push(n.child(s).text.trim())}return e}function le(i){return i.map(e=>{let n=e.text.split(":"),s=n[0]?.trim().split(/\s+/)??[],r=s[s.length-1]||"",o=n.slice(1).join(":").trim()||void 0;return{name:r,type:o,isOptional:o?.endsWith("?")||!1,defaultValue:void 0}})}function de(i){return u(i,["class_declaration","struct_declaration","protocol_declaration"]).map(n=>{let s=n.childForFieldName("name"),r=s?.text??"",o=L(n),a=o.includes("public")||o.includes("open"),c=[];for(let p=0;p<n.childCount;p++){let f=n.child(p);f.type==="type_identifier"&&f!==s&&c.push(f.text),(f.type==="inheritance_specifier"||f.type==="user_type")&&c.push(f.text)}let l=n.childForFieldName("body"),d=l?h(l,["function_declaration"],2):[],m=$(d);return{name:r,methods:m,properties:S(l,"swift"),isPublic:a,implements:c.slice(1),extends:c[0]||void 0,decorators:[],startLine:n.startPosition.row+1,endLine:n.endPosition.row+1}})}function ue(i){return u(i,["import_declaration"]).map(t=>{let n="";for(let s=0;s<t.childCount;s++){let r=t.child(s);(r.type==="identifier"||r.type==="simple_identifier")&&(n=r.text)}return{module:n,namedImports:[],isTypeOnly:!1}})}var v=class{language;supportedExtensions;constructor(e,t){this.language=e,this.supportedExtensions=t}async parseFile(e,t){let n=await X(this.language),s=y.Parser??y,r=new s;r.setLanguage(n);let o=r.parse(e),a=o.rootNode;try{return{...this.extractFromAST(a),language:this.language,filePath:t}}finally{o.delete(),r.delete()}}extractFromAST(e){let t=O[this.language];switch(this.language){case"python":{let n=u(e,t.nodeTypes.functionDecl),s=u(e,["decorated_definition"]).map(d=>{for(let m=0;m<d.childCount;m++)if(t.nodeTypes.functionDecl.includes(d.child(m).type))return d.child(m);return null}).filter(Boolean),r=[...n,...s],o=u(e,t.nodeTypes.classDecl),a=u(e,["decorated_definition"]).map(d=>{for(let m=0;m<d.childCount;m++)if(t.nodeTypes.classDecl.includes(d.child(m).type))return d.child(m);return null}).filter(Boolean),c=[...o,...a],l=u(e,t.nodeTypes.importDecl);return{functions:k(r),classes:Q(c),imports:H(l)}}case"java":{let n=h(e,t.nodeTypes.classDecl),s=u(e,t.nodeTypes.importDecl),o=[...u(e,t.nodeTypes.functionDecl)];for(let a of n){let c=a.childForFieldName("body");c&&o.push(...u(c,t.nodeTypes.functionDecl))}return{functions:T(o),classes:Z(n),imports:ee(s)}}case"csharp":return{functions:te(e),classes:se(e),imports:ie(e)};case"rust":return{functions:re(e,t),classes:ae(e),imports:ce(e)};case"swift":{let n=h(e,t.nodeTypes.functionDecl);return{functions:$(n),classes:de(e),imports:ue(e)}}default:return{functions:[],classes:[],imports:[]}}}},me={python:[".py"],java:[".java"],csharp:[".cs"],rust:[".rs"],swift:[".swift"]};function xe(){let i=new Map;for(let[e,t]of Object.entries(me))i.set(e,new v(e,t));return i}function pe(){if(process.env.AQE_PARSER_REGEX_ONLY==="1"||process.env.AQE_PARSER_REGEX_ONLY==="true")return!1;try{let{createRequire:i}=B;return i(import.meta.url).resolve("web-tree-sitter"),I("tree-sitter-python.wasm"),!0}catch{return!1}}var R=new Map;async function Fe(i){if(!pe())return null;try{await E();let e=R.get(i);return e||(e=await y.Language.load(I(i)),R.set(i,e)),{parse:t=>{let n=y.Parser??y,s=new n;s.setLanguage(e);let r=s.parse(t);return s.delete?.(),r}}}catch{return null}}function Ne(){y=null,g=null,F=0,w.clear()}export{v as a,xe as b,pe as c,Fe as d,Ne as e};
@@ -0,0 +1,65 @@
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.15.16");process.exit(0)}
2
+ import{d as G,e as X,g as oe,h as Y}from"./chunk-EA4YQVKS.js";import{a as ce}from"./chunk-GQ6TUIKY.js";import{a as le}from"./chunk-HVRRLYX6.js";import{i as F}from"./chunk-HGWXF45W.js";import{c as U,d as qe}from"./chunk-JDIYMZCQ.js";import{n as x,o as V}from"./chunk-M4FRQ4TE.js";import{i as Qe,j as $e,n as ze}from"./chunk-DXD6K2ZP.js";import{c as P,d as w}from"./chunk-LE4QJREF.js";import{B as z,D as k,G as se,P as L,S as _,b as O}from"./chunk-L6QSTQME.js";import{c as Ue}from"./chunk-EK7OLYOZ.js";import{c as Ne,d as pt}from"./chunk-AGRV5B3T.js";import{c as W,e as Me,f as He}from"./chunk-I7MQIM2U.js";import{a as ae,b as ke,d as Le,f as gt}from"./chunk-ZFL436FN.js";import{a as b,b as Fe,e as _e}from"./chunk-KNSRL6NO.js";import{c as j,e as mt}from"./chunk-AJMJNQMP.js";var ee=j(R=>{var Tt=R&&R.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(R,"__esModule",{value:!0});var Rt=Object.prototype.hasOwnProperty;function ge(n,e){return Rt.call(n,e)}R.hasOwnProperty=ge;function Ke(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)ge(n,i)&&r.push(i);return r}R._objectKeys=Ke;function xt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}R._deepClone=xt;function Ct(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}R.isInteger=Ct;function me(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}R.escapePathComponent=me;function It(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}R.unescapePathComponent=It;function ye(n,e){var t;for(var r in n)if(ge(n,r)){if(n[r]===e)return me(r)+"/";if(typeof n[r]=="object"&&(t=ye(n[r],e),t!=""))return me(r)+"/"+t}return""}R._getPathRecursive=ye;function Dt(n,e){if(n===e)return"/";var t=ye(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}R.getPath=Dt;function pe(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(pe(n[e]))return!0}else if(typeof n=="object"){for(var r=Ke(n),i=r.length,s=0;s<i;s++)if(pe(n[r[s]]))return!0}}return!1}R.hasUndefined=pe;function Ye(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var Ot=(function(n){Tt(e,n);function e(t,r,i,s,a){var l=this.constructor,d=n.call(this,Ye(t,{name:r,index:i,operation:s,tree:a}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=a,Object.setPrototypeOf(d,l.prototype),d.message=Ye(t,{name:r,index:i,operation:s,tree:a}),d}return e})(Error);R.PatchError=Ot});var ve=j(v=>{Object.defineProperty(v,"__esModule",{value:!0});var C=ee();v.JsonPatchError=C.PatchError;v.deepClone=C._deepClone;var q={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=te(t,this.path);r&&(r=C._deepClone(r));var i=N(t,{op:"remove",path:this.from}).removed;return N(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=te(t,this.from);return N(t,{op:"add",path:this.path,value:C._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:B(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Ft={add:function(n,e,t){return C.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:q.move,copy:q.copy,test:q.test,_get:q._get};function te(n,e){if(e=="")return n;var t={op:"_get",path:e};return N(n,t),t.value}v.getValueByPointer=te;function N(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):re(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=te(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=B(n,e.value),a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=C._deepClone(n));var l=e.path||"",d=l.split("/"),o=n,c=1,h=d.length,m=void 0,u=void 0,f=void 0;for(typeof t=="function"?f=t:f=re;;){if(u=d[c],u&&u.indexOf("~")!=-1&&(u=C.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&c>0&&d[c-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&&m===void 0&&(o[u]===void 0?m=d.slice(0,c).join("/"):c==h-1&&(m=e.path),m!==void 0&&f(e,0,n,m)),c++,Array.isArray(o)){if(u==="-")u=o.length;else{if(t&&!C.isInteger(u))throw new v.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);C.isInteger(u)&&(u=~~u)}if(c>=h){if(t&&e.op==="add"&&u>o.length)throw new v.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=Ft[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(c>=h){var a=q[e.op].call(e,o,u,n);if(a.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[u],t&&c<h&&(!o||typeof o!="object"))throw new v.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}v.applyOperation=N;function Ze(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=C._deepClone(n));for(var s=new Array(e.length),a=0,l=e.length;a<l;a++)s[a]=N(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}v.applyPatch=Ze;function _t(n,e,t){var r=N(n,e);if(r.test===!1)throw new v.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}v.applyReducer=_t;function re(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new v.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(q[n.op]){if(typeof n.path!="string")throw new v.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 v.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 v.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 v.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")&&C.hasUndefined(n.value))throw new v.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new v.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 v.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},l=et([a],t);if(l&&l.name==="OPERATION_PATH_UNRESOLVABLE")throw new v.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new v.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}v.validator=re;function et(n,e,t){try{if(!Array.isArray(n))throw new v.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ze(C._deepClone(e),C._deepClone(n),t||!0);else{t=t||re;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof v.JsonPatchError)return i;throw i}}v.validate=et;function B(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!B(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var l=Object.keys(n);if(s=l.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(l[i]))return!1;for(i=s;i--!==0;)if(a=l[i],!B(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}v._areEquals=B});var tt=j(Q=>{Object.defineProperty(Q,"__esModule",{value:!0});var A=ee(),Nt=ve(),Se=new WeakMap,Mt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),Ht=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function kt(n){return Se.get(n)}function Lt(n,e){return n.observers.get(e)}function Ut(n,e){n.observers.delete(e.callback)}function qt(n,e){e.unobserve()}Q.unobserve=qt;function Qt(n,e){var t=[],r,i=kt(n);if(!i)i=new Mt(n),Se.set(n,i);else{var s=Lt(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=A._deepClone(n),e){r.callback=e,r.next=null;var a=function(){we(r)},l=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",l),window.addEventListener("keyup",l),window.addEventListener("mousedown",l),window.addEventListener("keydown",l),window.addEventListener("change",l))}return r.patches=t,r.object=n,r.unobserve=function(){we(r),clearTimeout(r.next),Ut(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",l),window.removeEventListener("keyup",l),window.removeEventListener("mousedown",l),window.removeEventListener("keydown",l),window.removeEventListener("change",l))},i.observers.set(e,new Ht(e,r)),r}Q.observe=Qt;function we(n,e){e===void 0&&(e=!1);var t=Se.get(n.object);be(t.value,n.object,n.patches,"",e),n.patches.length&&Nt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}Q.generate=we;function be(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=A._objectKeys(e),a=A._objectKeys(n),l=!1,d=!1,o=a.length-1;o>=0;o--){var c=a[o],h=n[c];if(A.hasOwnProperty(e,c)&&!(e[c]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var m=e[c];typeof h=="object"&&h!=null&&typeof m=="object"&&m!=null&&Array.isArray(h)===Array.isArray(m)?be(h,m,t,r+"/"+A.escapePathComponent(c),i):h!==m&&(l=!0,i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"replace",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(m)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(h)}),t.push({op:"remove",path:r+"/"+A.escapePathComponent(c)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),l=!0)}if(!(!d&&s.length==a.length))for(var o=0;o<s.length;o++){var c=s[o];!A.hasOwnProperty(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+A.escapePathComponent(c),value:A._deepClone(e[c])})}}}function $t(n,e,t){t===void 0&&(t=!1);var r=[];return be(n,e,r,"",t),r}Q.compare=$t});var rt=j(M=>{var zt=ve();Object.assign(M,zt);var Jt=tt();Object.assign(M,Jt);var ne=ee();M.JsonPatchError=ne.PatchError;M.deepClone=ne._deepClone;M.escapePathComponent=ne.escapePathComponent;M.unescapePathComponent=ne.unescapePathComponent});var T=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};function ir(n){return n instanceof T&&n.disposition==="COMMITTED_PENDING_INDEX"?n.patternId:null}pt();import{existsSync as tr}from"node:fs";import{join as dt}from"node:path";_e();qe();var J=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??K,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;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(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{!this.embeddingSpaceId&&!x()&&await V();let e=x()?.spaceId??this.embeddingSpaceId??null;e?(this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),ze(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)):(this.rvfInitError=Qe,this.adapter=null,this.initialized=!0,$e())}catch(e){this.rvfInitError=b(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF initialization failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: check the embedder endpoint and @ruvector/rvf-node binding, or set RUVECTOR_USE_RVF_PATTERN_STORE=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-IXCNZRTW.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),l=new Set((a.entries??[]).map(c=>Array.isArray(c)?c[0]:void 0).filter(c=>typeof c=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(c=>c.id)),o=[...l].filter(c=>!d.has(c));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: ${b(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=Y(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)return w(new T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=x()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return w(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return w(new T(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return w(new T(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),a=this.adapter.ingest([{id:e.id,vector:s}]);if(a.accepted!==1||a.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${a.accepted}, rejected=${a.rejected})`)}catch(s){return w(new T(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:F(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:G({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let d=x()?.spaceId??this.embeddingSpaceId;if(!d||t.embeddingSpaceId!==d)return w(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let d=e instanceof Float32Array?e:new Float32Array(e),o=this.adapter.search(d,i*2);for(let c of o){let h=await this.get(c.id);if(h&&this.matchesFilters(h,t)){let m=this.calculateReuseInfo(h,c.score);s.push({pattern:h,score:c.score,matchType:"vector",similarity:c.score,canReuse:m.canReuse,estimatedTokenSavings:m.estimatedTokenSavings,reuseConfidence:m.reuseConfidence})}}}catch(d){console.warn("[RvfPatternStore] RVF search failed:",b(d))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let d=x()?.spaceId??this.embeddingSpaceId,o=this.sqliteStore.getAllEmbeddings(),c=e,h=Math.sqrt(c.reduce((m,u)=>m+u*u,0));if(h>0)for(let m of o){if(!d||m.spaceId!==d)continue;let u=this.sqliteStore.getPattern(m.patternId);if(!u||!this.matchesFilters(u,t))continue;let f=m.embedding;if(!f||f.length!==c.length)continue;let y=0,p=0;for(let E=0;E<c.length;E++)y+=c[E]*f[E],p+=f[E]*f[E];if(p=Math.sqrt(p),p===0)continue;let g=y/(h*p),S=this.calculateReuseInfo(u,g);s.push({pattern:u,score:g,matchType:"vector",similarity:g,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let d=this.sqliteStore.getPatterns({limit:i*2}),o=new Set(s.map(c=>c.pattern.id));for(let c of d)o.has(c.id)||this.matchesFilters(c,t)&&s.push({pattern:c,score:c.confidence,matchType:"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}catch{}let a=typeof e=="string"?e:t.textQuery;if(a?.trim()&&this.sqliteStore)try{let d=this.sqliteStore.searchFTS(a,i*2),o=new Set(s.map(h=>h.pattern.id)),c=new Map(d.map(h=>[h.id,h.ftsScore*h.coverage]));for(let h of s){let m=c.get(h.pattern.id);m!==void 0&&(h.score=de(h.score,m))}for(let h of d){if(o.has(h.id))continue;let m=await this.get(h.id);if(m&&this.matchesFilters(m,t)){let u=.5*h.ftsScore*h.coverage;s.push({pattern:m,score:u,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}catch{}s.sort((d,o)=>o.score-d.score);let l=performance.now()-r;return this.searchOps++,this.totalSearchMs+=l,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{let s=this.sqliteStore;return await U(s.getDatabase(),()=>s.recordUsage(e,t,r,i)),P(void 0)}catch(s){return w(new Error(`recordUsage failed: ${b(s)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{let t=this.sqliteStore;return await U(t.getDatabase(),()=>t.promotePattern(e)),P(void 0)}catch(t){return w(new Error(`promote failed: ${b(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,b(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${b(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,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 i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=X&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",b(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};gt();_e();_();function vt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let l of s){if(a==null)break;if(typeof a=="object"&&Object.hasOwn(a,l))a=a[l];else{a=void 0;break}}if(a!==void 0)return a}}function wt(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),l=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=l}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function Z(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>Z(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>Z(n,r))}case"NOT":return e.child?!Z(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=vt(n,e.field);return wt(t,e.operator,e.value)}default:return!0}}function Je(n,e){return e?n.filter(t=>Z(t,e)):n}_();_();var je=1e4,We=2166136261;function Ve(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 fe=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;fe[n]=e}var Be="0123456789abcdef";function St(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Be[i>>4]+Be[i&15]}return t}function bt(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 Pt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let l=0,d=1<<a;for(let o=0;o<n.length;o++)n[o][i]&d&&l++;l>=r&&(s|=d)}t[i]=s}return t}function Et(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=fe[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function At(n,e,t){return 1-Et(n,e,t)}var ue=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??je,this.baseSeed=e?.seed??We,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=Ve(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=bt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return Pt([r,i])}similarity(e,t){return At(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ce(e),i=0;for(;i<this.byteLen;){let a=r.next(),l=Math.min(4,this.byteLen-i);for(let d=0;d<l;d++)t[i++]=a>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},he=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??je,this.baseSeed=e?.seed??We,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=Ve(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:St(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=fe[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ce(e),s=0;for(;s<t;){let l=i.next(),d=t-s,o=d<4?d:4;for(let c=0;c<o;c++)r[s++]=l>>>c*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function Ge(n){return new he(n)}function Xe(n){return z()?new ue(n):null}qe();var Ee=mt(rt(),1),Pe=Ee.default??Ee,Bt=`
4
+ CREATE TABLE IF NOT EXISTS pattern_deltas (
5
+ id TEXT PRIMARY KEY,
6
+ pattern_id TEXT NOT NULL,
7
+ version INTEGER NOT NULL,
8
+ timestamp INTEGER NOT NULL,
9
+ type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
10
+ patch TEXT NOT NULL DEFAULT '[]',
11
+ reverse_patch TEXT NOT NULL DEFAULT '[]',
12
+ metadata TEXT
13
+ );
14
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
15
+ ON pattern_deltas (pattern_id, version);
16
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
17
+ ON pattern_deltas (timestamp);
18
+ `;function nt(n,e){let t=Pe.compare(n,e),r=Pe.compare(e,n);return{forward:t,reverse:r}}function jt(n,e){let t=JSON.parse(JSON.stringify(n));return Pe.applyPatch(t,e).newDocument}function it(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var ie=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(Bt),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
+ INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
+ `)),this.prepared.set("getHistory",this.db.prepare(`
22
+ SELECT * FROM pattern_deltas
23
+ WHERE pattern_id = ?
24
+ ORDER BY version ASC
25
+ `)),this.prepared.set("currentVersion",this.db.prepare(`
26
+ SELECT MAX(version) as max_version FROM pattern_deltas
27
+ WHERE pattern_id = ?
28
+ `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
+ SELECT * FROM pattern_deltas
30
+ WHERE timestamp > ?
31
+ ORDER BY timestamp ASC
32
+ `)),this.prepared.set("countForPattern",this.db.prepare(`
33
+ SELECT COUNT(*) as cnt FROM pattern_deltas
34
+ WHERE pattern_id = ?
35
+ `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
+ DELETE FROM pattern_deltas
37
+ WHERE pattern_id = ? AND version IN (
38
+ SELECT version FROM pattern_deltas
39
+ WHERE pattern_id = ?
40
+ ORDER BY version ASC
41
+ LIMIT ?
42
+ )
43
+ `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesisWhenUnlocked(e,t,r){return U(this.db,()=>this.createGenesis(e,t,r))}recordDeltaWhenUnlocked(e,t,r,i){return U(this.db,()=>this.recordDelta(e,t,r,i))}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:F(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:a,reverse:l}=nt(t,r),d={id:F(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:a,reversePatch:l,metadata:i};return this.insertEvent(d),this.enforceRetention(e),d}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),a=this.reconstructState(r,i),{forward:l,reverse:d}=nt(a,s),o={id:F(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:l,reversePatch:d,metadata:{rolledBackTo:t}};return this.insertEvent(o),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(it)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(it)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=jt(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
+ WHERE pattern_id = ? AND version != 0 AND id IN (
45
+ SELECT id FROM pattern_deltas
46
+ WHERE pattern_id = ? AND version != 0
47
+ ORDER BY version ASC
48
+ LIMIT ?
49
+ )`).run(e,e,s)}}};_();var Wt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Ae=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Wt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,l=this.computeSparseChanges(t,r),d={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:l,metadata:i,compressedSize:l.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let l=[...a.fullVector],d=a.version+1;for(let o of r)if(!(o.version<d)){if(o.version>t)break;this.applySparseForward(l,o.sparseChanges)}return l}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),l=i.slice(s),d=a.findIndex(h=>h.deltaType==="genesis");d>=0&&(l.unshift(a[d]),a.splice(d,1)),this.history.set(e,l);let o=l[0]?.version??0,c=this.snapshots.get(e);return c&&this.snapshots.set(e,c.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,l=s<t.length?t[s]:0;Math.abs(a-l)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:l})}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 st(n){return k()?new Ae(n):null}_();var Vt=128,Gt=8,Xt=1e4,Te=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Vt,this.beta=e?.beta??Gt,this.maxPatterns=e?.maxPatterns??Xt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let c=0;c<this.patterns.length;c++)r[c]=this.beta*this.dotProduct(this.patterns[c].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let c=1;c<i.length;c++)i[c]>a&&(a=i[c],s=c);let l=this.patterns[s],d=this.getEnergy(t),o=this.cosineSimilarity(t,l.pattern);return{pattern:new Float32Array(l.pattern),metadata:{...l.metadata},energy:d,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let l=1/this.beta*(s+Math.log(a)),d=this.dotProduct(t,t);return-l+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!O().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function at(n){return new Te(n)}_();var Yt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},H=1e-5,ot=1-H;function Kt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function I(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 D=class n{static poincareDistance(e,t){let r=I(Zt(e,t)),i=Math.max(H,1-I(e)),s=Math.max(H,1-I(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Kt(e,t),i=I(e),s=I(t),a=Math.max(H,1+2*r+i*s),l=1+2*r+s,d=1-i,o=new Float32Array(e.length);for(let c=0;c<e.length;c++)o[c]=(l*e[c]+d*t[c])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(H,1-I(e)),i=Math.sqrt(I(t));if(i<H)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let l=0;l<t.length;l++)a[l]=s/i*t[l];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(I(e));if(t<=ot)return new Float32Array(e);let r=ot/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(I(e));if(t<H)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Re=class{config;points=new Map;constructor(e){if(this.config={...Yt,...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:D.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=D.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:D.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let d of e)if(s.set(d.id,d),!d.parentId)a.push(d.id);else{let o=i.get(d.parentId);o||(o=[],i.set(d.parentId,o)),o.push(d.id)}let l=a.map((d,o)=>({id:d,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;l.length>0;){let{id:d,depth:o,angOff:c,angSpan:h}=l.shift(),m=Math.tanh(.3*(o+.1)),u=c+h/2,f=new Float32Array(r);f[0]=m*Math.cos(u),f[1]=m*Math.sin(u);let y=s.get(d);if(y&&y.features.length>0){let S=m*.1;for(let E=2;E<r&&E-2<y.features.length;E++)f[E]=y.features[E-2]*S}let p=D.project(f);t.set(d,p),this.points.set(d,{id:d,coordinates:p,metadata:{depth:o,parentId:y?.parentId}});let g=i.get(d)??[];for(let S=0;S<g.length;S++){let E=h/Math.max(1,g.length);l.push({id:g[S],depth:o+1,angOff:c+S*E,angSpan:E})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function ct(n){return er()?new Re(n):null}function er(){return O().useHyperbolicHnsw}_();var xe=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!L())return!1;try{return this.index=ct(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=D.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=D.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function lt(n){return new xe(n)}var Ce=null;function ut(){return Ce||(Ce=Ge({dimensions:1e4})),Ce}var Ie;function rr(){return Ie===void 0&&(Ie=Xe()),Ie}var $=null,De=0,ht;function ft(n,e){return(!$||De!==n||ht!==e)&&($=at({dimension:n,maxPatterns:1e4}),De=n,ht=e),$}var K={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:X,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}},Oe=class{constructor(e,t={}){this.memory=e;this.config={...K,...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;hnswSpaceId=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,k()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ie(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(){if(this.hnswIndex!==null){let e=x()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return 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(!x()&&!this.config.embeddingSpaceId&&await V(),this.hnswSpaceId=x()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(O().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-L27WS27N.js"),{HnswAdapter:l}=await import("./hnsw-adapter-LFMPLUJU.js"),d=new l("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(d),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-POCPMVJH.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,l)=>setTimeout(()=>l(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",b(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=x()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:a,embedding:l,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!l||l.length!==this.config.embeddingDimension){i++;continue}let o=this.patternCache.get(a);if(!o){i++;continue}try{await this.hnswIndex.insert(a,l,{filePath:o.patternType,lineCoverage:o.confidence*100,branchCoverage:o.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-o.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",b(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=st()),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:",b(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=Y(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}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return w(new T(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=x()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return w(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let a=this.patternCache.get(e.id)??null,l=!1,d=()=>{this.unindexPattern(e),a&&this.indexPattern(a)};if(this.indexPattern(e),this.sqliteStore)try{let o=await this.persistToSqlite(c=>c.storePattern(e,e.embedding,i));o&&o!==e.id&&(this.unindexPattern(e),e.id=o,this.indexPattern(e)),l=!0}catch(o){return d(),w(new T(e.id,"FAILED",o))}if(e.embedding){let o=await this.ensureHNSW();if(!o&&l)return w(new T(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!o&&r)return d(),w(new T(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(o)try{await o.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(c){return l||d(),w(new T(e.id,l?"COMMITTED_PENDING_INDEX":"FAILED",c))}}if(z())try{let c=ut().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,c.vector)}catch(o){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,b(o))}try{let o=rr();if(o){let c=[e.patternType,e.qeDomain];e.context?.tags&&c.push(...e.context.tags),e.name&&c.push(e.name);let h=o.fingerprintPattern(c);this.hdcTokenCache.set(e.id,h)}}catch(o){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,b(o))}if(se()&&e.embedding&&i)try{ft(e.embedding.length,i).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(o){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,b(o))}if(k()&&this.deltaTracker)try{let o={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};await this.deltaTracker.createGenesisWhenUnlocked(e.id,o)}catch(o){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,b(o))}if(e.embedding)try{let o=this.getVectorDeltaTracker();o&&(a?.embedding?o.recordDelta(e.id,a.embedding,e.embedding):o.getVersion(e.id)<0&&o.recordGenesis(e.id,e.embedding))}catch(o){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,b(o))}try{L()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:F(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{let a=x()?.spaceId??this.config.embeddingSpaceId;if(Array.isArray(e)&&(!a||t.embeddingSpaceId!==a))throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");if(Array.isArray(e)&&t.useVectorSearch!==!1&&a&&se())try{let f=ft(e.length,a);if(f.getPatternCount()>0){let y=f.recall(new Float32Array(e));if(y&&y.similarity>.98){let p=y.metadata.id,g=await this.get(p);if(g&&this.matchesFilters(g,t)){let S=this.calculateReuseInfo(g,y.similarity);s.push({pattern:g,score:y.similarity,matchType:"vector",similarity:y.similarity,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",b(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=await this.ensureHNSW();if(f){let y=await f.search(e,i*2);for(let p of y){let g=await this.get(p.key);if(g&&this.matchesFilters(g,t)){let S=this.calculateReuseInfo(g,p.score);s.push({pattern:g,score:p.score,matchType:"vector",similarity:p.score,canReuse:S.canReuse,estimatedTokenSavings:S.estimatedTokenSavings,reuseConfidence:S.reuseConfidence})}}}}let l=typeof e=="string"?e:t.textQuery;if(l?.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(l,i*2);if(f.length>0){let y=new Map(f.map(g=>[g.id,g.ftsScore*g.coverage])),p=new Set(s.map(g=>g.pattern.id));for(let g of s){let S=y.get(g.pattern.id);S!==void 0&&(g.score=de(g.score,S))}for(let g of f){if(p.has(g.id))continue;let S=await this.get(g.id);if(S&&this.matchesFilters(S,t)){let E=.5*g.ftsScore*g.coverage;s.push({pattern:S,score:E,matchType:"lexical",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(l??"",t,i-s.length),y=new Set(s.map(p=>p.pattern.id));for(let p of f)y.has(p.pattern.id)||s.push(p)}let d=720*60*60*1e3,o=Date.now();for(let f of s){let y=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),p=o-y,g=Math.pow(.5,p/d),S=f.pattern.usageCount>0?g:.5;f.score=f.score*(.7+.3*S)}let c=this.sqliteStore?.getDatabase();if(c&&s.length>0)try{this.nullStore||(this.nullStore=new le(c));let f=this.nullStore.getNullSummaries(s.map(y=>y.pattern.id));for(let y of s){let p=f.get(y.pattern.id);p&&(y.nullSummary=p,y.score=le.applyNullDiscount(y.score,p,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",b(f))}s.sort((f,y)=>y.score-f.score);let h=s;t.filter&&(h=Je(s,t.filter));let m=h.slice(0,i),u=performance.now()-r;return this.recordSearchLatency(u),P(m)}catch(a){return w(Fe(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let l=[...a];if(z()&&s&&this.hdcCache.size>0)try{let d=ut(),o=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),c=l.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(o.vector,this.hdcCache.get(u))}));c.sort((u,f)=>f.similarity-u.similarity);let h=c.map(u=>u.id),m=l.filter(u=>!this.hdcCache.has(u));l=[...h,...m]}catch{}for(let d of l){if(i.length>=r)break;let o=this.patternCache.get(d);if(!o||!this.matchesFilters(o,t))continue;let c=0;if(s){let h=o.name.toLowerCase(),m=o.description.toLowerCase();h.includes(s)&&(c+=.5),m.includes(s)&&(s.length/m.length>.3?c+=.5:c+=.3);for(let u of o.context.tags)if(u.toLowerCase().includes(s)){c+=.2;break}c=Math.min(c,1)}else c=o.qualityScore;(c>0||!s)&&i.push({pattern:o,score:s?.5*c:o.qualityScore,matchType:s?"lexical":"context",similarity:0,canReuse:!1,estimatedTokenSavings:0,reuseConfidence:0})}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&d,c=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,m=e.successRate,u=Math.min(e.reuseCount/10,1),f=o?h*.4+m*.4+u*.2:0;return{canReuse:o,estimatedTokenSavings:c,reuseConfidence:f}}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,i){let s=await this.get(e);if(!s)return w(new Error(`Pattern not found: ${e}`));let a=new Date,l=s.usageCount+1,d=s.successfulUses+(t?1:0),o=d/l,c=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+c)),m=G({confidence:h,usageCount:l,successRate:o}),u={...s,usageCount:l,successfulUses:d,successRate:o,confidence:h,qualityScore:m,lastUsedAt:a};if(this.sqliteStore)try{await this.persistToSqlite(p=>p.recordUsage(e,t,r,i))}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,b(p))}if(k()&&this.deltaTracker)try{let p={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},g={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};await this.deltaTracker.recordDeltaWhenUnlocked(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,b(p))}let f=oe(u);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}persistToSqlite(e){let t=this.sqliteStore,r=()=>e(t);return typeof t.writeWhenUnlocked=="function"?t.writeWhenUnlocked(r):new Promise(i=>i(r()))}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{await this.persistToSqlite(i=>i.promotePattern(e))}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{await this.persistToSqlite(r=>r.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,c]of this.domainIndex)e[o]=c.size;for(let[o,c]of this.typeIndex)t[o]=c.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let l=await this.ensureHNSW(),d=l!==null?await l.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=oe(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-d,c=o>10080*60*1e3,h=s.qualityScore<.2,m=s.usageCount===0&&o>1440*60*1e3;(c&&h||m)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let l=this.patternCache.get(a);l&&r.push(l)}r.sort((a,l)=>a.qualityScore-l.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),$&&($.clear(),$=null,De=0),this.initialized=!1}indexHyperbolic(e,t,r){if(L())try{this.hyperbolicIndex||(this.hyperbolicIndex=lt({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!L()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let l=Math.exp(-s.distance),d=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l,matchType:"vector",similarity:l,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function de(n,e){return Math.max(n,.75*n+.25*e)}function gn(n,e){try{if(O().useRVFPatternStore&&Le()){let r=process.env.AQE_PROJECT_ROOT??Ne(),i=dt(r,".agentic-qe"),s=dt(i,"patterns.rvf");if(tr(i)){let a={...K,...e},l=!1;try{let d=Ue(i,a.embeddingDimension);if(d){l=!0;let o=new J(()=>d,{rvfPath:s,base:a,skipCloseOnDispose:!0,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),o}}catch{}if(!l){let d=new J((o,c)=>{let h,m=()=>{try{return ke(o)}catch(f){return h=f,null}},u=m();if(!u&&W(h)&&(!Me(o)||(u=m(),!u&&W(h))))throw h;if(u){let f=u.dimension();if(f!==c){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${f}, requested=${c})`)}return u}try{return ae(o,c)}catch(f){if(u=m(),u){if(u.dimension()!==c){let y=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${y}, requested=${c})`)}return u}if(W(h))throw h;if(He(o,f instanceof Error?f.message:String(f),h))return ae(o,c);throw f}},{rvfPath:s,base:a,embeddingSpaceId:a.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new Oe(n,e)}export{T as a,ir as b,K as c,de as d,gn as e};
50
+ /*! Bundled license information:
51
+
52
+ fast-json-patch/commonjs/helpers.js:
53
+ (*!
54
+ * https://github.com/Starcounter-Jack/JSON-Patch
55
+ * (c) 2017-2022 Joachim Wester
56
+ * MIT licensed
57
+ *)
58
+
59
+ fast-json-patch/commonjs/duplex.js:
60
+ (*!
61
+ * https://github.com/Starcounter-Jack/JSON-Patch
62
+ * (c) 2017-2021 Joachim Wester
63
+ * MIT license
64
+ *)
65
+ */