agentic-qe 3.9.7 → 3.9.9

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 (335) hide show
  1. package/.claude/skills/README.md +4 -3
  2. package/.claude/skills/a11y-ally/SKILL.md +40 -18
  3. package/.claude/skills/accessibility-testing/SKILL.md +4 -0
  4. package/.claude/skills/compatibility-testing/SKILL.md +23 -0
  5. package/.claude/skills/e2e-flow-verifier/SKILL.md +87 -52
  6. package/.claude/skills/enterprise-integration-testing/SKILL.md +4 -0
  7. package/.claude/skills/localization-testing/SKILL.md +14 -0
  8. package/.claude/skills/observability-testing-patterns/SKILL.md +16 -0
  9. package/.claude/skills/qe-browser/SKILL.md +409 -0
  10. package/.claude/skills/qe-browser/evals/qe-browser.yaml +291 -0
  11. package/.claude/skills/qe-browser/fixtures/package.json +7 -0
  12. package/.claude/skills/qe-browser/fixtures/serve-skills.js +130 -0
  13. package/.claude/skills/qe-browser/references/assertion-kinds.md +132 -0
  14. package/.claude/skills/qe-browser/references/migration-from-playwright.md +195 -0
  15. package/.claude/skills/qe-browser/schemas/output.json +188 -0
  16. package/.claude/skills/qe-browser/scripts/assert.js +378 -0
  17. package/.claude/skills/qe-browser/scripts/batch.js +292 -0
  18. package/.claude/skills/qe-browser/scripts/check-injection.js +267 -0
  19. package/.claude/skills/qe-browser/scripts/intent-score.js +325 -0
  20. package/.claude/skills/qe-browser/scripts/lib/vibium.js +330 -0
  21. package/.claude/skills/qe-browser/scripts/package.json +7 -0
  22. package/.claude/skills/qe-browser/scripts/smoke-test.sh +212 -0
  23. package/.claude/skills/qe-browser/scripts/validate-config.json +46 -0
  24. package/.claude/skills/qe-browser/scripts/visual-diff.js +276 -0
  25. package/.claude/skills/qe-visual-accessibility/SKILL.md +31 -1
  26. package/.claude/skills/security-visual-testing/SKILL.md +18 -0
  27. package/.claude/skills/skills-manifest.json +20 -13
  28. package/.claude/skills/testability-scoring/SKILL.md +23 -0
  29. package/.claude/skills/trust-tier-manifest.json +14 -3
  30. package/.claude/skills/visual-testing-advanced/SKILL.md +41 -1
  31. package/CHANGELOG.md +79 -0
  32. package/README.md +5 -3
  33. package/assets/skills/README.md +4 -3
  34. package/assets/skills/a11y-ally/SKILL.md +40 -18
  35. package/assets/skills/accessibility-testing/SKILL.md +4 -0
  36. package/assets/skills/compatibility-testing/SKILL.md +23 -0
  37. package/assets/skills/e2e-flow-verifier/SKILL.md +87 -52
  38. package/assets/skills/enterprise-integration-testing/SKILL.md +4 -0
  39. package/assets/skills/localization-testing/SKILL.md +14 -0
  40. package/assets/skills/observability-testing-patterns/SKILL.md +16 -0
  41. package/assets/skills/qe-browser/SKILL.md +409 -0
  42. package/assets/skills/qe-browser/evals/qe-browser.yaml +291 -0
  43. package/assets/skills/qe-browser/fixtures/package.json +7 -0
  44. package/assets/skills/qe-browser/fixtures/serve-skills.js +130 -0
  45. package/assets/skills/qe-browser/references/assertion-kinds.md +132 -0
  46. package/assets/skills/qe-browser/references/migration-from-playwright.md +195 -0
  47. package/assets/skills/qe-browser/schemas/output.json +188 -0
  48. package/assets/skills/qe-browser/scripts/assert.js +378 -0
  49. package/assets/skills/qe-browser/scripts/batch.js +292 -0
  50. package/assets/skills/qe-browser/scripts/check-injection.js +267 -0
  51. package/assets/skills/qe-browser/scripts/intent-score.js +325 -0
  52. package/assets/skills/qe-browser/scripts/lib/vibium.js +330 -0
  53. package/assets/skills/qe-browser/scripts/package.json +7 -0
  54. package/assets/skills/qe-browser/scripts/smoke-test.sh +212 -0
  55. package/assets/skills/qe-browser/scripts/validate-config.json +46 -0
  56. package/assets/skills/qe-browser/scripts/visual-diff.js +276 -0
  57. package/assets/skills/qe-visual-accessibility/SKILL.md +31 -1
  58. package/assets/skills/security-visual-testing/SKILL.md +18 -0
  59. package/assets/skills/skills-manifest.json +211 -15
  60. package/assets/skills/testability-scoring/SKILL.md +23 -0
  61. package/assets/skills/trust-tier-manifest.json +14 -3
  62. package/assets/skills/visual-testing-advanced/SKILL.md +41 -1
  63. package/dist/cli/bundle.js +5 -5
  64. package/dist/cli/chunks/adapter-XKXEZEMM.js +2 -0
  65. package/dist/cli/chunks/{agent-booster-wasm-MXTWTD4D.js → agent-booster-wasm-QEN7W6VC.js} +2 -2
  66. package/dist/cli/chunks/{agent-handler-6NEP2BOA.js → agent-handler-F3RLG42J.js} +2 -2
  67. package/dist/cli/chunks/{agent-memory-branch-SAPEIGE2.js → agent-memory-branch-U3PZ3CPL.js} +2 -2
  68. package/dist/cli/chunks/aqe-learning-engine-K7XGBDMZ.js +2 -0
  69. package/dist/cli/chunks/{audit-53LCI6R3.js → audit-FF6SP7Q2.js} +2 -2
  70. package/dist/cli/chunks/base-NUF35LIJ.js +2 -0
  71. package/dist/cli/chunks/{better-sqlite3-UZSKFGCK.js → better-sqlite3-CVXRDGQX.js} +2 -2
  72. package/dist/cli/chunks/{brain-handler-67NDDXVO.js → brain-handler-AMTRZ35W.js} +3 -3
  73. package/dist/cli/chunks/{branch-enumerator-IUIGYEK5.js → branch-enumerator-Y4A34YFT.js} +2 -2
  74. package/dist/cli/chunks/{browser-UFUF65LQ.js → browser-ETSF5GZR.js} +2 -2
  75. package/dist/cli/chunks/browser-workflow-MWPELXFA.js +2 -0
  76. package/dist/cli/chunks/{chunk-XD4UFF2Y.js → chunk-22HQFULR.js} +1 -1
  77. package/dist/cli/chunks/{chunk-W4Y4GFRB.js → chunk-2BSVGL35.js} +1 -1
  78. package/dist/cli/chunks/{chunk-KHH5UJXY.js → chunk-2HFPJPQW.js} +2 -2
  79. package/dist/cli/chunks/{chunk-LPLCT2HH.js → chunk-2JAYDTSE.js} +2 -2
  80. package/dist/cli/chunks/{chunk-RGJ4RMUR.js → chunk-2KY5B4ON.js} +8 -8
  81. package/dist/cli/chunks/{chunk-XB2GVTY6.js → chunk-2O3WZ6E3.js} +1 -1
  82. package/dist/cli/chunks/{chunk-5EOM3W6Q.js → chunk-2UP3DYNH.js} +2 -2
  83. package/dist/cli/chunks/{chunk-DS3XAGGL.js → chunk-2X7LDTVD.js} +2 -2
  84. package/dist/cli/chunks/{chunk-NJ5IC6ZR.js → chunk-2ZHA6ORO.js} +1 -1
  85. package/dist/cli/chunks/{chunk-FKJ4XZ6E.js → chunk-3F666FYP.js} +2 -2
  86. package/dist/cli/chunks/{chunk-7TKZ6LK6.js → chunk-3FAEM5M7.js} +1 -1
  87. package/dist/cli/chunks/{chunk-TLTRL32T.js → chunk-3JCZTTFY.js} +1 -1
  88. package/dist/cli/chunks/{chunk-BPYWDM2Y.js → chunk-3NU4C62D.js} +3 -3
  89. package/dist/cli/chunks/{chunk-ZETZATNY.js → chunk-3XR7ARS6.js} +2 -2
  90. package/dist/cli/chunks/{chunk-FHBIJBZ3.js → chunk-4CDSEZD6.js} +2 -2
  91. package/dist/cli/chunks/{chunk-OURDPRGM.js → chunk-4CSINHCB.js} +1 -1
  92. package/dist/cli/chunks/{chunk-YTF5G3RQ.js → chunk-4HDG7OS4.js} +2 -2
  93. package/dist/cli/chunks/{chunk-PMZJ54WX.js → chunk-52RZZV4M.js} +3 -3
  94. package/dist/cli/chunks/{chunk-GOG6L2F7.js → chunk-5DU4YW2S.js} +2 -2
  95. package/dist/cli/chunks/{chunk-6MMRZYYS.js → chunk-5HM66R4W.js} +3 -3
  96. package/dist/cli/chunks/{chunk-BTZEKSWH.js → chunk-5L3EUZJA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-TD2WOW75.js → chunk-5SWY75MJ.js} +2 -2
  98. package/dist/cli/chunks/{chunk-3DXO5CWI.js → chunk-65XCVUP7.js} +1 -1
  99. package/dist/cli/chunks/{chunk-VMWLVRJO.js → chunk-6KQLF3ZO.js} +2 -2
  100. package/dist/cli/chunks/{chunk-HVJXXGB4.js → chunk-6LTJP3DO.js} +4 -4
  101. package/dist/cli/chunks/{chunk-FJEIX3IS.js → chunk-6PJUDLCT.js} +2 -2
  102. package/dist/cli/chunks/{chunk-2TRWUJWG.js → chunk-74FBSJVC.js} +2 -2
  103. package/dist/cli/chunks/{chunk-D3KORDD5.js → chunk-A6GYFTIA.js} +1 -1
  104. package/dist/cli/chunks/{chunk-3KX7CQEM.js → chunk-ADJGMTIW.js} +1 -1
  105. package/dist/cli/chunks/{chunk-TT2YXNHH.js → chunk-AHOP227C.js} +4 -4
  106. package/dist/cli/chunks/{chunk-UXCEJ3AV.js → chunk-ANLFEGDG.js} +2 -2
  107. package/dist/cli/chunks/{chunk-SQQ57TSJ.js → chunk-AT2VD2ZP.js} +2 -2
  108. package/dist/cli/chunks/{chunk-KLLHSXIC.js → chunk-AYMIF4W5.js} +2 -2
  109. package/dist/cli/chunks/{chunk-JJSJSQNJ.js → chunk-B3DA4SCL.js} +1 -1
  110. package/dist/cli/chunks/{chunk-FBVEHGNE.js → chunk-BSES27JE.js} +3 -3
  111. package/dist/cli/chunks/{chunk-MUEFXLGX.js → chunk-BVKS3X2I.js} +1 -1
  112. package/dist/cli/chunks/{chunk-MR7V7QVL.js → chunk-BVOGMK6N.js} +2 -2
  113. package/dist/cli/chunks/{chunk-PHBE2VBN.js → chunk-BYJEK6LX.js} +2 -2
  114. package/dist/cli/chunks/{chunk-YV2PVXJE.js → chunk-BYPBKVTC.js} +1 -1
  115. package/dist/cli/chunks/{chunk-IQLFWO5U.js → chunk-C7YD7O74.js} +2 -2
  116. package/dist/cli/chunks/{chunk-ZEFDSMF4.js → chunk-CCCBGKVY.js} +2 -2
  117. package/dist/cli/chunks/{chunk-SIIYQLKH.js → chunk-CJQLJEO4.js} +2 -2
  118. package/dist/cli/chunks/{chunk-AT6LBLUV.js → chunk-CXWA34RL.js} +2 -2
  119. package/dist/cli/chunks/{chunk-HFPT7QXQ.js → chunk-CZYTPNUI.js} +2 -2
  120. package/dist/cli/chunks/{chunk-YIVZ5Z4V.js → chunk-DI6R2AVP.js} +1 -1
  121. package/dist/cli/chunks/{chunk-JNEG6DKU.js → chunk-DNS7DP2O.js} +1 -1
  122. package/dist/cli/chunks/{chunk-DKBXIBRS.js → chunk-ECNPBD4Y.js} +2 -2
  123. package/dist/cli/chunks/{chunk-7OPVTN5W.js → chunk-ENG5UF7M.js} +2 -2
  124. package/dist/cli/chunks/{chunk-EIGXGMOR.js → chunk-EV2NMWJV.js} +1 -1
  125. package/dist/cli/chunks/{chunk-426OO3RH.js → chunk-FGW5W3YK.js} +2 -2
  126. package/dist/cli/chunks/{chunk-SMKRBNO7.js → chunk-FTF34UME.js} +1 -1
  127. package/dist/cli/chunks/{chunk-VAKJOTGU.js → chunk-GYNGJHYF.js} +2 -2
  128. package/dist/cli/chunks/{chunk-AHB2F42G.js → chunk-HDM43P7H.js} +1 -1
  129. package/dist/cli/chunks/{chunk-ZWAJV4SN.js → chunk-HOWZFW7G.js} +2 -2
  130. package/dist/cli/chunks/{chunk-INJPS7RF.js → chunk-IZC5NPHD.js} +1 -1
  131. package/dist/cli/chunks/{chunk-HEENVPYF.js → chunk-J2DNMVB5.js} +3 -3
  132. package/dist/cli/chunks/{chunk-SP3X35XC.js → chunk-J62N66ZH.js} +1 -1
  133. package/dist/cli/chunks/{chunk-QKJ4LUAM.js → chunk-JIPU4YQK.js} +2 -2
  134. package/dist/cli/chunks/{chunk-4B5IYFKE.js → chunk-JK4K4EH3.js} +2 -2
  135. package/dist/cli/chunks/{chunk-LP6EQI2P.js → chunk-JQJHRQRX.js} +2 -2
  136. package/dist/cli/chunks/{chunk-FOCGOVIM.js → chunk-KSJCMXAJ.js} +2 -2
  137. package/dist/cli/chunks/{chunk-EFHR7LML.js → chunk-MDTF7LE6.js} +2 -2
  138. package/dist/cli/chunks/{chunk-PFTR6XAO.js → chunk-MUCFC3YG.js} +2 -2
  139. package/dist/cli/chunks/{chunk-JRHKFRUB.js → chunk-MUIJVPGB.js} +2 -2
  140. package/dist/cli/chunks/{chunk-WLYSZV5U.js → chunk-MWZN4PYF.js} +2 -2
  141. package/dist/cli/chunks/{chunk-JZYCZMHN.js → chunk-MXMKHI2I.js} +2 -2
  142. package/dist/cli/chunks/{chunk-XOHRM3M7.js → chunk-MZOYBHJ3.js} +3 -3
  143. package/dist/cli/chunks/{chunk-WV3R5JFE.js → chunk-NLKJI73E.js} +2 -2
  144. package/dist/cli/chunks/{chunk-D2C4XNF5.js → chunk-NQ3WHTLT.js} +4 -4
  145. package/dist/cli/chunks/{chunk-BJKRAFS2.js → chunk-NVVF5ROM.js} +2 -2
  146. package/dist/cli/chunks/{chunk-STASZVMY.js → chunk-OEZA7Q2Z.js} +2 -2
  147. package/dist/cli/chunks/{chunk-LHGZRKPO.js → chunk-OFOFXJ3M.js} +2 -2
  148. package/dist/cli/chunks/{chunk-2SJQ3CYN.js → chunk-OMRZUYXN.js} +9 -9
  149. package/dist/cli/chunks/{chunk-KHEAWN23.js → chunk-P6YMECV2.js} +2 -2
  150. package/dist/cli/chunks/{chunk-ZSXSUUBS.js → chunk-PEEN4AAK.js} +1 -1
  151. package/dist/cli/chunks/{chunk-6ULPQTIE.js → chunk-PRJUO2OQ.js} +2 -2
  152. package/dist/cli/chunks/{chunk-ECRYU5XG.js → chunk-PYTXZMXR.js} +2 -2
  153. package/dist/cli/chunks/{chunk-4NHE7AJE.js → chunk-Q2ZBPOUX.js} +1 -1
  154. package/dist/cli/chunks/{chunk-XY5FMZRA.js → chunk-QHATTMJC.js} +2 -2
  155. package/dist/cli/chunks/{chunk-HE5VY2BI.js → chunk-QMNAELZG.js} +2 -2
  156. package/dist/cli/chunks/{chunk-KZSZHP32.js → chunk-QQLQEQJM.js} +2 -2
  157. package/dist/cli/chunks/{chunk-7GPYOMVY.js → chunk-QSA23PJ6.js} +1 -1
  158. package/dist/cli/chunks/{chunk-GGPGY5QT.js → chunk-QTYTM7C7.js} +2 -2
  159. package/dist/cli/chunks/{chunk-YR5ZNQT2.js → chunk-QZMBJ67L.js} +2 -2
  160. package/dist/cli/chunks/{chunk-URBXUDY3.js → chunk-R23PJGH7.js} +2 -2
  161. package/dist/cli/chunks/{chunk-NKX2Z546.js → chunk-R5ZKFJ3H.js} +1 -1
  162. package/dist/cli/chunks/{chunk-KO5HO6MY.js → chunk-RLLDZNLF.js} +2 -2
  163. package/dist/cli/chunks/{chunk-ZLQYGO6N.js → chunk-RZYTJSQT.js} +1 -1
  164. package/dist/cli/chunks/{chunk-ZV7FGZNJ.js → chunk-S6VT7VAO.js} +2 -2
  165. package/dist/cli/chunks/{chunk-QI5VGEKC.js → chunk-SVLO2DVL.js} +2 -2
  166. package/dist/cli/chunks/{chunk-SURZYSSL.js → chunk-TTENF6AH.js} +1 -1
  167. package/dist/cli/chunks/{chunk-6OKXGDT3.js → chunk-UEKDDUGV.js} +2 -2
  168. package/dist/cli/chunks/{chunk-UEFAPTBV.js → chunk-UYKIPSRX.js} +1 -1
  169. package/dist/cli/chunks/{chunk-WS4OVAWU.js → chunk-VIIUJRKA.js} +2 -2
  170. package/dist/cli/chunks/chunk-VRH3YLO2.js +2 -0
  171. package/dist/cli/chunks/{chunk-YHZWNT45.js → chunk-VTX4NAWB.js} +2 -2
  172. package/dist/cli/chunks/{chunk-APPVAGD5.js → chunk-VWHALAEO.js} +1 -1
  173. package/dist/cli/chunks/{chunk-BWNH22V2.js → chunk-W4VDPHWC.js} +1 -1
  174. package/dist/cli/chunks/{chunk-CDFYF33M.js → chunk-W57I57M4.js} +2 -2
  175. package/dist/cli/chunks/{chunk-LZ34CKYE.js → chunk-WDWIJDQR.js} +2 -2
  176. package/dist/cli/chunks/{chunk-W4HUWBPK.js → chunk-WEJJWJ5M.js} +2 -2
  177. package/dist/cli/chunks/{chunk-A5VULTCD.js → chunk-WZR4CKR4.js} +1 -1
  178. package/dist/cli/chunks/{chunk-DL46KSFX.js → chunk-XZ2JYMFT.js} +2 -2
  179. package/dist/cli/chunks/{chunk-WAP7ROO5.js → chunk-YISXT54V.js} +2 -2
  180. package/dist/cli/chunks/{chunk-HWDE4RB3.js → chunk-YRORPSPA.js} +2 -2
  181. package/dist/cli/chunks/{chunk-T7R5NXJW.js → chunk-YXE67VME.js} +6 -6
  182. package/dist/cli/chunks/{chunk-UDBSEFUT.js → chunk-Z7AFNZMI.js} +2 -2
  183. package/dist/cli/chunks/{chunk-52MUZGZF.js → chunk-ZEUORIH2.js} +2 -2
  184. package/dist/cli/chunks/{chunk-SQZ3H6WR.js → chunk-ZKXA4VBK.js} +3 -3
  185. package/dist/cli/chunks/{chunk-EL2WLSUI.js → chunk-ZTI3BATG.js} +2 -2
  186. package/dist/cli/chunks/{ci-F4F3SDHP.js → ci-4QYE6JBM.js} +2 -2
  187. package/dist/cli/chunks/{ci-output-4SUMOQGO.js → ci-output-MV75HUK7.js} +2 -2
  188. package/dist/cli/chunks/{claude-flow-setup-NKXPDFMJ.js → claude-flow-setup-CZITY7SG.js} +2 -2
  189. package/dist/cli/chunks/client-VXVVUQDV.js +2 -0
  190. package/dist/cli/chunks/{cline-installer-3FMNXEKM.js → cline-installer-ZLQKCPFF.js} +2 -2
  191. package/dist/cli/chunks/{code-5QEDZNKI.js → code-NYEXOJVP.js} +2 -2
  192. package/dist/cli/chunks/{code-index-extractor-RD5EAOLE.js → code-index-extractor-TITXUC44.js} +2 -2
  193. package/dist/cli/chunks/{codex-installer-UU4O2FIE.js → codex-installer-TWT4LIL2.js} +2 -2
  194. package/dist/cli/chunks/{completions-CS6RJLYZ.js → completions-2KNV2MZG.js} +2 -2
  195. package/dist/cli/chunks/{complexity-analyzer-U4DE2QTP.js → complexity-analyzer-2U3OVRDX.js} +2 -2
  196. package/dist/cli/chunks/{continuedev-installer-E55EG2TB.js → continuedev-installer-BWQBRVTC.js} +2 -2
  197. package/dist/cli/chunks/{copilot-installer-TVJUX3AZ.js → copilot-installer-CYN33NMG.js} +2 -2
  198. package/dist/cli/chunks/{cost-tracker-IAKDLDJH.js → cost-tracker-2GUCBYLK.js} +2 -2
  199. package/dist/cli/chunks/{coverage-LX7UIEKV.js → coverage-BAVD66VL.js} +3 -3
  200. package/dist/cli/chunks/cross-domain-router-HUJG6CFC.js +2 -0
  201. package/dist/cli/chunks/{cursor-installer-2NJ7MK23.js → cursor-installer-ZQAUD47B.js} +2 -2
  202. package/dist/cli/chunks/{daemon-T4CPOFHM.js → daemon-VY2LZPIM.js} +3 -3
  203. package/dist/cli/chunks/{dag-attention-scheduler-GAPYYUHZ.js → dag-attention-scheduler-JNQWWXSW.js} +2 -2
  204. package/dist/cli/chunks/{detect-RU5LBCCI.js → detect-Y7BBW4LI.js} +2 -2
  205. package/dist/cli/chunks/{domain-handler-LKPDVPF6.js → domain-handler-473WNSR2.js} +2 -2
  206. package/dist/cli/chunks/{domain-transfer-Q76ITWBK.js → domain-transfer-R4VK7CRR.js} +2 -2
  207. package/dist/cli/chunks/dream-QQDRI2EQ.js +2 -0
  208. package/dist/cli/chunks/esm-node-Y3HIFLTX.js +2 -0
  209. package/dist/cli/chunks/{eval-TFFIZGTW.js → eval-TJAZGRCM.js} +2 -2
  210. package/dist/cli/chunks/{fast-paths-V6KA3VWH.js → fast-paths-LMN542IB.js} +2 -2
  211. package/dist/cli/chunks/{feature-flags-MYSY53UU.js → feature-flags-IMFZ7KED.js} +2 -2
  212. package/dist/cli/chunks/{feature-flags-DWS4XL2P.js → feature-flags-WMXIDTXL.js} +2 -2
  213. package/dist/cli/chunks/{file-discovery-AMKZRFLT.js → file-discovery-GXXWQJV3.js} +2 -2
  214. package/dist/cli/chunks/{fleet-B2BJFKEV.js → fleet-WIC7RHJV.js} +3 -3
  215. package/dist/cli/chunks/{gnn-wrapper-SOJHQ7VC.js → gnn-wrapper-PVKCXV25.js} +2 -2
  216. package/dist/cli/chunks/{heartbeat-handler-O7FF6NRE.js → heartbeat-handler-BJ6ZZP7Q.js} +4 -4
  217. package/dist/cli/chunks/{heartbeat-scheduler-WOGW5R7J.js → heartbeat-scheduler-3SQXTFYU.js} +2 -2
  218. package/dist/cli/chunks/hnsw-adapter-VKS7ORL2.js +2 -0
  219. package/dist/cli/chunks/hnsw-index-GPUBY6EQ.js +2 -0
  220. package/dist/cli/chunks/{hnsw-legacy-bridge-CC5YS47X.js → hnsw-legacy-bridge-23HFWIPK.js} +2 -2
  221. package/dist/cli/chunks/{hnswlib-node-FTWYRETS.js → hnswlib-node-4GRFMUPD.js} +2 -2
  222. package/dist/cli/chunks/{hooks-ETOFFBMV.js → hooks-IXH5454I.js} +6 -6
  223. package/dist/cli/chunks/{hypergraph-engine-FGAHFWFO.js → hypergraph-engine-TEQMJFJJ.js} +2 -2
  224. package/dist/cli/chunks/{hypergraph-handler-GNWJD7E3.js → hypergraph-handler-3ECUWIG3.js} +3 -3
  225. package/dist/cli/chunks/impact-analyzer-D6MBGRKX.js +2 -0
  226. package/dist/cli/chunks/{init-handler-BEYOLKQO.js → init-handler-TZRKW3NZ.js} +6 -6
  227. package/dist/cli/chunks/init-wizard-S6P2MFJF.js +2 -0
  228. package/dist/cli/chunks/kernel-EFDDMNXJ.js +2 -0
  229. package/dist/cli/chunks/{kilocode-installer-ED6LYSEM.js → kilocode-installer-IPH3O3ZS.js} +2 -2
  230. package/dist/cli/chunks/{kiro-installer-NG77T5YR.js → kiro-installer-VROMOOQO.js} +2 -2
  231. package/dist/cli/chunks/knowledge-graph-4PM4DFH3.js +2 -0
  232. package/dist/cli/chunks/{learning-P3WY3LTI.js → learning-JYQLD66S.js} +3 -3
  233. package/dist/cli/chunks/{llm-router-ETSFMOWS.js → llm-router-CIICNICY.js} +2 -2
  234. package/dist/cli/chunks/{load-PP3GVQT7.js → load-DMAQB4NC.js} +2 -2
  235. package/dist/cli/chunks/load-test-PPSWF3TO.js +2 -0
  236. package/dist/cli/chunks/{mcp-B2VX7EKL.js → mcp-K6CSUBMU.js} +2 -2
  237. package/dist/cli/chunks/{memory-SBZQ6MZ4.js → memory-5BSXKHSK.js} +5 -5
  238. package/dist/cli/chunks/memory-backend-3E6BA2JU.js +2 -0
  239. package/dist/cli/chunks/{memory-handlers-5RMGG2CR.js → memory-handlers-APOLXPNH.js} +2 -2
  240. package/dist/cli/chunks/{opencode-installer-PIDIFO2L.js → opencode-installer-IUWO2QV6.js} +2 -2
  241. package/dist/cli/chunks/{orchestrator-FSGUODZI.js → orchestrator-Z2EM76CR.js} +22 -19
  242. package/dist/cli/chunks/{pipeline-BQ5MWZPT.js → pipeline-OL5SI2RI.js} +2 -2
  243. package/dist/cli/chunks/{platform-6EJK4QMD.js → platform-VNJIKIHZ.js} +2 -2
  244. package/dist/cli/chunks/{plugin-EDGOMUJY.js → plugin-SJJUE47D.js} +2 -2
  245. package/dist/cli/chunks/{prime-radiant-advanced-wasm-4S6FYKPP.js → prime-radiant-advanced-wasm-ZLVTCNSH.js} +2 -2
  246. package/dist/cli/chunks/protocol-executor-2RD52J5J.js +2 -0
  247. package/dist/cli/chunks/{protocol-handler-ETM7PMQU.js → protocol-handler-HTX44YTW.js} +2 -2
  248. package/dist/cli/chunks/{prove-YUBORZAP.js → prove-MGFLVZNS.js} +2 -2
  249. package/dist/cli/chunks/qe-reasoning-bank-OGKT52EN.js +2 -0
  250. package/dist/cli/chunks/{quality-XPZDC5FJ.js → quality-FMFKPICZ.js} +2 -2
  251. package/dist/cli/chunks/queen-coordinator-B63YXNI6.js +2 -0
  252. package/dist/cli/chunks/{real-embeddings-KTDUTUJL.js → real-embeddings-2BMEEOA2.js} +2 -2
  253. package/dist/cli/chunks/{roocode-installer-WADVKI3P.js → roocode-installer-2PA3B5JI.js} +2 -2
  254. package/dist/cli/chunks/router-NDQCJQC6.js +2 -0
  255. package/dist/cli/chunks/routing-feedback-PSN2RLDO.js +2 -0
  256. package/dist/cli/chunks/{routing-handler-OOPOYHEV.js → routing-handler-SNGSQ757.js} +2 -2
  257. package/dist/cli/chunks/{ruvector-commands-UPEZL4OK.js → ruvector-commands-54MYLF63.js} +2 -2
  258. package/dist/cli/chunks/{rvf-dual-writer-TOBBCJ7K.js → rvf-dual-writer-6Q44XJOJ.js} +2 -2
  259. package/dist/cli/chunks/{rvf-migration-adapter-U7UM2U36.js → rvf-migration-adapter-JECN625C.js} +2 -2
  260. package/dist/cli/chunks/{rvf-migration-coordinator-CUX3EU2X.js → rvf-migration-coordinator-MEAVIHQY.js} +2 -2
  261. package/dist/cli/chunks/rvf-native-adapter-F56HQKLS.js +2 -0
  262. package/dist/cli/chunks/safe-db-LMRMNROL.js +2 -0
  263. package/dist/cli/chunks/schedule-OZSUYPPC.js +2 -0
  264. package/dist/cli/chunks/scheduler-GFXCQ6ZA.js +2 -0
  265. package/dist/cli/chunks/{security-AQ4N5YKV.js → security-CXLXTNIV.js} +3 -3
  266. package/dist/cli/chunks/shared-rvf-adapter-RZPF4WWK.js +2 -0
  267. package/dist/cli/chunks/{shared-rvf-dual-writer-OKRIHVSY.js → shared-rvf-dual-writer-SOQDKE6S.js} +2 -2
  268. package/dist/cli/chunks/sqlite-persistence-VP67CJPK.js +2 -0
  269. package/dist/cli/chunks/{status-handler-HSJLJPNG.js → status-handler-NNEF4SQV.js} +2 -2
  270. package/dist/cli/chunks/{structural-health-KWZAS7ON.js → structural-health-FY6QIA55.js} +2 -2
  271. package/dist/cli/chunks/{sync-6L5Z4IWH.js → sync-2QMSZ67Q.js} +2 -2
  272. package/dist/cli/chunks/{task-handler-KEAIPB6G.js → task-handler-GZJPE2QW.js} +2 -2
  273. package/dist/cli/chunks/{task-handlers-BPDN6OSM.js → task-handlers-AHM37D4I.js} +2 -2
  274. package/dist/cli/chunks/{test-PICO6RLU.js → test-JVA2S2R2.js} +4 -4
  275. package/dist/cli/chunks/{test-scheduling-BI3R3DX5.js → test-scheduling-PRMP4H6X.js} +3 -3
  276. package/dist/cli/chunks/{token-bootstrap-KMQC6ALU.js → token-bootstrap-YJEHCBV2.js} +2 -2
  277. package/dist/cli/chunks/{token-usage-QGDX7MLB.js → token-usage-G73L32OF.js} +2 -2
  278. package/dist/cli/chunks/{transformers-UNRYJSIU.js → transformers-U3TSLEGO.js} +2 -2
  279. package/dist/cli/chunks/{tree-sitter-wasm-parser-U22JYPOG.js → tree-sitter-wasm-parser-QXP2MNSX.js} +2 -2
  280. package/dist/cli/chunks/{types-CYXAGOY5.js → types-BIQ7O5VR.js} +2 -2
  281. package/dist/cli/chunks/unified-memory-JB4KPMPI.js +2 -0
  282. package/dist/cli/chunks/unified-memory-hnsw-RPSZZIWP.js +2 -0
  283. package/dist/cli/chunks/unified-persistence-L23T4C5C.js +2 -0
  284. package/dist/cli/chunks/{validate-IUY5BWAV.js → validate-CTBEA4BZ.js} +2 -2
  285. package/dist/cli/chunks/{validate-swarm-FXFKSEOI.js → validate-swarm-PHT6XW3A.js} +2 -2
  286. package/dist/cli/chunks/{vibium-DKZ64NR3.js → vibium-CRCYAH3V.js} +2 -2
  287. package/dist/cli/chunks/visual-security-F2I524IQ.js +2 -0
  288. package/dist/cli/chunks/{web-tree-sitter-WQDTN5CV.js → web-tree-sitter-2MH3G7K7.js} +2 -2
  289. package/dist/cli/chunks/{windsurf-installer-O5WOBFOQ.js → windsurf-installer-LBRNYFSI.js} +2 -2
  290. package/dist/cli/chunks/witness-chain-CN6FCWRY.js +2 -0
  291. package/dist/cli/chunks/{witness-chain-F7WXEVJA.js → witness-chain-HNFQLO7Q.js} +2 -2
  292. package/dist/cli/chunks/{workflow-47524I5G.js → workflow-DNAF6BQ2.js} +4 -4
  293. package/dist/cli/chunks/workflow-orchestrator-JJBCCNYI.js +2 -0
  294. package/dist/cli/chunks/{wrappers-MP2HWQD7.js → wrappers-U7AO6ZZN.js} +2 -2
  295. package/dist/init/browser-engine-installer.d.ts +60 -0
  296. package/dist/init/browser-engine-installer.js +92 -0
  297. package/dist/init/phases/09-assets.d.ts +2 -0
  298. package/dist/init/phases/09-assets.js +65 -0
  299. package/dist/init/skills-installer.js +1 -0
  300. package/dist/mcp/bundle.js +1 -1
  301. package/package.json +1 -1
  302. package/dist/cli/chunks/adapter-GE3RSG32.js +0 -2
  303. package/dist/cli/chunks/aqe-learning-engine-IYL6TK6E.js +0 -2
  304. package/dist/cli/chunks/base-L3G3GEZY.js +0 -2
  305. package/dist/cli/chunks/browser-workflow-7KTCY5FI.js +0 -2
  306. package/dist/cli/chunks/chunk-N5SLJOBK.js +0 -2
  307. package/dist/cli/chunks/client-3DPPDO2H.js +0 -2
  308. package/dist/cli/chunks/cross-domain-router-JOYTUBFT.js +0 -2
  309. package/dist/cli/chunks/dream-IF2HCRW4.js +0 -2
  310. package/dist/cli/chunks/esm-node-LNRP5BNU.js +0 -2
  311. package/dist/cli/chunks/hnsw-adapter-UPX4AXOQ.js +0 -2
  312. package/dist/cli/chunks/hnsw-index-CSI2EXXR.js +0 -2
  313. package/dist/cli/chunks/impact-analyzer-2YVBHMES.js +0 -2
  314. package/dist/cli/chunks/init-wizard-V6GZQMMR.js +0 -2
  315. package/dist/cli/chunks/kernel-EHJ4SP2Y.js +0 -2
  316. package/dist/cli/chunks/knowledge-graph-ZYXBWGKL.js +0 -2
  317. package/dist/cli/chunks/load-test-VDZEYGKV.js +0 -2
  318. package/dist/cli/chunks/memory-backend-IB3BU4VM.js +0 -2
  319. package/dist/cli/chunks/protocol-executor-H2ZG7JBJ.js +0 -2
  320. package/dist/cli/chunks/qe-reasoning-bank-ZCSHSKZU.js +0 -2
  321. package/dist/cli/chunks/queen-coordinator-NEC373VS.js +0 -2
  322. package/dist/cli/chunks/router-3PP5XRTD.js +0 -2
  323. package/dist/cli/chunks/routing-feedback-JNUFV2X3.js +0 -2
  324. package/dist/cli/chunks/rvf-native-adapter-PTOZXG4W.js +0 -2
  325. package/dist/cli/chunks/safe-db-CGYNYUES.js +0 -2
  326. package/dist/cli/chunks/schedule-NRN4WOHX.js +0 -2
  327. package/dist/cli/chunks/scheduler-DRAQGYLL.js +0 -2
  328. package/dist/cli/chunks/shared-rvf-adapter-6UVVDOHK.js +0 -2
  329. package/dist/cli/chunks/sqlite-persistence-3WG7PBPL.js +0 -2
  330. package/dist/cli/chunks/unified-memory-EXRANFUS.js +0 -2
  331. package/dist/cli/chunks/unified-memory-hnsw-GB752D44.js +0 -2
  332. package/dist/cli/chunks/unified-persistence-V2B3YWFD.js +0 -2
  333. package/dist/cli/chunks/visual-security-YMPI7X7V.js +0 -2
  334. package/dist/cli/chunks/witness-chain-7LIPUVMI.js +0 -2
  335. package/dist/cli/chunks/workflow-orchestrator-QPIAR4LI.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.7");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.9");process.exit(0)}
