agentic-qe 3.9.30 → 3.9.31

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 (326) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +120 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/bridge/captured-experience-bridge.js +31 -2
  5. package/dist/cli/bundle.js +5 -5
  6. package/dist/cli/chunks/adapter-CI2GZYME.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-TOSXWTUQ.js → agent-booster-wasm-AQXZYWZY.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-2BU6TYZZ.js → agent-handler-7N4ZPXCY.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-JFG3BXZY.js → agent-memory-branch-FLKF2JVX.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-KNQKALLI.js +2 -0
  11. package/dist/cli/chunks/{audit-4IGZZKUW.js → audit-B4V4IKTA.js} +2 -2
  12. package/dist/cli/chunks/base-P7PRMQWY.js +2 -0
  13. package/dist/cli/chunks/{hnswlib-node-STKRZIU3.js → better-sqlite3-NYOVLWBG.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-RIDW27HH.js → brain-handler-OOXJ2KYY.js} +4 -4
  15. package/dist/cli/chunks/{branch-enumerator-GMYHLLWD.js → branch-enumerator-LFKFW3A4.js} +2 -2
  16. package/dist/cli/chunks/{browser-N76A3I2P.js → browser-F72IES2I.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-QUP4A763.js +2 -0
  18. package/dist/cli/chunks/{chunk-JCDEMPJS.js → chunk-2NLZXG6V.js} +1 -1
  19. package/dist/cli/chunks/{chunk-ETEHVG76.js → chunk-35SFAIXE.js} +2 -2
  20. package/dist/cli/chunks/{chunk-FG5GL26L.js → chunk-3VKB4HVT.js} +2 -2
  21. package/dist/cli/chunks/{chunk-XKH4E2IQ.js → chunk-462MZLJB.js} +1 -1
  22. package/dist/cli/chunks/{chunk-MZ7M2CDV.js → chunk-47QIAHUJ.js} +2 -2
  23. package/dist/cli/chunks/{chunk-IP6ZTXNJ.js → chunk-4N736EES.js} +2 -2
  24. package/dist/cli/chunks/{chunk-YXR5RYRE.js → chunk-52D3CYE5.js} +2 -2
  25. package/dist/cli/chunks/{chunk-C6TNYLD7.js → chunk-5AMAJCZS.js} +3 -3
  26. package/dist/cli/chunks/{chunk-ZKZTSYPU.js → chunk-5G2L4XRU.js} +2 -2
  27. package/dist/cli/chunks/{chunk-2MKSEL6F.js → chunk-5M4F3PAL.js} +1 -1
  28. package/dist/cli/chunks/{chunk-37I6K7QO.js → chunk-5WWQLPB4.js} +2 -2
  29. package/dist/cli/chunks/chunk-5Z6PYYWK.js +2 -0
  30. package/dist/cli/chunks/{chunk-MHPK4ZPK.js → chunk-62KYX5NH.js} +2 -2
  31. package/dist/cli/chunks/{chunk-TYZGEVP6.js → chunk-7MXQV7RB.js} +12 -6
  32. package/dist/cli/chunks/{chunk-XVTZXCHI.js → chunk-7OVVBBOZ.js} +2 -2
  33. package/dist/cli/chunks/{chunk-MOLOWMON.js → chunk-7RPEBKQZ.js} +2 -2
  34. package/dist/cli/chunks/{chunk-5F26LSG2.js → chunk-7UHRT5AX.js} +2 -2
  35. package/dist/cli/chunks/{chunk-MV3NUANS.js → chunk-7V7TP242.js} +1 -1
  36. package/dist/cli/chunks/{chunk-WTXRPYNN.js → chunk-A424Z7LA.js} +1 -1
  37. package/dist/cli/chunks/{chunk-UYLHIGNC.js → chunk-AKFRM4IO.js} +2 -2
  38. package/dist/cli/chunks/{chunk-OEGFOMXP.js → chunk-AKJWBJDK.js} +2 -2
  39. package/dist/cli/chunks/{chunk-2GBBZLXT.js → chunk-AQN6PDHI.js} +1 -1
  40. package/dist/cli/chunks/{chunk-ITBPDVK5.js → chunk-BMS7WFDB.js} +1 -1
  41. package/dist/cli/chunks/{chunk-2O5TT3UT.js → chunk-BYHUGO73.js} +3 -3
  42. package/dist/cli/chunks/{chunk-CNNVL5W4.js → chunk-CFLA2GBS.js} +2 -2
  43. package/dist/cli/chunks/{chunk-Y57V4FDT.js → chunk-CNKOIHF6.js} +2 -2
  44. package/dist/cli/chunks/{chunk-3EP2YZSY.js → chunk-CQWZNVIM.js} +2 -2
  45. package/dist/cli/chunks/{chunk-GEXVUFK4.js → chunk-CUSLB7MB.js} +2 -2
  46. package/dist/cli/chunks/chunk-CYUGE5ZQ.js +2 -0
  47. package/dist/cli/chunks/{chunk-QNSUPXUU.js → chunk-DMF4Z2M6.js} +2 -2
  48. package/dist/cli/chunks/{chunk-Z3TXQOS7.js → chunk-DUF733Z7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-XK6YXCS7.js → chunk-EAIPJSKH.js} +2 -2
  50. package/dist/cli/chunks/{chunk-TULNR2AH.js → chunk-EJXRBAQF.js} +2 -2
  51. package/dist/cli/chunks/{chunk-XDYTQPJM.js → chunk-EKYPQ5DX.js} +1 -1
  52. package/dist/cli/chunks/{chunk-QBDXUI2H.js → chunk-ENCFLC44.js} +2 -2
  53. package/dist/cli/chunks/{chunk-SAVITYEX.js → chunk-FOAWHNOP.js} +2 -2
  54. package/dist/cli/chunks/{chunk-QOJ7EAF5.js → chunk-FUHPLXJX.js} +1 -1
  55. package/dist/cli/chunks/{chunk-KR2PGNXX.js → chunk-G2U7Q6V6.js} +2 -2
  56. package/dist/cli/chunks/{chunk-DDMFTEJP.js → chunk-G3YKCZWQ.js} +3 -3
  57. package/dist/cli/chunks/{chunk-YETPSL6H.js → chunk-GJSH4UZ3.js} +3 -3
  58. package/dist/cli/chunks/{chunk-BQLFOJ5G.js → chunk-GN7FUCJH.js} +1 -1
  59. package/dist/cli/chunks/{chunk-GY4EGQO3.js → chunk-GQFAVT2I.js} +1 -1
  60. package/dist/cli/chunks/{chunk-IHRFR5SV.js → chunk-HHEIQHLQ.js} +2 -2
  61. package/dist/cli/chunks/{chunk-YKFURJNP.js → chunk-I3TFGMOQ.js} +1 -1
  62. package/dist/cli/chunks/{chunk-LDGNVPBZ.js → chunk-IRRGUXAU.js} +1 -1
  63. package/dist/cli/chunks/{chunk-IWC6GR24.js → chunk-IY4P35N3.js} +2 -2
  64. package/dist/cli/chunks/{chunk-AWWD3EI3.js → chunk-JF3U456G.js} +2 -2
  65. package/dist/cli/chunks/{chunk-5E3YCZC5.js → chunk-JJRZOLDY.js} +2 -2
  66. package/dist/cli/chunks/{chunk-Q53UMLLC.js → chunk-JKKV5KKS.js} +2 -2
  67. package/dist/cli/chunks/{chunk-MYF7F3ZP.js → chunk-JMLOEW7Y.js} +2 -2
  68. package/dist/cli/chunks/chunk-JRIDPOEZ.js +95 -0
  69. package/dist/cli/chunks/{chunk-T2DIMSQF.js → chunk-K37CNLQZ.js} +1 -1
  70. package/dist/cli/chunks/{chunk-RNO6CE7I.js → chunk-K6MFAVXK.js} +2 -2
  71. package/dist/cli/chunks/{chunk-UWWX4RK7.js → chunk-KJAIE7SL.js} +4 -4
  72. package/dist/cli/chunks/{chunk-ND6VCNN5.js → chunk-KXRDQQGN.js} +2 -2
  73. package/dist/cli/chunks/{chunk-GRPEDIYG.js → chunk-L4JTTPU7.js} +2 -2
  74. package/dist/cli/chunks/{chunk-BM73MJLE.js → chunk-L63KB63A.js} +2 -2
  75. package/dist/cli/chunks/{chunk-R57J3O6I.js → chunk-L7DNPOAQ.js} +2 -2
  76. package/dist/cli/chunks/{chunk-SJCEPKZO.js → chunk-LF5RO6WO.js} +1 -1
  77. package/dist/cli/chunks/{chunk-GZ3U2QT2.js → chunk-LRWRFKQH.js} +1 -1
  78. package/dist/cli/chunks/{chunk-QTS2DS42.js → chunk-M6RVKGIP.js} +2 -2
  79. package/dist/cli/chunks/{chunk-ECX6VXMW.js → chunk-MAJ5QFVY.js} +1 -1
  80. package/dist/cli/chunks/chunk-MYCVU3D3.js +14 -0
  81. package/dist/cli/chunks/{chunk-3AICELMQ.js → chunk-N6P7ENG7.js} +2 -2
  82. package/dist/cli/chunks/{chunk-7D2DM23U.js → chunk-N6SIKSCO.js} +2 -2
  83. package/dist/cli/chunks/{chunk-FI4HRS2G.js → chunk-NBKM7NKX.js} +2 -2
  84. package/dist/cli/chunks/{chunk-QSV4ROZD.js → chunk-NLUBN642.js} +2 -2
  85. package/dist/cli/chunks/{chunk-FGDEM4HU.js → chunk-NNF3GCGF.js} +2 -2
  86. package/dist/cli/chunks/{chunk-5DJAJPBG.js → chunk-NTVJKQ5S.js} +2 -2
  87. package/dist/cli/chunks/{chunk-3WIU2E2Y.js → chunk-NZQYNUGM.js} +2 -2
  88. package/dist/cli/chunks/{chunk-52TRKIAQ.js → chunk-ONMJJ2C3.js} +1 -1
  89. package/dist/cli/chunks/{chunk-JNRRDG7O.js → chunk-OXOXNAEZ.js} +2 -2
  90. package/dist/cli/chunks/chunk-PSF6YQQM.js +180 -0
  91. package/dist/cli/chunks/{chunk-WP6X67YI.js → chunk-PTOTOBOU.js} +1 -1
  92. package/dist/cli/chunks/{chunk-UEXOMDRS.js → chunk-PUSZ4NBY.js} +2 -2
  93. package/dist/cli/chunks/chunk-PYYNY7RJ.js +2 -0
  94. package/dist/cli/chunks/{chunk-L7X3A36M.js → chunk-QEJBJST4.js} +1 -1
  95. package/dist/cli/chunks/{chunk-TA3QYAZ6.js → chunk-QGLWFZVQ.js} +2 -2
  96. package/dist/cli/chunks/{chunk-HB52S6IV.js → chunk-QITO7E7Y.js} +1 -1
  97. package/dist/cli/chunks/{chunk-KJZXBZQR.js → chunk-QMSDKKYG.js} +1 -1
  98. package/dist/cli/chunks/{chunk-AQJ6XS34.js → chunk-RBDAHW2M.js} +2 -2
  99. package/dist/cli/chunks/{chunk-VOBNJWZF.js → chunk-RDJWUKIR.js} +2 -2
  100. package/dist/cli/chunks/{chunk-EWNJ6OAT.js → chunk-REJEFTWX.js} +1 -1
  101. package/dist/cli/chunks/{chunk-H27XUYWZ.js → chunk-ROEIR3OD.js} +1 -1
  102. package/dist/cli/chunks/{chunk-JCWHX4XV.js → chunk-RTGNWRQI.js} +2 -2
  103. package/dist/cli/chunks/{chunk-FU74OETU.js → chunk-SL4TAJOE.js} +2 -2
  104. package/dist/cli/chunks/{chunk-3PZDXE5E.js → chunk-T4DDCMKG.js} +113 -113
  105. package/dist/cli/chunks/{chunk-UROPIIB2.js → chunk-TJGIIGKL.js} +2 -2
  106. package/dist/cli/chunks/{chunk-BFJLKG3D.js → chunk-TLCCM2AF.js} +1 -1
  107. package/dist/cli/chunks/{chunk-HJDHQBMJ.js → chunk-TVHWI77X.js} +1 -1
  108. package/dist/cli/chunks/{chunk-ER6BT4GS.js → chunk-TYUIQSSF.js} +2 -2
  109. package/dist/cli/chunks/{chunk-R5IW5ARI.js → chunk-UIIEZMSM.js} +1 -1
  110. package/dist/cli/chunks/{chunk-NMBHF7ZD.js → chunk-UIRTXM7C.js} +15 -15
  111. package/dist/cli/chunks/{chunk-RYMHYTOK.js → chunk-UNXUSYRL.js} +3 -3
  112. package/dist/cli/chunks/chunk-VA45HLBF.js +2 -0
  113. package/dist/cli/chunks/{chunk-DEDFPHJL.js → chunk-VAIOZDG5.js} +1 -1
  114. package/dist/cli/chunks/{chunk-IEGAEXQX.js → chunk-VLAGWLHF.js} +2 -2
  115. package/dist/cli/chunks/{chunk-WVODEWH5.js → chunk-VOOJDHLI.js} +14 -8
  116. package/dist/cli/chunks/{chunk-IOINZWNA.js → chunk-VSKABN3B.js} +29 -17
  117. package/dist/cli/chunks/{chunk-HQIWLMDS.js → chunk-VUL5HIKR.js} +2 -2
  118. package/dist/cli/chunks/{chunk-OOFWYDG6.js → chunk-W7XVEWKQ.js} +1 -1
  119. package/dist/cli/chunks/{chunk-Q4HJRYQB.js → chunk-WB6TI6Q3.js} +2 -2
  120. package/dist/cli/chunks/{chunk-DJRWVNHK.js → chunk-X2FLWV5C.js} +2 -2
  121. package/dist/cli/chunks/{chunk-QLNS6DGB.js → chunk-XE4YKDIM.js} +2 -2
  122. package/dist/cli/chunks/{chunk-6EP3GHED.js → chunk-XGBIXRKD.js} +2 -2
  123. package/dist/cli/chunks/{chunk-AUNNGKLN.js → chunk-XMMWYQJK.js} +2 -2
  124. package/dist/cli/chunks/{chunk-FGMHVSLV.js → chunk-XNJ6DIEW.js} +2 -2
  125. package/dist/cli/chunks/{chunk-4UZQSPR4.js → chunk-XTWYCMAM.js} +2 -2
  126. package/dist/cli/chunks/{chunk-2NFGUFYU.js → chunk-XY3WUGD3.js} +2 -2
  127. package/dist/cli/chunks/{chunk-VRP4GB4Y.js → chunk-YEZJE2ZW.js} +4 -4
  128. package/dist/cli/chunks/{chunk-MCXRS2TZ.js → chunk-YLEMSN46.js} +1 -1
  129. package/dist/cli/chunks/{chunk-Q26GG6WO.js → chunk-YMN4C32S.js} +3 -3
  130. package/dist/cli/chunks/{chunk-HA7N45KB.js → chunk-YN7HCVUP.js} +2 -2
  131. package/dist/cli/chunks/{chunk-E7UHOKKL.js → chunk-YQJBE6NX.js} +2 -2
  132. package/dist/cli/chunks/{chunk-OTFJCZNY.js → chunk-ZBJRNCWX.js} +2 -2
  133. package/dist/cli/chunks/{chunk-QHKK2H4H.js → chunk-ZG4EKPGV.js} +1 -1
  134. package/dist/cli/chunks/{chunk-USN2JKUW.js → chunk-ZWSRIJ2T.js} +2 -2
  135. package/dist/cli/chunks/{ci-BYCH3NPL.js → ci-LRTJSZHT.js} +2 -2
  136. package/dist/cli/chunks/{ci-output-P7P4XH6F.js → ci-output-LISCHUKD.js} +2 -2
  137. package/dist/cli/chunks/{circuit-breaker-VLX556ZI.js → circuit-breaker-7PMP25KZ.js} +2 -2
  138. package/dist/cli/chunks/{claude-flow-setup-JPR425PL.js → claude-flow-setup-DOW4QVMC.js} +2 -2
  139. package/dist/cli/chunks/client-XF6SJO2C.js +2 -0
  140. package/dist/cli/chunks/{cline-installer-FOY47NSH.js → cline-installer-2NXQGW73.js} +2 -2
  141. package/dist/cli/chunks/{code-57SN4ZDY.js → code-3X6RWAS7.js} +2 -2
  142. package/dist/cli/chunks/{code-index-extractor-GT7UFRYU.js → code-index-extractor-4ABP5WCP.js} +2 -2
  143. package/dist/cli/chunks/{codex-installer-JAGWONAV.js → codex-installer-V7PII6GL.js} +2 -2
  144. package/dist/cli/chunks/{completions-7YLHPGSV.js → completions-Y7LNQ63I.js} +2 -2
  145. package/dist/cli/chunks/{complexity-analyzer-TQUF6BEI.js → complexity-analyzer-XLYMAM6I.js} +2 -2
  146. package/dist/cli/chunks/{continuedev-installer-TICV6IGT.js → continuedev-installer-GOT4TKNT.js} +2 -2
  147. package/dist/cli/chunks/{copilot-installer-A6PDMI52.js → copilot-installer-D6BAQVIO.js} +2 -2
  148. package/dist/cli/chunks/{cost-tracker-NZPNHNV2.js → cost-tracker-VT7C5Q52.js} +2 -2
  149. package/dist/cli/chunks/{coverage-HBEB2LKS.js → coverage-C62MRP4M.js} +3 -3
  150. package/dist/cli/chunks/cross-domain-router-J2OFPM6R.js +2 -0
  151. package/dist/cli/chunks/{cursor-installer-R4FM7MGN.js → cursor-installer-WAWSS2K2.js} +2 -2
  152. package/dist/cli/chunks/{daemon-PHIZPZIE.js → daemon-CP2ETHRF.js} +3 -3
  153. package/dist/cli/chunks/{dag-attention-scheduler-2L7VCYZ3.js → dag-attention-scheduler-SZIZWPV7.js} +2 -2
  154. package/dist/cli/chunks/{detect-EEWB4IYE.js → detect-AJX6NJEP.js} +2 -2
  155. package/dist/cli/chunks/{dist-node-7RM6BB2X.js → dist-node-E5X47QTY.js} +2 -2
  156. package/dist/cli/chunks/{domain-handler-RVGHBDUJ.js → domain-handler-FN3PIP45.js} +2 -2
  157. package/dist/cli/chunks/{domain-transfer-M5MERQG5.js → domain-transfer-N3TOJEMT.js} +2 -2
  158. package/dist/cli/chunks/dream-D5LD5SOZ.js +2 -0
  159. package/dist/cli/chunks/{embed-and-insert-pattern-MS55QS73.js → embed-and-insert-pattern-PJI5TZKR.js} +2 -2
  160. package/dist/cli/chunks/{eval-MBTMI7KN.js → eval-OS54TDQU.js} +2 -2
  161. package/dist/cli/chunks/{experience-capture-middleware-Z5XB7D6A.js → experience-capture-middleware-FBM4ANZW.js} +3 -3
  162. package/dist/cli/chunks/{fast-paths-FSWLHI4I.js → fast-paths-2CVAAPQO.js} +2 -2
  163. package/dist/cli/chunks/{feature-flags-QUPNH2J5.js → feature-flags-A5KFWVFC.js} +2 -2
  164. package/dist/cli/chunks/{feature-flags-ATYOPR5D.js → feature-flags-GEXTW6OT.js} +2 -2
  165. package/dist/cli/chunks/{file-discovery-SOJJEQ2E.js → file-discovery-KWLVC7KN.js} +2 -2
  166. package/dist/cli/chunks/{fleet-PWBTDWVG.js → fleet-MNKH356S.js} +3 -3
  167. package/dist/cli/chunks/{gnn-wrapper-2N67VQOQ.js → gnn-wrapper-ALTWYFVZ.js} +2 -2
  168. package/dist/cli/chunks/{heartbeat-handler-5PSG2UPO.js → heartbeat-handler-MBMEPEGW.js} +4 -4
  169. package/dist/cli/chunks/{heartbeat-scheduler-CNJBAO5C.js → heartbeat-scheduler-OH3SS7MH.js} +2 -2
  170. package/dist/cli/chunks/hnsw-adapter-M2MMM3N6.js +2 -0
  171. package/dist/cli/chunks/hnsw-index-JO7KNF7M.js +2 -0
  172. package/dist/cli/chunks/{hnsw-legacy-bridge-YIXH5T4U.js → hnsw-legacy-bridge-WTD5PR5V.js} +2 -2
  173. package/dist/cli/chunks/{better-sqlite3-3U2AVWQ3.js → hnswlib-node-WENGW3YX.js} +2 -2
  174. package/dist/cli/chunks/hooks-ELHGEBFK.js +248 -0
  175. package/dist/cli/chunks/{hybrid-router-RL47S47Z.js → hybrid-router-D6ZMIZCE.js} +2 -2
  176. package/dist/cli/chunks/{hypergraph-engine-XW2IHFWW.js → hypergraph-engine-JOQ6TERZ.js} +2 -2
  177. package/dist/cli/chunks/{hypergraph-handler-AQXKY4UF.js → hypergraph-handler-HX45YWWN.js} +3 -3
  178. package/dist/cli/chunks/impact-analyzer-ROQL4J7P.js +2 -0
  179. package/dist/cli/chunks/{init-handler-KXYGJQI5.js → init-handler-TNVU6NQ6.js} +6 -6
  180. package/dist/cli/chunks/init-wizard-4BDFZX4M.js +2 -0
  181. package/dist/cli/chunks/kernel-37Y63WKR.js +2 -0
  182. package/dist/cli/chunks/{kilocode-installer-VSULDGRO.js → kilocode-installer-YC5RJIY4.js} +2 -2
  183. package/dist/cli/chunks/{kiro-installer-SH4D2UXW.js → kiro-installer-EAB26M55.js} +2 -2
  184. package/dist/cli/chunks/knowledge-graph-V3DX6ZCX.js +2 -0
  185. package/dist/cli/chunks/learning-A2OB7D2B.js +117 -0
  186. package/dist/cli/chunks/{llm-router-YXXSQX5K.js → llm-router-KEG6PA7C.js} +4 -4
  187. package/dist/cli/chunks/{load-S52R2SLL.js → load-D6ZDLVA3.js} +2 -2
  188. package/dist/cli/chunks/load-test-HPBA2CMT.js +2 -0
  189. package/dist/cli/chunks/{mcp-ZWMAJIU7.js → mcp-ERJHZ6FN.js} +2 -2
  190. package/dist/cli/chunks/{memory-4YTWWDK7.js → memory-GSRIJIVR.js} +5 -5
  191. package/dist/cli/chunks/memory-backend-DODDBB46.js +2 -0
  192. package/dist/cli/chunks/memory-handlers-MFLCRS7V.js +2 -0
  193. package/dist/cli/chunks/{multi-model-executor-F3VEM2UF.js → multi-model-executor-GK3V7ERC.js} +2 -2
  194. package/dist/cli/chunks/{opencode-installer-Z2CUJQ6D.js → opencode-installer-6TTN26RG.js} +2 -2
  195. package/dist/cli/chunks/{orchestrator-UPXR2XOF.js → orchestrator-YVTSM6QW.js} +37 -18
  196. package/dist/cli/chunks/{pipeline-6MEMAIXM.js → pipeline-EWLJCY5G.js} +2 -2
  197. package/dist/cli/chunks/{platform-H72FLOM7.js → platform-2ULHQQME.js} +2 -2
  198. package/dist/cli/chunks/{plugin-GIMQFDVR.js → plugin-PYN2KOXA.js} +2 -2
  199. package/dist/cli/chunks/{prime-radiant-advanced-wasm-DM5FR5SV.js → prime-radiant-advanced-wasm-IULCTOGZ.js} +2 -2
  200. package/dist/cli/chunks/protocol-executor-D56OYMCJ.js +2 -0
  201. package/dist/cli/chunks/{protocol-handler-YW3N333B.js → protocol-handler-FZYI2SBP.js} +2 -2
  202. package/dist/cli/chunks/{prove-IJY524KK.js → prove-DN7S74SP.js} +2 -2
  203. package/dist/cli/chunks/{provider-manager-FNG6YR2V.js → provider-manager-FT3MCROB.js} +2 -2
  204. package/dist/cli/chunks/qe-reasoning-bank-KXROIEK7.js +2 -0
  205. package/dist/cli/chunks/{quality-EZLAMSCP.js → quality-ITBU6LGC.js} +2 -2
  206. package/dist/cli/chunks/queen-coordinator-XOGATERL.js +2 -0
  207. package/dist/cli/chunks/{real-embeddings-MFRCC6GH.js → real-embeddings-PZUZ5RXJ.js} +2 -2
  208. package/dist/cli/chunks/{roocode-installer-H3ZIRGWU.js → roocode-installer-2LMVZOUZ.js} +2 -2
  209. package/dist/cli/chunks/router-3EHNUCOM.js +2 -0
  210. package/dist/cli/chunks/routing-feedback-ZHKGET22.js +2 -0
  211. package/dist/cli/chunks/{routing-handler-T2A7FYHW.js → routing-handler-5RB73UCF.js} +2 -2
  212. package/dist/cli/chunks/{ruvector-commands-TCLWBP2M.js → ruvector-commands-VBN4APMG.js} +2 -2
  213. package/dist/cli/chunks/{rvf-dual-writer-BE3JCPYC.js → rvf-dual-writer-BNY4AUWT.js} +2 -2
  214. package/dist/cli/chunks/{rvf-migration-adapter-MLUX5YGR.js → rvf-migration-adapter-73MKPBGV.js} +2 -2
  215. package/dist/cli/chunks/{rvf-migration-coordinator-OAQXTASZ.js → rvf-migration-coordinator-SGVB7ZAZ.js} +2 -2
  216. package/dist/cli/chunks/rvf-native-adapter-4YC5IQUW.js +2 -0
  217. package/dist/cli/chunks/safe-db-PLJRHQIC.js +2 -0
  218. package/dist/cli/chunks/schedule-7DGELVJE.js +2 -0
  219. package/dist/cli/chunks/scheduler-VWASEC2J.js +2 -0
  220. package/dist/cli/chunks/{security-SHWJWJ4M.js → security-XUH4H7R3.js} +3 -3
  221. package/dist/cli/chunks/shared-rvf-adapter-DCVDY2XW.js +2 -0
  222. package/dist/cli/chunks/{shared-rvf-dual-writer-BKSR2FFK.js → shared-rvf-dual-writer-GML4EDYF.js} +2 -2
  223. package/dist/cli/chunks/sqlite-persistence-CTEBGVOW.js +2 -0
  224. package/dist/cli/chunks/{status-handler-QK5KMKYC.js → status-handler-XI7GJF6Z.js} +2 -2
  225. package/dist/cli/chunks/{structural-health-3BRNCAYQ.js → structural-health-WPCYKOXV.js} +2 -2
  226. package/dist/cli/chunks/{sync-5CDYOT3H.js → sync-SFKTCRZC.js} +2 -2
  227. package/dist/cli/chunks/{task-handler-VH2CLUIA.js → task-handler-FZB55IEG.js} +2 -2
  228. package/dist/cli/chunks/{task-handlers-BUZNV2VX.js → task-handlers-EXZGFH7F.js} +3 -3
  229. package/dist/cli/chunks/{test-K24JQQZ2.js → test-XYRN4OVU.js} +4 -4
  230. package/dist/cli/chunks/{test-scheduling-MHXRV5VI.js → test-scheduling-FLVOPGOT.js} +3 -3
  231. package/dist/cli/chunks/{token-bootstrap-3NZDLG52.js → token-bootstrap-FDCFVRHM.js} +2 -2
  232. package/dist/cli/chunks/{token-usage-C4BGA2O7.js → token-usage-MHNZF3DM.js} +2 -2
  233. package/dist/cli/chunks/{transformers-ZIIFB2V4.js → transformers-4CRVTMWY.js} +2 -2
  234. package/dist/cli/chunks/{tree-sitter-wasm-parser-GES2AV7A.js → tree-sitter-wasm-parser-CI3V4AND.js} +2 -2
  235. package/dist/cli/chunks/{types-L3MO5VNC.js → types-RKCD4BNL.js} +2 -2
  236. package/dist/cli/chunks/unified-memory-YDKXKW3D.js +2 -0
  237. package/dist/cli/chunks/unified-memory-hnsw-6N7YZCLR.js +2 -0
  238. package/dist/cli/chunks/unified-persistence-UTWLPUQI.js +2 -0
  239. package/dist/cli/chunks/{upgrade-EKJYS5S5.js → upgrade-463W7VKH.js} +2 -2
  240. package/dist/cli/chunks/{validate-WYWWB5PQ.js → validate-LENSMEAY.js} +2 -2
  241. package/dist/cli/chunks/{validate-swarm-SBSWKJ3H.js → validate-swarm-4FEBNAWA.js} +2 -2
  242. package/dist/cli/chunks/{vibium-VEMTLNFV.js → vibium-TXNVIVWJ.js} +2 -2
  243. package/dist/cli/chunks/visual-security-DGXSOFKD.js +2 -0
  244. package/dist/cli/chunks/{web-tree-sitter-STW2WR2J.js → web-tree-sitter-BZEGWID4.js} +2 -2
  245. package/dist/cli/chunks/{windsurf-installer-6ZXMJASZ.js → windsurf-installer-7AFXJTPU.js} +2 -2
  246. package/dist/cli/chunks/{witness-chain-PTULB4MR.js → witness-chain-G6SUZOZG.js} +2 -2
  247. package/dist/cli/chunks/witness-chain-VP4MF6EU.js +2 -0
  248. package/dist/cli/chunks/{workflow-TEBAAHNR.js → workflow-EVQPO6FH.js} +4 -4
  249. package/dist/cli/chunks/workflow-orchestrator-VXSYAKQY.js +2 -0
  250. package/dist/cli/chunks/{wrappers-DVMVRKXK.js → wrappers-HR6RUDI2.js} +2 -2
  251. package/dist/cli/commands/hooks-handlers/editing-hooks.js +9 -3
  252. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +16 -24
  253. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +1 -1
  254. package/dist/cli/commands/hooks-handlers/hooks-shared.js +8 -1
  255. package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -3
  256. package/dist/cli/commands/hooks-handlers/task-hooks.js +37 -46
  257. package/dist/cli/commands/learning.js +194 -0
  258. package/dist/init/phases/10-workers.js +20 -1
  259. package/dist/kernel/interfaces.d.ts +12 -0
  260. package/dist/kernel/kernel.d.ts +1 -0
  261. package/dist/kernel/kernel.js +57 -0
  262. package/dist/kernel/unified-memory-schemas.d.ts +1 -1
  263. package/dist/kernel/unified-memory-schemas.js +7 -1
  264. package/dist/learning/agent-routing.d.ts +134 -1
  265. package/dist/learning/agent-routing.js +185 -2
  266. package/dist/learning/dream/dream-insights-pruner.d.ts +49 -0
  267. package/dist/learning/dream/dream-insights-pruner.js +53 -0
  268. package/dist/learning/dream/dream-scheduler.js +17 -0
  269. package/dist/learning/loop-health.d.ts +84 -0
  270. package/dist/learning/loop-health.js +91 -0
  271. package/dist/learning/pattern-usage-recorder.d.ts +58 -0
  272. package/dist/learning/pattern-usage-recorder.js +72 -0
  273. package/dist/learning/qe-reasoning-bank-types.d.ts +11 -0
  274. package/dist/learning/qe-reasoning-bank.d.ts +11 -0
  275. package/dist/learning/qe-reasoning-bank.js +86 -3
  276. package/dist/learning/routing-topology-gate.d.ts +40 -0
  277. package/dist/learning/routing-topology-gate.js +55 -0
  278. package/dist/learning/sqlite-persistence.d.ts +6 -1
  279. package/dist/learning/sqlite-persistence.js +14 -20
  280. package/dist/mcp/bundle.js +3831 -3805
  281. package/dist/routing/routing-feedback.js +7 -3
  282. package/dist/routing/routing-outcomes-migration.d.ts +31 -0
  283. package/dist/routing/routing-outcomes-migration.js +60 -0
  284. package/dist/workers/workers/learning-consolidation.d.ts +28 -0
  285. package/dist/workers/workers/learning-consolidation.js +204 -0
  286. package/package.json +1 -1
  287. package/dist/cli/chunks/adapter-HV42JOZD.js +0 -2
  288. package/dist/cli/chunks/aqe-learning-engine-GL22PE2V.js +0 -2
  289. package/dist/cli/chunks/base-4KQ2FGUX.js +0 -2
  290. package/dist/cli/chunks/browser-workflow-CTE7BDM4.js +0 -2
  291. package/dist/cli/chunks/chunk-3NGNSKL3.js +0 -14
  292. package/dist/cli/chunks/chunk-6HSFZ6SL.js +0 -180
  293. package/dist/cli/chunks/chunk-7Z3GBQNV.js +0 -2
  294. package/dist/cli/chunks/chunk-H2IMXQCJ.js +0 -2
  295. package/dist/cli/chunks/chunk-SPCANEJY.js +0 -95
  296. package/dist/cli/chunks/client-FRVNMXQO.js +0 -2
  297. package/dist/cli/chunks/cross-domain-router-BVCPAWG2.js +0 -2
  298. package/dist/cli/chunks/dream-77ODIFIF.js +0 -2
  299. package/dist/cli/chunks/hnsw-adapter-CQGQS3V7.js +0 -2
  300. package/dist/cli/chunks/hnsw-index-2ACF6FOJ.js +0 -2
  301. package/dist/cli/chunks/hooks-YROFO6PE.js +0 -259
  302. package/dist/cli/chunks/impact-analyzer-LWEGK23B.js +0 -2
  303. package/dist/cli/chunks/init-wizard-7BS3QMWR.js +0 -2
  304. package/dist/cli/chunks/kernel-TX67WXSI.js +0 -2
  305. package/dist/cli/chunks/knowledge-graph-TDSP2UE2.js +0 -2
  306. package/dist/cli/chunks/learning-RRWV3SEL.js +0 -107
  307. package/dist/cli/chunks/load-test-GEBBBUMV.js +0 -2
  308. package/dist/cli/chunks/memory-backend-WQS2MLW2.js +0 -2
  309. package/dist/cli/chunks/memory-handlers-RTY5MBA5.js +0 -2
  310. package/dist/cli/chunks/protocol-executor-DT7XHMLL.js +0 -2
  311. package/dist/cli/chunks/qe-reasoning-bank-LDNETZVA.js +0 -2
  312. package/dist/cli/chunks/queen-coordinator-AF7HCQSM.js +0 -2
  313. package/dist/cli/chunks/router-OWQ5EI72.js +0 -2
  314. package/dist/cli/chunks/routing-feedback-B43DEQMK.js +0 -2
  315. package/dist/cli/chunks/rvf-native-adapter-XBJDXHNI.js +0 -2
  316. package/dist/cli/chunks/safe-db-RT3LEDUG.js +0 -2
  317. package/dist/cli/chunks/schedule-EHUDCKS2.js +0 -2
  318. package/dist/cli/chunks/scheduler-GEGZ4J3C.js +0 -2
  319. package/dist/cli/chunks/shared-rvf-adapter-LNBUNRAM.js +0 -2
  320. package/dist/cli/chunks/sqlite-persistence-3DGRJH3K.js +0 -2
  321. package/dist/cli/chunks/unified-memory-ZSBX4LYU.js +0 -2
  322. package/dist/cli/chunks/unified-memory-hnsw-Y6EKAMRP.js +0 -2
  323. package/dist/cli/chunks/unified-persistence-2PDVU2U5.js +0 -2
  324. package/dist/cli/chunks/visual-security-RHMFLKVQ.js +0 -2
  325. package/dist/cli/chunks/witness-chain-QO237QOF.js +0 -2
  326. package/dist/cli/chunks/workflow-orchestrator-RHM5MIGE.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{a as g}from"./chunk-YXR5RYRE.js";import{b as p,c}from"./chunk-LDGNVPBZ.js";import{a as x,b as f,c as w}from"./chunk-RNO6CE7I.js";import{i as v}from"./chunk-GY4EGQO3.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{a as g}from"./chunk-52D3CYE5.js";import{b as p,c}from"./chunk-IRRGUXAU.js";import{a as x,b as f,c as w}from"./chunk-K6MFAVXK.js";import{i as v}from"./chunk-GQFAVT2I.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{k as K,o as ot}from"./chunk-TYZGEVP6.js";import{a as rt}from"./chunk-7Z3GBQNV.js";import{c as U}from"./chunk-3WIU2E2Y.js";import{a as j,c as et}from"./chunk-RNO6CE7I.js";import{a as G,d as at}from"./chunk-37I6K7QO.js";import{a as nt,b as it}from"./chunk-QNSUPXUU.js";import{c as H,e as V,g as w}from"./chunk-ITBPDVK5.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-2N67VQOQ.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.31");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-7MXQV7RB.js";import{a as rt}from"./chunk-5Z6PYYWK.js";import{c as U}from"./chunk-NZQYNUGM.js";import{a as j,c as et}from"./chunk-K6MFAVXK.js";import{a as G,d as at}from"./chunk-5WWQLPB4.js";import{a as nt,b as it}from"./chunk-DMF4Z2M6.js";import{c as H,e as V,g as w}from"./chunk-BMS7WFDB.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-ALTWYFVZ.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,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.30");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.31");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.30");process.exit(0)}
