agentic-qe 3.9.19 → 3.9.20

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 (296) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +28 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/adapters/claude-flow/trajectory-bridge.d.ts +12 -1
  5. package/dist/adapters/claude-flow/trajectory-bridge.js +33 -31
  6. package/dist/cli/bundle.js +5 -5
  7. package/dist/cli/chunks/adapter-UOX57IAN.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-HVBKHNIS.js → agent-booster-wasm-T5JB3MOF.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-XNBDYRSJ.js → agent-handler-EASMQSQO.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-YCVTQEMJ.js → agent-memory-branch-7GWN2KCG.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-KZES2SKE.js +2 -0
  12. package/dist/cli/chunks/{audit-6C2PE7OY.js → audit-VHV4GXPW.js} +2 -2
  13. package/dist/cli/chunks/base-7MXMBRSW.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-HZPCHUQU.js → better-sqlite3-GNK7MDXZ.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-OV75Q2NM.js → brain-handler-ALXZKWO4.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-QW6D42HJ.js → branch-enumerator-JNYLOLMM.js} +2 -2
  17. package/dist/cli/chunks/{browser-5BA7Q7OR.js → browser-FXRW6LID.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-4C5R54CZ.js +2 -0
  19. package/dist/cli/chunks/{chunk-2WJLEZKP.js → chunk-2J5OO63R.js} +2 -2
  20. package/dist/cli/chunks/{chunk-D2EHD2KF.js → chunk-35HDLA22.js} +1 -1
  21. package/dist/cli/chunks/{chunk-IG2RCBHJ.js → chunk-3BFNYFXV.js} +1 -1
  22. package/dist/cli/chunks/{chunk-NMYZSZHW.js → chunk-3CLKKAGH.js} +2 -2
  23. package/dist/cli/chunks/{chunk-VXUIIZNG.js → chunk-3GPNZPM4.js} +1 -1
  24. package/dist/cli/chunks/{chunk-AEET2WOI.js → chunk-3HQ4VKK6.js} +46 -34
  25. package/dist/cli/chunks/{chunk-3546SG2L.js → chunk-3ZHUKLU7.js} +2 -2
  26. package/dist/cli/chunks/{chunk-QOK4TIE4.js → chunk-4G6OH5LQ.js} +2 -2
  27. package/dist/cli/chunks/{chunk-U257SS7D.js → chunk-4HD7YRW7.js} +2 -2
  28. package/dist/cli/chunks/{chunk-CYLQTVIA.js → chunk-4IUNBRKQ.js} +2 -2
  29. package/dist/cli/chunks/{chunk-BB3KUX6C.js → chunk-4PNLBMKY.js} +1 -1
  30. package/dist/cli/chunks/{chunk-W3IO4FQ5.js → chunk-4SBMTHTA.js} +2 -2
  31. package/dist/cli/chunks/{chunk-HQFREZRX.js → chunk-5GA4BUQU.js} +2 -2
  32. package/dist/cli/chunks/{chunk-U2WMCNNR.js → chunk-5ILP2ZDZ.js} +2 -2
  33. package/dist/cli/chunks/{chunk-6BRUQTC7.js → chunk-5LM2W3NE.js} +1 -1
  34. package/dist/cli/chunks/{chunk-FJJLNCSL.js → chunk-6LKEFWKI.js} +3 -3
  35. package/dist/cli/chunks/{chunk-5X2AUPK2.js → chunk-6R7SJ5FS.js} +1 -1
  36. package/dist/cli/chunks/{chunk-FNVA7U7X.js → chunk-7I6ROJGF.js} +2 -2
  37. package/dist/cli/chunks/{chunk-LTE3CDOY.js → chunk-7J34I3CI.js} +2 -2
  38. package/dist/cli/chunks/{chunk-XP4T7CZY.js → chunk-7OGFOHG5.js} +2 -2
  39. package/dist/cli/chunks/{chunk-UIASVDYG.js → chunk-7Q7SCQMQ.js} +2 -2
  40. package/dist/cli/chunks/{chunk-ALYUJEYA.js → chunk-7R45TEY6.js} +2 -2
  41. package/dist/cli/chunks/{chunk-VHG67L7O.js → chunk-7WXYQDML.js} +2 -2
  42. package/dist/cli/chunks/{chunk-BOUCIIUI.js → chunk-7Y4QQ6JL.js} +1 -1
  43. package/dist/cli/chunks/{chunk-SKNHAGYP.js → chunk-AFMLL2G3.js} +2 -2
  44. package/dist/cli/chunks/{chunk-YXLQJ226.js → chunk-AVVRA6FG.js} +2 -2
  45. package/dist/cli/chunks/{chunk-B2EHSFUW.js → chunk-BIODM56C.js} +2 -2
  46. package/dist/cli/chunks/{chunk-B65GTWF3.js → chunk-BJF77EFA.js} +2 -2
  47. package/dist/cli/chunks/chunk-BKGCMWFL.js +12 -0
  48. package/dist/cli/chunks/{chunk-MN4366PQ.js → chunk-BXGAXGME.js} +2 -2
  49. package/dist/cli/chunks/{chunk-TXCOK5DC.js → chunk-CEVIRL2S.js} +2 -2
  50. package/dist/cli/chunks/{chunk-2SIQ742L.js → chunk-CPVGZYEP.js} +1 -1
  51. package/dist/cli/chunks/{chunk-R5IL3XD5.js → chunk-CQSME43Z.js} +2 -2
  52. package/dist/cli/chunks/{chunk-FT3MAIRW.js → chunk-DERQRIAR.js} +3 -3
  53. package/dist/cli/chunks/{chunk-37DTXQ6P.js → chunk-DJCLA5AG.js} +2 -2
  54. package/dist/cli/chunks/{chunk-7WMHLBNZ.js → chunk-DODH6CEQ.js} +1 -1
  55. package/dist/cli/chunks/{chunk-TCUIYIZ4.js → chunk-DSPH4GI3.js} +1 -1
  56. package/dist/cli/chunks/{chunk-HVNW3TZS.js → chunk-EJQRDMON.js} +1 -1
  57. package/dist/cli/chunks/{chunk-VWWLJBRA.js → chunk-EYSGJZ7Y.js} +9 -9
  58. package/dist/cli/chunks/chunk-F32R4LVS.js +2 -0
  59. package/dist/cli/chunks/{chunk-MTHO6A3V.js → chunk-F3PX6EJX.js} +1 -1
  60. package/dist/cli/chunks/{chunk-O6UMETOH.js → chunk-FAQPPMEC.js} +2 -2
  61. package/dist/cli/chunks/{chunk-SRKBR4DU.js → chunk-FHDYN73D.js} +2 -2
  62. package/dist/cli/chunks/{chunk-7IV2RK5M.js → chunk-FPBNTPCM.js} +2 -2
  63. package/dist/cli/chunks/{chunk-XF32XZMY.js → chunk-FUTRX4ZT.js} +2 -2
  64. package/dist/cli/chunks/{chunk-GYESQBDU.js → chunk-G7HYTJDG.js} +2 -2
  65. package/dist/cli/chunks/{chunk-3HQ4AZDH.js → chunk-GJACTPDK.js} +2 -2
  66. package/dist/cli/chunks/{chunk-J7F65KKG.js → chunk-GXO42P3X.js} +4 -4
  67. package/dist/cli/chunks/{chunk-WULMXLNN.js → chunk-H647PYXW.js} +1 -1
  68. package/dist/cli/chunks/{chunk-D74RGYKI.js → chunk-HCFRGEMK.js} +1 -1
  69. package/dist/cli/chunks/{chunk-IV74GAZN.js → chunk-HW47UOFK.js} +2 -2
  70. package/dist/cli/chunks/{chunk-FPVXXQVX.js → chunk-HXQ7GAUV.js} +3 -3
  71. package/dist/cli/chunks/{chunk-O5ZP3CBF.js → chunk-ICLWWAGZ.js} +2 -2
  72. package/dist/cli/chunks/{chunk-HJ7CRPZY.js → chunk-IHBRFVGA.js} +1 -1
  73. package/dist/cli/chunks/{chunk-WZUQT2BE.js → chunk-J7SDO52P.js} +2 -2
  74. package/dist/cli/chunks/{chunk-5R2DUR3A.js → chunk-JCPXG42O.js} +2 -2
  75. package/dist/cli/chunks/{chunk-H4QM37XS.js → chunk-K2D5L7YV.js} +1 -1
  76. package/dist/cli/chunks/{chunk-VSI45JCP.js → chunk-KMDZOVCF.js} +1 -1
  77. package/dist/cli/chunks/{chunk-P6EYD4V3.js → chunk-KNOZWD6E.js} +2 -2
  78. package/dist/cli/chunks/{chunk-RL5CBCBV.js → chunk-LATJ2LKJ.js} +1 -1
  79. package/dist/cli/chunks/{chunk-IPLQPBJA.js → chunk-LGSPAQSP.js} +2 -2
  80. package/dist/cli/chunks/{chunk-AZKVGH5I.js → chunk-LJW7BTMK.js} +2 -2
  81. package/dist/cli/chunks/{chunk-AOASQYOO.js → chunk-LSYMQG52.js} +1 -1
  82. package/dist/cli/chunks/{chunk-5KGFDNYI.js → chunk-MIST354H.js} +2 -2
  83. package/dist/cli/chunks/{chunk-AG7J7DTM.js → chunk-MXAEZHW6.js} +2 -2
  84. package/dist/cli/chunks/{chunk-5LXWEAEJ.js → chunk-MXDGMXJA.js} +2 -2
  85. package/dist/cli/chunks/{chunk-EW5TQQBR.js → chunk-MXHJUAM7.js} +2 -2
  86. package/dist/cli/chunks/{chunk-I3JRRFVT.js → chunk-NGWGOMOP.js} +2 -2
  87. package/dist/cli/chunks/{chunk-5MGRZ4YD.js → chunk-NN6VRHNL.js} +2 -2
  88. package/dist/cli/chunks/{chunk-MIQAFOFO.js → chunk-NQIOXSHW.js} +1 -1
  89. package/dist/cli/chunks/{chunk-SKDDAPBV.js → chunk-NWYYWFUO.js} +1 -1
  90. package/dist/cli/chunks/{chunk-NBBIA3QA.js → chunk-O3PLWCCD.js} +2 -2
  91. package/dist/cli/chunks/{chunk-VRGXYOIN.js → chunk-OD5SVOVP.js} +1 -1
  92. package/dist/cli/chunks/{chunk-JYHZK44T.js → chunk-P2ABIGYB.js} +1 -1
  93. package/dist/cli/chunks/{chunk-255CWHTF.js → chunk-Q4OITFDX.js} +2 -2
  94. package/dist/cli/chunks/{chunk-OEQCZBBM.js → chunk-QAZYSC3T.js} +2 -2
  95. package/dist/cli/chunks/{chunk-LDBHCOM3.js → chunk-QCLEA3CM.js} +2 -2
  96. package/dist/cli/chunks/{chunk-BFBR2ZZJ.js → chunk-QKOPJ5CZ.js} +2 -2
  97. package/dist/cli/chunks/{chunk-KTDGHN2J.js → chunk-QLZPCEVI.js} +1 -1
  98. package/dist/cli/chunks/{chunk-Y3GX66VZ.js → chunk-QMGXALN3.js} +2 -2
  99. package/dist/cli/chunks/{chunk-JCPJG2KU.js → chunk-QMUZMIV7.js} +3 -3
  100. package/dist/cli/chunks/{chunk-NPSWRGNT.js → chunk-QQMHE4RT.js} +2 -2
  101. package/dist/cli/chunks/{chunk-VLQYU7ZQ.js → chunk-RCPFDAOC.js} +1 -1
  102. package/dist/cli/chunks/{chunk-MMVSIESL.js → chunk-RVWGW7TI.js} +2 -2
  103. package/dist/cli/chunks/{chunk-C5YFCM2H.js → chunk-RXXKU3VP.js} +2 -2
  104. package/dist/cli/chunks/{chunk-GYDE5TCN.js → chunk-RYBFRFKY.js} +1 -1
  105. package/dist/cli/chunks/{chunk-DAPBSAVT.js → chunk-S6SRHNJV.js} +2 -2
  106. package/dist/cli/chunks/{chunk-NXO7CT5K.js → chunk-SGGY4QYU.js} +2 -2
  107. package/dist/cli/chunks/{chunk-SLDYG7LC.js → chunk-SH2UPGO7.js} +2 -2
  108. package/dist/cli/chunks/{chunk-3X3QQZ7Q.js → chunk-SL7WTN5Z.js} +2 -2
  109. package/dist/cli/chunks/{chunk-XKD6AFY5.js → chunk-SMQ5OARZ.js} +1 -1
  110. package/dist/cli/chunks/{chunk-EZZJ5XD6.js → chunk-SYXPLFK7.js} +2 -2
  111. package/dist/cli/chunks/{chunk-GVDLCJC5.js → chunk-T3TEQH2H.js} +1 -1
  112. package/dist/cli/chunks/{chunk-2XATUQIG.js → chunk-T5MMSSSF.js} +2 -2
  113. package/dist/cli/chunks/{chunk-TMAIHTE3.js → chunk-TG6P44UT.js} +4 -4
  114. package/dist/cli/chunks/{chunk-N2PLNYEV.js → chunk-TV5OVFKK.js} +1 -1
  115. package/dist/cli/chunks/{chunk-XXHJKAE6.js → chunk-U7RTH6F4.js} +2 -2
  116. package/dist/cli/chunks/{chunk-2SSDY6OE.js → chunk-UABC2Z3S.js} +2 -2
  117. package/dist/cli/chunks/{chunk-DZS7XQ2Z.js → chunk-UAE37LHP.js} +2 -2
  118. package/dist/cli/chunks/{chunk-XQZ63XSL.js → chunk-UHWRRJBH.js} +1 -1
  119. package/dist/cli/chunks/{chunk-G2V4GMPR.js → chunk-UNAVOVD7.js} +3 -3
  120. package/dist/cli/chunks/{chunk-GJ5FON37.js → chunk-V5UB75TQ.js} +2 -2
  121. package/dist/cli/chunks/{chunk-KU7OXAFY.js → chunk-VQI6JQQP.js} +1 -1
  122. package/dist/cli/chunks/{chunk-GL742O2V.js → chunk-WALYYW6B.js} +4 -4
  123. package/dist/cli/chunks/{chunk-PUUTYV32.js → chunk-WF6MKBRI.js} +2 -2
  124. package/dist/cli/chunks/{chunk-K554X3T4.js → chunk-X3NADG4S.js} +2 -2
  125. package/dist/cli/chunks/{chunk-BGTYOZRK.js → chunk-XJRXB5Z5.js} +2 -2
  126. package/dist/cli/chunks/{chunk-M6EP724N.js → chunk-Y6U4CCPP.js} +1 -1
  127. package/dist/cli/chunks/{chunk-V7ZPTEP7.js → chunk-YPUDYGIU.js} +1 -1
  128. package/dist/cli/chunks/{chunk-HCSTXZYE.js → chunk-YPVPWDKL.js} +2 -2
  129. package/dist/cli/chunks/{chunk-FL2DMHOQ.js → chunk-Z5MG54R4.js} +1 -1
  130. package/dist/cli/chunks/{chunk-PS72GF4R.js → chunk-Z65DB2Z7.js} +3 -3
  131. package/dist/cli/chunks/{chunk-JLX35EPX.js → chunk-ZBBHJGPI.js} +2 -2
  132. package/dist/cli/chunks/{chunk-44SPMVML.js → chunk-ZCH5MNST.js} +2 -2
  133. package/dist/cli/chunks/{chunk-2WM4NYM5.js → chunk-ZTWHRDUY.js} +2 -2
  134. package/dist/cli/chunks/{ci-FTZE4PD3.js → ci-TE3744OR.js} +2 -2
  135. package/dist/cli/chunks/{ci-output-C3ORCIHU.js → ci-output-GSNS52SY.js} +2 -2
  136. package/dist/cli/chunks/{circuit-breaker-GS5OTOJZ.js → circuit-breaker-7ROW7QBW.js} +2 -2
  137. package/dist/cli/chunks/{claude-flow-setup-RWOFP5L2.js → claude-flow-setup-Z5GPMILN.js} +2 -2
  138. package/dist/cli/chunks/client-S5TFLKHN.js +2 -0
  139. package/dist/cli/chunks/{cline-installer-D7RGRAUH.js → cline-installer-6D4SAAM4.js} +2 -2
  140. package/dist/cli/chunks/{code-HBDMMYHY.js → code-JZKH7FRS.js} +2 -2
  141. package/dist/cli/chunks/{code-index-extractor-B2KUPAEH.js → code-index-extractor-JJFTZLOK.js} +2 -2
  142. package/dist/cli/chunks/{codex-installer-MPXV4AOD.js → codex-installer-O5KIPN3Z.js} +2 -2
  143. package/dist/cli/chunks/{completions-QJS6QOZQ.js → completions-QNMAUYKK.js} +2 -2
  144. package/dist/cli/chunks/{complexity-analyzer-YQQXWZIL.js → complexity-analyzer-JYJ7TLYE.js} +2 -2
  145. package/dist/cli/chunks/{continuedev-installer-Z6PBKYMB.js → continuedev-installer-JYMVLG6S.js} +2 -2
  146. package/dist/cli/chunks/{copilot-installer-RWVD44CV.js → copilot-installer-SSV6GF5G.js} +2 -2
  147. package/dist/cli/chunks/{cost-tracker-DFPBFYWL.js → cost-tracker-2VZ3IMJZ.js} +2 -2
  148. package/dist/cli/chunks/{coverage-DYST26FK.js → coverage-KW4V5D5L.js} +3 -3
  149. package/dist/cli/chunks/cross-domain-router-GZG5GU7Q.js +2 -0
  150. package/dist/cli/chunks/{cursor-installer-LL6UWKTZ.js → cursor-installer-QVGDAHOI.js} +2 -2
  151. package/dist/cli/chunks/{daemon-6PIHFZNR.js → daemon-JKMFDYK2.js} +3 -3
  152. package/dist/cli/chunks/{dag-attention-scheduler-WS3HJW4F.js → dag-attention-scheduler-WKRV7DFE.js} +2 -2
  153. package/dist/cli/chunks/{detect-J4OITSUD.js → detect-ROCCKX63.js} +2 -2
  154. package/dist/cli/chunks/{dist-node-QSLD5K6K.js → dist-node-QGU7TJTW.js} +2 -2
  155. package/dist/cli/chunks/{domain-handler-BD53QZ4Q.js → domain-handler-3UJHQPOR.js} +2 -2
  156. package/dist/cli/chunks/{domain-transfer-VZBWINQL.js → domain-transfer-R47ISVU5.js} +2 -2
  157. package/dist/cli/chunks/dream-PGYTIOQS.js +2 -0
  158. package/dist/cli/chunks/{embed-and-insert-pattern-5UAFXNDX.js → embed-and-insert-pattern-ZVK7WSY2.js} +2 -2
  159. package/dist/cli/chunks/{eval-GBKU6VTD.js → eval-WNZWXFOW.js} +2 -2
  160. package/dist/cli/chunks/{fast-paths-MYZ6GITZ.js → fast-paths-QPF47RZJ.js} +2 -2
  161. package/dist/cli/chunks/{feature-flags-2WVV66AO.js → feature-flags-2MAHHM66.js} +2 -2
  162. package/dist/cli/chunks/{feature-flags-6ALWBTHS.js → feature-flags-PGIG2W3G.js} +2 -2
  163. package/dist/cli/chunks/{file-discovery-FOYCPGD6.js → file-discovery-JL6FCXRB.js} +2 -2
  164. package/dist/cli/chunks/{fleet-JROEDHAT.js → fleet-LMBZU2GU.js} +3 -3
  165. package/dist/cli/chunks/{gnn-wrapper-KAXTFFEE.js → gnn-wrapper-GFNFVEER.js} +2 -2
  166. package/dist/cli/chunks/{heartbeat-handler-PG24CBMQ.js → heartbeat-handler-YN7ES3AX.js} +4 -4
  167. package/dist/cli/chunks/{heartbeat-scheduler-LSS3RD6E.js → heartbeat-scheduler-SII2KJSQ.js} +2 -2
  168. package/dist/cli/chunks/hnsw-adapter-ANJKCXK6.js +2 -0
  169. package/dist/cli/chunks/hnsw-index-D4CJEP7L.js +2 -0
  170. package/dist/cli/chunks/{hnsw-legacy-bridge-HYH4AJAO.js → hnsw-legacy-bridge-CPMBYE7C.js} +2 -2
  171. package/dist/cli/chunks/{hnswlib-node-WTTST5LC.js → hnswlib-node-NWNBNU3W.js} +2 -2
  172. package/dist/cli/chunks/{hooks-RDZSAFQG.js → hooks-EYSB7XDW.js} +58 -47
  173. package/dist/cli/chunks/{hybrid-router-HNPS6EFL.js → hybrid-router-BR7O6WT2.js} +2 -2
  174. package/dist/cli/chunks/{hypergraph-engine-JUFXRXCC.js → hypergraph-engine-HAKGWDYX.js} +2 -2
  175. package/dist/cli/chunks/{hypergraph-handler-YFRF53TF.js → hypergraph-handler-UCI3LXUF.js} +3 -3
  176. package/dist/cli/chunks/impact-analyzer-55JW3OK6.js +2 -0
  177. package/dist/cli/chunks/{init-handler-P4W5F57S.js → init-handler-7RYGU3W5.js} +6 -6
  178. package/dist/cli/chunks/init-wizard-MWKJNVB2.js +2 -0
  179. package/dist/cli/chunks/kernel-5MKKDS4J.js +2 -0
  180. package/dist/cli/chunks/{kilocode-installer-5VWY4DMH.js → kilocode-installer-W6ITMEFA.js} +2 -2
  181. package/dist/cli/chunks/{kiro-installer-PZC3BQII.js → kiro-installer-2BO34D3O.js} +2 -2
  182. package/dist/cli/chunks/knowledge-graph-2A7AE7L7.js +2 -0
  183. package/dist/cli/chunks/{learning-4OH4ZG25.js → learning-GEXYG72Z.js} +3 -3
  184. package/dist/cli/chunks/{llm-router-LZBR6SZQ.js → llm-router-EGHA5YOC.js} +4 -4
  185. package/dist/cli/chunks/{load-SPWP6VB3.js → load-VU2OOAEF.js} +2 -2
  186. package/dist/cli/chunks/load-test-UD4ZXCGG.js +2 -0
  187. package/dist/cli/chunks/{mcp-QYPQMM7L.js → mcp-NVQFFQ2R.js} +2 -2
  188. package/dist/cli/chunks/{memory-54ILJMWQ.js → memory-JNXMKTZQ.js} +5 -5
  189. package/dist/cli/chunks/memory-backend-X3Z4IAYG.js +2 -0
  190. package/dist/cli/chunks/{memory-handlers-YK7H5UCX.js → memory-handlers-NLGQ5I7K.js} +2 -2
  191. package/dist/cli/chunks/{multi-model-executor-XAOAVPPI.js → multi-model-executor-SG6OME2A.js} +2 -2
  192. package/dist/cli/chunks/{opencode-installer-CNS4XMUF.js → opencode-installer-AY4JCZIM.js} +2 -2
  193. package/dist/cli/chunks/{orchestrator-SSEMSKUI.js → orchestrator-GWI7HQG6.js} +5 -5
  194. package/dist/cli/chunks/{pipeline-DS3AENTB.js → pipeline-7T6IAMC7.js} +2 -2
  195. package/dist/cli/chunks/{platform-BL6LH5NF.js → platform-IXUST66M.js} +2 -2
  196. package/dist/cli/chunks/{plugin-FNXPEQ2C.js → plugin-PW7F6MVH.js} +2 -2
  197. package/dist/cli/chunks/{prime-radiant-advanced-wasm-E6S6BGNA.js → prime-radiant-advanced-wasm-BUAZHZCM.js} +2 -2
  198. package/dist/cli/chunks/protocol-executor-AB6KPFK5.js +2 -0
  199. package/dist/cli/chunks/{protocol-handler-D4WIUU3W.js → protocol-handler-6746OC4P.js} +2 -2
  200. package/dist/cli/chunks/{prove-OLB3PKW6.js → prove-VYV5DQGC.js} +2 -2
  201. package/dist/cli/chunks/{provider-manager-GKTQ75DT.js → provider-manager-GEO3CUOO.js} +3 -3
  202. package/dist/cli/chunks/qe-reasoning-bank-Y4IDDIYA.js +2 -0
  203. package/dist/cli/chunks/{quality-ZYJVYTUL.js → quality-4XXENNNW.js} +2 -2
  204. package/dist/cli/chunks/queen-coordinator-GBSTXGA2.js +2 -0
  205. package/dist/cli/chunks/{real-embeddings-SKJRHLCS.js → real-embeddings-ZVEZVXVT.js} +2 -2
  206. package/dist/cli/chunks/{roocode-installer-WZGKOLWE.js → roocode-installer-ZRNDOIDL.js} +2 -2
  207. package/dist/cli/chunks/router-JA2X4MF6.js +2 -0
  208. package/dist/cli/chunks/routing-feedback-YCVJIWFM.js +2 -0
  209. package/dist/cli/chunks/{routing-handler-4GIMINCI.js → routing-handler-MPSJ7DDI.js} +2 -2
  210. package/dist/cli/chunks/{ruvector-commands-YZONXZ2W.js → ruvector-commands-V4BVCY2U.js} +2 -2
  211. package/dist/cli/chunks/{rvf-dual-writer-WSS5GF54.js → rvf-dual-writer-X4VNU5KH.js} +2 -2
  212. package/dist/cli/chunks/{rvf-migration-adapter-WS4HHVEU.js → rvf-migration-adapter-KOYYJSNH.js} +2 -2
  213. package/dist/cli/chunks/{rvf-migration-coordinator-6BY5GI47.js → rvf-migration-coordinator-SF5IBKTK.js} +2 -2
  214. package/dist/cli/chunks/rvf-native-adapter-5YN7EEB5.js +2 -0
  215. package/dist/cli/chunks/safe-db-S46Y7IC5.js +2 -0
  216. package/dist/cli/chunks/schedule-KSDHFWSY.js +2 -0
  217. package/dist/cli/chunks/scheduler-PLFJHU54.js +2 -0
  218. package/dist/cli/chunks/{security-HCNOL2K3.js → security-AA5GBNNU.js} +3 -3
  219. package/dist/cli/chunks/shared-rvf-adapter-MLXVW4N6.js +2 -0
  220. package/dist/cli/chunks/{shared-rvf-dual-writer-QRNLSDS7.js → shared-rvf-dual-writer-EGP3BYIY.js} +2 -2
  221. package/dist/cli/chunks/sqlite-persistence-RK3JWKB4.js +2 -0
  222. package/dist/cli/chunks/{status-handler-QXZ442MY.js → status-handler-ARHPRXJ4.js} +2 -2
  223. package/dist/cli/chunks/{structural-health-OFYZ3Z4A.js → structural-health-IDV4RBZV.js} +2 -2
  224. package/dist/cli/chunks/{sync-J4BG65NF.js → sync-7BRLSLDG.js} +2 -2
  225. package/dist/cli/chunks/{task-handler-UBSFCKK3.js → task-handler-XY42QA3K.js} +2 -2
  226. package/dist/cli/chunks/task-handlers-QEHOKEJC.js +9 -0
  227. package/dist/cli/chunks/{test-WTNAHJHH.js → test-TQIHDBEX.js} +4 -4
  228. package/dist/cli/chunks/{test-scheduling-QREBYRGW.js → test-scheduling-BBVOLGFT.js} +3 -3
  229. package/dist/cli/chunks/{token-bootstrap-HE5H77OL.js → token-bootstrap-BUHTWVEF.js} +2 -2
  230. package/dist/cli/chunks/{token-usage-V5B6K3JL.js → token-usage-MRVQ7G3H.js} +2 -2
  231. package/dist/cli/chunks/{transformers-HIVMQP4O.js → transformers-3PFLFSWR.js} +2 -2
  232. package/dist/cli/chunks/{tree-sitter-wasm-parser-WP2SF2M5.js → tree-sitter-wasm-parser-6GDZQNFV.js} +2 -2
  233. package/dist/cli/chunks/{types-7ZBTAO5Z.js → types-F2LWFMRI.js} +2 -2
  234. package/dist/cli/chunks/unified-memory-JVZZMZRE.js +2 -0
  235. package/dist/cli/chunks/unified-memory-hnsw-EJJHCMFR.js +2 -0
  236. package/dist/cli/chunks/unified-persistence-IEKOYCBL.js +2 -0
  237. package/dist/cli/chunks/{upgrade-WIFAJDBG.js → upgrade-N676MSDA.js} +2 -2
  238. package/dist/cli/chunks/{validate-W63V36GA.js → validate-56AA6YYM.js} +2 -2
  239. package/dist/cli/chunks/{validate-swarm-CK5BM3YY.js → validate-swarm-YPHV7MMC.js} +2 -2
  240. package/dist/cli/chunks/{vibium-MJCCO36E.js → vibium-ABPFT3DX.js} +2 -2
  241. package/dist/cli/chunks/visual-security-APS7K3TZ.js +2 -0
  242. package/dist/cli/chunks/{web-tree-sitter-ESERXLPK.js → web-tree-sitter-KN4PWKMV.js} +2 -2
  243. package/dist/cli/chunks/{windsurf-installer-FDWQ5BWI.js → windsurf-installer-IZOJBDNN.js} +2 -2
  244. package/dist/cli/chunks/witness-chain-DMHO7R75.js +2 -0
  245. package/dist/cli/chunks/{witness-chain-L5KSYE2S.js → witness-chain-H2DM5WMB.js} +2 -2
  246. package/dist/cli/chunks/{workflow-34GYJDFW.js → workflow-R42PK45F.js} +4 -4
  247. package/dist/cli/chunks/workflow-orchestrator-BDHRNVOG.js +2 -0
  248. package/dist/cli/chunks/{wrappers-VGKEBQLW.js → wrappers-6TIJNWN4.js} +2 -2
  249. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +54 -0
  250. package/dist/cli/commands/init.js +3 -1
  251. package/dist/coordination/consensus/providers/claude-provider.js +1 -1
  252. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +82 -0
  253. package/dist/learning/dream/dream-engine.js +8 -0
  254. package/dist/mcp/bundle.js +347 -338
  255. package/dist/mcp/entry.js +15 -0
  256. package/dist/mcp/handlers/core-handlers.js +2 -2
  257. package/dist/mcp/handlers/task-handlers.js +45 -0
  258. package/dist/mcp/handlers/trajectory-judge.d.ts +13 -0
  259. package/dist/mcp/handlers/trajectory-judge.js +100 -0
  260. package/dist/shared/llm/providers/claude.js +1 -1
  261. package/package.json +1 -1
  262. package/dist/cli/chunks/adapter-5NI3IO42.js +0 -2
  263. package/dist/cli/chunks/aqe-learning-engine-JOUK5HMO.js +0 -2
  264. package/dist/cli/chunks/base-DCAB7AHK.js +0 -2
  265. package/dist/cli/chunks/browser-workflow-A4UV73SZ.js +0 -2
  266. package/dist/cli/chunks/chunk-VPDZTMMB.js +0 -24
  267. package/dist/cli/chunks/chunk-Z2E5DTKX.js +0 -2
  268. package/dist/cli/chunks/client-UTNF2C5K.js +0 -2
  269. package/dist/cli/chunks/cross-domain-router-FCM34JOR.js +0 -2
  270. package/dist/cli/chunks/dream-6KCS7EWS.js +0 -2
  271. package/dist/cli/chunks/hnsw-adapter-PG6O67CQ.js +0 -2
  272. package/dist/cli/chunks/hnsw-index-AHYZHLNZ.js +0 -2
  273. package/dist/cli/chunks/impact-analyzer-USAJVJY5.js +0 -2
  274. package/dist/cli/chunks/init-wizard-GL7LAZID.js +0 -2
  275. package/dist/cli/chunks/kernel-2YAIESTR.js +0 -2
  276. package/dist/cli/chunks/knowledge-graph-QSIYZRAG.js +0 -2
  277. package/dist/cli/chunks/load-test-UEHSHLVN.js +0 -2
  278. package/dist/cli/chunks/memory-backend-4NE4ADPG.js +0 -2
  279. package/dist/cli/chunks/protocol-executor-YI4HNXND.js +0 -2
  280. package/dist/cli/chunks/qe-reasoning-bank-ANBAXQXC.js +0 -2
  281. package/dist/cli/chunks/queen-coordinator-MYYUSWVX.js +0 -2
  282. package/dist/cli/chunks/router-RYCLZ7A4.js +0 -2
  283. package/dist/cli/chunks/routing-feedback-5KSRG2UI.js +0 -2
  284. package/dist/cli/chunks/rvf-native-adapter-NEIOLJRF.js +0 -2
  285. package/dist/cli/chunks/safe-db-3JQP4EPU.js +0 -2
  286. package/dist/cli/chunks/schedule-2QKCL64E.js +0 -2
  287. package/dist/cli/chunks/scheduler-FMOP45FC.js +0 -2
  288. package/dist/cli/chunks/shared-rvf-adapter-BMFIVWMJ.js +0 -2
  289. package/dist/cli/chunks/sqlite-persistence-I5RYLFOE.js +0 -2
  290. package/dist/cli/chunks/task-handlers-JFUT2FQ7.js +0 -2
  291. package/dist/cli/chunks/unified-memory-2ETCY22B.js +0 -2
  292. package/dist/cli/chunks/unified-memory-hnsw-OALJW537.js +0 -2
  293. package/dist/cli/chunks/unified-persistence-SQMP7A3O.js +0 -2
  294. package/dist/cli/chunks/visual-security-JUJPF2QO.js +0 -2
  295. package/dist/cli/chunks/witness-chain-QJVKAAZT.js +0 -2
  296. package/dist/cli/chunks/workflow-orchestrator-WXB2RVVW.js +0 -2
@@ -0,0 +1,12 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
+ import{a as U,b as G}from"./chunk-MXDGMXJA.js";import{g as N}from"./chunk-QMUZMIV7.js";import{a as W}from"./chunk-GXO42P3X.js";import{e as T}from"./chunk-5LM2W3NE.js";import{b as v,c as x}from"./chunk-7R45TEY6.js";import{a as re}from"./chunk-F32R4LVS.js";import{c as O}from"./chunk-MIST354H.js";import{b as k,d as q}from"./chunk-JCPXG42O.js";import{b,c as E}from"./chunk-TV5OVFKK.js";import{a as y,c as z}from"./chunk-NN6VRHNL.js";import{i as I}from"./chunk-NQIOXSHW.js";import{S as ae,b as _}from"./chunk-4SBMTHTA.js";import{randomUUID as Y}from"crypto";z();q();import{randomUUID as se}from"node:crypto";var j=x(),P=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),r=["--no-install",j,"hooks","intelligence","trajectory-start","--task",e];t&&r.push("--agent",t);let s=n("npx",r,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(n){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",n instanceof Error?n.message:n)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,n){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",j,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),n!==void 0&&s.push("--quality",String(n)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let r=this.localTrajectories.get(e);r&&r.steps.push({id:`step-${r.steps.length+1}`,action:t,result:i,quality:n,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),a=["--no-install",j,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),r("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let n=this.localTrajectories.get(e);if(n)return n.success=t,n.feedback=i,n.completedAt=Date.now(),await this.persistTrajectory(n),n}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{getUnifiedMemory:t}=await import("./unified-memory-JVZZMZRE.js"),i=t();i.isInitialized()||await i.initialize();let n=i.getDatabase();try{n.prepare("PRAGMA table_info(qe_trajectories)").all().some(o=>o.name==="feedback")||n.exec("ALTER TABLE qe_trajectories ADD COLUMN feedback TEXT")}catch{}let r=new Date(e.startedAt).toISOString(),a=e.completedAt?new Date(e.completedAt).toISOString():null;n.prepare(`
3
+ INSERT OR REPLACE INTO qe_trajectories
4
+ (id, task, agent, domain, started_at, ended_at, success, steps_json, feedback)
5
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
6
+ `).run(e.id,e.task,e.agent||null,null,r,a,e.success?1:0,JSON.stringify(e.steps),e.feedback||null)}catch(t){console.debug("[TrajectoryBridge] Trajectory persistence failed:",t instanceof Error?t.message:t)}}};var H=x(),V={low:[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i],high:[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/database.*migration/i,/distributed/i,/concurrent/i]},R=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;routingHistory=[];async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async routeTask(e){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",H,"hooks","model-route","--task",e],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}),n=i.match(/model[:\s]+["']?(haiku|sonnet|opus)/i),r=i.match(/confidence[:\s]+([0-9.]+)/i),a=i.match(/reason(?:ing)?[:\s]+["']?([^"'\n]+)/i);if(n)return{model:n[1].toLowerCase(),confidence:r?parseFloat(r[1]):.7,reasoning:a?.[1]?.trim()}}catch(t){console.debug("[ModelRouterBridge] Claude Flow routing failed:",t instanceof Error?t.message:t)}return this.localRoute(e)}async recordOutcome(e){if(this.routingHistory.push(e),this.routingHistory.length>1e3&&(this.routingHistory=this.routingHistory.slice(-500)),this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process");t("npx",["--no-install",H,"hooks","model-outcome","--task",e.task,"--model",e.model,"--outcome",e.outcome],{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch(t){console.debug("[ModelRouterBridge] Outcome recording failed:",t instanceof Error?t.message:t)}}getStats(){let e={totalRoutings:this.routingHistory.length,modelDistribution:{haiku:0,sonnet:0,opus:0},successRate:{haiku:0,sonnet:0,opus:0}},t={haiku:0,sonnet:0,opus:0};for(let i of this.routingHistory)e.modelDistribution[i.model]++,i.outcome==="success"&&t[i.model]++;for(let i of["haiku","sonnet","opus"]){let n=e.modelDistribution[i];e.successRate[i]=n>0?t[i]/n:0}return e}isClaudeFlowAvailable(){return this.claudeFlowAvailable}localRoute(e){let t=e.toLowerCase();for(let i of V.low)if(i.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task detected - using haiku for speed"};for(let i of V.high)if(i.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task detected - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task description - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity task - using sonnet for balance"}}};q();z();var B=x(),S=class{constructor(e){this.options=e}options;claudeFlowAvailable=!1;analysisCache=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async analyze(e,t="medium"){let i=e||this.options.projectRoot,n=`${i}:${t}`,r=this.analysisCache.get(n);if(r)return r;if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=a("npx",["--no-install",B,"hooks","pretrain","--path",i,"--depth",t],{encoding:"utf-8",timeout:12e4,cwd:this.options.projectRoot});try{let o=k(s),d={success:!0,repositoryPath:i,depth:t,analysis:o.analysis||void 0,agentConfigs:o.agentConfigs};return this.analysisCache.set(n,d),d}catch{return{success:!0,repositoryPath:i,depth:t}}}catch(a){console.debug("[PretrainBridge] Claude Flow analyze failed, using local:",a instanceof Error?a.message:a)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowAvailable)try{let{execFileSync:t}=await import("child_process"),i=t("npx",["--no-install",B,"hooks","build-agents","--format",e],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot});try{return k(i)}catch(n){return console.debug("[PretrainBridge] Agent config parse error:",n instanceof Error?n.message:n),[]}}catch(t){console.debug("[PretrainBridge] Claude Flow generateAgentConfigs failed:",t instanceof Error?t.message:t)}return this.generateLocalAgentConfigs()}async transferPatterns(e,t=.7){if(this.claudeFlowAvailable)try{let{execFileSync:i}=await import("child_process"),n=i("npx",["--no-install",B,"hooks","transfer","--source-path",e,"--min-confidence",String(t)],{encoding:"utf-8",timeout:6e4,cwd:this.options.projectRoot}),r=n.match(/transferred[:\s]+(\d+)/i),a=n.match(/skipped[:\s]+(\d+)/i);return{transferred:r?parseInt(r[1]):0,skipped:a?parseInt(a[1]):0}}catch(i){console.debug("[PretrainBridge] Claude Flow transferPatterns failed:",i instanceof Error?i.message:i)}return{transferred:0,skipped:0}}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],d=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),m=new Set,p=new Set;for(let u of d.slice(0,100))(u.endsWith(".ts")||u.endsWith(".tsx"))&&m.add("typescript"),(u.endsWith(".js")||u.endsWith(".jsx"))&&m.add("javascript"),u.endsWith(".py")&&m.add("python"),u.endsWith(".go")&&m.add("go"),u.endsWith(".rs")&&m.add("rust");let w=a(e,"package.json");if(n(w))try{let u=k(r(w,"utf-8")),f={...u.dependencies,...u.devDependencies};f.react&&p.add("react"),f.vue&&p.add("vue"),f.angular&&p.add("angular"),f.vitest&&p.add("vitest"),f.jest&&p.add("jest"),f.playwright&&p.add("playwright"),f.express&&p.add("express"),f.fastify&&p.add("fastify")}catch(u){console.debug("[PretrainBridge] package.json parse error:",u instanceof Error?u.message:u)}let g={success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(m),frameworks:Array.from(p),patterns:[],complexity:d.length>500?3:d.length>100?2:1}};return this.analysisCache.set(`${e}:${t}`,g),g}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}generateLocalAgentConfigs(){return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-quality-gate",type:"worker",capabilities:["quality-assessment","risk-scoring"],model:"sonnet"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}};var D=class{constructor(e){this.options=e;this.trajectory=new P(e),this.modelRouter=new R(e),this.pretrain=new S(e)}options;trajectory;modelRouter;pretrain;initialized=!1;async initialize(){this.initialized||(await Promise.all([this.trajectory.initialize(),this.modelRouter.initialize(),this.pretrain.initialize()]),this.initialized=!0)}getStatus(){return{available:this.isAvailable(),features:{trajectories:this.trajectory.isClaudeFlowAvailable(),modelRouting:this.modelRouter.isClaudeFlowAvailable(),pretrain:this.pretrain.isClaudeFlowAvailable(),patternSearch:this.trajectory.isClaudeFlowAvailable()}}}isAvailable(){return this.trajectory.isClaudeFlowAvailable()||this.modelRouter.isClaudeFlowAvailable()||this.pretrain.isClaudeFlowAvailable()}};function J(l){return new D(l)}re();ae();var M=O.create("experience-capture"),K={"catches-bug":1,flaky:-1,"false-positive":-1,"new-coverage":.3,redundant:0,"code-smell":-.5,neutral:0},oe=new Set(Object.keys(K));function X(l){return typeof l=="string"&&oe.has(l)}function ce(l){if(X(l))return K[l]}var le={namespace:"qe-experiences",minQualityForPatternExtraction:.7,similarityThreshold:.85,promotionThreshold:T,maxExperiencesPerDomain:1e3,enableCrossDomainSharing:!0,autoCleanup:!0,cleanupIntervalMs:864e5},Q=class{constructor(e,t,i,n={}){this.memory=e;this.patternStore=t;this.eventBus=i;this.config={...le,...n}}memory;patternStore;eventBus;config;initialized=!1;cleanupTimer;activeExperiences=new Map;stats={totalCaptured:0,successfulCaptures:0,patternsExtracted:0,patternsPromoted:0,byDomain:new Map};sessionCaptureCount=0;witnessChain;setWitnessChain(e){this.witnessChain=e}async initialize(){this.initialized||(await this.loadStats(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0,console.log("[ExperienceCapture] Initialized"))}startCapture(e,t){let i=`exp-${Date.now()}-${I().slice(0,8)}`,n={id:i,task:e,agent:t?.agent,domain:t?.domain,model:t?.model,startedAt:Date.now(),completedAt:0,durationMs:0,steps:[],success:!1,quality:0,trajectoryId:t?.trajectoryId,metadata:t?.metadata};return this.activeExperiences.set(i,n),i}recordStep(e,t){let i=this.activeExperiences.get(e);if(!i){console.warn(`[ExperienceCapture] Experience not found: ${e}`);return}i.steps.push({...t,timestamp:Date.now()})}async completeCapture(e,t){let i=this.activeExperiences.get(e);if(!i)return E(new Error(`Experience not found: ${e}`));let n=Date.now();i.completedAt=n,i.durationMs=n-i.startedAt,i.success=t.success,i.feedback=t.feedback,t.quality!==void 0?i.quality=t.quality:i.quality=this.calculateQuality(i);let r=t.testOutcome??i.metadata?.testOutcome;if(r&&X(r)&&(i.testOutcome=r,i.reward=ce(r)),this.witnessChain&&_().useWitnessChain)try{let s=this.witnessChain.appendWitness({type:"experience-capture",decision:i.success?"PASS":"FAIL",context:{experienceId:i.id,task:i.task,quality:i.quality,domain:i.domain,reward:i.reward},evidence:i.reward});i.witnessHash=s.hash}catch(s){M.warn("Failed to create witness receipt for experience",{experienceId:i.id,error:s instanceof Error?s.message:String(s)})}this.activeExperiences.delete(e),await this.storeExperience(i),this.updateStats(i);let a=i.reward===void 0||i.reward>0;if(i.success&&i.quality>=this.config.minQualityForPatternExtraction&&a){let s=await this.extractPattern(i);(s.newPattern||s.reinforced)&&(i.patterns=[s.patternId])}return this.emitExperienceCaptured(i),b(i)}getActiveExperience(e){return this.activeExperiences.get(e)}getPendingCount(){return this.activeExperiences.size}async flushPending(){let e=Array.from(this.activeExperiences.entries());if(e.length===0)return 0;let t=0;for(let[i,n]of e){let r=Date.now();n.completedAt=r,n.durationMs=r-n.startedAt,n.quality=n.quality||this.calculateQuality(n),n.metadata={...n.metadata,flushedByCompaction:!0},await this.storeExperience(n),this.updateStats(n),this.activeExperiences.delete(i),t++}return M.info(`Flushed ${t} pending experiences before compaction`),t}async getExperience(e){let t=`${this.config.namespace}:experience:${e}`;return await this.memory.get(t)??null}async searchExperiences(e={}){let t=e.limit||100,i=[],n;e.domain?n=await this.memory.search(`${this.config.namespace}:index:domain:${e.domain}:*`,t*2):n=await this.memory.search(`${this.config.namespace}:experience:*`,t*2);for(let r of n){if(i.length>=t)break;let a=r.includes(":index:")?await this.memory.get(r):null,s=a?await this.getExperience(a):await this.memory.get(r);s&&(e.agent&&s.agent!==e.agent||e.success!==void 0&&s.success!==e.success||e.minQuality!==void 0&&s.quality<e.minQuality||i.push(s))}return i}async getStats(){let e={};for(let[t,i]of this.stats.byDomain)e[t]=i;return{totalExperiences:this.stats.totalCaptured,byDomain:e,successRate:this.stats.totalCaptured>0?this.stats.successfulCaptures/this.stats.totalCaptured:0,avgQuality:await this.calculateAvgQuality(),patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted}}async extractPattern(e){if(!this.patternStore)return{newPattern:!1,reinforced:!1,promoted:!1};let t=await this.patternStore.search(e.task,{limit:1,domain:e.domain,useVectorSearch:!0});if(t.success&&t.value.length>0){let r=t.value[0];if(r.similarity>=this.config.similarityThreshold){let a=await this.patternStore.recordUsage(r.pattern.id,e.success),s=await this.patternStore.get(r.pattern.id),o=!1;return s&&s.tier==="short-term"&&s.usageCount>=this.config.promotionThreshold&&(await this.patternStore.promote(r.pattern.id)).success&&(o=!0,this.stats.patternsPromoted++,console.log(`[ExperienceCapture] Pattern promoted: ${r.pattern.id} (${s.usageCount} uses)`)),{newPattern:!1,patternId:r.pattern.id,reinforced:a.success,promoted:o}}}let i=this.experienceToPatternOptions(e),n=await this.patternStore.create(i);return n.success?(this.stats.patternsExtracted++,await this.patternStore.recordUsage(n.value.id,e.success),{newPattern:!0,patternId:n.value.id,reinforced:!1,promoted:!1}):{newPattern:!1,reinforced:!1,promoted:!1}}async shareAcrossDomains(e){if(!this.config.enableCrossDomainSharing||!e.domain)return;let t=this.getRelatedDomains(e.domain);for(let i of t){let n=`${this.config.namespace}:shared:${i}:${e.id}`;await this.memory.set(n,{sourceExperience:e.id,sourceDomain:e.domain,sharedAt:Date.now()},{persist:!0})}}async cleanup(){let e=0,t=0;for(let i of this.stats.byDomain.keys()){let n=this.stats.byDomain.get(i)||0;if(n>this.config.maxExperiencesPerDomain){let r=await this.searchExperiences({domain:i,limit:n});r.sort((s,o)=>s.quality-o.quality||s.startedAt-o.startedAt);let a=n-this.config.maxExperiencesPerDomain;for(let s=0;s<Math.min(a,r.length);s++){let o=r[s];await this.softDeleteExperience(o.id),t++}}}return console.log(`[ExperienceCapture] Cleanup: ${t} archived (0 destroyed)`),{removed:0,consolidated:e,archived:t}}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),await this.saveStats(),this.sessionCaptureCount===0&&console.warn("[ExperienceCapture] WARNING: Zero experiences captured this session. Learning cannot improve without experience data. Ensure tasks call startCapture()/completeCapture() to feed the learning loop."),this.activeExperiences.clear(),this.initialized=!1}async storeExperience(e){let t=`${this.config.namespace}:experience:${e.id}`;if(await this.memory.set(t,e,{persist:!0}),e.domain){let i=`${this.config.namespace}:index:domain:${e.domain}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}if(e.agent){let i=`${this.config.namespace}:index:agent:${e.agent}:${e.id}`;await this.memory.set(i,e.id,{persist:!0})}}async deleteExperience(e){await this.softDeleteExperience(e)}async softDeleteExperience(e){let t=await this.getExperience(e);if(!t)return;let i=`${this.config.namespace}:experience:${e}`,n={...t,_archived:!0};await this.memory.set(i,n,{persist:!0})}calculateQuality(e){if(e.steps.length===0)return e.success?.5:.2;let t=e.steps.filter(n=>n.quality!==void 0);if(t.length===0)return e.success?.6:.3;let i=t.reduce((n,r)=>n+(r.quality||0),0)/t.length;return e.success?Math.min(1,i+.1):Math.max(0,i-.2)}updateStats(e){if(this.stats.totalCaptured++,this.sessionCaptureCount++,e.success&&this.stats.successfulCaptures++,e.domain){let t=this.stats.byDomain.get(e.domain)||0;this.stats.byDomain.set(e.domain,t+1)}}async calculateAvgQuality(){let e=await this.searchExperiences({limit:100});return e.length===0?0:e.reduce((i,n)=>i+n.quality,0)/e.length}experienceToPatternOptions(e){let t=this.detectPatternType(e.task),n=`Task: {{task}}
7
+
8
+ Steps:
9
+ ${e.steps.map((r,a)=>`${a+1}. ${r.action}${r.result?` \u2192 ${r.result}`:""}`).join(`
10
+ `)}
11
+
12
+ Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:n,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),n=["unit","integration","e2e","api","mock","coverage","security"];for(let r of n)i.some(a=>a.includes(r))&&t.push(r);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){M.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Z(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:T},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}memory;eventBus;config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=W(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=N(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-EGP3BYIY.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Z(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-H2DM5WMB.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-H2DM5WMB.js"),{getUnifiedPersistence:n}=await import("./unified-persistence-IEKOYCBL.js"),r=n();if(r.isInitialized()){let a=r.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-PGIG2W3G.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-R47ISVU5.js"),i=t(),n=this.patternStore,r=await n.getStats();this._domainTransferInterval=setInterval(async()=>{try{r=await n.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=r.byDomain?.[a]??0,o=r.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:r.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=J({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let n=this.enhanceRoutingWithPatterns(i.value,t.value);return b(n)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(n=>n.pattern.id),avgSimilarity:t.length>0?t.reduce((n,r)=>n+r.similarity,0)/t.length:0};try{let n=`pattern-usage:search:${Date.now()}-${Y().slice(0,8)}`;await this.memory.set(n,i,{persist:!0,ttl:10080*60*1e3})}catch(n){console.debug("[AQELearningEngine] Failed to track pattern search:",y(n))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(o=>o.similarity>=.5&&o.pattern.qualityScore>=.3);if(i.length===0)return e;let n=i.map(o=>{let d=o.pattern;return`[Pattern: ${d.name}] ${d.description} (confidence: ${(d.confidence*100).toFixed(0)}%, similarity: ${(o.similarity*100).toFixed(0)}%)`}),r=[...e.guidance,"--- Relevant Patterns ---",...n],a=[...e.patterns,...i.map(o=>o.pattern)],s=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((o,d)=>o+d.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:r,reasoning:e.reasoning+s,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let r of i)if(r.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let n=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let r of n)if(r.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let n=`task-${Date.now()}-${Y().slice(0,8)}`,r=n;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{r=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(o){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(o))}let a;this.experienceCapture&&(a=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:r!==n?r:void 0}));let s={id:a||r,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(s.id,s),s.id}async recordStep(e,t,i,n){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,n)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:n});let r=this.activeTasks.get(e);r&&r.steps.push({action:t,result:i,quality:n,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(r){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(r))}let n=this.activeTasks.get(e);if(n)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(n),n}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(n){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",n instanceof Error?n.message:n)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((n,r)=>n+(r.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:n,readFileSync:r}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],d=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),m=new Set,p=new Set;for(let g of d.slice(0,100))(g.endsWith(".ts")||g.endsWith(".tsx"))&&m.add("typescript"),(g.endsWith(".js")||g.endsWith(".jsx"))&&m.add("javascript"),g.endsWith(".py")&&m.add("python"),g.endsWith(".go")&&m.add("go"),g.endsWith(".rs")&&m.add("rust");let w=a(e,"package.json");if(n(w))try{let g=k(r(w,"utf-8")),u={...g.dependencies,...g.devDependencies};u.react&&p.add("react"),u.vue&&p.add("vue"),u.vitest&&p.add("vitest"),u.jest&&p.add("jest"),u.playwright&&p.add("playwright")}catch(g){console.debug("[AQELearningEngine] package.json parse failed:",g instanceof Error?g.message:g)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(m),frameworks:Array.from(p),patterns:[],complexity:d.length>500?3:d.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),n=e.slice(t),r=[],a=Date.now(),s=h(i.map(c=>c.tokenMetrics.costUsd)),o=h(n.map(c=>c.tokenMetrics.costUsd)),d=h(i.map(c=>c.tokenMetrics.savingsUsd)),m=h(n.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&m<=d*1.05){let c=Math.min(1,(o-s)/(s||1));r.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:F(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let p=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(n.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-p)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&r.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:F(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let u=h(i.map(c=>c.learningMetrics.patternCount)),f=h(n.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(n.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-u),ne=Math.abs($-te);ie<1&&ne<.02&&r.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:F(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),A=h(n.map(c=>c.performanceMetrics.p95LatencyMs));if(A>C*1.2&&C>0){let c=Math.min(1,(A-C)/(C||1));r.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${A.toFixed(0)}ms`,confidence:F(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return r}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function F(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
- import{c as R,g as L}from"./chunk-AZKVGH5I.js";import{k as N,o as w}from"./chunk-TXCOK5DC.js";import{b,d as q}from"./chunk-5R2DUR3A.js";import{a as _,c as I}from"./chunk-5MGRZ4YD.js";import{i as f}from"./chunk-MIQAFOFO.js";import{a as S,b as A}from"./chunk-PUUTYV32.js";A();q();I();w();var D={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function C(m,e=384){let n=new Array(e).fill(0),t=m.toLowerCase().trim();for(let a=0;a<3;a++)for(let i=0;i<t.length;i++){let s=t.charCodeAt(i),o=s*(i+1)*(a+1)%e;n[o]+=Math.sin(s*(a+1))/(i+1)}let r=Math.sqrt(n.reduce((a,i)=>a+i*i,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...D,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=N(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=S(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
+ import{c as R,g as L}from"./chunk-LJW7BTMK.js";import{k as N,o as w}from"./chunk-CEVIRL2S.js";import{b,d as q}from"./chunk-JCPXG42O.js";import{a as _,c as I}from"./chunk-NN6VRHNL.js";import{i as f}from"./chunk-NQIOXSHW.js";import{a as S,b as A}from"./chunk-WF6MKBRI.js";A();q();I();w();var D={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function C(m,e=384){let n=new Array(e).fill(0),t=m.toLowerCase().trim();for(let a=0;a<3;a++)for(let i=0;i<t.length;i++){let s=t.charCodeAt(i),o=s*(i+1)*(a+1)%e;n[o]+=Math.sin(s*(a+1))/(i+1)}let r=Math.sqrt(n.reduce((a,i)=>a+i*i,0));if(r>0)for(let a=0;a<e;a++)n[a]/=r;return n}var h=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...D,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=N(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),n=await import("fs"),t=e.dirname(this.config.dbPath);n.existsSync(t)||n.mkdirSync(t,{recursive:!0}),this.db=S(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  -- QE Patterns table
4
4
  CREATE TABLE IF NOT EXISTS qe_patterns (
5
5
  id TEXT PRIMARY KEY,
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
- import{d as k,f as we}from"./chunk-AG7J7DTM.js";import{a as ye}from"./chunk-Z2E5DTKX.js";import{c as Q}from"./chunk-5KGFDNYI.js";import{b as C,d as Z}from"./chunk-5R2DUR3A.js";import{a as V,c as be}from"./chunk-5MGRZ4YD.js";import{a as J,b as Xe}from"./chunk-PUUTYV32.js";import{a as ee,d as b,e as te,f as ne}from"./chunk-GYESQBDU.js";import{a as v,e as De}from"./chunk-WZUQT2BE.js";import{c as R,e as ve}from"./chunk-WULMXLNN.js";function O(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
+ import{d as k,f as we}from"./chunk-MXAEZHW6.js";import{a as ye}from"./chunk-F32R4LVS.js";import{c as Q}from"./chunk-MIST354H.js";import{b as C,d as Z}from"./chunk-JCPXG42O.js";import{a as V,c as be}from"./chunk-NN6VRHNL.js";import{a as J,b as Xe}from"./chunk-WF6MKBRI.js";import{a as ee,d as b,e as te,f as ne}from"./chunk-G7HYTJDG.js";import{a as v,e as De}from"./chunk-J7SDO52P.js";import{c as R,e as ve}from"./chunk-H647PYXW.js";function O(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
3
3
  CREATE TABLE IF NOT EXISTS schema_version (
4
4
  id INTEGER PRIMARY KEY CHECK (id = 1),
5
5
  version INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
2
  import*as o from"fs";import*as l from"path";var m=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??l.join(process.cwd(),".agentic-qe","plugins"),this.keepVersions=e.keepVersions??2}has(e,t){let s=this.versionDir(e,t);return o.existsSync(s)&&o.existsSync(l.join(s,"qe-plugin.json"))}get(e,t){if(!this.has(e,t))return;let s=this.versionDir(e,t),i=o.readFileSync(l.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),c=o.statSync(s);return{manifest:r,path:s,cachedAt:c.birthtime.toISOString()}}store(e,t){let s=this.versionDir(e.name,e.version);return o.existsSync(s)||(o.mkdirSync(s,{recursive:!0}),this.copyDir(t,s),o.writeFileSync(l.join(s,"qe-plugin.json"),JSON.stringify(e,null,2)),this.pruneOldVersions(e.name)),s}remove(e,t){let s=this.versionDir(e,t);return o.existsSync(s)?(o.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let t=l.join(this.cacheDir,e);if(!o.existsSync(t))return[];let s=[],i=o.readdirSync(t);for(let r of i){let c=l.join(t,r),h=l.join(c,"qe-plugin.json");if(o.existsSync(h))try{let a=o.readFileSync(h,"utf-8"),f=JSON.parse(a),u=o.statSync(c);s.push({manifest:f,path:c,cachedAt:u.birthtime.toISOString()})}catch{}}return s}listAll(){if(!o.existsSync(this.cacheDir))return[];let e=[],t=o.readdirSync(this.cacheDir);for(let s of t){let i=this.listVersions(s);i.length>0&&(i.sort((r,c)=>c.manifest.version.localeCompare(r.manifest.version)),e.push(i[0]))}return e}versionDir(e,t){return l.join(this.cacheDir,e,t)}pruneOldVersions(e){let t=this.listVersions(e);if(t.length<=this.keepVersions)return;t.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=t.slice(0,t.length-this.keepVersions);for(let i of s)o.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,t){if(!o.existsSync(e))return;let s=o.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=l.join(e,i.name),c=l.join(t,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;o.mkdirSync(c,{recursive:!0}),this.copyDir(r,c)}else o.copyFileSync(r,c)}}};var R=/^[a-z][a-z0-9-]*$/,S=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/,j=["aqe-core-","agentic-qe-core-"];function E(n){let e=[],t=[];if(!n||typeof n!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=n;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):D(s.name,e,t),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):S.test(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>500&&t.push("description exceeds 500 characters"),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):V(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"&&e.push(`Dependency "${i}" must have a string version range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!S.test(s.minAqeVersion))&&t.push("minAqeVersion should be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:t}}function b(n){let e=typeof n=="string"?JSON.parse(n):n,t=E(e);if(!t.valid)throw new Error(`Invalid plugin manifest:
3
3
  - ${t.errors.join(`
4
4
  - `)}`);return e}function D(n,e,t){n.length>64&&e.push("name must be 64 characters or fewer"),R.test(n)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(n)&&e.push("name must contain only ASCII characters");for(let s of j)n.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(n)&&t.push(`name "${n}" is very generic \u2014 consider a more descriptive name`)}function V(n,e){n.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!n.endsWith(".js")&&!n.endsWith(".ts")&&!n.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var y=class{resolve(e){let t=new Map;for(let a of e)t.set(a.name,a);let s=[],i=new Set,r=new Set,c=new Map,h=(a,f)=>{if(i.has(a))return;if(r.has(a)){let g=[...f.slice(f.indexOf(a)),a];throw new Error(`Dependency cycle detected: ${g.join(" -> ")}`)}let u=t.get(a);if(!u)return;r.add(a);let k=Object.keys(u.dependencies??{}),P=[];for(let g of k)t.has(g)?h(g,[...f,a]):P.push(g);P.length>0&&c.set(a,P),r.delete(a),i.add(a),s.push(u)};for(let a of e)h(a.name,[]);return{ordered:s.map((a,f)=>({manifest:a,order:f})),missing:c}}canLoad(e,t){let i=Object.keys(e.dependencies??{}).filter(r=>!t.has(r));return{canLoad:i.length===0,missingDeps:i}}};var N=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],M=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),_=["..","~","/etc/","/proc/","/dev/","node_modules/"];function A(n){let e=[];return $(n.name,e),q(n.entryPoint,e),C(n.hooks,e),I(n.permissions,e),{safe:e.length===0,violations:e}}function $(n,e){/[^\x20-\x7E]/.test(n)&&e.push(`Plugin name "${n}" contains non-ASCII characters`),M.has(n.toLowerCase())&&e.push(`Plugin name "${n}" is a reserved name`);for(let s of N)n.toLowerCase().startsWith(s)&&e.push(`Plugin name "${n}" uses reserved prefix "${s}"`);let t=n.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");M.has(t)&&e.push(`Plugin name "${n}" is visually similar to a reserved name`)}function q(n,e){w(n,"entryPoint",e),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function C(n,e){if(n)for(let[t,s]of Object.entries(n))w(s,`hook[${t}]`,e)}function w(n,e,t){for(let s of _)n.includes(s)&&t.push(`${e} contains dangerous path pattern "${s}"`);n.includes("\0")&&t.push(`${e} contains null byte (path injection attempt)`)}function I(n,e){if(!n)return;let t=["fs:write-root","net:arbitrary","exec:shell"];for(let s of n)t.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as p from"fs";import*as d from"path";var v=class{type="local";async resolve(e){let t=d.resolve(e),s=d.join(t,"qe-plugin.json");if(!p.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=p.readFileSync(s,"utf-8");return b(i)}async getPluginPath(e){let t=d.resolve(e);if(!p.existsSync(t))throw new Error(`Plugin directory does not exist: ${t}`);return t}};var x=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new m,this.resolver=new y;let t=new v;if(this.sources.set("local",t),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,t="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(t);if(!i)return{success:!1,errors:[`Unknown source type: ${t}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(u){return{success:!1,errors:[`Failed to resolve plugin: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let c=E(r);if(!c.valid)return{success:!1,manifest:r,errors:c.errors,securityViolations:[]};let h=A(r);if(!h.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:h.violations};if(this.cache.has(r.name,r.version)){let u=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:u.path,errors:[],securityViolations:[]}}let a;try{a=await i.getPluginPath(e)}catch(u){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let f=this.cache.store(r,a);return{success:!0,manifest:r,cachePath:f,errors:s,securityViolations:[]}}remove(e,t){if(t)return this.cache.remove(e,t);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(t=>({name:t.manifest.name,version:t.manifest.version,description:t.manifest.description,domains:t.manifest.domains,source:"cached",cachePath:t.path}))}resolveLoadOrder(){let e=this.cache.listAll();return this.resolver.resolve(e.map(t=>t.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{b as a,m as b,x as c};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as $}from"./chunk-AG7J7DTM.js";import{b as S,d as z}from"./chunk-5R2DUR3A.js";import{a as b,c as F}from"./chunk-5MGRZ4YD.js";import{i as v}from"./chunk-MIQAFOFO.js";import*as I from"node:path";$();z();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],R=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function H(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function f(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function C(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},_=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new R}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},i=H(r);return this.config.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as $}from"./chunk-MXAEZHW6.js";import{b as S,d as z}from"./chunk-JCPXG42O.js";import{a as b,c as F}from"./chunk-NN6VRHNL.js";import{i as v}from"./chunk-NQIOXSHW.js";import*as I from"node:path";$();z();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],R=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function H(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function f(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function C(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},_=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new R}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},i=H(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(i.id,i.type,i.name,i.file_path,i.line_start,i.line_end,i.complexity,i.coverage,i.metadata,i.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},i=M(r);return this.config.db.prepare(`
@@ -1,12 +1,12 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
- import{a as E}from"./chunk-6BRUQTC7.js";import{a as b}from"./chunk-Z2E5DTKX.js";import{c as y}from"./chunk-5KGFDNYI.js";import{a as f,c as k}from"./chunk-5MGRZ4YD.js";k();b();var l=y.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function h(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-2ETCY22B.js");o=c().getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
+ import{a as E}from"./chunk-5LM2W3NE.js";import{a as b}from"./chunk-F32R4LVS.js";import{c as y}from"./chunk-MIST354H.js";import{a as f,c as k}from"./chunk-NN6VRHNL.js";k();b();var l=y.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function h(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-JVZZMZRE.js");o=c().getDatabase().prepare(`
3
3
  SELECT u.pattern_id, u.success, u.feedback
4
4
  FROM qe_pattern_usage u
5
5
  JOIN qe_patterns p ON u.pattern_id = p.id
6
6
  WHERE p.qe_domain = 'test-generation'
7
7
  ORDER BY u.created_at DESC
8
8
  LIMIT 10
9
- `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-2ETCY22B.js");r=n().getDatabase().prepare(`
9
+ `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,p=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(p=1)}catch(d){l.debug("Pattern learning failed",{error:d instanceof Error?d.message:String(d)})}return{success:!0,patternsLearned:p,data:{learned:p>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-JVZZMZRE.js");r=n().getDatabase().prepare(`
10
10
  SELECT u.pattern_id, u.success, u.feedback
11
11
  FROM qe_pattern_usage u
12
12
  JOIN qe_patterns p ON u.pattern_id = p.id
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
2
- import{k as K,o as ot}from"./chunk-TXCOK5DC.js";import{a as rt}from"./chunk-Z2E5DTKX.js";import{c as U}from"./chunk-5KGFDNYI.js";import{a as j,c as et}from"./chunk-5MGRZ4YD.js";import{a as G,d as at}from"./chunk-SKNHAGYP.js";import{a as nt,b as it}from"./chunk-YXLQJ226.js";import{c as H,e as V,g as w}from"./chunk-WULMXLNN.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-KAXTFFEE.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-CEVIRL2S.js";import{a as rt}from"./chunk-F32R4LVS.js";import{c as U}from"./chunk-MIST354H.js";import{a as j,c as et}from"./chunk-NN6VRHNL.js";import{a as G,d as at}from"./chunk-AFMLL2G3.js";import{a as nt,b as it}from"./chunk-AVVRA6FG.js";import{c as H,e as V,g as w}from"./chunk-H647PYXW.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-GFNFVEER.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
@@ -1 +1 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
2
  var s={copilot:{id:"copilot",name:"GitHub Copilot",configPath:".vscode/mcp.json",configFormat:"json",configKey:"servers",rulesPath:".github/copilot-instructions.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cursor:{id:"cursor",name:"Cursor",configPath:".cursor/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".cursorrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cline:{id:"cline",name:"Cline",configPath:".vscode/cline_mcp_settings.json",configFormat:"json",configKey:"mcpServers",rulesPath:".vscode/cline_custom_modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},kilocode:{id:"kilocode",name:"Kilo Code",configPath:".kilocode/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".kilocode/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},roocode:{id:"roocode",name:"Roo Code",configPath:".roo/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".roo/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},codex:{id:"codex",name:"OpenAI Codex CLI",configPath:".codex/config.toml",configFormat:"toml",configKey:"mcp_servers",rulesPath:"AGENTS.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},windsurf:{id:"windsurf",name:"Windsurf",configPath:".windsurf/mcp_config.json",configFormat:"json",configKey:"mcpServers",rulesPath:".windsurfrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},continuedev:{id:"continuedev",name:"Continue.dev",configPath:".continue/config.yaml",configFormat:"yaml",configKey:"mcpServers",rulesPath:".continue/rules/aqe-qe-standards.yaml",rulesFormat:"yaml",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1}},i=["fleet_init","fleet_status","fleet_health","agent_list","agent_metrics","agent_status","team_list","team_health","task_list","task_status","test_generate_enhanced","coverage_analyze_sublinear","quality_assess","defect_predict","code_index","memory_store","memory_retrieve","memory_query","memory_usage","model_route","routing_metrics","aqe_health"];function l(n){let e={command:"npx",args:["-y","agentic-qe@latest","mcp"],env:{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_V3_MODE:"true"}};return n&&(e.disabled=!1,e.alwaysAllow=i),e}function c(n){let e=l(n.supportsAutoApprove);if(n.id==="copilot"){let o={[n.configKey]:{"agentic-qe":{type:"stdio",...e}}};return JSON.stringify(o,null,2)+`
3
3
  `}let t={[n.configKey]:{"agentic-qe":e}};return JSON.stringify(t,null,2)+`
4
4
  `}function u(){return`# Agentic QE MCP Server
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.19");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.20");process.exit(0)}
2
2
  var s=["qe-pentest-validator","qe-security-auditor","qe-security-scanner","qe-security-reviewer"],c="anthropic/claude-sonnet-4.6",u="claude-sonnet-4-6";function o(n){return n.includes("claude-opus-4-7")||n.includes("claude-opus-4.7")}function i(n,e=process.env){return e.AQE_CYBER_VERIFIED==="true"?!1:s.includes(n)}function a(n,e,r,t=process.env){return!i(n,t)||!o(e)?e:r}export{c as a,u as b,o as c,i as d,a as e};