2
2
  import{randomUUID as v}from"crypto";var m={"claude-opus-4-5-20251101":{input:15,output:75,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}},d=class c{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,r){let e=m[t];if(!e)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=r.promptTokens/1e6*e.input,o=r.completionTokens/1e6*e.output;return{inputCost:i,outputCost:o,totalCost:i+o,currency:"USD"}}static getCostPerToken(t){let r=m[t];return r?{input:r.input/1e6,output:r.output/1e6}:{input:0,output:0}}recordUsage(t,r,e,i,o){let n=c.calculateCost(r,e),p={timestamp:new Date,provider:t,model:r,usage:e,cost:n,requestId:i,metadata:o};return this.records.push(p),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),n}getSummary(t){let r=new Date,e=this.getPeriodStart(r,t),i=r,o=this.records.filter(s=>s.timestamp>=e&&s.timestamp<=i),n={claude:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0},p={},u=0,l=0;for(let s of o)u+=s.cost.totalCost,l+=s.usage.totalTokens,n[s.provider]+=s.cost.totalCost,p[s.model]=(p[s.model]||0)+s.cost.totalCost;return{period:t,periodStart:e,periodEnd:i,totalCost:u,byProvider:n,byModel:p,totalTokens:l,totalRequests:o.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,r="all"){let e=this.getPeriodStart(new Date,r),i=this.records.filter(u=>u.provider===t&&u.timestamp>=e),o={},n=0,p=0;for(let u of i)n+=u.cost.totalCost,p+=u.usage.totalTokens,o[u.model]||(o[u.model]={cost:0,tokens:0,requests:0}),o[u.model].cost+=u.cost.totalCost,o[u.model].tokens+=u.usage.totalTokens,o[u.model].requests+=1;return{totalCost:n,totalTokens:p,totalRequests:i.length,models:o}}addAlert(t,r,e){let i=`alert-${Date.now()}-${v().slice(0,12)}`;return this.alerts.push({threshold:t,period:r,onThreshold:e,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let r of t)r.timestamp=new Date(r.timestamp),this.records.push(r);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,r,e){return c.calculateCost(t,{promptTokens:r,completionTokens:e,totalTokens:r+e})}wouldExceedLimit(t,r,e,i,o){let n=this.getCurrentCost(o),p=this.estimateCost(t,r,e);return n+p.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,r){let e=new Date(t);switch(r){case"minute":e.setSeconds(0,0),e.setMinutes(e.getMinutes()-1);break;case"hour":e.setMinutes(0,0,0),e.setHours(e.getHours()-1);break;case"day":e.setHours(0,0,0,0);break;case"week":e.setHours(0,0,0,0),e.setDate(e.getDate()-7);break;case"month":e.setHours(0,0,0,0),e.setDate(1);break;case"all":return new Date(0)}return e}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let r=this.getSummary(t.period);if(r.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(r)}catch(e){console.error("Cost alert callback error:",e)}}}}},a;function h(){return a||(a=new d),a}function b(){a&&(a.dispose(),a=void 0)}export{m as a,d as b,h as c,b 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.7");process.exit(0)}
2
- import{a as S}from"./chunk-N5SLJOBK.js";import{c as g}from"./chunk-6OKXGDT3.js";import{S as T,b as l}from"./chunk-WV3R5JFE.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.9");process.exit(0)}
2
+ import{a as S}from"./chunk-VRH3YLO2.js";import{c as g}from"./chunk-UEKDDUGV.js";import{S as T,b as l}from"./chunk-NLKJI73E.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},y=class{constructor(e=100){this.decayThreshold=e}getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},v=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new y,this.plateauDetector=new v,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{p as a,h as b,V as c,y as d,v as e,D as f,C as g,P as h,J as i};
@@ -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.7");process.exit(0)}
2
- import{c as b,e as v,g as T}from"./chunk-UEFAPTBV.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>W,LinearAttention:()=>j,MoEAttention:()=>K,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>q,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>J});import{createRequire as A}from"module";var I,g,O,_,E,L,V,B,D,k,z,F,W,j,K,q,J,S=b(()=>{I=A(import.meta.url),g=I("@ruvector/rvf-node"),O=g,{RuvectorLayer:_,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:W,LinearAttention:j,MoEAttention:K,SonaEngine:q,pipeline:J}=g||{}});var Z={};v(Z,{createRvfStore:()=>Q,isRvfNativeAvailable:()=>Y,openRvfStore:()=>U,openRvfStoreReadonly:()=>X});import{readFileSync as C,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";function l(){if(R)return f;R=!0;try{let i=(S(),T(y));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),f=i}catch{f=null}return f}function w(i){return`${i}.idmap.json`}function N(i){let e=w(i),t=new Map,n=new Map,s=1;if(G(e))try{let r=JSON.parse(C(e,"utf-8"));s=r.nextLabel;for(let[a,m]of r.entries)t.set(a,m),n.set(m,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function h(i,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(i),JSON.stringify(n),"utf-8")}function Q(i,e){let t=l();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(i,{dimension:e}),s=n.dimension();return new d(n,i,s,new Map,new Map,1)}function U(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function X(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function Y(){return l()!==null}var f,R,d,P=b(()=>{f=null,R=!1;d=class i{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,s,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=s,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),s=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:p,metadata:x}=e[o],c=this.strToNum.get(u);c===void 0&&(c=this.nextLabel++,this.strToNum.set(u,c),this.numToStr.set(c,u)),s.push(c),r.push(x);let M=p instanceof Float32Array?p:new Float32Array(p);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,s,o)}else a=this.db.ingestBatch(n,s);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let s of e){let r=this.strToNum.get(s);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let s of e){let r=this.strToNum.get(s);r!==void 0&&(this.strToNum.delete(s),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),$(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);h(e,t,this.nextLabel);let r=l().RvfDatabase.open(e);return new i(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(s=>s.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen(),this.db.compact()}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=l();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return h(e,s,this.nextLabel),new i(n,e,this._dimension,s,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){h(this._path,this.strToNum,this.nextLabel)}}});export{Q as a,U as b,X as c,Y as d,Z as e,P as f};
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.9");process.exit(0)}
2
+ import{c as b,e as v,g as T}from"./chunk-UYKIPSRX.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>W,LinearAttention:()=>j,MoEAttention:()=>K,MultiHeadAttention:()=>F,RuvectorLayer:()=>_,SonaEngine:()=>q,TensorCompress:()=>E,default:()=>O,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>J});import{createRequire as A}from"module";var I,g,O,_,E,L,V,B,D,k,z,F,W,j,K,q,J,S=b(()=>{I=A(import.meta.url),g=I("@ruvector/rvf-node"),O=g,{RuvectorLayer:_,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:W,LinearAttention:j,MoEAttention:K,SonaEngine:q,pipeline:J}=g||{}});var Z={};v(Z,{createRvfStore:()=>Q,isRvfNativeAvailable:()=>Y,openRvfStore:()=>U,openRvfStoreReadonly:()=>X});import{readFileSync as C,writeFileSync as H,copyFileSync as $,existsSync as G}from"fs";function l(){if(R)return f;R=!0;try{let i=(S(),T(y));!i.RvfDatabase&&i.default&&i.default.RvfDatabase&&(i=i.default),f=i}catch{f=null}return f}function w(i){return`${i}.idmap.json`}function N(i){let e=w(i),t=new Map,n=new Map,s=1;if(G(e))try{let r=JSON.parse(C(e,"utf-8"));s=r.nextLabel;for(let[a,m]of r.entries)t.set(a,m),n.set(m,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:s}}function h(i,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(i),JSON.stringify(n),"utf-8")}function Q(i,e){let t=l();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(i,{dimension:e}),s=n.dimension();return new d(n,i,s,new Map,new Map,1)}function U(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function X(i){let e=l();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(i),n=t.dimension(),{strToNum:s,numToStr:r,nextLabel:a}=N(i);return new d(t,i,n,s,r,a)}function Y(){return l()!==null}var f,R,d,P=b(()=>{f=null,R=!1;d=class i{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,s,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=s,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),s=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:p,metadata:x}=e[o],c=this.strToNum.get(u);c===void 0&&(c=this.nextLabel++,this.strToNum.set(u,c),this.numToStr.set(c,u)),s.push(c),r.push(x);let M=p instanceof Float32Array?p:new Float32Array(p);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,s,o)}else a=this.db.ingestBatch(n,s);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let s of e){let r=this.strToNum.get(s);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let s of e){let r=this.strToNum.get(s);r!==void 0&&(this.strToNum.delete(s),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),$(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);h(e,t,this.nextLabel);let r=l().RvfDatabase.open(e);return new i(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(s=>s.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen(),this.db.compact()}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=l();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),s=new Map(this.strToNum),r=new Map(this.numToStr);return h(e,s,this.nextLabel),new i(n,e,this._dimension,s,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){h(this._path,this.strToNum,this.nextLabel)}}});export{Q as a,U as b,X as c,Y as d,Z as e,P as f};
@@ -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.7");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.9");process.exit(0)}
2
2
  var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}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.7");process.exit(0)}