2
- import{a as v}from"./chunk-7Z3GBQNV.js";import{c as l}from"./chunk-3WIU2E2Y.js";import{S as R,b as g}from"./chunk-UYLHIGNC.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.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.31");process.exit(0)}
2
+ import{a as v}from"./chunk-5Z6PYYWK.js";import{c as l}from"./chunk-NZQYNUGM.js";import{S as R,b as g}from"./chunk-AKFRM4IO.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain_receipts (
4
4
  id TEXT PRIMARY KEY,
5
5
  chain_index INTEGER NOT NULL,
@@ -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.30");process.exit(0)}
2
- import{a as y}from"./chunk-WTXRPYNN.js";import{a as g,c as h}from"./chunk-H2IMXQCJ.js";import{S as b,b as p}from"./chunk-UYLHIGNC.js";b();var m=class{calculator;constructor(){this.calculator=new g}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new h;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{a as y}from"./chunk-A424Z7LA.js";import{a as g,c as h}from"./chunk-PYYNY7RJ.js";import{S as b,b as p}from"./chunk-AKFRM4IO.js";b();var m=class{calculator;constructor(){this.calculator=new h}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new g;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{i as e}from"./chunk-GY4EGQO3.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},o={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},s={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...o,...s,...d,...l,...c,...m,...p};export{g as a,i as b,o as c,s as d,d as e,l as f,c as g,m as h,p as i};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{i as e}from"./chunk-GQFAVT2I.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},o={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},s={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...o,...s,...d,...l,...c,...m,...p};export{g as a,i as b,o as c,s as d,d as e,l as f,c as g,m as h,p as i};
@@ -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.30");process.exit(0)}
2
- import{a as v}from"./chunk-QHKK2H4H.js";import{a as h}from"./chunk-7Z3GBQNV.js";import{c as E}from"./chunk-3WIU2E2Y.js";import{a as y,c as b}from"./chunk-RNO6CE7I.js";b();h();var l=E.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 Q(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-ZSBX4LYU.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.31");process.exit(0)}
2
+ import{a as v}from"./chunk-ZG4EKPGV.js";import{a as h}from"./chunk-5Z6PYYWK.js";import{c as E}from"./chunk-NZQYNUGM.js";import{a as y,c as b}from"./chunk-K6MFAVXK.js";b();h();var l=E.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 Q(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-YDKXKW3D.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,d=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&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>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-ZSBX4LYU.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,d=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&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>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-YDKXKW3D.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.30");process.exit(0)}
2
- import{d as m}from"./chunk-37I6K7QO.js";import{d as T}from"./chunk-KR2PGNXX.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{d as m}from"./chunk-5WWQLPB4.js";import{d as T}from"./chunk-G2U7Q6V6.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");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.31");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
@@ -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.30");process.exit(0)}
2
- import{c as t}from"./chunk-ITBPDVK5.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{c as t}from"./chunk-BMS7WFDB.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{a as e,b as g,e as r}from"./chunk-NZQYNUGM.js";import{c as o}from"./chunk-BMS7WFDB.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
2
- import{a as C,f as x}from"./chunk-H27XUYWZ.js";import{a as h}from"./chunk-2MKSEL6F.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{a as C,f as x}from"./chunk-ROEIR3OD.js";import{a as h}from"./chunk-5M4F3PAL.js";var d={mechanical:["convert var to const","add types","remove console","convert to async","convert to esm","arrow function","rename variable","format code"],simple:["fix typo","update comment","fix simple bug","add documentation","format","rename","simple refactor","basic test"],moderate:["implement feature","implement","refactor","complex refactor","performance optimization","optimize","test generation","generate test","error handling","validation logic","api integration","code index","coverage analysis","quality assessment","defect prediction","predict defect","analyze coverage","analyze","assess","scan","detect"],complex:["multi-file refactor","orchestrate","coordinate","large codebase","migration","cross-domain","workflow","system design","analyze security","security scan","security analysis","vulnerability scan","chaos test","resilience test","contract validation"],critical:["architecture","security audit","critical bug","algorithm design","system-wide","vulnerability","cryptography","performance critical","hardcoded secret","cve","owasp","penetration test","exploit"]},f={architecture:/\b(architect|design|system design|overall structure|component design)\b/i,security:/\b(security|vulnerability|audit|xss|sql injection|csrf|encryption|auth|authentication|authorization)\b/i,multiStep:/\b(orchestrate|coordinate|workflow|pipeline|multi[- ]step)\b/i,crossDomain:/\b(cross[- ]domain|across (domains|modules)|integrate|coordination)\b/i},m=class{config;agentBoosterAdapter;constructor(e,t){this.config=e,this.agentBoosterAdapter=t}async collectSignals(e){let t=e.task.toLowerCase(),r=await this.checkAgentBoosterEligibility(e),o={simple:this.findKeywordMatches(t,d.simple),moderate:this.findKeywordMatches(t,d.moderate),complex:this.findKeywordMatches(t,d.complex),critical:this.findKeywordMatches(t,d.critical)},c=e.codeContext?e.codeContext.split(`
3
3
  `).length:void 0,n=e.filePaths?e.filePaths.length:void 0,i=f.architecture.test(t),a=f.security.test(t),l=f.multiStep.test(t),g=f.crossDomain.test(t),b=this.detectCreativityRequirement(t),S=this.estimateLanguageComplexity(e.codeContext,e.filePaths),T=e.codeContext?this.estimateCyclomaticComplexity(e.codeContext):void 0;return{linesOfCode:c,fileCount:n,hasArchitectureScope:i,hasSecurityScope:a,requiresMultiStepReasoning:l,requiresCrossDomainCoordination:g,isMechanicalTransform:r.eligible,languageComplexity:S,cyclomaticComplexity:T,dependencyCount:this.countDependencies(e.codeContext),requiresCreativity:b,detectedTransformType:r.transformType,keywordMatches:o}}async checkAgentBoosterEligibility(e){if(!this.config.enableAgentBooster)return{eligible:!1,confidence:0,reason:"Agent Booster is disabled"};let t=e.task.toLowerCase(),r,o=0;for(let n of h){let i=this.getTransformKeywords(n),a=0;for(let l of i)t.includes(l.toLowerCase())&&(a=a===0?.5:a+.25);for(let l of d.mechanical)t.includes(l.toLowerCase())&&(a=Math.max(a,.6));a>o&&(o=a,r=n)}if(e.codeContext&&r&&this.agentBoosterAdapter)try{let i=(await this.agentBoosterAdapter.detectTransformOpportunities(e.codeContext)).opportunities.find(a=>a.type===r);if(i)return{eligible:i.confidence>=this.config.agentBoosterThreshold,transformType:r,confidence:i.confidence,reason:i.reason}}catch(n){console.debug("[SignalCollector] WASM analysis error:",n instanceof Error?n.message:n)}let c=o>=this.config.agentBoosterThreshold&&r!==void 0;return{eligible:c,transformType:r,confidence:Math.min(o,1),reason:c?`Detected ${r} transform pattern`:"No mechanical transform pattern detected"}}findKeywordMatches(e,t){let r=[];for(let o of t)e.includes(o.toLowerCase())&&r.push(o);return r}detectCreativityRequirement(e){return e.includes("design")||e.includes("creative")||e.includes("innovative")||e.includes("novel")}estimateLanguageComplexity(e,t){if(!e&&(!t||t.length===0))return;let r=[".ts",".tsx",".rs",".cpp",".c",".go"],o=[".js",".jsx",".py",".java"],c=[".json",".yaml",".md",".txt",".css",".html"];if(t){for(let n of t)if(r.some(i=>n.endsWith(i)))return"high";for(let n of t)if(o.some(i=>n.endsWith(i)))return"medium";for(let n of t)if(c.some(i=>n.endsWith(i)))return"low"}if(e){let n=/<[A-Z][^>]*>/.test(e),i=/\b(async|await)\b/.test(e),a=/\b(interface|type|class)\b/.test(e);return n&&a?"high":i||a?"medium":"low"}return"medium"}estimateCyclomaticComplexity(e){let t=[/\bif\b/g,/\bfor\b/g,/\bwhile\b/g,/\bcase\b/g,/\bcatch\b/g,/&&/g,/\|\|/g,/\?/g],r=1;for(let o of t){let c=e.match(o);c&&(r+=c.length)}return r}countDependencies(e){if(!e)return;let t=e.match(/\b(import|require|from)\b.*['"].*['"]/g);return t?t.length:0}getTransformKeywords(e){return{"var-to-const":["var to const","convert var","var declaration","var to let","convert var to const","change var to const"],"add-types":["add types","add type","typescript types","type annotations","type annotation","add type annotations"],"remove-console":["remove console","delete console","console.log","remove console.log","strip console"],"promise-to-async":["promise to async","async await",".then to async","convert to async","convert function to async"],"cjs-to-esm":["commonjs to esm","require to import","convert to esm","cjs to esm","module conversion"],"func-to-arrow":["arrow function","function to arrow","convert to arrow","convert function to arrow"]}[e]||[]}};function v(s,e){return new m(s,e)}var u=class{calculateCodeComplexity(e){let t=0;return t+=this.calculateLinesOfCodeContribution(e.linesOfCode),t+=this.calculateFileCountContribution(e.fileCount),t+=this.calculateCyclomaticContribution(e.cyclomaticComplexity),t+=this.calculateLanguageContribution(e.languageComplexity),Math.min(t,100)}calculateReasoningComplexity(e){let t=0;return t+=this.calculateKeywordScore(e.keywordMatches),e.requiresMultiStepReasoning&&(t+=20),e.requiresCreativity&&(t+=20),Math.min(t,100)}calculateScopeComplexity(e){let t=0;return e.hasArchitectureScope&&(t+=40),e.hasSecurityScope&&(t+=30),e.requiresCrossDomainCoordination&&(t+=20),t+=this.calculateDependencyContribution(e.dependencyCount),Math.min(t,100)}calculateOverallComplexity(e,t,r,o){if(o.isMechanicalTransform&&!o.hasSecurityScope&&!o.hasArchitectureScope&&!o.requiresMultiStepReasoning&&!o.requiresCrossDomainCoordination&&e===0&&t===0&&r===0)return 5;let c=e*.3+t*.4+r*.3,n=0;return o.hasSecurityScope&&(n=Math.max(n,50)),o.hasArchitectureScope&&(n=Math.max(n,55)),o.requiresCrossDomainCoordination&&(n=Math.max(n,35)),o.requiresMultiStepReasoning&&(n=Math.max(n,30)),o.keywordMatches.simple.length+o.keywordMatches.moderate.length+o.keywordMatches.complex.length+o.keywordMatches.critical.length===0&&!o.isMechanicalTransform&&c<15&&(n=Math.max(n,15)),Math.min(Math.max(Math.round(c),n),100)}calculateConfidence(e,t){let r=.5;return t.codeContext&&(r+=.2),t.filePaths&&t.filePaths.length>0&&(r+=.1),r+=this.calculateKeywordConfidenceBoost(e.keywordMatches),e.isMechanicalTransform&&(r+=.15),Math.min(r,1)}calculateLinesOfCodeContribution(e){return e===void 0||e<10?0:e<50?10:e<200?20:30}calculateFileCountContribution(e){return e===void 0||e===1?0:e<5?10:20}calculateCyclomaticContribution(e){return e===void 0||e<5?0:e<10?10:e<20?20:30}calculateLanguageContribution(e){return e==="low"?0:e==="medium"?10:e==="high"?20:0}calculateKeywordScore(e){let t=e.simple.length*5+e.moderate.length*15+e.complex.length*25+e.critical.length*35;return Math.min(t,60)}calculateDependencyContribution(e){return e===void 0||e<3?0:e<10?5:10}calculateKeywordConfidenceBoost(e){let t=e.simple.length+e.moderate.length+e.complex.length+e.critical.length;return t>=3?.1:t>=1?.05:0}};function M(){return new u}var p=class{getRecommendedTier(e){for(let t of[0,1,2,3,4]){let[r,o]=C[t].complexityRange;if(e>=r&&e<=o)return t}return 2}findAlternateTiers(e,t){let r=[];return t>0&&r.push(t-1),t<4&&r.push(t+1),t<3&&!r.includes(4)&&r.push(4),r}generateExplanation(e,t,r){let o=[];return o.push(`Complexity score: ${e}/100 (Tier ${t})`),r.isMechanicalTransform&&o.push(this.formatMechanicalTransformInfo(r.detectedTransformType)),o.push(...this.formatScopeExplanations(r)),o.push(...this.formatCodeMetricsExplanations(r)),o.join(". ")}formatMechanicalTransformInfo(e){return`Detected mechanical transform: ${e}`}formatScopeExplanations(e){let t=[];return e.hasArchitectureScope&&t.push("Architecture scope detected"),e.hasSecurityScope&&t.push("Security scope detected"),e.requiresMultiStepReasoning&&t.push("Multi-step reasoning required"),e.requiresCrossDomainCoordination&&t.push("Cross-domain coordination required"),t}formatCodeMetricsExplanations(e){let t=[];return e.linesOfCode!==void 0&&e.linesOfCode>100&&t.push(`Large code change: ${e.linesOfCode} lines`),e.fileCount!==void 0&&e.fileCount>3&&t.push(`Multi-file change: ${e.fileCount} files`),t}};function w(){return new p}var y=class{config;signalCollector;scoreCalculator;tierRecommender;constructor(e,t,r,o){this.config=e,this.signalCollector=t,this.scoreCalculator=r,this.tierRecommender=o}async analyze(e){try{let t=await this.signalCollector.collectSignals(e),r=this.scoreCalculator.calculateCodeComplexity(t),o=this.scoreCalculator.calculateReasoningComplexity(t),c=this.scoreCalculator.calculateScopeComplexity(t),n=this.scoreCalculator.calculateOverallComplexity(r,o,c,t),i=this.tierRecommender.getRecommendedTier(n),a=this.tierRecommender.findAlternateTiers(n,i),l=this.scoreCalculator.calculateConfidence(t,e),g=this.tierRecommender.generateExplanation(n,i,t);return{overall:n,codeComplexity:r,reasoningComplexity:o,scopeComplexity:c,confidence:l,signals:t,recommendedTier:i,alternateTiers:a,explanation:g}}catch(t){throw new x(`Failed to analyze task complexity: ${t instanceof Error?t.message:"Unknown error"}`,t instanceof Error?t:void 0)}}async checkAgentBoosterEligibility(e){return this.signalCollector.checkAgentBoosterEligibility(e)}getRecommendedTier(e){return this.tierRecommender.getRecommendedTier(e)}};function L(s,e){let t=new m(s,e),r=new u,o=new p;return new y(s,t,r,o)}function z(s,e,t,r){return new y(s,e,t,r)}export{m as a,v as b,u as c,M as d,p as e,w as f,y as g,L as h,z as i};
@@ -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.30");process.exit(0)}
2
- import{d as k,f as we}from"./chunk-DJRWVNHK.js";import{a as ye}from"./chunk-7Z3GBQNV.js";import{c as Q}from"./chunk-3WIU2E2Y.js";import{b as C,d as Z}from"./chunk-Q4HJRYQB.js";import{a as V,c as be}from"./chunk-RNO6CE7I.js";import{a as J,b as Xe}from"./chunk-CNNVL5W4.js";import{a as ee,d as b,e as te,f as ne}from"./chunk-7D2DM23U.js";import{a as v,e as De}from"./chunk-XVTZXCHI.js";import{c as R,e as ve}from"./chunk-ITBPDVK5.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.31");process.exit(0)}
2
+ import{d as k,f as we}from"./chunk-X2FLWV5C.js";import{b as C,d as Z}from"./chunk-WB6TI6Q3.js";import{a as ye}from"./chunk-5Z6PYYWK.js";import{c as Q}from"./chunk-NZQYNUGM.js";import{a as V,c as De}from"./chunk-K6MFAVXK.js";import{a as J,b as Xe}from"./chunk-CFLA2GBS.js";import{a as ee,d as D,e as te,f as ne}from"./chunk-N6SIKSCO.js";import{a as v,e as be}from"./chunk-7OVVBBOZ.js";import{c as R,e as ve}from"./chunk-BMS7WFDB.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 b,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();b=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,
@@ -502,7 +502,8 @@ import{d as k,f as we}from"./chunk-DJRWVNHK.js";import{a as ye}from"./chunk-7Z3G
502
502
  CREATE INDEX IF NOT EXISTS idx_test_outcomes_domain ON test_outcomes(domain);
503
503
  CREATE INDEX IF NOT EXISTS idx_test_outcomes_created ON test_outcomes(created_at);
504
504
 
505
- -- Routing outcomes (ADR-022: Adaptive QE Agent Routing, ADR-092: advisor_consultation_json)
505
+ -- Routing outcomes (ADR-022: Adaptive QE Agent Routing, ADR-092: advisor_consultation_json,
506
+ -- ADR-095: exploration / criticality / q_weight for \u03B5-greedy routing telemetry)
506
507
  CREATE TABLE IF NOT EXISTS routing_outcomes (
507
508
  id TEXT PRIMARY KEY,
508
509
  task_json TEXT NOT NULL,
@@ -515,11 +516,16 @@ import{d as k,f as we}from"./chunk-DJRWVNHK.js";import{a as ye}from"./chunk-7Z3G
515
516
  error TEXT,
516
517
  model_tier TEXT,
517
518
  advisor_consultation_json TEXT,
519
+ -- ADR-095: routing exploration telemetry
520
+ exploration INTEGER NOT NULL DEFAULT 0,
521
+ criticality REAL,
522
+ q_weight REAL,
518
523
  created_at TEXT DEFAULT (datetime('now'))
519
524
  );
520
525
  CREATE INDEX IF NOT EXISTS idx_routing_outcomes_agent ON routing_outcomes(used_agent);
521
526
  CREATE INDEX IF NOT EXISTS idx_routing_outcomes_created ON routing_outcomes(created_at);
522
527
  CREATE INDEX IF NOT EXISTS idx_routing_outcomes_tier ON routing_outcomes(model_tier);
528
+ CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration);
523
529
 
524
530
  -- Coverage sessions (ADR-023: Coverage Learning)
525
531
  CREATE TABLE IF NOT EXISTS coverage_sessions (
@@ -545,7 +551,7 @@ import{d as k,f as we}from"./chunk-DJRWVNHK.js";import{a as ye}from"./chunk-7Z3G
545
551
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
546
552
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
547
553
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
548
- `,pe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","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","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function y(i,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?i:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function c(o,a,l,E){return o!==l?o-l:a.localeCompare(E)}return{get(){return n.value},set(o,a){let l=a??Date.now();(n.timestamp===0||c(l,i,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:l,nodeId:i,version:n.version+1,lastUpdated:Date.now()})},merge(o){let a=o.getState();this.applyState(a)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||c(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return i},getTimestamp(){return n.timestamp}}}function X(i,e){let t=y(i);return t.applyState(e),t}var j=R(()=>{"use strict"});function I(i){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[i]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[i]=(e.counts[i]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[c,o]of Object.entries(t.counts)){let a=e.counts[c]||0;o>a&&(e.counts[c]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return i},getLocalCount(){return e.counts[i]||0}}}function w(i,e){let t=I(i);return t.applyState(e),t}var U=R(()=>{"use strict"});function F(i){let e=I(i),t=I(i),n=0,c=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,c=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,c=Date.now())},merge(o){let a=o.getState();this.applyState(a)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:c}},applyState(o){let a=this.get();e.applyState(o.positive),t.applyState(o.negative);let l=this.get();a!==l&&(n=Math.max(n,o.version)+1,c=Date.now())},getNodeId(){return i}}}function x(i,e){let t=F(i);return t.applyState(e),t}var B=R(()=>{"use strict";U()});function Ue(i,e){return`${i}:${Date.now()}:${e}`}function W(i){return typeof i=="string"?`s:${i}`:typeof i=="number"?`n:${i}`:typeof i=="boolean"?`b:${i}`:`j:${JSON.stringify(i)}`}function Fe(i){let e=i.substring(0,2),t=i.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function M(i){let e=new Map,t=new Map,n=0,c=Date.now(),o=0;function a(E){let d=e.get(E);if(!d||d.size===0)return!1;let u=t.get(E);if(!u||u.size===0)return!0;for(let m of d)if(!u.has(m))return!0;return!1}function l(E){let d=e.get(E);if(!d)return new Set;let u=t.get(E)||new Set,m=new Set;for(let p of d)u.has(p)||m.add(p);return m}return{has(E){let d=W(E);return a(d)},values(){let E=[];for(let[d]of e)a(d)&&E.push(Fe(d));return E},size(){let E=0;for(let[d]of e)a(d)&&E++;return E},add(E){let d=W(E),u=Ue(i,o++);e.has(d)||e.set(d,new Set),e.get(d).add(u),n++,c=Date.now()},remove(E){let d=W(E),u=e.get(d);if(!u||u.size===0)return;t.has(d)||t.set(d,new Set);let m=t.get(d);for(let p of u)m.add(p);n++,c=Date.now()},merge(E){let d=E.getState();this.applyState(d)},getState(){let E={};for(let[u,m]of e)E[u]=Array.from(m);let d={};for(let[u,m]of t)m.size>0&&(d[u]=Array.from(m));return{elements:E,tombstones:d,version:n,lastUpdated:c}},applyState(E){let d=!1;for(let[u,m]of Object.entries(E.elements)){e.has(u)||e.set(u,new Set);let p=e.get(u);for(let S of m)p.has(S)||(p.add(S),d=!0)}for(let[u,m]of Object.entries(E.tombstones)){t.has(u)||t.set(u,new Set);let p=t.get(u);for(let S of m)p.has(S)||(p.add(S),d=!0)}d&&(n=Math.max(n,E.version)+1,c=Date.now())},getNodeId(){return i},clear(){for(let[E,d]of e){t.has(E)||t.set(E,new Set);let u=t.get(E);for(let m of d)u.add(m)}n++,c=Date.now()}}}function P(i,e){let t=M(i);return t.applyState(e),t}var Y=R(()=>{"use strict";Z()});function H(i){let e={...xe,...i},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:c}=e,o=new Map,a=new Map,l=new Map,E=new Map,d=0,u=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function S(s,r,T){let _={key:s,type:r,operation:T,timestamp:Date.now(),nodeId:t};for(let Oe of m)try{Oe(_)}catch(Ae){console.error("[CRDTStore] Error in change listener:",Ae)}}function N(s,r){d++,n&&p[s].add(r)}function K(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:u.length>0?u[u.length-1].toVersion:0,toVersion:d,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let T of p.registers){let _=o.get(T);_&&(r.registers[T]=_.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let T of p.gCounters){let _=a.get(T);_&&(r.gCounters[T]=_.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let T of p.pnCounters){let _=l.get(T);_&&(r.pnCounters[T]=_.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let T of p.sets){let _=E.get(T);_&&(r.sets[T]=_.getState())}p.sets.clear()}for(u.push(r);u.length>c;)u.shift()}let L={getRegister(s){return o.has(s)||o.set(s,y(t)),o.get(s)},setRegister(s,r){L.getRegister(s).set(r),N("registers",s),S(s,"lww-register","set")},hasRegister(s){return o.has(s)},deleteRegister(s){let r=o.delete(s);return r&&N("registers",s),r},getGCounter(s){return a.has(s)||a.set(s,I(t)),a.get(s)},incrementGCounter(s,r){L.getGCounter(s).increment(r),N("gCounters",s),S(s,"g-counter","increment")},hasGCounter(s){return a.has(s)},deleteGCounter(s){let r=a.delete(s);return r&&N("gCounters",s),r},getCounter(s){return l.has(s)||l.set(s,F(t)),l.get(s)},incrementCounter(s,r){L.getCounter(s).increment(r),N("pnCounters",s),S(s,"pn-counter","increment")},decrementCounter(s,r){L.getCounter(s).decrement(r),N("pnCounters",s),S(s,"pn-counter","decrement")},hasCounter(s){return l.has(s)},deleteCounter(s){let r=l.delete(s);return r&&N("pnCounters",s),r},getSet(s){return E.has(s)||E.set(s,M(t)),E.get(s)},addToSet(s,r){L.getSet(s).add(r),N("sets",s),S(s,"or-set","add")},removeFromSet(s,r){L.getSet(s).remove(r),N("sets",s),S(s,"or-set","remove")},hasSet(s){return E.has(s)},deleteSet(s){let r=E.delete(s);return r&&N("sets",s),r},merge(s){let r=s.getState();L.applyState(r)},getState(){K();let s={version:d,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,T]of o)s.registers[r]=T.getState();for(let[r,T]of a)s.gCounters[r]=T.getState();for(let[r,T]of l)s.pnCounters[r]=T.getState();for(let[r,T]of E)s.sets[r]=T.getState();return s},applyState(s){for(let[r,T]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(T):o.set(r,X(t,T)),N("registers",r),S(r,"lww-register","merge");for(let[r,T]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(T):a.set(r,w(t,T)),N("gCounters",r),S(r,"g-counter","merge");for(let[r,T]of Object.entries(s.pnCounters))l.has(r)?l.get(r).applyState(T):l.set(r,x(t,T)),N("pnCounters",r),S(r,"pn-counter","merge");for(let[r,T]of Object.entries(s.sets))E.has(r)?E.get(r).applyState(T):E.set(r,P(t,T)),N("sets",r),S(r,"or-set","merge");d=Math.max(d,s.version)+1},getDelta(s){if(K(),u.length===0)return s>=d,null;let r=u.filter(_=>_.toVersion>s);if(r.length===0)return null;let T={fromVersion:s,toVersion:d,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let _ of r)_.registers&&Object.assign(T.registers,_.registers),_.gCounters&&Object.assign(T.gCounters,_.gCounters),_.pnCounters&&Object.assign(T.pnCounters,_.pnCounters),_.sets&&Object.assign(T.sets,_.sets);return Object.keys(T.registers).length===0&&delete T.registers,Object.keys(T.gCounters).length===0&&delete T.gCounters,Object.keys(T.pnCounters).length===0&&delete T.pnCounters,Object.keys(T.sets).length===0&&delete T.sets,T},applyDelta(s){if(s.registers)for(let[r,T]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(T):o.set(r,X(t,T)),N("registers",r),S(r,"lww-register","merge");if(s.gCounters)for(let[r,T]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(T):a.set(r,w(t,T)),N("gCounters",r),S(r,"g-counter","merge");if(s.pnCounters)for(let[r,T]of Object.entries(s.pnCounters))l.has(r)?l.get(r).applyState(T):l.set(r,x(t,T)),N("pnCounters",r),S(r,"pn-counter","merge");if(s.sets)for(let[r,T]of Object.entries(s.sets))E.has(r)?E.get(r).applyState(T):E.set(r,P(t,T)),N("sets",r),S(r,"or-set","merge");d=Math.max(d,s.toVersion)+1},getVersion(){return d},getNodeId(){return t},on(s,r){if(s==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){m.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(o.keys())),(!s||s==="g-counter")&&r.push(...Array.from(a.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(l.keys())),(!s||s==="or-set")&&r.push(...Array.from(E.keys())),r},clear(){o.clear(),a.clear(),l.clear(),E.clear(),u.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),d=0},getStats(){return{total:o.size+a.size+l.size+E.size,registers:o.size,gCounters:a.size,pnCounters:l.size,sets:E.size,version:d,nodeId:t,deltaHistorySize:u.length}}};return L}var xe,me=R(()=>{"use strict";j();U();B();Y();xe={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var _e=R(()=>{"use strict"});var fe=R(()=>{"use strict";j();U();B();Y();me();_e()});var ke={};ve(ke,{ALLOWED_TABLE_NAMES:()=>q,BinaryHeap:()=>ee,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>Le,UnifiedHnswIndex:()=>b,UnifiedMemoryManager:()=>A,clearProjectRootCache:()=>Re,createHnswIndex:()=>te,findProjectRoot:()=>G,getDefaultDbPath:()=>he,getResolvedDefaultConfig:()=>Ce,getUnifiedMemory:()=>Ie,initializeUnifiedMemory:()=>Me,resetUnifiedMemory:()=>Pe,validateTableName:()=>O});import*as g from"fs";import*as Ne from"os";import*as f from"path";function Re(){h=null}function G(i=process.cwd()){if(h)return h;if(process.env.AQE_PROJECT_ROOT)return h=process.env.AQE_PROJECT_ROOT,h;let e=i,t=f.parse(e).root,n=e,c=null,o=null,a=null;for(;n!==t;)g.existsSync(f.join(n,".agentic-qe"))&&(c=n),g.existsSync(f.join(n,".git"))&&o===null&&(o=n),g.existsSync(f.join(n,"package.json"))&&(a=n),n=f.dirname(n);return c?h=c:o?h=o:a?h=a:h=process.cwd(),h}function he(){let i=G();return f.join(i,".agentic-qe","memory.db")}function Ce(){return{...Le,dbPath:he()}}function Ie(i){return A.getInstance(i)}async function Me(i){let e=Ie(i);return await e.initialize(),e}function Pe(){A.resetInstance()}function Ge(){if(Se)return;Se=!0;let i=()=>{try{let e=A.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",i),process.on("SIGINT",()=>{i(),process.exit(0)}),process.on("SIGTERM",()=>{i(),process.exit(0)})}var $,h,Le,A,Se,qe=R(()=>{Xe();Z();be();De();ye();z();z();ne();ne();ge();fe();$=Q.create("unified-memory"),h=null;Le={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:v.MMAP_SIZE_BYTES,cacheSize:v.CACHE_SIZE_KB,busyTimeout:v.BUSY_TIMEOUT_MS,vectorDimensions:v.DEFAULT_VECTOR_DIMENSIONS};A=class i{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new b("qe-memory");crdtStore=null;constructor(e){let t=Ce();if(this.config={...t,...e},!f.isAbsolute(this.config.dbPath)){let n=G();this.config.dbPath=f.join(n,this.config.dbPath)}}static getInstance(e){return i.instance||(i.instance=new i(e)),i.instance}static async getInstanceAsync(e){return i.instance?.initialized?i.instance:(i.instancePromise||(i.instancePromise=(async()=>{let t=i.getInstance(e);return await t.initialize(),t})()),i.instancePromise)}static resetInstance(){i.instance&&(i.instance.close(),i.instance=null),i.instancePromise=null,Re()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let e=process.env.AQE_PROJECT_ROOT;if(e){let o=f.resolve(this.config.dbPath),a=f.resolve(e);!o.startsWith(a)&&!o.startsWith(Ne.tmpdir())&&o.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${e}". Redirecting to test-safe path.`),this.config.dbPath=f.join(e,".agentic-qe","memory.db"))}let t=f.dirname(this.config.dbPath);g.existsSync(t)||g.mkdirSync(t,{recursive:!0});let n=g.existsSync(this.config.dbPath),c=0;if(n)c=g.statSync(this.config.dbPath).size;else if(g.existsSync(t)){let o=this.findRecentBackups(t);if(o.length>0){let a=o[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
554
+ `,pe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","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","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function y(i,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?i:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function c(o,a,l,E){return o!==l?o-l:a.localeCompare(E)}return{get(){return n.value},set(o,a){let l=a??Date.now();(n.timestamp===0||c(l,i,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:l,nodeId:i,version:n.version+1,lastUpdated:Date.now()})},merge(o){let a=o.getState();this.applyState(a)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||c(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return i},getTimestamp(){return n.timestamp}}}function X(i,e){let t=y(i);return t.applyState(e),t}var j=R(()=>{"use strict"});function I(i){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[i]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[i]=(e.counts[i]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[c,o]of Object.entries(t.counts)){let a=e.counts[c]||0;o>a&&(e.counts[c]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return i},getLocalCount(){return e.counts[i]||0}}}function w(i,e){let t=I(i);return t.applyState(e),t}var U=R(()=>{"use strict"});function F(i){let e=I(i),t=I(i),n=0,c=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,c=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,c=Date.now())},merge(o){let a=o.getState();this.applyState(a)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:c}},applyState(o){let a=this.get();e.applyState(o.positive),t.applyState(o.negative);let l=this.get();a!==l&&(n=Math.max(n,o.version)+1,c=Date.now())},getNodeId(){return i}}}function x(i,e){let t=F(i);return t.applyState(e),t}var B=R(()=>{"use strict";U()});function Ue(i,e){return`${i}:${Date.now()}:${e}`}function W(i){return typeof i=="string"?`s:${i}`:typeof i=="number"?`n:${i}`:typeof i=="boolean"?`b:${i}`:`j:${JSON.stringify(i)}`}function Fe(i){let e=i.substring(0,2),t=i.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function M(i){let e=new Map,t=new Map,n=0,c=Date.now(),o=0;function a(E){let d=e.get(E);if(!d||d.size===0)return!1;let u=t.get(E);if(!u||u.size===0)return!0;for(let m of d)if(!u.has(m))return!0;return!1}function l(E){let d=e.get(E);if(!d)return new Set;let u=t.get(E)||new Set,m=new Set;for(let p of d)u.has(p)||m.add(p);return m}return{has(E){let d=W(E);return a(d)},values(){let E=[];for(let[d]of e)a(d)&&E.push(Fe(d));return E},size(){let E=0;for(let[d]of e)a(d)&&E++;return E},add(E){let d=W(E),u=Ue(i,o++);e.has(d)||e.set(d,new Set),e.get(d).add(u),n++,c=Date.now()},remove(E){let d=W(E),u=e.get(d);if(!u||u.size===0)return;t.has(d)||t.set(d,new Set);let m=t.get(d);for(let p of u)m.add(p);n++,c=Date.now()},merge(E){let d=E.getState();this.applyState(d)},getState(){let E={};for(let[u,m]of e)E[u]=Array.from(m);let d={};for(let[u,m]of t)m.size>0&&(d[u]=Array.from(m));return{elements:E,tombstones:d,version:n,lastUpdated:c}},applyState(E){let d=!1;for(let[u,m]of Object.entries(E.elements)){e.has(u)||e.set(u,new Set);let p=e.get(u);for(let S of m)p.has(S)||(p.add(S),d=!0)}for(let[u,m]of Object.entries(E.tombstones)){t.has(u)||t.set(u,new Set);let p=t.get(u);for(let S of m)p.has(S)||(p.add(S),d=!0)}d&&(n=Math.max(n,E.version)+1,c=Date.now())},getNodeId(){return i},clear(){for(let[E,d]of e){t.has(E)||t.set(E,new Set);let u=t.get(E);for(let m of d)u.add(m)}n++,c=Date.now()}}}function P(i,e){let t=M(i);return t.applyState(e),t}var Y=R(()=>{"use strict";Z()});function H(i){let e={...xe,...i},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:c}=e,o=new Map,a=new Map,l=new Map,E=new Map,d=0,u=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function S(s,r,T){let _={key:s,type:r,operation:T,timestamp:Date.now(),nodeId:t};for(let Oe of m)try{Oe(_)}catch(Ae){console.error("[CRDTStore] Error in change listener:",Ae)}}function N(s,r){d++,n&&p[s].add(r)}function K(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:u.length>0?u[u.length-1].toVersion:0,toVersion:d,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let T of p.registers){let _=o.get(T);_&&(r.registers[T]=_.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let T of p.gCounters){let _=a.get(T);_&&(r.gCounters[T]=_.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let T of p.pnCounters){let _=l.get(T);_&&(r.pnCounters[T]=_.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let T of p.sets){let _=E.get(T);_&&(r.sets[T]=_.getState())}p.sets.clear()}for(u.push(r);u.length>c;)u.shift()}let L={getRegister(s){return o.has(s)||o.set(s,y(t)),o.get(s)},setRegister(s,r){L.getRegister(s).set(r),N("registers",s),S(s,"lww-register","set")},hasRegister(s){return o.has(s)},deleteRegister(s){let r=o.delete(s);return r&&N("registers",s),r},getGCounter(s){return a.has(s)||a.set(s,I(t)),a.get(s)},incrementGCounter(s,r){L.getGCounter(s).increment(r),N("gCounters",s),S(s,"g-counter","increment")},hasGCounter(s){return a.has(s)},deleteGCounter(s){let r=a.delete(s);return r&&N("gCounters",s),r},getCounter(s){return l.has(s)||l.set(s,F(t)),l.get(s)},incrementCounter(s,r){L.getCounter(s).increment(r),N("pnCounters",s),S(s,"pn-counter","increment")},decrementCounter(s,r){L.getCounter(s).decrement(r),N("pnCounters",s),S(s,"pn-counter","decrement")},hasCounter(s){return l.has(s)},deleteCounter(s){let r=l.delete(s);return r&&N("pnCounters",s),r},getSet(s){return E.has(s)||E.set(s,M(t)),E.get(s)},addToSet(s,r){L.getSet(s).add(r),N("sets",s),S(s,"or-set","add")},removeFromSet(s,r){L.getSet(s).remove(r),N("sets",s),S(s,"or-set","remove")},hasSet(s){return E.has(s)},deleteSet(s){let r=E.delete(s);return r&&N("sets",s),r},merge(s){let r=s.getState();L.applyState(r)},getState(){K();let s={version:d,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,T]of o)s.registers[r]=T.getState();for(let[r,T]of a)s.gCounters[r]=T.getState();for(let[r,T]of l)s.pnCounters[r]=T.getState();for(let[r,T]of E)s.sets[r]=T.getState();return s},applyState(s){for(let[r,T]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(T):o.set(r,X(t,T)),N("registers",r),S(r,"lww-register","merge");for(let[r,T]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(T):a.set(r,w(t,T)),N("gCounters",r),S(r,"g-counter","merge");for(let[r,T]of Object.entries(s.pnCounters))l.has(r)?l.get(r).applyState(T):l.set(r,x(t,T)),N("pnCounters",r),S(r,"pn-counter","merge");for(let[r,T]of Object.entries(s.sets))E.has(r)?E.get(r).applyState(T):E.set(r,P(t,T)),N("sets",r),S(r,"or-set","merge");d=Math.max(d,s.version)+1},getDelta(s){if(K(),u.length===0)return s>=d,null;let r=u.filter(_=>_.toVersion>s);if(r.length===0)return null;let T={fromVersion:s,toVersion:d,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let _ of r)_.registers&&Object.assign(T.registers,_.registers),_.gCounters&&Object.assign(T.gCounters,_.gCounters),_.pnCounters&&Object.assign(T.pnCounters,_.pnCounters),_.sets&&Object.assign(T.sets,_.sets);return Object.keys(T.registers).length===0&&delete T.registers,Object.keys(T.gCounters).length===0&&delete T.gCounters,Object.keys(T.pnCounters).length===0&&delete T.pnCounters,Object.keys(T.sets).length===0&&delete T.sets,T},applyDelta(s){if(s.registers)for(let[r,T]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(T):o.set(r,X(t,T)),N("registers",r),S(r,"lww-register","merge");if(s.gCounters)for(let[r,T]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(T):a.set(r,w(t,T)),N("gCounters",r),S(r,"g-counter","merge");if(s.pnCounters)for(let[r,T]of Object.entries(s.pnCounters))l.has(r)?l.get(r).applyState(T):l.set(r,x(t,T)),N("pnCounters",r),S(r,"pn-counter","merge");if(s.sets)for(let[r,T]of Object.entries(s.sets))E.has(r)?E.get(r).applyState(T):E.set(r,P(t,T)),N("sets",r),S(r,"or-set","merge");d=Math.max(d,s.toVersion)+1},getVersion(){return d},getNodeId(){return t},on(s,r){if(s==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){m.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(o.keys())),(!s||s==="g-counter")&&r.push(...Array.from(a.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(l.keys())),(!s||s==="or-set")&&r.push(...Array.from(E.keys())),r},clear(){o.clear(),a.clear(),l.clear(),E.clear(),u.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),d=0},getStats(){return{total:o.size+a.size+l.size+E.size,registers:o.size,gCounters:a.size,pnCounters:l.size,sets:E.size,version:d,nodeId:t,deltaHistorySize:u.length}}};return L}var xe,me=R(()=>{"use strict";j();U();B();Y();xe={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var _e=R(()=>{"use strict"});var fe=R(()=>{"use strict";j();U();B();Y();me();_e()});var ke={};ve(ke,{ALLOWED_TABLE_NAMES:()=>q,BinaryHeap:()=>ee,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>Le,UnifiedHnswIndex:()=>D,UnifiedMemoryManager:()=>A,clearProjectRootCache:()=>Re,createHnswIndex:()=>te,findProjectRoot:()=>G,getDefaultDbPath:()=>he,getResolvedDefaultConfig:()=>Ce,getUnifiedMemory:()=>Ie,initializeUnifiedMemory:()=>Me,resetUnifiedMemory:()=>Pe,validateTableName:()=>O});import*as g from"fs";import*as Ne from"os";import*as f from"path";function Re(){h=null}function G(i=process.cwd()){if(h)return h;if(process.env.AQE_PROJECT_ROOT)return h=process.env.AQE_PROJECT_ROOT,h;let e=i,t=f.parse(e).root,n=e,c=null,o=null,a=null;for(;n!==t;)g.existsSync(f.join(n,".agentic-qe"))&&(c=n),g.existsSync(f.join(n,".git"))&&o===null&&(o=n),g.existsSync(f.join(n,"package.json"))&&(a=n),n=f.dirname(n);return c?h=c:o?h=o:a?h=a:h=process.cwd(),h}function he(){let i=G();return f.join(i,".agentic-qe","memory.db")}function Ce(){return{...Le,dbPath:he()}}function Ie(i){return A.getInstance(i)}async function Me(i){let e=Ie(i);return await e.initialize(),e}function Pe(){A.resetInstance()}function Ge(){if(Se)return;Se=!0;let i=()=>{try{let e=A.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",i),process.on("SIGINT",()=>{i(),process.exit(0)}),process.on("SIGTERM",()=>{i(),process.exit(0)})}var $,h,Le,A,Se,qe=R(()=>{Xe();Z();De();be();ye();z();z();ne();ne();ge();fe();$=Q.create("unified-memory"),h=null;Le={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:v.MMAP_SIZE_BYTES,cacheSize:v.CACHE_SIZE_KB,busyTimeout:v.BUSY_TIMEOUT_MS,vectorDimensions:v.DEFAULT_VECTOR_DIMENSIONS};A=class i{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new D("qe-memory");crdtStore=null;constructor(e){let t=Ce();if(this.config={...t,...e},!f.isAbsolute(this.config.dbPath)){let n=G();this.config.dbPath=f.join(n,this.config.dbPath)}}static getInstance(e){return i.instance||(i.instance=new i(e)),i.instance}static async getInstanceAsync(e){return i.instance?.initialized?i.instance:(i.instancePromise||(i.instancePromise=(async()=>{let t=i.getInstance(e);return await t.initialize(),t})()),i.instancePromise)}static resetInstance(){i.instance&&(i.instance.close(),i.instance=null),i.instancePromise=null,Re()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let e=process.env.AQE_PROJECT_ROOT;if(e){let o=f.resolve(this.config.dbPath),a=f.resolve(e);!o.startsWith(a)&&!o.startsWith(Ne.tmpdir())&&o.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${e}". Redirecting to test-safe path.`),this.config.dbPath=f.join(e,".agentic-qe","memory.db"))}let t=f.dirname(this.config.dbPath);g.existsSync(t)||g.mkdirSync(t,{recursive:!0});let n=g.existsSync(this.config.dbPath),c=0;if(n)c=g.statSync(this.config.dbPath).size;else if(g.existsSync(t)){let o=this.findRecentBackups(t);if(o.length>0){let a=o[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
549
555
  Expected: ${this.config.dbPath}
550
556
  Found ${o.length} backup(s), newest: ${a.path} (${(a.size/1024/1024).toFixed(1)}MB)
551
557
  Restoring from backup to prevent data loss...`),g.copyFileSync(a.path,this.config.dbPath);for(let l of["-wal","-shm"]){let E=this.config.dbPath+l;g.existsSync(E)&&g.unlinkSync(E)}c=a.size}}if(this.db=J(this.config.dbPath,{walMode:this.config.walMode,busyTimeout:this.config.busyTimeout}),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.db.pragma("foreign_keys = ON"),await this.runMigrations(),n&&c>1e6)try{let o=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(o&&o.cnt===0){let a=g.statSync(this.config.dbPath).size;a<c*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
@@ -554,7 +560,7 @@ import{d as k,f as we}from"./chunk-DJRWVNHK.js";import{a as ye}from"./chunk-7Z3G
554
560
  Check backups in ${t} and restore manually.`)}}catch{}this.vectorsLoaded=!1,this.initialized=!0,console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`),this.warnIfDuplicateDatabases()}catch(e){throw this.initPromise=null,new Error(`Failed to initialize UnifiedMemoryManager: ${V(e)}`)}}findRecentBackups(e){try{let n=g.readdirSync(e).filter(o=>o.startsWith("memory")&&o.endsWith(".db")&&o!=="memory.db").map(o=>{let a=f.join(e,o),l=g.statSync(a);return{path:a,size:l.size,mtime:l.mtimeMs}}).filter(o=>o.size>1e6).sort((o,a)=>a.mtime-o.mtime),c=f.join(e,"backups");if(g.existsSync(c)){let o=g.readdirSync(c);for(let a of o)if(a.endsWith(".db")){let l=f.join(c,a),E=g.statSync(l);E.size>1e6&&n.push({path:l,size:E.size,mtime:E.mtimeMs})}n.sort((a,l)=>l.mtime-a.mtime)}return n}catch{return[]}}warnIfDuplicateDatabases(){try{let e=G(),t=f.resolve(this.config.dbPath),c=[f.join(e,".agentic-qe","memory.db"),f.join(e,"v3",".agentic-qe","memory.db")].map(o=>f.resolve(o)).filter(o=>o!==t&&g.existsSync(o));c.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
555
561
  Canonical: ${t}
556
562
  Duplicates: ${c.join(", ")}
557
- This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){$.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=O(e);return this.db.prepare(`PRAGMA table_info(${n})`).all().some(o=>o.name===t)}catch(n){return $.debug("Column existence check failed",{table:e,column:t,error:n instanceof Error?n.message:String(n)}),!1}}handleV2SchemaIncompatibilities(){if(!this.db)return;let e=[{table:"goap_plans",requiredColumn:"status",columnDef:"TEXT DEFAULT 'pending'"},{table:"goap_actions",requiredColumn:"agent_type",columnDef:"TEXT DEFAULT 'unknown'"},{table:"concept_nodes",requiredColumn:"concept_type",columnDef:"TEXT DEFAULT 'general'"},{table:"concept_edges",requiredColumn:"edge_type",columnDef:"TEXT DEFAULT 'related'"},{table:"dream_insights",requiredColumn:"cycle_id",columnDef:"TEXT DEFAULT ''"},{table:"rl_q_values",requiredColumn:"algorithm",columnDef:"TEXT DEFAULT 'q-learning'"}];for(let{table:t,requiredColumn:n,columnDef:c}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,n)){let a=O(t);try{this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${n} ${c}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(l){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${l instanceof Error?l.message:String(l)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(se),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<D&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${D}`),this.db.transaction(()=>{t<1&&this.db.exec(oe),t<2&&this.db.exec(ie),t<3&&(this.db.exec(ae),this.db.exec(ce),this.db.exec(Te)),t<4&&this.db.exec(Ee),t<5&&this.db.exec(de),t<6&&this.db.exec(k),t<7&&this.db.exec(ue),t<8&&this.db.exec(le),t<9&&(this.db.exec(`
563
+ This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){$.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=O(e);return this.db.prepare(`PRAGMA table_info(${n})`).all().some(o=>o.name===t)}catch(n){return $.debug("Column existence check failed",{table:e,column:t,error:n instanceof Error?n.message:String(n)}),!1}}handleV2SchemaIncompatibilities(){if(!this.db)return;let e=[{table:"goap_plans",requiredColumn:"status",columnDef:"TEXT DEFAULT 'pending'"},{table:"goap_actions",requiredColumn:"agent_type",columnDef:"TEXT DEFAULT 'unknown'"},{table:"concept_nodes",requiredColumn:"concept_type",columnDef:"TEXT DEFAULT 'general'"},{table:"concept_edges",requiredColumn:"edge_type",columnDef:"TEXT DEFAULT 'related'"},{table:"dream_insights",requiredColumn:"cycle_id",columnDef:"TEXT DEFAULT ''"},{table:"rl_q_values",requiredColumn:"algorithm",columnDef:"TEXT DEFAULT 'q-learning'"}];for(let{table:t,requiredColumn:n,columnDef:c}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,n)){let a=O(t);try{this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${n} ${c}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(l){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${l instanceof Error?l.message:String(l)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(se),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<b&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${b}`),this.db.transaction(()=>{t<1&&this.db.exec(oe),t<2&&this.db.exec(ie),t<3&&(this.db.exec(ae),this.db.exec(ce),this.db.exec(Te)),t<4&&this.db.exec(Ee),t<5&&this.db.exec(de),t<6&&this.db.exec(k),t<7&&this.db.exec(ue),t<8&&this.db.exec(le),t<9&&(this.db.exec(`
558
564
  CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
559
565
  name, description, pattern_type, qe_domain,
560
566
  content='qe_patterns',
@@ -583,7 +589,7 @@ import{d as k,f as we}from"./chunk-DJRWVNHK.js";import{a as ye}from"./chunk-7Z3G
583
589
  `)),this.db.prepare(`
584
590
  INSERT OR REPLACE INTO schema_version (id, version, migrated_at)
585
591
  VALUES (1, ?, datetime('now'))
586
- `).run(D)})(),console.log("[UnifiedMemory] Migration complete"))}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",c){this.ensureInitialized();let o=c?Date.now()+c*1e3:null,a=JSON.stringify(t);this.db.prepare(`
592
+ `).run(b)})(),console.log("[UnifiedMemory] Migration complete"))}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",c){this.ensureInitialized();let o=c?Date.now()+c*1e3:null,a=JSON.stringify(t);this.db.prepare(`
587
593
  INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
588
594
  VALUES (?, ?, ?, ?)
589
595
  `).run(e,n,a,o)}async kvGet(e,t="default"){this.ensureInitialized();let n=this.db.prepare(`
@@ -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.30");process.exit(0)}
2
- import{c as T}from"./chunk-ITBPDVK5.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
+ import{c as T}from"./chunk-BMS7WFDB.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};