agentic-qe 3.9.31 → 3.9.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (306) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +88 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-CDQOF5TF.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-AQXZYWZY.js → agent-booster-wasm-WKS3E6KT.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-7N4ZPXCY.js → agent-handler-LYCAWE7S.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-FLKF2JVX.js → agent-memory-branch-XF7IOMRK.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +2 -0
  10. package/dist/cli/chunks/{audit-B4V4IKTA.js → audit-D2AY3HFP.js} +2 -2
  11. package/dist/cli/chunks/base-UGH6TVO4.js +2 -0
  12. package/dist/cli/chunks/{hnswlib-node-WENGW3YX.js → better-sqlite3-K2VWFDKT.js} +2 -2
  13. package/dist/cli/chunks/{brain-handler-OOXJ2KYY.js → brain-handler-NNW4TAO2.js} +3 -3
  14. package/dist/cli/chunks/{branch-enumerator-LFKFW3A4.js → branch-enumerator-OM5HNZKV.js} +2 -2
  15. package/dist/cli/chunks/{browser-F72IES2I.js → browser-Y2FU2NV4.js} +2 -2
  16. package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +2 -0
  17. package/dist/cli/chunks/{chunk-35SFAIXE.js → chunk-2L5GAOST.js} +2 -2
  18. package/dist/cli/chunks/{chunk-MAJ5QFVY.js → chunk-2XC4XVCI.js} +1 -1
  19. package/dist/cli/chunks/{chunk-QEJBJST4.js → chunk-2Z2IQBIJ.js} +1 -1
  20. package/dist/cli/chunks/{chunk-AKFRM4IO.js → chunk-33PGBYTC.js} +2 -2
  21. package/dist/cli/chunks/{chunk-W7XVEWKQ.js → chunk-3MHWBCSC.js} +1 -1
  22. package/dist/cli/chunks/{chunk-NBKM7NKX.js → chunk-3R4CMTWF.js} +2 -2
  23. package/dist/cli/chunks/{chunk-4N736EES.js → chunk-45N22VAB.js} +2 -2
  24. package/dist/cli/chunks/{chunk-3VKB4HVT.js → chunk-4H4PEZUX.js} +2 -2
  25. package/dist/cli/chunks/{chunk-CFLA2GBS.js → chunk-4VAZSCTZ.js} +2 -2
  26. package/dist/cli/chunks/{chunk-JF3U456G.js → chunk-5A6LBGRU.js} +2 -2
  27. package/dist/cli/chunks/{chunk-TYUIQSSF.js → chunk-5DSANX6S.js} +2 -2
  28. package/dist/cli/chunks/chunk-5R5WOLZM.js +5 -0
  29. package/dist/cli/chunks/{chunk-K6MFAVXK.js → chunk-5WR42V5O.js} +2 -2
  30. package/dist/cli/chunks/{chunk-PUSZ4NBY.js → chunk-5XY6SULI.js} +2 -2
  31. package/dist/cli/chunks/{chunk-VOOJDHLI.js → chunk-62UXGD5J.js} +3 -3
  32. package/dist/cli/chunks/{chunk-REJEFTWX.js → chunk-667I4RTC.js} +1 -1
  33. package/dist/cli/chunks/{chunk-KXRDQQGN.js → chunk-6EKXBWJD.js} +2 -2
  34. package/dist/cli/chunks/{chunk-CNKOIHF6.js → chunk-6R6QCGNU.js} +2 -2
  35. package/dist/cli/chunks/{chunk-YEZJE2ZW.js → chunk-6SYP7QX6.js} +4 -4
  36. package/dist/cli/chunks/{chunk-TLCCM2AF.js → chunk-6YGFAJ3X.js} +1 -1
  37. package/dist/cli/chunks/{chunk-KJAIE7SL.js → chunk-6ZG6TBWF.js} +4 -4
  38. package/dist/cli/chunks/{chunk-NLUBN642.js → chunk-7AISRWBS.js} +2 -2
  39. package/dist/cli/chunks/{chunk-LF5RO6WO.js → chunk-7IDPVSTF.js} +1 -1
  40. package/dist/cli/chunks/{chunk-VUL5HIKR.js → chunk-7PTW3M67.js} +2 -2
  41. package/dist/cli/chunks/{chunk-QGLWFZVQ.js → chunk-A4UNK5SY.js} +2 -2
  42. package/dist/cli/chunks/{chunk-JRIDPOEZ.js → chunk-A6VI5BZU.js} +4 -4
  43. package/dist/cli/chunks/{chunk-7OVVBBOZ.js → chunk-BBPOTFIY.js} +2 -2
  44. package/dist/cli/chunks/{chunk-AKJWBJDK.js → chunk-BDXEL3GM.js} +2 -2
  45. package/dist/cli/chunks/{chunk-GJSH4UZ3.js → chunk-BGRC4676.js} +3 -3
  46. package/dist/cli/chunks/{chunk-PSF6YQQM.js → chunk-BQML7B4W.js} +3 -3
  47. package/dist/cli/chunks/{chunk-VAIOZDG5.js → chunk-BV3SGEV7.js} +1 -1
  48. package/dist/cli/chunks/{chunk-XNJ6DIEW.js → chunk-DBE2LIYG.js} +2 -2
  49. package/dist/cli/chunks/{chunk-AQN6PDHI.js → chunk-DFY7F4TE.js} +1 -1
  50. package/dist/cli/chunks/{chunk-IRRGUXAU.js → chunk-EFEJLZDN.js} +1 -1
  51. package/dist/cli/chunks/{chunk-5G2L4XRU.js → chunk-ESNBKAT6.js} +2 -2
  52. package/dist/cli/chunks/{chunk-7UHRT5AX.js → chunk-EVSUZKD5.js} +2 -2
  53. package/dist/cli/chunks/{chunk-FUHPLXJX.js → chunk-FFBF5BLQ.js} +1 -1
  54. package/dist/cli/chunks/{chunk-N6P7ENG7.js → chunk-FIONYUVH.js} +2 -2
  55. package/dist/cli/chunks/{chunk-TJGIIGKL.js → chunk-FNQCWEVJ.js} +2 -2
  56. package/dist/cli/chunks/{chunk-NTVJKQ5S.js → chunk-FV2MU6CY.js} +2 -2
  57. package/dist/cli/chunks/{chunk-M6RVKGIP.js → chunk-FWEYOD3S.js} +2 -2
  58. package/dist/cli/chunks/{chunk-EAIPJSKH.js → chunk-G6AJMFWL.js} +3 -3
  59. package/dist/cli/chunks/{chunk-L7DNPOAQ.js → chunk-G6VVOUUF.js} +2 -2
  60. package/dist/cli/chunks/{chunk-BYHUGO73.js → chunk-G77CYF7H.js} +3 -3
  61. package/dist/cli/chunks/{chunk-EJXRBAQF.js → chunk-H7YKTJMY.js} +2 -2
  62. package/dist/cli/chunks/{chunk-CUSLB7MB.js → chunk-HGWQC7PR.js} +2 -2
  63. package/dist/cli/chunks/{chunk-XE4YKDIM.js → chunk-HHBFI3YA.js} +2 -2
  64. package/dist/cli/chunks/{chunk-PTOTOBOU.js → chunk-HPQZSXED.js} +1 -1
  65. package/dist/cli/chunks/{chunk-YN7HCVUP.js → chunk-HR6NX6DW.js} +2 -2
  66. package/dist/cli/chunks/{chunk-QITO7E7Y.js → chunk-I6Q6BPVH.js} +1 -1
  67. package/dist/cli/chunks/{chunk-L63KB63A.js → chunk-IGEZVFOM.js} +2 -2
  68. package/dist/cli/chunks/{chunk-ENCFLC44.js → chunk-IGQPGXP7.js} +2 -2
  69. package/dist/cli/chunks/{chunk-YMN4C32S.js → chunk-IJQJV7BC.js} +3 -3
  70. package/dist/cli/chunks/chunk-JDW6GN3A.js +2 -0
  71. package/dist/cli/chunks/{chunk-LRWRFKQH.js → chunk-JRYNHFZA.js} +1 -1
  72. package/dist/cli/chunks/{chunk-7V7TP242.js → chunk-KHZRNJ3A.js} +1 -1
  73. package/dist/cli/chunks/{chunk-PYYNY7RJ.js → chunk-LHDTXTS7.js} +1 -1
  74. package/dist/cli/chunks/{chunk-ONMJJ2C3.js → chunk-LI2IOJMM.js} +1 -1
  75. package/dist/cli/chunks/{heartbeat-scheduler-OH3SS7MH.js → chunk-LR5VW3OS.js} +2 -2
  76. package/dist/cli/chunks/{chunk-XY3WUGD3.js → chunk-LTSNDM5N.js} +2 -2
  77. package/dist/cli/chunks/{chunk-CQWZNVIM.js → chunk-M5PYPGBC.js} +2 -2
  78. package/dist/cli/chunks/{chunk-RTGNWRQI.js → chunk-MEHNT37H.js} +2 -2
  79. package/dist/cli/chunks/{chunk-ZG4EKPGV.js → chunk-MERMCKPG.js} +1 -1
  80. package/dist/cli/chunks/{chunk-JKKV5KKS.js → chunk-MIHQIAVK.js} +2 -2
  81. package/dist/cli/chunks/{chunk-RDJWUKIR.js → chunk-MMVSERJQ.js} +2 -2
  82. package/dist/cli/chunks/{chunk-5WWQLPB4.js → chunk-MQQANXFS.js} +2 -2
  83. package/dist/cli/chunks/{chunk-I3TFGMOQ.js → chunk-MTOHV22P.js} +1 -1
  84. package/dist/cli/chunks/{chunk-7RPEBKQZ.js → chunk-NVZHCAEB.js} +2 -2
  85. package/dist/cli/chunks/{chunk-52D3CYE5.js → chunk-NW5FYGDE.js} +2 -2
  86. package/dist/cli/chunks/{chunk-UIRTXM7C.js → chunk-NZRJWK5H.js} +61 -121
  87. package/dist/cli/chunks/chunk-O5NEZCTB.js +2 -0
  88. package/dist/cli/chunks/{chunk-YQJBE6NX.js → chunk-O5UGJ3OI.js} +2 -2
  89. package/dist/cli/chunks/{chunk-WB6TI6Q3.js → chunk-OK2TFTXP.js} +2 -2
  90. package/dist/cli/chunks/{chunk-NNF3GCGF.js → chunk-OKEHGXIS.js} +2 -2
  91. package/dist/cli/chunks/{chunk-5AMAJCZS.js → chunk-OKRY4LNE.js} +3 -3
  92. package/dist/cli/chunks/{chunk-NZQYNUGM.js → chunk-OMOGD2NN.js} +2 -2
  93. package/dist/cli/chunks/{chunk-X2FLWV5C.js → chunk-ONNTJXU7.js} +2 -2
  94. package/dist/cli/chunks/{chunk-MYCVU3D3.js → chunk-OPOGZAN5.js} +2 -2
  95. package/dist/cli/chunks/{chunk-ZBJRNCWX.js → chunk-PG5F2VHA.js} +2 -2
  96. package/dist/cli/chunks/{chunk-JMLOEW7Y.js → chunk-PHRMWRXA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-N6SIKSCO.js → chunk-PIXUX2NR.js} +2 -2
  98. package/dist/cli/chunks/{chunk-IY4P35N3.js → chunk-PLGMPG7S.js} +2 -2
  99. package/dist/cli/chunks/{chunk-K37CNLQZ.js → chunk-PPS6VN24.js} +1 -1
  100. package/dist/cli/chunks/{chunk-XMMWYQJK.js → chunk-PQAYCK2U.js} +2 -2
  101. package/dist/cli/chunks/{chunk-SL4TAJOE.js → chunk-PS6ISBED.js} +2 -2
  102. package/dist/cli/chunks/{chunk-OXOXNAEZ.js → chunk-QPYNQSWD.js} +2 -2
  103. package/dist/cli/chunks/{chunk-62KYX5NH.js → chunk-QRTZ67BC.js} +2 -2
  104. package/dist/cli/chunks/{chunk-DUF733Z7.js → chunk-REW3W3ZW.js} +1 -1
  105. package/dist/cli/chunks/{chunk-T4DDCMKG.js → chunk-RHXYZ6AZ.js} +127 -127
  106. package/dist/cli/chunks/{chunk-VLAGWLHF.js → chunk-RZXAXWBD.js} +2 -2
  107. package/dist/cli/chunks/{chunk-XTWYCMAM.js → chunk-S4M7U6CZ.js} +2 -2
  108. package/dist/cli/chunks/{chunk-ROEIR3OD.js → chunk-SJETAUZA.js} +1 -1
  109. package/dist/cli/chunks/{chunk-47QIAHUJ.js → chunk-SLH7LFVY.js} +2 -2
  110. package/dist/cli/chunks/{chunk-XGBIXRKD.js → chunk-SRJ5N7LD.js} +2 -2
  111. package/dist/cli/chunks/{chunk-EKYPQ5DX.js → chunk-T5ADVYPH.js} +1 -1
  112. package/dist/cli/chunks/{chunk-7MXQV7RB.js → chunk-THYGFSTA.js} +2 -2
  113. package/dist/cli/chunks/{chunk-462MZLJB.js → chunk-TX2DBLTL.js} +1 -1
  114. package/dist/cli/chunks/{chunk-TVHWI77X.js → chunk-UJMGNO6L.js} +1 -1
  115. package/dist/cli/chunks/{chunk-YLEMSN46.js → chunk-UUQ3SOKM.js} +1 -1
  116. package/dist/cli/chunks/{chunk-ZWSRIJ2T.js → chunk-V5RLGPEW.js} +2 -2
  117. package/dist/cli/chunks/{chunk-CYUGE5ZQ.js → chunk-V6HM2BKJ.js} +1 -1
  118. package/dist/cli/chunks/{chunk-UIIEZMSM.js → chunk-V7I6FTLG.js} +1 -1
  119. package/dist/cli/chunks/{chunk-5M4F3PAL.js → chunk-V7ZBPSVG.js} +1 -1
  120. package/dist/cli/chunks/{chunk-VSKABN3B.js → chunk-VJL7DNUU.js} +2 -2
  121. package/dist/cli/chunks/{chunk-2NLZXG6V.js → chunk-VKCWWR6C.js} +1 -1
  122. package/dist/cli/chunks/chunk-VKNCMGOJ.js +29 -0
  123. package/dist/cli/chunks/{chunk-L4JTTPU7.js → chunk-W2VTHUDK.js} +2 -2
  124. package/dist/cli/chunks/{chunk-FOAWHNOP.js → chunk-W3JB3G7C.js} +2 -2
  125. package/dist/cli/chunks/{chunk-A424Z7LA.js → chunk-WQ4MT74X.js} +1 -1
  126. package/dist/cli/chunks/{chunk-GQFAVT2I.js → chunk-WTNM7NA4.js} +1 -1
  127. package/dist/cli/chunks/chunk-XB3SIYGU.js +62 -0
  128. package/dist/cli/chunks/{chunk-HHEIQHLQ.js → chunk-XCUNQ3FK.js} +2 -2
  129. package/dist/cli/chunks/{chunk-BMS7WFDB.js → chunk-XHQFVTFD.js} +1 -1
  130. package/dist/cli/chunks/{chunk-QMSDKKYG.js → chunk-YBUUAFKR.js} +1 -1
  131. package/dist/cli/chunks/{chunk-G2U7Q6V6.js → chunk-YJV6TTCW.js} +2 -2
  132. package/dist/cli/chunks/{chunk-GN7FUCJH.js → chunk-YUSGT2CU.js} +1 -1
  133. package/dist/cli/chunks/{chunk-JJRZOLDY.js → chunk-YUTSN5BK.js} +2 -2
  134. package/dist/cli/chunks/{chunk-G3YKCZWQ.js → chunk-YVMJTBXB.js} +3 -3
  135. package/dist/cli/chunks/chunk-YVQ4PR4H.js +2 -0
  136. package/dist/cli/chunks/{chunk-UNXUSYRL.js → chunk-Z2EDNMCQ.js} +2 -2
  137. package/dist/cli/chunks/{chunk-DMF4Z2M6.js → chunk-ZESMMAKZ.js} +2 -2
  138. package/dist/cli/chunks/{chunk-VA45HLBF.js → chunk-ZIVOT3B7.js} +2 -2
  139. package/dist/cli/chunks/{ci-LRTJSZHT.js → ci-NSF6OHB4.js} +2 -2
  140. package/dist/cli/chunks/{ci-output-LISCHUKD.js → ci-output-ZPDJ42U3.js} +2 -2
  141. package/dist/cli/chunks/{circuit-breaker-7PMP25KZ.js → circuit-breaker-Y2RUJDYG.js} +2 -2
  142. package/dist/cli/chunks/{claude-flow-setup-DOW4QVMC.js → claude-flow-setup-OH6G6KM2.js} +2 -2
  143. package/dist/cli/chunks/client-QQGRKAY7.js +2 -0
  144. package/dist/cli/chunks/{cline-installer-2NXQGW73.js → cline-installer-IHH4F27G.js} +2 -2
  145. package/dist/cli/chunks/{code-3X6RWAS7.js → code-SFAHWFTX.js} +2 -2
  146. package/dist/cli/chunks/{code-index-extractor-4ABP5WCP.js → code-index-extractor-GXECMOM2.js} +2 -2
  147. package/dist/cli/chunks/{codex-installer-V7PII6GL.js → codex-installer-UPMSAFCQ.js} +2 -2
  148. package/dist/cli/chunks/{completions-Y7LNQ63I.js → completions-5TX6LDHY.js} +2 -2
  149. package/dist/cli/chunks/{complexity-analyzer-XLYMAM6I.js → complexity-analyzer-J2ZR3XZB.js} +2 -2
  150. package/dist/cli/chunks/{continuedev-installer-GOT4TKNT.js → continuedev-installer-GWYZKB5A.js} +2 -2
  151. package/dist/cli/chunks/{copilot-installer-D6BAQVIO.js → copilot-installer-DQZMQWI7.js} +2 -2
  152. package/dist/cli/chunks/{cost-tracker-VT7C5Q52.js → cost-tracker-V7KIGCLZ.js} +2 -2
  153. package/dist/cli/chunks/{coverage-C62MRP4M.js → coverage-3X6LA2GZ.js} +3 -3
  154. package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +2 -0
  155. package/dist/cli/chunks/{cursor-installer-WAWSS2K2.js → cursor-installer-ENDG4JIU.js} +2 -2
  156. package/dist/cli/chunks/daemon-4XVAO7GT.js +16 -0
  157. package/dist/cli/chunks/daemon-TC65CQFK.js +10 -0
  158. package/dist/cli/chunks/{dag-attention-scheduler-SZIZWPV7.js → dag-attention-scheduler-JOSCDRZC.js} +2 -2
  159. package/dist/cli/chunks/{detect-AJX6NJEP.js → detect-KWZX3OMK.js} +2 -2
  160. package/dist/cli/chunks/{dist-node-E5X47QTY.js → dist-node-R4U2PJ47.js} +2 -2
  161. package/dist/cli/chunks/{domain-handler-FN3PIP45.js → domain-handler-BMYYZO2L.js} +2 -2
  162. package/dist/cli/chunks/{domain-transfer-N3TOJEMT.js → domain-transfer-MSDBBDLC.js} +2 -2
  163. package/dist/cli/chunks/dream-OCZK42FM.js +2 -0
  164. package/dist/cli/chunks/{embed-and-insert-pattern-PJI5TZKR.js → embed-and-insert-pattern-MFINPOLS.js} +2 -2
  165. package/dist/cli/chunks/{eval-OS54TDQU.js → eval-OER6UNUY.js} +2 -2
  166. package/dist/cli/chunks/{experience-capture-middleware-FBM4ANZW.js → experience-capture-middleware-F5I77ECG.js} +3 -3
  167. package/dist/cli/chunks/{fast-paths-2CVAAPQO.js → fast-paths-P3KT5DUQ.js} +2 -2
  168. package/dist/cli/chunks/{feature-flags-A5KFWVFC.js → feature-flags-5EBWQ5WU.js} +2 -2
  169. package/dist/cli/chunks/{feature-flags-GEXTW6OT.js → feature-flags-DYFZSQLV.js} +2 -2
  170. package/dist/cli/chunks/{file-discovery-KWLVC7KN.js → file-discovery-MOBVABSM.js} +2 -2
  171. package/dist/cli/chunks/{fleet-MNKH356S.js → fleet-J3R3NQNC.js} +3 -3
  172. package/dist/cli/chunks/{gnn-wrapper-ALTWYFVZ.js → gnn-wrapper-QD76SULF.js} +2 -2
  173. package/dist/cli/chunks/{heartbeat-handler-MBMEPEGW.js → heartbeat-handler-AJEWTPZ4.js} +4 -4
  174. package/dist/cli/chunks/heartbeat-scheduler-EAVZR6TJ.js +2 -0
  175. package/dist/cli/chunks/hnsw-adapter-BY4XB7FB.js +2 -0
  176. package/dist/cli/chunks/hnsw-index-657CZRG7.js +2 -0
  177. package/dist/cli/chunks/{hnsw-legacy-bridge-WTD5PR5V.js → hnsw-legacy-bridge-5VRM5N7K.js} +2 -2
  178. package/dist/cli/chunks/{better-sqlite3-NYOVLWBG.js → hnswlib-node-BWUH4OQT.js} +2 -2
  179. package/dist/cli/chunks/{hooks-ELHGEBFK.js → hooks-7PMVKQOE.js} +10 -10
  180. package/dist/cli/chunks/{hybrid-router-D6ZMIZCE.js → hybrid-router-2K2LW45J.js} +2 -2
  181. package/dist/cli/chunks/{hypergraph-engine-JOQ6TERZ.js → hypergraph-engine-2CQ735JO.js} +2 -2
  182. package/dist/cli/chunks/{hypergraph-handler-HX45YWWN.js → hypergraph-handler-AQ53GVIW.js} +3 -3
  183. package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +2 -0
  184. package/dist/cli/chunks/{init-handler-TNVU6NQ6.js → init-handler-ZOVJPAWO.js} +6 -6
  185. package/dist/cli/chunks/init-wizard-HOH577MH.js +2 -0
  186. package/dist/cli/chunks/kernel-JDYBG5GE.js +2 -0
  187. package/dist/cli/chunks/{kilocode-installer-YC5RJIY4.js → kilocode-installer-GWQCNLKI.js} +2 -2
  188. package/dist/cli/chunks/{kiro-installer-EAB26M55.js → kiro-installer-6KVES4MO.js} +2 -2
  189. package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +2 -0
  190. package/dist/cli/chunks/{learning-A2OB7D2B.js → learning-6XMNWXRT.js} +3 -3
  191. package/dist/cli/chunks/{llm-router-KEG6PA7C.js → llm-router-GS4AZJJC.js} +4 -4
  192. package/dist/cli/chunks/{load-D6ZDLVA3.js → load-FEMEQNE6.js} +2 -2
  193. package/dist/cli/chunks/load-test-3MEJ43U2.js +2 -0
  194. package/dist/cli/chunks/{mcp-ERJHZ6FN.js → mcp-6V2H7EXU.js} +2 -2
  195. package/dist/cli/chunks/{memory-GSRIJIVR.js → memory-YLGPOB2H.js} +5 -5
  196. package/dist/cli/chunks/memory-backend-2A47ZRGO.js +2 -0
  197. package/dist/cli/chunks/memory-handlers-UBTBC7D2.js +2 -0
  198. package/dist/cli/chunks/{multi-model-executor-GK3V7ERC.js → multi-model-executor-SL2EKAH2.js} +2 -2
  199. package/dist/cli/chunks/{opencode-installer-6TTN26RG.js → opencode-installer-ADOJVGNA.js} +2 -2
  200. package/dist/cli/chunks/{orchestrator-YVTSM6QW.js → orchestrator-O4IWW2VU.js} +5 -5
  201. package/dist/cli/chunks/{pipeline-EWLJCY5G.js → pipeline-5BD5YQNQ.js} +2 -2
  202. package/dist/cli/chunks/{platform-2ULHQQME.js → platform-HXSUOOJH.js} +2 -2
  203. package/dist/cli/chunks/{plugin-PYN2KOXA.js → plugin-HOLH5CUH.js} +2 -2
  204. package/dist/cli/chunks/{prime-radiant-advanced-wasm-IULCTOGZ.js → prime-radiant-advanced-wasm-PJTL7OLS.js} +2 -2
  205. package/dist/cli/chunks/protocol-executor-3FR7FBVM.js +2 -0
  206. package/dist/cli/chunks/{protocol-handler-FZYI2SBP.js → protocol-handler-K27YGLC7.js} +2 -2
  207. package/dist/cli/chunks/{prove-DN7S74SP.js → prove-MHCLHQQ6.js} +2 -2
  208. package/dist/cli/chunks/{provider-manager-FT3MCROB.js → provider-manager-3645PPXX.js} +2 -2
  209. package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +2 -0
  210. package/dist/cli/chunks/{quality-ITBU6LGC.js → quality-NDE6EDOY.js} +2 -2
  211. package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +2 -0
  212. package/dist/cli/chunks/{real-embeddings-PZUZ5RXJ.js → real-embeddings-VD3EVV3U.js} +2 -2
  213. package/dist/cli/chunks/{roocode-installer-2LMVZOUZ.js → roocode-installer-63Y45UUG.js} +2 -2
  214. package/dist/cli/chunks/router-23HRN2Z6.js +2 -0
  215. package/dist/cli/chunks/routing-feedback-R6A4B6ZG.js +2 -0
  216. package/dist/cli/chunks/{routing-handler-5RB73UCF.js → routing-handler-76XISU2E.js} +2 -2
  217. package/dist/cli/chunks/{ruvector-commands-VBN4APMG.js → ruvector-commands-AEKOZZHZ.js} +2 -2
  218. package/dist/cli/chunks/{rvf-dual-writer-BNY4AUWT.js → rvf-dual-writer-4DMUIZQF.js} +2 -2
  219. package/dist/cli/chunks/{rvf-migration-adapter-73MKPBGV.js → rvf-migration-adapter-YUTXFOZ3.js} +2 -2
  220. package/dist/cli/chunks/{rvf-migration-coordinator-SGVB7ZAZ.js → rvf-migration-coordinator-XJ5N2W37.js} +2 -2
  221. package/dist/cli/chunks/rvf-native-adapter-QINEJZM7.js +2 -0
  222. package/dist/cli/chunks/safe-db-YXMCSKFH.js +2 -0
  223. package/dist/cli/chunks/schedule-XVFD27P5.js +2 -0
  224. package/dist/cli/chunks/scheduler-NWH2IDEU.js +2 -0
  225. package/dist/cli/chunks/{security-XUH4H7R3.js → security-6YS6GQGO.js} +3 -3
  226. package/dist/cli/chunks/shared-rvf-adapter-FTZY35WI.js +2 -0
  227. package/dist/cli/chunks/{shared-rvf-dual-writer-GML4EDYF.js → shared-rvf-dual-writer-MH2Y65HA.js} +2 -2
  228. package/dist/cli/chunks/sqlite-persistence-BR6YJF5P.js +2 -0
  229. package/dist/cli/chunks/{status-handler-XI7GJF6Z.js → status-handler-57JQMPY5.js} +2 -2
  230. package/dist/cli/chunks/{structural-health-WPCYKOXV.js → structural-health-34D5VWRD.js} +2 -2
  231. package/dist/cli/chunks/sync-HJD2US5P.js +2 -0
  232. package/dist/cli/chunks/sync-TTQ6ZB5D.js +17 -0
  233. package/dist/cli/chunks/{task-handler-FZB55IEG.js → task-handler-4RF57637.js} +2 -2
  234. package/dist/cli/chunks/{task-handlers-EXZGFH7F.js → task-handlers-BRSK7HDE.js} +3 -3
  235. package/dist/cli/chunks/{test-XYRN4OVU.js → test-GMUW2VR3.js} +4 -4
  236. package/dist/cli/chunks/{test-scheduling-FLVOPGOT.js → test-scheduling-7LF24IFV.js} +3 -3
  237. package/dist/cli/chunks/{token-bootstrap-FDCFVRHM.js → token-bootstrap-VYT4RTHU.js} +2 -2
  238. package/dist/cli/chunks/{token-usage-MHNZF3DM.js → token-usage-NFNCPQGW.js} +2 -2
  239. package/dist/cli/chunks/{transformers-4CRVTMWY.js → transformers-GGD5GIEY.js} +2 -2
  240. package/dist/cli/chunks/{tree-sitter-wasm-parser-CI3V4AND.js → tree-sitter-wasm-parser-GKYG6NKT.js} +2 -2
  241. package/dist/cli/chunks/{types-RKCD4BNL.js → types-WJ3ZTRD5.js} +2 -2
  242. package/dist/cli/chunks/unified-memory-AT3Z4CY7.js +2 -0
  243. package/dist/cli/chunks/unified-memory-hnsw-6FOIGINN.js +2 -0
  244. package/dist/cli/chunks/unified-persistence-TCJB7MQS.js +2 -0
  245. package/dist/cli/chunks/{upgrade-463W7VKH.js → upgrade-IMBT4F6K.js} +2 -2
  246. package/dist/cli/chunks/{validate-LENSMEAY.js → validate-76OVF45Z.js} +2 -2
  247. package/dist/cli/chunks/{validate-swarm-4FEBNAWA.js → validate-swarm-HH2ZYWXA.js} +2 -2
  248. package/dist/cli/chunks/{vibium-TXNVIVWJ.js → vibium-74WQNDBX.js} +2 -2
  249. package/dist/cli/chunks/visual-security-IBAUX2K5.js +2 -0
  250. package/dist/cli/chunks/{web-tree-sitter-BZEGWID4.js → web-tree-sitter-W6RGE4SL.js} +2 -2
  251. package/dist/cli/chunks/{windsurf-installer-7AFXJTPU.js → windsurf-installer-7DMSFCA2.js} +2 -2
  252. package/dist/cli/chunks/{witness-chain-G6SUZOZG.js → witness-chain-BLZ4ZKAD.js} +2 -2
  253. package/dist/cli/chunks/witness-chain-GNNF23XU.js +2 -0
  254. package/dist/cli/chunks/{workflow-EVQPO6FH.js → workflow-RNSDKRZ4.js} +4 -4
  255. package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +2 -0
  256. package/dist/cli/chunks/{wrappers-HR6RUDI2.js → wrappers-J7RXMIOY.js} +2 -2
  257. package/dist/domains/learning-optimization/services/learning-coordinator.js +37 -17
  258. package/dist/kernel/hybrid-backend.d.ts +17 -7
  259. package/dist/kernel/hybrid-backend.js +24 -10
  260. package/dist/kernel/interfaces.d.ts +21 -6
  261. package/dist/kernel/memory-backend.d.ts +5 -5
  262. package/dist/kernel/memory-backend.js +14 -7
  263. package/dist/mcp/bundle.js +447 -447
  264. package/dist/mcp/handlers/core-handlers.js +21 -0
  265. package/dist/workers/interfaces.d.ts +26 -0
  266. package/dist/workers/worker-manager.d.ts +15 -12
  267. package/dist/workers/worker-manager.js +11 -0
  268. package/dist/workers/workers/learning-consolidation.js +116 -89
  269. package/package.json +3 -1
  270. package/dist/cli/chunks/adapter-CI2GZYME.js +0 -2
  271. package/dist/cli/chunks/aqe-learning-engine-KNQKALLI.js +0 -2
  272. package/dist/cli/chunks/base-P7PRMQWY.js +0 -2
  273. package/dist/cli/chunks/browser-workflow-QUP4A763.js +0 -2
  274. package/dist/cli/chunks/chunk-5Z6PYYWK.js +0 -2
  275. package/dist/cli/chunks/chunk-RBDAHW2M.js +0 -2
  276. package/dist/cli/chunks/client-XF6SJO2C.js +0 -2
  277. package/dist/cli/chunks/cross-domain-router-J2OFPM6R.js +0 -2
  278. package/dist/cli/chunks/daemon-CP2ETHRF.js +0 -19
  279. package/dist/cli/chunks/dream-D5LD5SOZ.js +0 -2
  280. package/dist/cli/chunks/hnsw-adapter-M2MMM3N6.js +0 -2
  281. package/dist/cli/chunks/hnsw-index-JO7KNF7M.js +0 -2
  282. package/dist/cli/chunks/impact-analyzer-ROQL4J7P.js +0 -2
  283. package/dist/cli/chunks/init-wizard-4BDFZX4M.js +0 -2
  284. package/dist/cli/chunks/kernel-37Y63WKR.js +0 -2
  285. package/dist/cli/chunks/knowledge-graph-V3DX6ZCX.js +0 -2
  286. package/dist/cli/chunks/load-test-HPBA2CMT.js +0 -2
  287. package/dist/cli/chunks/memory-backend-DODDBB46.js +0 -2
  288. package/dist/cli/chunks/memory-handlers-MFLCRS7V.js +0 -2
  289. package/dist/cli/chunks/protocol-executor-D56OYMCJ.js +0 -2
  290. package/dist/cli/chunks/qe-reasoning-bank-KXROIEK7.js +0 -2
  291. package/dist/cli/chunks/queen-coordinator-XOGATERL.js +0 -2
  292. package/dist/cli/chunks/router-3EHNUCOM.js +0 -2
  293. package/dist/cli/chunks/routing-feedback-ZHKGET22.js +0 -2
  294. package/dist/cli/chunks/rvf-native-adapter-4YC5IQUW.js +0 -2
  295. package/dist/cli/chunks/safe-db-PLJRHQIC.js +0 -2
  296. package/dist/cli/chunks/schedule-7DGELVJE.js +0 -2
  297. package/dist/cli/chunks/scheduler-VWASEC2J.js +0 -2
  298. package/dist/cli/chunks/shared-rvf-adapter-DCVDY2XW.js +0 -2
  299. package/dist/cli/chunks/sqlite-persistence-CTEBGVOW.js +0 -2
  300. package/dist/cli/chunks/sync-SFKTCRZC.js +0 -23
  301. package/dist/cli/chunks/unified-memory-YDKXKW3D.js +0 -2
  302. package/dist/cli/chunks/unified-memory-hnsw-6N7YZCLR.js +0 -2
  303. package/dist/cli/chunks/unified-persistence-UTWLPUQI.js +0 -2
  304. package/dist/cli/chunks/visual-security-DGXSOFKD.js +0 -2
  305. package/dist/cli/chunks/witness-chain-VP4MF6EU.js +0 -2
  306. package/dist/cli/chunks/workflow-orchestrator-VXSYAKQY.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as f}from"./chunk-5Z6PYYWK.js";import{c as p}from"./chunk-NZQYNUGM.js";import{a as l,d as b}from"./chunk-5WWQLPB4.js";import{a as d,c as g}from"./chunk-CUSLB7MB.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H 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.32");process.exit(0)}