2
- import{k as p,o as N}from"./chunk-JRHKFRUB.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function u(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.9");process.exit(0)}
2
+ import{k as p,o as N}from"./chunk-MUIJVPGB.js";N();import{createHash as y}from"crypto";var g="0".repeat(64);function m(s){return y("sha256").update(s,"utf-8").digest("hex")}function R(s){try{return y("shake256",{outputLength:32}).update(s,"utf-8").digest("hex")}catch{return m(s)}}function u(s,t){return s==="shake256"?R(t):m(t)}function f(s){return JSON.stringify({id:s.id,prev_hash:s.prev_hash,action_hash:s.action_hash,action_type:s.action_type,action_data:s.action_data,timestamp:s.timestamp,actor:s.actor})}var d=class{constructor(t,i){this.externalDb=t;this.keyManager=i??null}db=null;initialized=!1;keyManager=null;async initialize(){if(!this.initialized){if(this.externalDb)this.db=this.externalDb;else{let t=p();await t.initialize(),this.db=t.getDatabase()}this.ensureTable(),this.initialized=!0}}getDatabase(){return this.db}getKeyManager(){return this.keyManager}ensureTable(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  prev_hash TEXT NOT NULL, action_hash TEXT NOT NULL, action_type TEXT NOT NULL,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");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.9");process.exit(0)}
2
2
  var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
@@ -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.7");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.9");process.exit(0)}
2
2
  import{isIP as o}from"net";import{lookup as n}from"dns/promises";var f=[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^0\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/,/^fd[0-9a-f]{2}:/i];function t(r){return f.some(s=>s.test(r))}async function u(r){if(process.env.AQE_HOOKS_SSRF_DISABLED==="true")return{safe:!0};let s;try{s=new URL(r)}catch{return{safe:!1,reason:`Invalid URL: ${r}`}}let e=s.hostname.replace(/^\[|\]$/g,"");if(o(e))return t(e)?{safe:!1,reason:`Private IP blocked: ${e}`}:{safe:!0};try{let a=await n(e);if(t(a.address))return{safe:!1,reason:`DNS resolves to private IP: ${a.address}`}}catch(a){return{safe:!1,reason:`DNS lookup failed for ${e}: ${a.message}`}}return{safe:!0}}export{t as a,u as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");process.exit(0)}
2
- import{a as U,b as G}from"./chunk-UDBSEFUT.js";import{g as W}from"./chunk-6MMRZYYS.js";import{a as _}from"./chunk-D2C4XNF5.js";import{e as S}from"./chunk-7TKZ6LK6.js";import{b as v,c as x}from"./chunk-FHBIJBZ3.js";import{a as ne}from"./chunk-N5SLJOBK.js";import{c as z}from"./chunk-6OKXGDT3.js";import{b as k,d as q}from"./chunk-WLYSZV5U.js";import{b,c as E}from"./chunk-ZSXSUUBS.js";import{a as y,c as I}from"./chunk-MR7V7QVL.js";import{f as O}from"./chunk-SMKRBNO7.js";import{S as ae,b as N}from"./chunk-WV3R5JFE.js";import{randomUUID as Z}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var j=x(),P=class{constructor(e){this.options=e}claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),n=["--no-install",j,"hooks","intelligence","trajectory-start","--task",e];t&&n.push("--agent",t);let s=r("npx",n,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(r){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",r instanceof Error?r.message:r)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,r){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",j,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),r!==void 0&&s.push("--quality",String(r)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let n=this.localTrajectories.get(e);n&&n.steps.push({id:`step-${n.steps.length+1}`,action:t,result:i,quality:r,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),a=["--no-install",j,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),n("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let r=this.localTrajectories.get(e);if(r)return r.success=t,r.feedback=i,r.completedAt=Date.now(),await this.persistTrajectory(r),r}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{join:t}=await import("path"),{existsSync:i,mkdirSync:r}=await import("fs"),{createRequire:n}=await import("module"),a=n(import.meta.url),{openDatabase:s}=a("../../shared/safe-db.js"),o=t(this.options.projectRoot,".agentic-qe","trajectories.db"),u=t(this.options.projectRoot,".agentic-qe");i(u)||r(u,{recursive:!0});let p=s(o);p.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.9");process.exit(0)}
2
+ import{a as U,b as G}from"./chunk-Z7AFNZMI.js";import{g as W}from"./chunk-5HM66R4W.js";import{a as _}from"./chunk-NQ3WHTLT.js";import{e as S}from"./chunk-3FAEM5M7.js";import{b as v,c as x}from"./chunk-4CDSEZD6.js";import{a as ne}from"./chunk-VRH3YLO2.js";import{c as z}from"./chunk-UEKDDUGV.js";import{b as k,d as q}from"./chunk-MWZN4PYF.js";import{b,c as E}from"./chunk-PEEN4AAK.js";import{a as y,c as I}from"./chunk-BVOGMK6N.js";import{f as O}from"./chunk-FTF34UME.js";import{S as ae,b as N}from"./chunk-NLKJI73E.js";import{randomUUID as Z}from"crypto";I();q();import{randomUUID as se}from"node:crypto";var j=x(),P=class{constructor(e){this.options=e}claudeFlowAvailable=!1;localTrajectories=new Map;async initialize(){this.claudeFlowAvailable=await this.checkClaudeFlow()}async checkClaudeFlow(){return v(this.options.projectRoot).available}async startTrajectory(e,t){let i=`trajectory-${se()}`;if(this.claudeFlowAvailable)try{let{execFileSync:r}=await import("child_process"),n=["--no-install",j,"hooks","intelligence","trajectory-start","--task",e];t&&n.push("--agent",t);let s=r("npx",n,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot}).match(/trajectoryId[:\s]+["']?([^"'\s,}]+)/i);if(s?.[1])return s[1]}catch(r){console.debug("[TrajectoryBridge] Claude Flow trajectory start failed:",r instanceof Error?r.message:r)}return this.localTrajectories.set(i,{id:i,task:e,agent:t,steps:[],startedAt:Date.now()}),i}async recordStep(e,t,i,r){if(this.claudeFlowAvailable)try{let{execFileSync:a}=await import("child_process"),s=["--no-install",j,"hooks","intelligence","trajectory-step","--trajectory-id",e,"--action",t];i&&s.push("--result",i),r!==void 0&&s.push("--quality",String(r)),a("npx",s,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot});return}catch(a){console.debug("[TrajectoryBridge] Claude Flow trajectory step failed:",a instanceof Error?a.message:a)}let n=this.localTrajectories.get(e);n&&n.steps.push({id:`step-${n.steps.length+1}`,action:t,result:i,quality:r,timestamp:Date.now()})}async endTrajectory(e,t,i){if(this.claudeFlowAvailable)try{let{execFileSync:n}=await import("child_process"),a=["--no-install",j,"hooks","intelligence","trajectory-end","--trajectory-id",e,"--success",String(t)];i&&a.push("--feedback",i),n("npx",a,{encoding:"utf-8",timeout:1e4,cwd:this.options.projectRoot})}catch{}let r=this.localTrajectories.get(e);if(r)return r.success=t,r.feedback=i,r.completedAt=Date.now(),await this.persistTrajectory(r),r}getTrajectory(e){return this.localTrajectories.get(e)}isClaudeFlowAvailable(){return this.claudeFlowAvailable}async persistTrajectory(e){try{let{join:t}=await import("path"),{existsSync:i,mkdirSync:r}=await import("fs"),{createRequire:n}=await import("module"),a=n(import.meta.url),{openDatabase:s}=a("../../shared/safe-db.js"),o=t(this.options.projectRoot,".agentic-qe","trajectories.db"),u=t(this.options.projectRoot,".agentic-qe");i(u)||r(u,{recursive:!0});let p=s(o);p.exec(`
3
3
  CREATE TABLE IF NOT EXISTS trajectories (
4
4
  id TEXT PRIMARY KEY,
5
5
  task TEXT NOT NULL,
@@ -21,4 +21,4 @@ Steps:
21
21
  ${e.steps.map((n,a)=>`${a+1}. ${n.action}${n.result?` \u2192 ${n.result}`:""}`).join(`
22
22
  `)}
23
23
 
24
- Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:r,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),r=["unit","integration","e2e","api","mock","coverage","security"];for(let n of r)i.some(a=>a.includes(n))&&t.push(n);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){M.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:S},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=_(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=W(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-OKRIHVSY.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-F7WXEVJA.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-F7WXEVJA.js"),{getUnifiedPersistence:r}=await import("./unified-persistence-V2B3YWFD.js"),n=r();if(n.isInitialized()){let a=n.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-DWS4XL2P.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-Q76ITWBK.js"),i=t(),r=this.patternStore,n=await r.getStats();this._domainTransferInterval=setInterval(async()=>{try{n=await r.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=n.byDomain?.[a]??0,o=n.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:n.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=V({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let r=this.enhanceRoutingWithPatterns(i.value,t.value);return b(r)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(r=>r.pattern.id),avgSimilarity:t.length>0?t.reduce((r,n)=>r+n.similarity,0)/t.length:0};try{let r=`pattern-usage:search:${Date.now()}-${Z().slice(0,8)}`;await this.memory.set(r,i,{persist:!0,ttl:10080*60*1e3})}catch(r){console.debug("[AQELearningEngine] Failed to track pattern search:",y(r))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(o=>o.similarity>=.5&&o.pattern.qualityScore>=.3);if(i.length===0)return e;let r=i.map(o=>{let u=o.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(o.similarity*100).toFixed(0)}%)`}),n=[...e.guidance,"--- Relevant Patterns ---",...r],a=[...e.patterns,...i.map(o=>o.pattern)],s=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((o,u)=>o+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:n,reasoning:e.reasoning+s,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let n of i)if(n.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let r=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let n of r)if(n.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let r=`task-${Date.now()}-${Z().slice(0,8)}`,n=r;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{n=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(o){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(o))}let a;this.experienceCapture&&(a=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:n!==r?n:void 0}));let s={id:a||n,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(s.id,s),s.id}async recordStep(e,t,i,r){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,r)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:r});let n=this.activeTasks.get(e);n&&n.steps.push({action:t,result:i,quality:r,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(n){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(n))}let r=this.activeTasks.get(e);if(r)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(r),r}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(r){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",r instanceof Error?r.message:r)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((r,n)=>r+(n.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),p=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&p.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&p.add("javascript"),m.endsWith(".py")&&p.add("python"),m.endsWith(".go")&&p.add("go"),m.endsWith(".rs")&&p.add("rust");let w=a(e,"package.json");if(r(w))try{let m=k(n(w,"utf-8")),d={...m.dependencies,...m.devDependencies};d.react&&g.add("react"),d.vue&&g.add("vue"),d.vitest&&g.add("vitest"),d.jest&&g.add("jest"),d.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(p),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),r=e.slice(t),n=[],a=Date.now(),s=h(i.map(c=>c.tokenMetrics.costUsd)),o=h(r.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),p=h(r.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&p<=u*1.05){let c=Math.min(1,(o-s)/(s||1));n.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:F(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(r.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&n.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:F(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let d=h(i.map(c=>c.learningMetrics.patternCount)),f=h(r.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(r.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-d),re=Math.abs($-te);ie<1&&re<.02&&n.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:F(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),A=h(r.map(c=>c.performanceMetrics.p95LatencyMs));if(A>C*1.2&&C>0){let c=Math.min(1,(A-C)/(C||1));n.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${A.toFixed(0)}ms`,confidence:F(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return n}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function F(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
24
+ Duration: ${e.durationMs}ms`;return{patternType:t,name:this.generatePatternName(e),description:`Pattern extracted from: ${e.task}`,context:{tags:this.extractTags(e),testType:this.detectTestType(e.task)},template:{type:"workflow",content:r,variables:[{name:"task",type:"string",description:"The task to execute",required:!0}]}}}detectPatternType(e){let t=e.toLowerCase();return t.includes("test")||t.includes("spec")?(t.includes("unit")||t.includes("integration")||t.includes("e2e"),"test-template"):t.includes("mock")||t.includes("stub")?"mock-pattern":t.includes("assert")||t.includes("expect")?"assertion-pattern":t.includes("coverage")?"coverage-strategy":t.includes("api")||t.includes("contract")?"api-contract":t.includes("visual")||t.includes("screenshot")?"visual-baseline":t.includes("accessibility")||t.includes("a11y")?"a11y-check":t.includes("performance")||t.includes("perf")?"perf-benchmark":t.includes("flaky")?"flaky-fix":t.includes("refactor")?"refactor-safe":t.includes("error")||t.includes("exception")?"error-handling":"test-template"}generatePatternName(e){let t=e.task.replace(/[^a-zA-Z0-9\s-]/g,"").slice(0,50).trim();return`${e.domain?`[${e.domain}] `:""}${t}`}extractTags(e){let t=[];e.domain&&t.push(e.domain),e.agent&&t.push(e.agent),e.model&&t.push(`model:${e.model}`);let i=e.task.toLowerCase().split(/\s+/),r=["unit","integration","e2e","api","mock","coverage","security"];for(let n of r)i.some(a=>a.includes(n))&&t.push(n);return t}detectTestType(e){let t=e.toLowerCase();if(t.includes("unit"))return"unit";if(t.includes("integration"))return"integration";if(t.includes("e2e")||t.includes("end-to-end"))return"e2e";if(t.includes("contract")||t.includes("api"))return"contract";if(t.includes("smoke"))return"smoke"}getRelatedDomains(e){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution"],"quality-assessment":["test-execution","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment","test-execution"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":[]}[e]||[]}emitExperienceCaptured(e){this.eventBus&&this.eventBus.publish({id:`exp-captured-${e.id}`,type:"learning.ExperienceCaptured",source:"learning-optimization",timestamp:new Date,payload:{experience:e,reward:e.reward,testOutcome:e.testOutcome}})}async loadStats(){try{let e=await this.memory.get(`${this.config.namespace}:stats`);e&&(this.stats.totalCaptured=e.totalCaptured,this.stats.successfulCaptures=e.successfulCaptures,this.stats.patternsExtracted=e.patternsExtracted,this.stats.patternsPromoted=e.patternsPromoted,this.stats.byDomain=new Map(e.byDomain))}catch(e){M.debug("Stats restoration failed, starting fresh",{error:e instanceof Error?e.message:String(e)})}}async saveStats(){try{await this.memory.set(`${this.config.namespace}:stats`,{totalCaptured:this.stats.totalCaptured,successfulCaptures:this.stats.successfulCaptures,patternsExtracted:this.stats.patternsExtracted,patternsPromoted:this.stats.patternsPromoted,byDomain:Array.from(this.stats.byDomain.entries())},{persist:!0})}catch(e){console.error("[ExperienceCapture] Failed to save stats:",e)}}};function Y(l,e,t,i){return new Q(l,e,t,i)}var ue={enableClaudeFlow:!0,enableExperienceCapture:!0,enablePatternPromotion:!0,promotionThreshold:S},L=class{constructor(e,t,i){this.memory=e;this.eventBus=i;this.config={...ue,...t}}config;reasoningBank;claudeFlowBridge;experienceCapture;patternStore;coherenceService;initialized=!1;_domainTransferEngine=null;_domainTransferInterval=null;activeTasks=new Map;completedTasks=0;claudeFlowErrors=0;async initialize(){if(!this.initialized){try{this.coherenceService=await U(G),this.coherenceService.isInitialized()&&console.log("[AQELearningEngine] CoherenceService initialized with WASM engines")}catch(e){console.log("[AQELearningEngine] CoherenceService WASM unavailable, using fallback:",y(e))}this.patternStore=_(this.memory,{promotionThreshold:this.config.promotionThreshold}),await this.patternStore.initialize(),this.reasoningBank=W(this.memory,this.eventBus,this.config.reasoningBank,this.coherenceService),await this.reasoningBank.initialize();try{let{getSharedRvfDualWriter:e}=await import("./shared-rvf-dual-writer-SOQDKE6S.js"),t=await e();t&&this.reasoningBank.setRvfDualWriter(t)}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] RVF wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableExperienceCapture){this.experienceCapture=Y(this.memory,this.patternStore,this.eventBus,{promotionThreshold:this.config.promotionThreshold}),await this.experienceCapture.initialize();try{let{isWitnessChainFeatureEnabled:e}=await import("./witness-chain-HNFQLO7Q.js");if(e()){let{createPersistentWitnessChain:t,createWitnessChainSQLitePersistence:i}=await import("./witness-chain-HNFQLO7Q.js"),{getUnifiedPersistence:r}=await import("./unified-persistence-L23T4C5C.js"),n=r();if(n.isInitialized()){let a=n.getDatabase(),s=i(a),o=t(s);this.experienceCapture.setWitnessChain(o)}}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Witness chain wiring skipped:",e instanceof Error?e.message:e)}}try{let{isCrossDomainTransferEnabled:e}=await import("./feature-flags-WMXIDTXL.js");if(e()&&this.patternStore){let{createDomainTransferEngine:t}=await import("./domain-transfer-R4VK7CRR.js"),i=t(),r=this.patternStore,n=await r.getStats();this._domainTransferInterval=setInterval(async()=>{try{n=await r.getStats()}catch(a){process.env.DEBUG&&console.debug("[AQELearningEngine] Stats refresh failed:",a instanceof Error?a.message:a)}},6e4),this._domainTransferInterval.unref?.(),i.setPerformanceProvider(a=>{let s=n.byDomain?.[a]??0,o=n.totalPatterns??0;return{domain:a,successRate:o>0?s/o:.5,avgConfidence:n.avgConfidence??.5,patternCount:s,timestamp:Date.now()}}),this._domainTransferEngine=i}}catch(e){process.env.DEBUG&&console.debug("[AQELearningEngine] Domain transfer wiring skipped:",e instanceof Error?e.message:e)}if(this.config.enableClaudeFlow)try{this.claudeFlowBridge=V({projectRoot:this.config.projectRoot}),await this.claudeFlowBridge.initialize(),this.claudeFlowBridge.isAvailable()&&console.log("[AQELearningEngine] Claude Flow integration enabled")}catch(e){process.env.DEBUG&&console.log("[AQELearningEngine] Claude Flow not available, using standalone mode:",y(e))}this.initialized=!0,console.log("[AQELearningEngine] Initialized")}}getStatus(){let e=this.claudeFlowBridge?.getStatus();return{initialized:this.initialized,claudeFlowAvailable:e?.available??!1,features:{patternLearning:!0,vectorSearch:!0,taskRouting:!0,trajectories:e?.features.trajectories??!1,modelRouting:e?.features.modelRouting??!1,pretrain:e?.features.pretrain??!1}}}async getStats(){if(!this.initialized||!this.reasoningBank)throw new Error("Engine not initialized");let e=await this.reasoningBank.getStats(),t=this.experienceCapture?await this.experienceCapture.getStats():{totalExperiences:0,byDomain:{},successRate:0,avgQuality:0,patternsExtracted:0,patternsPromoted:0};return{...e,activeTasks:this.activeTasks.size,completedTasks:this.completedTasks,claudeFlowStatus:this.claudeFlowBridge?.getStatus()??{available:!1,features:{trajectories:!1,modelRouting:!1,pretrain:!1,patternSearch:!1}},claudeFlowErrors:this.claudeFlowErrors,experienceCapture:t}}async storePattern(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.storePattern(e)}async searchPatterns(e,t){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.searchPatterns(e,t)}async getPattern(e){return!this.initialized||!this.reasoningBank?null:this.reasoningBank.getPattern(e)}async recordOutcome(e){return!this.initialized||!this.reasoningBank?E(new Error("Engine not initialized")):this.reasoningBank.recordOutcome(e)}async routeTask(e){if(!this.initialized||!this.reasoningBank)return E(new Error("Engine not initialized"));let t=await this.searchPatternsForTask(e.task,{limit:5,minConfidence:.4,domain:e.domain});t.success&&t.value.length>0&&await this.trackPatternSearch(e.task,t.value);let i=await this.reasoningBank.routeTask(e);if(i.success&&this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable(),i.success&&t.success){let r=this.enhanceRoutingWithPatterns(i.value,t.value);return b(r)}return i}async route(e,t){let i=await this.routeTask({task:e,context:t});return i.success?i.value:null}async searchPatternsForTask(e,t={}){if(!this.reasoningBank)return b([]);try{return await this.reasoningBank.searchPatterns(e,{limit:t.limit||5,minConfidence:t.minConfidence||.4,domain:t.domain,useVectorSearch:!0})}catch(i){return console.warn("[AQELearningEngine] Pattern search failed:",y(i)),b([])}}async trackPatternSearch(e,t){let i={timestamp:Date.now(),task:e.slice(0,500),patternsFound:t.length,patternIds:t.map(r=>r.pattern.id),avgSimilarity:t.length>0?t.reduce((r,n)=>r+n.similarity,0)/t.length:0};try{let r=`pattern-usage:search:${Date.now()}-${Z().slice(0,8)}`;await this.memory.set(r,i,{persist:!0,ttl:10080*60*1e3})}catch(r){console.debug("[AQELearningEngine] Failed to track pattern search:",y(r))}}enhanceRoutingWithPatterns(e,t){let i=t.filter(o=>o.similarity>=.5&&o.pattern.qualityScore>=.3);if(i.length===0)return e;let r=i.map(o=>{let u=o.pattern;return`[Pattern: ${u.name}] ${u.description} (confidence: ${(u.confidence*100).toFixed(0)}%, similarity: ${(o.similarity*100).toFixed(0)}%)`}),n=[...e.guidance,"--- Relevant Patterns ---",...r],a=[...e.patterns,...i.map(o=>o.pattern)],s=i.length>0?`; Found ${i.length} relevant pattern(s) with avg similarity ${(i.reduce((o,u)=>o+u.similarity,0)/i.length*100).toFixed(0)}%`:"";return{...e,patterns:a,guidance:n,reasoning:e.reasoning+s,confidence:Math.min(1,e.confidence+i.length*.02)}}async recommendModel(e){if(this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.modelRouter.routeTask(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow model routing failed:",t instanceof Error?t.message:t)}return this.localModelRoute(e)}async recordModelOutcome(e,t,i){this.claudeFlowBridge?.modelRouter.isClaudeFlowAvailable()&&await this.claudeFlowBridge.modelRouter.recordOutcome({task:e,model:t,outcome:i})}localModelRoute(e){let t=e.toLowerCase(),i=[/simple/i,/basic/i,/fix typo/i,/rename/i,/format/i,/add comment/i,/lint/i,/minor/i,/quick/i,/small/i];for(let n of i)if(n.test(t))return{model:"haiku",confidence:.75,reasoning:"Low complexity task - using haiku for speed"};let r=[/architect/i,/design/i,/complex/i,/security/i,/performance/i,/refactor.*large/i,/critical/i,/analysis/i,/multi.*file/i,/distributed/i,/concurrent/i,/migration/i];for(let n of r)if(n.test(t))return{model:"opus",confidence:.8,reasoning:"High complexity task - using opus for capability"};return e.length>500?{model:"opus",confidence:.65,reasoning:"Long task description - using opus for complex reasoning"}:e.length<50?{model:"haiku",confidence:.6,reasoning:"Short task - using haiku for efficiency"}:{model:"sonnet",confidence:.7,reasoning:"Medium complexity - using sonnet for balance"}}async startTask(e,t,i){let r=`task-${Date.now()}-${Z().slice(0,8)}`,n=r;if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{n=await this.claudeFlowBridge.trajectory.startTrajectory(e,t)}catch(o){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow startTrajectory failed (${this.claudeFlowErrors} total errors):`,y(o))}let a;this.experienceCapture&&(a=this.experienceCapture.startCapture(e,{agent:t,domain:i,trajectoryId:n!==r?n:void 0}));let s={id:a||n,task:e,agent:t,startedAt:Date.now(),steps:[]};return this.activeTasks.set(s.id,s),s.id}async recordStep(e,t,i,r){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.recordStep(e,t,i,r)}catch(a){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow recordStep failed (${this.claudeFlowErrors} total errors):`,y(a))}this.experienceCapture&&this.experienceCapture.recordStep(e,{action:t,result:i,quality:r});let n=this.activeTasks.get(e);n&&n.steps.push({action:t,result:i,quality:r,timestamp:Date.now()})}async endTask(e,t,i){if(this.claudeFlowBridge?.trajectory.isClaudeFlowAvailable())try{await this.claudeFlowBridge.trajectory.endTrajectory(e,t,i)}catch(n){this.claudeFlowErrors++,console.warn(`[AQELearningEngine] Claude Flow endTrajectory failed (${this.claudeFlowErrors} total errors):`,y(n))}let r=this.activeTasks.get(e);if(r)return this.activeTasks.delete(e),this.completedTasks++,this.config.enableExperienceCapture&&t&&await this.captureExperience(r),r}getTask(e){return this.activeTasks.get(e)}async analyzeCodebase(e,t="medium"){let i=e||this.config.projectRoot;if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.analyze(i,t)}catch(r){console.debug("[AQELearningEngine] Claude Flow pretrain analyze failed:",r instanceof Error?r.message:r)}return this.localAnalyze(i,t)}async generateAgentConfigs(e="yaml"){if(this.claudeFlowBridge?.pretrain.isClaudeFlowAvailable())try{return await this.claudeFlowBridge.pretrain.generateAgentConfigs(e)}catch(t){console.debug("[AQELearningEngine] Claude Flow agent config failed:",t instanceof Error?t.message:t)}return[{name:"qe-test-architect",type:"worker",capabilities:["test-generation","test-design"],model:"sonnet"},{name:"qe-coverage-specialist",type:"worker",capabilities:["coverage-analysis","gap-detection"],model:"haiku"},{name:"qe-security-scanner",type:"worker",capabilities:["security-scanning","vulnerability-detection"],model:"opus"}]}async captureExperience(e){if(!this.experienceCapture||!this.config.enableExperienceCapture)return;let t=e.steps.length>0?e.steps.reduce((r,n)=>r+(n.quality??.5),0)/e.steps.length:.5;await this.experienceCapture.completeCapture(e.id,{success:!0,quality:t});let i=await this.experienceCapture.getExperience(e.id);i&&i.quality>=.7&&await this.experienceCapture.shareAcrossDomains(i)}startExperienceCapture(e,t){if(this.experienceCapture)return this.experienceCapture.startCapture(e,t)}getExperienceCaptureService(){return this.experienceCapture}async localAnalyze(e,t){try{let i=await import("fast-glob"),{existsSync:r,readFileSync:n}=await import("fs"),{join:a}=await import("path"),s=t==="shallow"?["*.ts","*.js","*.json"]:t==="medium"?["**/*.ts","**/*.js","**/*.json","**/*.py"]:["**/*"],o=["node_modules/**","dist/**","coverage/**",".git/**"],u=await i.default(s,{cwd:e,ignore:o,onlyFiles:!0}),p=new Set,g=new Set;for(let m of u.slice(0,100))(m.endsWith(".ts")||m.endsWith(".tsx"))&&p.add("typescript"),(m.endsWith(".js")||m.endsWith(".jsx"))&&p.add("javascript"),m.endsWith(".py")&&p.add("python"),m.endsWith(".go")&&p.add("go"),m.endsWith(".rs")&&p.add("rust");let w=a(e,"package.json");if(r(w))try{let m=k(n(w,"utf-8")),d={...m.dependencies,...m.devDependencies};d.react&&g.add("react"),d.vue&&g.add("vue"),d.vitest&&g.add("vitest"),d.jest&&g.add("jest"),d.playwright&&g.add("playwright")}catch(m){console.debug("[AQELearningEngine] package.json parse failed:",m instanceof Error?m.message:m)}return{success:!0,repositoryPath:e,depth:t,analysis:{languages:Array.from(p),frameworks:Array.from(g),patterns:[],complexity:u.length>500?3:u.length>100?2:1}}}catch(i){return{success:!1,repositoryPath:e,depth:t,error:y(i)}}}getGuidance(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.getGuidance(e,t)}generateContext(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.generateContext(e,t)}checkAntiPatterns(e,t){if(!this.reasoningBank)throw new Error("Engine not initialized");return this.reasoningBank.checkAntiPatterns(e,t)}async dispose(){this._domainTransferInterval&&(clearInterval(this._domainTransferInterval),this._domainTransferInterval=null),this._domainTransferEngine=null,this.experienceCapture&&await this.experienceCapture.dispose(),this.patternStore&&await this.patternStore.dispose(),this.reasoningBank&&await this.reasoningBank.dispose(),this.activeTasks.clear(),this.initialized=!1}},de={enabled:!1,snapshotIntervalMs:3e5,minSnapshotsForAnalysis:5,autoApplyThreshold:.8},ee=class{config;constructor(e){this.config={...de,...e}}runMetaLearningCycle(e){if(process.env.AQE_META_LEARNING_ENABLED!=="true")return[];if(!this.config.enabled)return[];if(e.length<this.config.minSnapshotsForAnalysis)return[];let t=Math.floor(e.length/2),i=e.slice(0,t),r=e.slice(t),n=[],a=Date.now(),s=h(i.map(c=>c.tokenMetrics.costUsd)),o=h(r.map(c=>c.tokenMetrics.costUsd)),u=h(i.map(c=>c.tokenMetrics.savingsUsd)),p=h(r.map(c=>c.tokenMetrics.savingsUsd));if(o>s*1.1&&p<=u*1.05){let c=Math.min(1,(o-s)/(s||1));n.push({id:`meta-tw-${a}`,type:"token-waste",description:`Token cost increased by ${((o/(s||1)-1)*100).toFixed(1)}% while savings remained flat`,confidence:F(c),suggestedAction:"Review cache configuration and increase pattern reuse thresholds",detectedAt:a})}let g=h(i.map(c=>c.qualityMetrics.gatePassRate)),w=h(r.map(c=>c.qualityMetrics.gatePassRate));Math.abs(w-g)<.02&&e.length>=this.config.minSnapshotsForAnalysis&&n.push({id:`meta-qp-${a}`,type:"quality-plateau",description:`Gate pass rate has been flat at ${(w*100).toFixed(1)}% across ${e.length} snapshots`,confidence:F(.6+(e.length-this.config.minSnapshotsForAnalysis)*.05),suggestedAction:"Consider reviewing quality thresholds or adding new test coverage domains",detectedAt:a});let d=h(i.map(c=>c.learningMetrics.patternCount)),f=h(r.map(c=>c.learningMetrics.patternCount)),te=h(i.map(c=>c.learningMetrics.averageConfidence)),$=h(r.map(c=>c.learningMetrics.averageConfidence)),ie=Math.abs(f-d),re=Math.abs($-te);ie<1&&re<.02&&n.push({id:`meta-ls-${a}`,type:"learning-stall",description:`Pattern count (~${Math.round(f)}) and confidence (~${$.toFixed(2)}) have stagnated`,confidence:F(.65+(e.length-this.config.minSnapshotsForAnalysis)*.04),suggestedAction:"Expand to new QE domains or lower pattern creation thresholds to encourage exploration",detectedAt:a});let C=h(i.map(c=>c.performanceMetrics.p95LatencyMs)),A=h(r.map(c=>c.performanceMetrics.p95LatencyMs));if(A>C*1.2&&C>0){let c=Math.min(1,(A-C)/(C||1));n.push({id:`meta-pr-${a}`,type:"performance-regression",description:`P95 latency increased from ${C.toFixed(0)}ms to ${A.toFixed(0)}ms`,confidence:F(c),suggestedAction:"Profile hot paths and consider HNSW index tuning or batch size reduction",detectedAt:a})}return n}shouldAutoApply(e,t){let i=(t??this.config).autoApplyThreshold;return e.confidence>=i}};function h(l){return l.length===0?0:l.reduce((e,t)=>e+t,0)/l.length}function F(l){return Math.max(0,Math.min(1,l))}function pe(l,e,t){return new L(l,e,t)}function et(l,e,t){return pe(l,{projectRoot:e},t)}export{ue as a,L as b,de as c,ee as d,pe as e,et as f};
@@ -1,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.7");process.exit(0)}
2
- import{a as v}from"./chunk-EL2WLSUI.js";import{h as U}from"./chunk-CDFYF33M.js";import{c as D,d as R,e as h,g as x}from"./chunk-YV2PVXJE.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-GE3RSG32.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.9");process.exit(0)}
2
+ import{a as v}from"./chunk-ZTI3BATG.js";import{h as U}from"./chunk-W57I57M4.js";import{c as D,d as R,e as h,g as x}from"./chunk-BYPBKVTC.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-XKXEZEMM.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,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.7");process.exit(0)}
2
- import{b as r,d as f}from"./chunk-WLYSZV5U.js";import{a as d}from"./chunk-UEFAPTBV.js";f();import{existsSync as i,readFileSync as a}from"node:fs";import{join as s}from"node:path";import{execSync as p}from"node:child_process";var c=null,u=0,g=6e4;function F(){c=null,u=0}function x(e){if(c&&Date.now()-u<g)return c;let n=m(e);return c=n,u=Date.now(),n}function m(e){let n=w(e);if(n)return n;let o=h(e);if(o)return o;let t=v(e);return t||{available:!1}}function w(e){let n=s(e,".claude","mcp.json");if(i(n))try{let t=r(a(n,"utf-8"));if(t.mcpServers?.ruflo||t.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let o=s(e,".claude","settings.json");if(i(o))try{let t=r(a(o,"utf-8")),l=t.mcpServers||t.mcp?.servers||{};if(l.ruflo||l["claude-flow"]||l["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function h(e){let n=s(e,"package.json");if(!i(n))return null;try{let o=r(a(n,"utf-8")),t={...o.dependencies,...o.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function v(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:p(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function b(){for(let e of["ruflo","@claude-flow/cli"])try{return d.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function S(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].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.9");process.exit(0)}
2
+ import{b as r,d as f}from"./chunk-MWZN4PYF.js";import{a as d}from"./chunk-UYKIPSRX.js";f();import{existsSync as i,readFileSync as a}from"node:fs";import{join as s}from"node:path";import{execSync as p}from"node:child_process";var c=null,u=0,g=6e4;function F(){c=null,u=0}function x(e){if(c&&Date.now()-u<g)return c;let n=m(e);return c=n,u=Date.now(),n}function m(e){let n=w(e);if(n)return n;let o=h(e);if(o)return o;let t=v(e);return t||{available:!1}}function w(e){let n=s(e,".claude","mcp.json");if(i(n))try{let t=r(a(n,"utf-8"));if(t.mcpServers?.ruflo||t.mcpServers?.["claude-flow"])return{available:!0,method:"mcp-config"}}catch{}let o=s(e,".claude","settings.json");if(i(o))try{let t=r(a(o,"utf-8")),l=t.mcpServers||t.mcp?.servers||{};if(l.ruflo||l["claude-flow"]||l["@anthropic/claude-flow"])return{available:!0,method:"mcp-config"}}catch{}return null}function h(e){let n=s(e,"package.json");if(!i(n))return null;try{let o=r(a(n,"utf-8")),t={...o.dependencies,...o.devDependencies};if(t.ruflo||t["@claude-flow/cli"]||t["claude-flow"])return{available:!0,method:"npm-dependency"}}catch{}return null}function v(e){for(let n of["ruflo","@claude-flow/cli"])try{return{available:!0,method:"npx-cached",version:p(`npx --no-install ${n} --version`,{encoding:"utf-8",timeout:5e3,cwd:e,stdio:["pipe","pipe","pipe"]}).trim().match(/\d+\.\d+\.\d+[\w.-]*/)?.[0]}}catch{}return null}function b(){for(let e of["ruflo","@claude-flow/cli"])try{return d.resolve(`${e}/package.json`),e}catch{}return"ruflo"}function S(){return[" Claude Flow not found \u2014 running in standalone mode.",""," Claude Flow adds optional features:"," - SONA trajectory tracking (reinforcement learning)"," - 3-tier model routing (haiku / sonnet / opus)"," - Codebase pretrain analysis",""," To install later:"," npm install -g ruflo"," claude mcp add ruflo -- npx -y ruflo@3.5.18"," aqe init --auto --with-claude-flow"].join(`
3
3
  `)}export{F as a,x as b,b as c,S as d};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.7");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.9");process.exit(0)}
2
2
  import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as y,basename as v}from"path";function m(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let t=r;if((!t.agent||typeof t.agent!="string")&&e.push('Overlay must have a string "agent" field'),t.replace!==void 0)if(typeof t.replace!="object"||t.replace===null)e.push('"replace" must be an object');else{let n=t.replace;n.description!==void 0&&typeof n.description!="string"&&e.push('"replace.description" must be a string'),n.domains!==void 0&&!Array.isArray(n.domains)&&e.push('"replace.domains" must be an array'),n.complexity!==void 0&&typeof n.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(t.append!==void 0)if(typeof t.append!="object"||t.append===null)e.push('"append" must be an object');else{let n=t.append;n.instructions!==void 0&&typeof n.instructions!="string"&&e.push('"append.instructions" must be a string'),n.capabilities!==void 0&&!Array.isArray(n.capabilities)&&e.push('"append.capabilities" must be an array'),n.tags!==void 0&&!Array.isArray(n.tags)&&e.push('"append.tags" must be an array')}if(t.config!==void 0)if(typeof t.config!="object"||t.config===null)e.push('"config" must be an object');else{let n=t.config;n.minimumFindings!==void 0&&typeof n.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),n.maxParallelAgents!==void 0&&typeof n.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),n.preferredFrameworks!==void 0&&!Array.isArray(n.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),n.needsContext!==void 0&&typeof n.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var w=".claude/agent-overrides";function $(r){let e={},t=r.split(`
3
3
  `),n=null,i=null,s=null,a=null;for(let o of t){let l=o.replace(/\r$/,"");if(l.trim().startsWith("#")||l.trim()==="")continue;let u=l.length-l.trimStart().length,g=l.trim();if(g.startsWith("- ")){let c=g.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(c);continue}if(s&&a){if(i&&n){let c=e[n]||{};c[a]=s,e[n]=c}else if(n){let c=e[n]||{};c[a]=s,e[n]=c}s=null,a=null}let f=g.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!f)continue;let[,p,b]=f,d=b.trim().replace(/^["']|["']$/g,"");if(u===0)d===""||d===void 0?(n=p,i=null,e[p]||(e[p]={})):(e[p]=h(d),n=null,i=null);else if(u<=4&&n)if(d===""||d===void 0)i=p,s=[],a=p;else{let c=e[n]||{};c[p]=h(d),e[n]=c}}if(s&&a&&n){let o=e[n]||{};o[a]=s,e[n]=o}return e}function h(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function N(r){let e=y(r,w),t={overlays:[],warnings:[],errors:[]};if(!x(e))return t;let n;try{n=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return t.errors.push(`Failed to read overrides directory: ${i.message}`),t}for(let i of n){let s=y(e,i);try{let a=O(s,"utf-8"),o=$(a);if(!o.agent){let u=v(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");o.agent=u}let l=m(o);if(l.length>0){t.warnings.push(`Overlay ${i} has validation issues: ${l.join("; ")}. Loading without overlay.`);continue}t.overlays.push(o)}catch(a){t.warnings.push(`Failed to parse overlay ${i}: ${a.message}. Agent loads without overlay.`)}}return t}function E(r,e){let t=r,n={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.description}`),n.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.domains.join(", ")}`),n.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(t)&&(t=t.replace(i,`$1${e.replace.complexity}`),n.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(t+=`
4
4
 
@@ -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.7");process.exit(0)}
2
- import{f as m}from"./chunk-DKBXIBRS.js";import{a as l,c as d}from"./chunk-MR7V7QVL.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-PP3GVQT7.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.9");process.exit(0)}
2
+ import{f as m}from"./chunk-ECNPBD4Y.js";import{a as l,c as d}from"./chunk-BVOGMK6N.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-DMAQB4NC.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};