2
+ import{a as f}from"./chunk-YVQ4PR4H.js";import{c as p}from"./chunk-OMOGD2NN.js";import{a as l,d as b}from"./chunk-MQQANXFS.js";import{a as d,c as g}from"./chunk-HGWQC7PR.js";f();g();b();var v={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine",namespace:"coverage-hnsw",maxElements:1e5},S=p.create("coverage-analysis/hnsw-index"),u=class{constructor(e,t={}){this.memory=e;this.config={...v,...t},this.stats={vectorCount:0,searchOperations:0,insertOperations:0}}memory;config;stats;searchLatencies=[];backendType="ruvector-gnn";adapter=null;initialized=!1;metadataStore=new Map;async initialize(){if(this.initialized)return;let e=this.config.metric==="cosine"?"cosine":"euclidean",t=`coverage-${this.config.namespace}`;d.close(t),this.adapter=d.create(t,{dimensions:this.config.dimensions,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:e}),S.info(`HnswAdapter initialized: dimension=${this.config.dimensions}, metric=${this.config.metric}, M=${this.config.M} (unified backend via ADR-071)`),this.initialized=!0}isNativeAvailable(){return this.initialized&&this.adapter!==null}getBackendType(){return this.backendType}isRuvectorAvailable(){return this.initialized&&this.adapter!==null&&this.adapter.isRuvectorAvailable()}async insert(e,t,a){this.initialized||await this.initialize(),t=this.validateVector(t),this.adapter.addByStringId(e,t),a&&this.metadataStore.set(e,a),this.stats.insertOperations++,this.stats.vectorCount=this.adapter.size()}async search(e,t){this.initialized||await this.initialize(),e=this.validateVector(e);let a=performance.now(),n=[];this.adapter.size()>0&&(n=this.adapter.searchByArray(e,t).map(({id:i,score:o})=>({key:i,score:o,distance:1-o,metadata:this.metadataStore.get(i)})));let s=performance.now()-a;return this.recordSearchLatency(s),this.stats.searchOperations++,n}async batchInsert(e){this.initialized||await this.initialize();let t=100;for(let a=0;a<e.length;a+=t){let n=e.slice(a,a+t);await Promise.all(n.map(r=>this.insert(r.key,r.vector,r.metadata)))}}async delete(e){if(!this.adapter)return!1;let t=this.adapter.removeByStringId(e);if(t){this.metadataStore.delete(e);let a=this.buildKey(e);await this.memory.delete(a),this.stats.vectorCount=this.adapter.size()}return t}async getStats(){return{nativeHNSW:this.initialized&&this.adapter!==null,backendType:this.backendType,vectorCount:this.stats.vectorCount,indexSizeBytes:this.stats.vectorCount*this.config.dimensions*4,avgSearchLatencyMs:this.calculateAvgLatency(),p95SearchLatencyMs:this.calculatePercentileLatency(95),p99SearchLatencyMs:this.calculatePercentileLatency(99),searchOperations:this.stats.searchOperations,insertOperations:this.stats.insertOperations}}async clear(){this.metadataStore.clear(),this.adapter&&this.adapter.clear(),this.stats.vectorCount=0,this.searchLatencies=[]}validateVector(e){if(e.length!==this.config.dimensions)return this.resizeVector(e,this.config.dimensions);for(let t=0;t<e.length;t++)if(!Number.isFinite(e[t]))throw new Error(`Invalid vector value at index ${t}: ${e[t]}`);return e}resizeVector(e,t){if(e.length===t)return e;if(e.length>t){let n=new Array(t).fill(0),r=e.length/t;for(let s=0;s<t;s++){let h=Math.floor(s*r),i=Math.floor((s+1)*r),o=0;for(let m=h;m<i;m++)o+=e[m];n[s]=o/(i-h)}return n}let a=new Array(t).fill(0);for(let n=0;n<e.length;n++)a[n]=e[n];return a}buildKey(e){return`${this.config.namespace}:${e}`}recordSearchLatency(e){this.searchLatencies.push(e);let t=1e3;this.searchLatencies.length>t&&(this.searchLatencies=this.searchLatencies.slice(-t))}calculateAvgLatency(){return this.searchLatencies.length===0?0:this.searchLatencies.reduce((t,a)=>t+a,0)/this.searchLatencies.length}calculatePercentileLatency(e){if(this.searchLatencies.length===0)return 0;let t=[...this.searchLatencies].sort((n,r)=>n-r),a=Math.ceil(e/100*t.length)-1;return t[Math.max(0,a)]}setEfSearch(e){this.config.efSearch=e}};function C(c,e){return new u(c,e)}async function H(c,e=1e4,t=1e3){let n=performance.now();for(let i=0;i<e;i++){let o=Array.from({length:384},()=>l());await c.insert(`bench-${i}`,o)}let r=performance.now()-n,s=performance.now();for(let i=0;i<t;i++){let o=Array.from({length:384},()=>l());await c.search(o,10)}let h=performance.now()-s;return{insertTimeMs:r,searchTimeMs:h,avgSearchLatencyMs:h/t,isNative:c.isNativeAvailable(),backendType:c.getBackendType()}}export{v as a,u as b,C as c,H as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as F,c as D}from"./chunk-K6MFAVXK.js";import{d as $}from"./chunk-G2U7Q6V6.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-4CRVTMWY.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as F,c as D}from"./chunk-5WR42V5O.js";import{d as $}from"./chunk-YJV6TTCW.js";$();D();var b=null,l=null,d=null,g=!1,f="",h={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4},o=new Map,P=36e5;function I(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function A(t={}){if(g)throw new Error(`Transformer initialization previously failed: ${f}`);if(d)return d;let e={...h,...t};return d=(async()=>{try{b=(await import("./transformers-GGD5GIEY.js")).pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let a=performance.now();l=await b("feature-extraction",e.modelName,{quantized:e.quantized});let s=performance.now()-a;console.log(`[RealEmbeddings] Model loaded in ${s.toFixed(0)}ms`)}catch(r){throw g=!0,f=F(r),new Error(`Failed to initialize transformer model: ${f}`)}})(),d}async function q(t,e={}){let r={...h,...e};if(I(t))return new Array(N()).fill(0);if(r.enableCache){let i=o.get(t);if(i&&Date.now()-i.timestamp<P)return i.embedding}if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let a=performance.now(),s=await l(t,{pooling:"mean",normalize:!0}),m=Array.from(s.data),n=performance.now()-a;if(n>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${n.toFixed(1)}ms for "${t.slice(0,50)}..."`),r.enableCache){if(o.size>=r.maxCacheSize){let i=o.keys().next().value;i&&o.delete(i)}o.set(t,{embedding:m,timestamp:Date.now()})}return m}async function B(t,e={}){let r={...h,...e},a=[],s=[],m=new Array(t.length).fill(null);if(r.enableCache)for(let n=0;n<t.length;n++){let i=o.get(t[n]);i&&Date.now()-i.timestamp<P?m[n]=i.embedding:(a.push(t[n]),s.push(n))}else{a.push(...t);for(let n=0;n<t.length;n++)s.push(n)}if(a.length>0){if(l||await A(e),!l)throw new Error("Embedding model failed to initialize");let n=performance.now(),i=32;for(let c=0;c<a.length;c+=i){let M=Math.min(c+i,a.length),p=a.slice(c,M),E=await l(p,{pooling:"mean",normalize:!0}),w=E.dims||[p.length,384],R=w[0],C=w[1];for(let u=0;u<R;u++){let z=u*C,x=Array.from(E.data.slice(z,z+C)),y=c+u,v=s[y];if(m[v]=x,r.enableCache){if(o.size>=r.maxCacheSize){let T=o.keys().next().value;T&&o.delete(T)}o.set(a[y],{embedding:x,timestamp:Date.now()})}}}let S=performance.now()-n;console.log(`[RealEmbeddings] Batch computed ${a.length} embeddings in ${S.toFixed(0)}ms`)}return m.filter(n=>n!==null)}function O(){o.clear(),console.log("[RealEmbeddings] Cache cleared")}function W(){return{size:o.size,hitRate:0}}function k(){return!g&&l!==null}function N(){return 384}function G(){b=null,l=null,d=null,g=!1,f="",o.clear()}export{h as a,q as b,B as c,O as d,W as e,k as f,N as g,G as h};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}timeoutMs};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as 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(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as v}from"./chunk-YVQ4PR4H.js";import{c as l}from"./chunk-OMOGD2NN.js";import{S as R,b as g}from"./chunk-33PGBYTC.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,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{a as T,c as N}from"./chunk-K6MFAVXK.js";import{b as D,c as L,d as V}from"./chunk-5WWQLPB4.js";N();V();import*as C from"fs";import*as v from"path";import*as W from"yaml";var q=5,H=4,Q=3e4,K=".claude/skills",B=5e3,J=500,$=100,Y=1e3,F=500,z=.8,X=.2,Z=.1,w=.1,ee=.1,te=.1,se=.1,re=200,ne=500,ae=300,ie=1,oe=.9,U={maxWorkers:q,batchSize:H,retryFailedTests:!0,timeout:Q,skillsDir:K,progressIntervalMs:B},S=class{async execute(e,r,t){let s=L($,J+$);return await new Promise(o=>setTimeout(o,s)),{output:this.generateMockResponse(e),tokensUsed:D(F,Y+F),durationMs:s}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as T,c as N}from"./chunk-5WR42V5O.js";import{b as D,c as L,d as V}from"./chunk-MQQANXFS.js";N();V();import*as C from"fs";import*as v from"path";import*as W from"yaml";var q=5,H=4,Q=3e4,K=".claude/skills",B=5e3,J=500,$=100,Y=1e3,F=500,z=.8,X=.2,Z=.1,w=.1,ee=.1,te=.1,se=.1,re=200,ne=500,ae=300,ie=1,oe=.9,U={maxWorkers:q,batchSize:H,retryFailedTests:!0,timeout:Q,skillsDir:K,progressIntervalMs:B},S=class{async execute(e,r,t){let s=L($,J+$);return await new Promise(o=>setTimeout(o,s)),{output:this.generateMockResponse(e),tokensUsed:D(F,Y+F),durationMs:s}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
3
3
  Recommendations: Implement proper ${r[0]} attributes for better accessibility.
4
4
  Severity: ${e.includes("critical")?"critical":"serious"}`}},M=class{constructor(e,r,t){this.executor=r;this.config=t;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let t of e){this.lastHeartbeat=Date.now();try{let s=await this.executeTestCase(t);if(r.push(s),s.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!s.passed){let n=await this.executeTestCase(t,!0);n.passed&&(r[r.length-1]=n,this.tasksCompleted++,this.tasksFailed--)}}catch(s){this.tasksFailed++,r.push({testId:t.testCaseId,passed:!1,expectedPatterns:t.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:t.testCase.category,priority:t.testCase.priority,error:T(s)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let t=Date.now(),s=this.buildPrompt(e),n=await this.executor.execute(s,e.model,{timeout:this.config.timeout}),o=this.validateResponse(n.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:o.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:o.foundPatterns,reasoningQuality:o.reasoningQuality,executionTimeMs:Date.now()-t,category:e.testCase.category,priority:e.testCase.priority,error:o.error}}buildPrompt(e){let{testCase:r}=e,t=r.input.context;return`Analyze the following ${t.language||"HTML"} code for accessibility issues.
5
5
  Context: ${t.description||r.description}
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{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=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{d as k,f as we}from"./chunk-ONNTJXU7.js";import{b as C,d as Z}from"./chunk-OK2TFTXP.js";import{a as ye}from"./chunk-YVQ4PR4H.js";import{c as Q}from"./chunk-OMOGD2NN.js";import{a as V,c as De}from"./chunk-5WR42V5O.js";import{a as J,b as Xe}from"./chunk-4VAZSCTZ.js";import{a as ee,d as D,e as te,f as ne}from"./chunk-PIXUX2NR.js";import{a as v,e as be}from"./chunk-BBPOTFIY.js";import{c as R,e as ve}from"./chunk-XHQFVTFD.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,
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  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,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{h as U}from"./chunk-62KYX5NH.js";import{c as D,d as R,e as h,g as x}from"./chunk-ROEIR3OD.js";import{a as v}from"./chunk-JJRZOLDY.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function $(u={},e,t){return new p(u,e,t)}async function I(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-CI2GZYME.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,$ as b,I as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{a as v}from"./chunk-YUTSN5BK.js";import{h as U}from"./chunk-QRTZ67BC.js";import{c as D,d as R,e as h,g as x}from"./chunk-SJETAUZA.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function $(u={},e,t){return new p(u,e,t)}async function I(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-CDQOF5TF.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,$ as b,I as c};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var o=!1;function r(t){if(!o){for(let e of["ALTER TABLE routing_outcomes ADD COLUMN exploration INTEGER NOT NULL DEFAULT 0","ALTER TABLE routing_outcomes ADD COLUMN criticality REAL","ALTER TABLE routing_outcomes ADD COLUMN q_weight REAL"])try{t.prepare(e).run()}catch{}try{t.prepare("CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration)").run()}catch{}o=!0}}export{r as a};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var i={domain:"test-generation",bestPractices:["Follow Arrange-Act-Assert (AAA) pattern for clear test structure","One logical assertion per test - test one behavior at a time","Use descriptive test names: should_returnValue_when_condition","Mock external dependencies to isolate unit under test","Test edge cases and boundary conditions, not just happy paths","Keep tests deterministic - avoid time-dependent assertions","Use test data builders or factories for complex objects","Prefer integration tests for workflows, unit tests for logic","Maintain test independence - no shared mutable state between tests","Write failing test first (TDD Red) before implementation"],antiPatterns:[{name:"God Test",description:"A single test that verifies too many behaviors",reason:"Hard to diagnose failures, brittle, slow to run",alternative:"Split into focused tests, each verifying one behavior",detection:"expect.*expect.*expect.*expect.*expect"},{name:"Mystery Guest",description:"Test relies on external data files or state not visible in test",reason:"Tests are hard to understand and maintain",alternative:"Make test data explicit within the test or use fixtures"},{name:"Eager Test",description:"Test that verifies more than needed for the current behavior",reason:"Creates unnecessary coupling, breaks easily",alternative:"Only assert what is necessary for this specific test case"},{name:"Flaky Assertion",description:"Assertions that depend on timing, order, or external state",reason:"Creates unreliable test suite, erodes trust",alternative:"Use deterministic assertions, mock time/random",detection:"setTimeout|Date\\.now|Math\\.random"},{name:"Test Code Duplication",description:"Same setup or assertion code repeated across tests",reason:"Maintenance burden, inconsistency risk",alternative:"Extract to beforeEach, helpers, or fixtures"}],frameworkGuidance:{jest:["Use describe blocks to group related tests","Prefer toEqual for deep equality, toBe for primitives","Use jest.mock() at module level for consistent mocking","Use jest.spyOn for partial mocking of objects","Enable --coverage to track test coverage"],vitest:["Use vi.mock() for module mocking","Prefer vi.fn() over jest.fn() syntax","Use vitest/ui for interactive test debugging","Enable browser mode for component tests","Use inline snapshots for small expected values"],mocha:["Use beforeEach/afterEach for setup/teardown","Combine with chai for assertions","Use sinon for spies, stubs, and mocks","Set appropriate timeouts for async tests"],pytest:["Use fixtures for reusable test setup","Use parametrize for data-driven tests","Use conftest.py for shared fixtures","Use pytest.raises for exception testing","Use pytest-cov for coverage reporting"],junit:["Use @BeforeEach and @AfterEach for setup/teardown","Use @DisplayName for readable test names","Use @ParameterizedTest for data-driven tests","Use Mockito for mocking dependencies"],testng:["Use @BeforeMethod and @AfterMethod appropriately","Use @DataProvider for parameterized tests","Configure test groups for selective execution"],playwright:["Use page.locator() for resilient element selection","Use expect(locator) for auto-waiting assertions","Use page.waitForLoadState for navigation","Use test.describe for grouping tests","Use fixtures for reusable browser contexts"],cypress:["Use cy.intercept() for API mocking","Avoid conditional testing - use deterministic state","Use data-cy attributes for stable selectors","Use cy.within() for scoped queries","Prefer cy.contains() for text-based selection"],selenium:["Use explicit waits over implicit waits","Use Page Object Model for maintainability","Handle stale element references with retry logic","Clean up browser state between tests"]},languageGuidance:{typescript:["Use type assertions in tests for better IDE support","Create typed test fixtures and builders","Use satisfies operator for test data validation","Mock types with ts-mockito or typed mocking libs"],javascript:["Use JSDoc comments for test documentation","Consider TypeScript for larger test suites","Use ESLint with testing plugins"],python:["Use type hints in test functions","Use dataclasses for test data","Follow PEP 8 naming: test_should_do_something"],java:["Use AssertJ for fluent assertions","Use Lombok for test data classes","Follow naming: shouldDoSomething_whenCondition"],go:["Use table-driven tests for multiple cases","Use testify for assertions and mocking","Place tests in _test.go files"],rust:["Use #[test] attribute for test functions","Use assert!, assert_eq!, assert_ne! macros","Place unit tests in same file with #[cfg(test)]"],csharp:["Use xUnit or NUnit for testing","Use FluentAssertions for readable assertions","Use Moq for mocking interfaces"],kotlin:["Use kotest for BDD-style testing","Use MockK for Kotlin-first mocking","Use data classes for test fixtures"]},examples:[{title:"Unit Test Template (TypeScript + Vitest)",description:"Standard AAA pattern for unit tests",content:`describe('UserService', () => {
3
3
  describe('createUser', () => {
4
4
  it('should create user with valid data', async () => {
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  var 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,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.31");process.exit(0)}
2
- import{c as N,g as O}from"./chunk-XTWYCMAM.js";import{k as R,o as D}from"./chunk-7MXQV7RB.js";import{b as g,d as C}from"./chunk-WB6TI6Q3.js";import{a as _,c as A}from"./chunk-K6MFAVXK.js";import{i as h}from"./chunk-GQFAVT2I.js";import{a as S,b as q}from"./chunk-CFLA2GBS.js";q();C();A();D();function L(E,e){let n=E.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!n)return{updated:!1};let t=e.success?1:0,r=n.usage_count+1,s=n.successful_uses+t,a=s/r,i=Math.min(1,r/100),o=n.confidence*.3+i*.2+a*.5,c=E.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.32");process.exit(0)}
2
+ import{c as N,g as O}from"./chunk-S4M7U6CZ.js";import{k as R,o as D}from"./chunk-THYGFSTA.js";import{b as g,d as C}from"./chunk-OK2TFTXP.js";import{a as _,c as A}from"./chunk-5WR42V5O.js";import{i as h}from"./chunk-WTNM7NA4.js";import{a as S,b as q}from"./chunk-4VAZSCTZ.js";q();C();A();D();function L(E,e){let n=E.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!n)return{updated:!1};let t=e.success?1:0,r=n.usage_count+1,s=n.successful_uses+t,a=s/r,i=Math.min(1,r/100),o=n.confidence*.3+i*.2+a*.5,c=E.prepare(`
3
3
  INSERT INTO qe_pattern_usage (pattern_id, success, metrics_json, feedback)
4
4
  VALUES (?, ?, ?, ?)
5
5
  `),p=E.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.31");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
2
  import{createRequire as t}from"module";var o=t(import.meta.url),e=o("@xenova/transformers"),n=e,{RuvectorLayer:i,TensorCompress:a,differentiableSearch:s,hierarchicalForward:c,getCompressionLevel:l,init:p,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:d,HyperbolicAttention:A,LinearAttention:f,MoEAttention:h,SonaEngine:_,pipeline:v}=e||{};export{n as a,i as b,a as c,s as d,c as e,l as f,p as g,m as h,u as i,d as j,A as k,f as l,h as m,_ as n,v as o};
@@ -0,0 +1,29 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
2
+ import{o as me}from"./chunk-VKCWWR6C.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-THYGFSTA.js";import{a as Re,b as _,d as ee}from"./chunk-OK2TFTXP.js";import{a as v}from"./chunk-YVQ4PR4H.js";import{c as b}from"./chunk-OMOGD2NN.js";import{a as d,b as q,c as P}from"./chunk-5WR42V5O.js";import{i as I}from"./chunk-WTNM7NA4.js";import{a as T,b as z}from"./chunk-4VAZSCTZ.js";import{a as le,d as Te}from"./chunk-YJV6TTCW.js";import{f as Ce}from"./chunk-XHQFVTFD.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function ke(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}A();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
3
+ INSERT INTO ${u} (${p.join(", ")})
4
+ VALUES ${s.join(", ")}
5
+ ${h}
6
+ `;try{return(await this.client.query(y,a)).rowCount||0}catch(f){throw N.debug(`Upsert failed for ${e}`,{error:d(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){N.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function O(l){return new J(l)}A();P();v();var G=b.create("postgres-reader"),Q=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${E(n)}.${E(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let i=await this.writer.query(n,r);return G.debug(`Read ${i.length} records from ${e.cloudTable}`,{env:this.environment}),i.map(o=>this.transformRecord(o,e))}catch(i){throw new Error(`Failed to read from ${e.cloudTable}: ${d(i)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return G.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let i,o;this.environment!=="all"?(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1 AND source_env = $2`,o=[t.toISOString(),this.environment]):(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1`,o=[t.toISOString()]);try{return(await this.writer.query(i,o)).map(a=>this.transformRecord(a,e))}catch(s){return G.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:d(s)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let i=await this.writer.query(n,r);return await this.writer.commit(),typeof i[0]?.count=="string"?parseInt(i[0].count,10):i[0]?.count||0}catch(i){try{await this.writer.rollback()}catch{}return G.debug(`Count query failed for ${e.cloudTable}`,{error:d(i)}),-1}}transformRecord(e,t){let n={};for(let[r,i]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let o=t.columnMap?.[r]||r;n[o]=this.transformValue(i,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],o=(await this.writer.query(`SELECT column_name FROM information_schema.columns
7
+ WHERE table_schema = $1 AND table_name = $2
8
+ AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(s=>s.column_name);for(let s of t)if(o.includes(s))return s;return o[0]||null}catch{return null}}};function ie(l){return new Q(l)}z();A();P();v();import*as ye from"fs";var D=b.create("sqlite-writer"),V=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!ye.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=T(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),D.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=w(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return D.debug(`No columns found for table ${e}`),0;let i=new Set(r),o=0;for(let s=0;s<t.length;s+=this.batchSize){let a=t.slice(s,s+this.batchSize);try{let c=this.upsertBatch(n,a,i);o+=c}catch(c){let u=Math.floor(s/this.batchSize)+1;D.debug(`Batch ${u} failed for ${e}, retrying individually`,{error:d(c)});let p=0;for(let m of a)try{p+=this.upsertBatch(n,[m],i)}catch(g){let h=m.id||m.key||"?";D.debug(`Skipped record ${String(h).slice(0,50)} in ${e}`,{error:d(g)})}o+=p}}return o}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=w(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,D.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(i=>i.pk>0).sort((i,o)=>i.pk-o.pk).map(i=>i.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],i=Object.keys(r).filter(g=>n.has(g));if(i.length===0)return 0;let o=i.map(E),s=i.map(()=>"?").join(", "),a=e.replace(/"/g,""),c=this.getPrimaryKeyColumns(a),u;if(c.length>0){let g=c.map(E),h=i.filter(y=>!c.includes(y));if(h.length>0){let y=h.map(f=>`${E(f)} = excluded.${E(f)}`).join(", ");u=`INSERT INTO ${e} (${o.join(", ")}) VALUES (${s}) ON CONFLICT(${g.join(", ")}) DO UPDATE SET ${y}`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`;let p=this.db.prepare(u);return this.db.transaction(g=>{let h=0;for(let y of g){let f=i.map(S=>this.serializeValue(y[S]));p.run(...f),h++}return h})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function oe(l){return new V(l)}v();P();var Ne=b.create("sync-agent"),H=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...x,...e,local:{...x.local,...e.local},cloud:{...x.cloud,...e.cloud},sync:{...x.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let i=await this.syncSource(r);this.report.results.push(i),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let i=await this.syncSourceIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let i=await r.readAll();if(this.log(`Read ${i.length} records from ${e.name}`),i.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let o=await this.writer.upsert(e.targetTable,i,{skipIfExists:e.mode==="append"});n.recordsSynced=o}else n.recordsSynced=i.length,this.log(`[DRY RUN] Would sync ${i.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=d(r),this.config.onError?.(q(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let i=this.readers.get(e.name);if(!i)throw new Error(`Reader not found: ${e.name}`);let o=await i.readChanged(t);if(this.log(`Read ${o.length} changed records from ${e.name} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o);r.recordsSynced=s}else r.recordsSynced=o.length;r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),i=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),i=o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}Ne.debug("Cloud count query failed",{source:t.name,error:o instanceof Error?o.message:String(o)}),i=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:i,match:r===i,diff:r-i})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?ne({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=$(this.config.cloud);this.writer=O({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function se(l){return new H(l)}async function Oe(l){let e=se({...l,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function De(l,e){let t=se({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(l)}finally{await t.close()}}import*as Y from"fs";import*as ae from"path";ue();P();v();var qt=b.create("pull-agent"),X=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...k,...e,cloud:{...k.cloud,...e.cloud},sources:e.sources||k.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=$(this.config.cloud);this.cloudWriter=O({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=oe({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let i=await this.pullTableIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let i=await this.writer.upsert(e.localTable,r);n.recordsSynced=i,n.recordsSkipped=r.length-i}n.success=!0}catch(r){n.error=d(r),this.config.onError?.(q(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let i=await this.reader.readChanged(e,t);if(this.log(`Read ${i.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),i.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=i.length;else{let o=await this.writer.upsert(e.localTable,i);r.recordsSynced=o}r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?ae.resolve(this.config.targetDb):ae.resolve(j(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Y.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Y.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${d(r)}`,"warn")}}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ce(l){return new X(l)}async function Le(l){let e=ce({...l,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function qe(l,e){let t=ce({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(l)}finally{await t.close()}}z();ue();ee();import{join as be}from"path";import{existsSync as Ie,mkdirSync as ze}from"fs";var K=class{memoryCache;maxSize;ttl;persistent;compression;db=null;storagePath;useUnified;unifiedMemory=null;pendingWrites=[];dbInitializing=!1;constructor(e={}){this.maxSize=e.maxSize||1e4,this.ttl=e.ttl||0,this.persistent=e.persistent??!0,this.compression=e.compression??!0,this.useUnified=e.useUnified??!0,this.storagePath=e.storagePath||be(j(),".agentic-qe","embeddings-cache.db"),this.memoryCache=new Map;let t=["text","code","test","coverage","defect"];for(let n of t)this.memoryCache.set(n,new Map);this.persistent&&this.initializePersistentStorage()}initializePersistentStorage(){try{if(this.useUnified)this.unifiedMemory=de(),this.dbInitializing=!0,this.unifiedMemory.initialize().then(()=>{this.db=this.unifiedMemory.getDatabase(),this.dbInitializing=!1,console.log(`[EmbeddingCache] Using unified storage: ${this.unifiedMemory.getDbPath()}`),this.loadFromDisk(),this.flushPendingWrites()}).catch(e=>{console.warn("[EmbeddingCache] Failed to initialize unified storage:",e),this.db=null,this.dbInitializing=!1,this.unifiedMemory=null,this.pendingWrites=[]});else{let e=be(this.storagePath,"..");Ie(e)||ze(e,{recursive:!0}),this.db=T(this.storagePath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.exec(`
9
+ CREATE TABLE IF NOT EXISTS embeddings (
10
+ key TEXT NOT NULL,
11
+ namespace TEXT NOT NULL,
12
+ vector BLOB NOT NULL,
13
+ dimension INTEGER NOT NULL,
14
+ text TEXT NOT NULL,
15
+ timestamp INTEGER NOT NULL,
16
+ quantization TEXT NOT NULL,
17
+ metadata TEXT,
18
+ access_count INTEGER DEFAULT 1,
19
+ last_access INTEGER NOT NULL,
20
+ PRIMARY KEY (key, namespace)
21
+ );
22
+
23
+ CREATE INDEX IF NOT EXISTS idx_namespace ON embeddings(namespace);
24
+ CREATE INDEX IF NOT EXISTS idx_timestamp ON embeddings(timestamp);
25
+ `),console.log(`[EmbeddingCache] Initialized (legacy): ${this.storagePath}`),this.loadFromDisk()}}catch(e){console.warn("Failed to initialize persistent storage:",e),this.db=null}}get(e,t="text"){let n=this.memoryCache.get(t);if(!n)return null;let r=n.get(e);return r?this.ttl>0&&Date.now()-r.lastAccess>this.ttl*1e3?(n.delete(e),null):(r.accessCount++,r.lastAccess=Date.now(),r.embedding):null}set(e,t,n="text"){let r=this.memoryCache.get(n);if(!r)return;r.size>=this.maxSize&&!r.has(e)&&this.evictLRU(n);let i={key:e,embedding:t,accessCount:1,lastAccess:Date.now()};r.set(e,i),this.persistent&&(this.db?this.persistToDisk(e,t,n):this.dbInitializing&&this.pendingWrites.push({key:e,embedding:t,namespace:n}))}has(e,t="text"){return this.memoryCache.get(t)?.has(e)||!1}delete(e,t="text"){let r=this.memoryCache.get(t)?.delete(e)||!1;return r&&this.persistent&&this.db&&this.db.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(e,t),r}clear(e){if(e)this.memoryCache.get(e)?.clear(),this.persistent&&this.db&&this.db.prepare("DELETE FROM embeddings WHERE namespace = ?").run(e);else{for(let t of this.memoryCache.values())t.clear();this.persistent&&this.db&&this.db.exec("DELETE FROM embeddings")}}getAll(e){let t=[];if(e)this.memoryCache.get(e)?.forEach(r=>t.push(r.embedding));else for(let n of this.memoryCache.values())n.forEach(r=>t.push(r.embedding));return t}evictLRU(e){let t=this.memoryCache.get(e);if(!t||t.size===0)return;let n=null,r=1/0;for(let[i,o]of t.entries())o.lastAccess<r&&(r=o.lastAccess,n=i);n&&(t.delete(n),this.persistent&&this.db&&this.db.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(n,e))}persistToDisk(e,t,n){if(this.db)try{let r=this.serializeVector(t.vector),i=t.metadata?JSON.stringify(t.metadata):null;this.db.prepare(`
26
+ INSERT OR REPLACE INTO embeddings
27
+ (key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
28
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
29
+ `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();this.config.onnxEnabled&&(this.model=await me("feature-extraction",this.config.model,{quantized:this.config.quantization!=="none",progress_callback:n=>{n.status==="downloading"&&console.log(`Downloading model: ${(n.progress*100).toFixed(0)}%`)}}));let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(i=>Math.fround(i)));case"int8":let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(i=>Math.round(i/n*127)));case"binary":let r=new Uint8Array(Math.ceil(e.length/8));for(let i=0;i<e.length;i++)e[i]>=0&&(r[Math.floor(i/8)]|=1<<i%8);return r;default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();A();P();ee();v();import{resolve as je,dirname as Fe}from"path";import{fileURLToPath as We}from"url";var Se=b.create("sync-embedding-generator"),Ue=We(import.meta.url),Be=Fe(Ue),L=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||je(Be,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){Se.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){Se.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function we(l){return new L(l)}export{k as a,Pe as b,x as c,W as d,re as e,U as f,ne as g,M as h,ke as i,B as j,$ as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Oe as t,De as u,X as v,ce as w,Le as x,qe as y,L as z,we 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.31");process.exit(0)}
2
- import{f as m}from"./chunk-AKJWBJDK.js";import{a as l,c as d}from"./chunk-K6MFAVXK.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-D6ZDLVA3.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};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.32");process.exit(0)}
2
+ import{f as m}from"./chunk-BDXEL3GM.js";import{a as l,c as d}from"./chunk-5WR42V5O.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-FEMEQNE6.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};export{c as a};