agentic-qe 3.9.8 → 3.9.10

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 (394) hide show
  1. package/.claude/agents/_shared/executor-preamble.md +86 -0
  2. package/.claude/agents/v3/qe-coverage-specialist.md +20 -1
  3. package/.claude/agents/v3/qe-fleet-commander.md +20 -1
  4. package/.claude/agents/v3/qe-pentest-validator.md +20 -1
  5. package/.claude/agents/v3/qe-queen-coordinator.md +20 -1
  6. package/.claude/agents/v3/qe-risk-assessor.md +20 -1
  7. package/.claude/agents/v3/qe-root-cause-analyzer.md +19 -0
  8. package/.claude/agents/v3/qe-security-auditor.md +20 -1
  9. package/.claude/agents/v3/qe-test-architect.md +33 -1
  10. package/.claude/helpers/advisor-call.cjs +283 -0
  11. package/.claude/skills/README.md +4 -3
  12. package/.claude/skills/a11y-ally/SKILL.md +40 -18
  13. package/.claude/skills/accessibility-testing/SKILL.md +4 -0
  14. package/.claude/skills/compatibility-testing/SKILL.md +23 -0
  15. package/.claude/skills/e2e-flow-verifier/SKILL.md +87 -52
  16. package/.claude/skills/enterprise-integration-testing/SKILL.md +4 -0
  17. package/.claude/skills/localization-testing/SKILL.md +14 -0
  18. package/.claude/skills/observability-testing-patterns/SKILL.md +16 -0
  19. package/.claude/skills/qe-browser/SKILL.md +409 -0
  20. package/.claude/skills/qe-browser/evals/qe-browser.yaml +291 -0
  21. package/.claude/skills/qe-browser/fixtures/package.json +7 -0
  22. package/.claude/skills/qe-browser/fixtures/serve-skills.js +130 -0
  23. package/.claude/skills/qe-browser/references/assertion-kinds.md +132 -0
  24. package/.claude/skills/qe-browser/references/migration-from-playwright.md +195 -0
  25. package/.claude/skills/qe-browser/schemas/output.json +188 -0
  26. package/.claude/skills/qe-browser/scripts/assert.js +378 -0
  27. package/.claude/skills/qe-browser/scripts/batch.js +292 -0
  28. package/.claude/skills/qe-browser/scripts/check-injection.js +267 -0
  29. package/.claude/skills/qe-browser/scripts/intent-score.js +325 -0
  30. package/.claude/skills/qe-browser/scripts/lib/vibium.js +330 -0
  31. package/.claude/skills/qe-browser/scripts/package.json +7 -0
  32. package/.claude/skills/qe-browser/scripts/smoke-test.sh +212 -0
  33. package/.claude/skills/qe-browser/scripts/validate-config.json +46 -0
  34. package/.claude/skills/qe-browser/scripts/visual-diff.js +276 -0
  35. package/.claude/skills/qe-visual-accessibility/SKILL.md +31 -1
  36. package/.claude/skills/security-visual-testing/SKILL.md +18 -0
  37. package/.claude/skills/skills-manifest.json +20 -13
  38. package/.claude/skills/testability-scoring/SKILL.md +23 -0
  39. package/.claude/skills/trust-tier-manifest.json +14 -3
  40. package/.claude/skills/visual-testing-advanced/SKILL.md +41 -1
  41. package/CHANGELOG.md +75 -0
  42. package/README.md +5 -3
  43. package/assets/agents/v3/helpers/advisor-call.cjs +283 -0
  44. package/assets/agents/v3/qe-coverage-specialist.md +20 -1
  45. package/assets/agents/v3/qe-fleet-commander.md +20 -1
  46. package/assets/agents/v3/qe-pentest-validator.md +20 -1
  47. package/assets/agents/v3/qe-queen-coordinator.md +20 -1
  48. package/assets/agents/v3/qe-risk-assessor.md +20 -1
  49. package/assets/agents/v3/qe-root-cause-analyzer.md +19 -0
  50. package/assets/agents/v3/qe-security-auditor.md +20 -1
  51. package/assets/agents/v3/qe-test-architect.md +33 -1
  52. package/assets/skills/README.md +4 -3
  53. package/assets/skills/a11y-ally/SKILL.md +40 -18
  54. package/assets/skills/accessibility-testing/SKILL.md +4 -0
  55. package/assets/skills/compatibility-testing/SKILL.md +23 -0
  56. package/assets/skills/e2e-flow-verifier/SKILL.md +87 -52
  57. package/assets/skills/enterprise-integration-testing/SKILL.md +4 -0
  58. package/assets/skills/localization-testing/SKILL.md +14 -0
  59. package/assets/skills/observability-testing-patterns/SKILL.md +16 -0
  60. package/assets/skills/qe-browser/SKILL.md +409 -0
  61. package/assets/skills/qe-browser/evals/qe-browser.yaml +291 -0
  62. package/assets/skills/qe-browser/fixtures/package.json +7 -0
  63. package/assets/skills/qe-browser/fixtures/serve-skills.js +130 -0
  64. package/assets/skills/qe-browser/references/assertion-kinds.md +132 -0
  65. package/assets/skills/qe-browser/references/migration-from-playwright.md +195 -0
  66. package/assets/skills/qe-browser/schemas/output.json +188 -0
  67. package/assets/skills/qe-browser/scripts/assert.js +378 -0
  68. package/assets/skills/qe-browser/scripts/batch.js +292 -0
  69. package/assets/skills/qe-browser/scripts/check-injection.js +267 -0
  70. package/assets/skills/qe-browser/scripts/intent-score.js +325 -0
  71. package/assets/skills/qe-browser/scripts/lib/vibium.js +330 -0
  72. package/assets/skills/qe-browser/scripts/package.json +7 -0
  73. package/assets/skills/qe-browser/scripts/smoke-test.sh +212 -0
  74. package/assets/skills/qe-browser/scripts/validate-config.json +46 -0
  75. package/assets/skills/qe-browser/scripts/visual-diff.js +276 -0
  76. package/assets/skills/qe-visual-accessibility/SKILL.md +31 -1
  77. package/assets/skills/security-visual-testing/SKILL.md +18 -0
  78. package/assets/skills/skills-manifest.json +211 -15
  79. package/assets/skills/testability-scoring/SKILL.md +23 -0
  80. package/assets/skills/trust-tier-manifest.json +14 -3
  81. package/assets/skills/visual-testing-advanced/SKILL.md +41 -1
  82. package/dist/cli/bundle.js +5 -5
  83. package/dist/cli/chunks/adapter-IKCDCMSI.js +2 -0
  84. package/dist/cli/chunks/{agent-booster-wasm-LAE4NTVX.js → agent-booster-wasm-HM4XSABF.js} +2 -2
  85. package/dist/cli/chunks/{agent-handler-FVXHR6XN.js → agent-handler-UDBDLLO4.js} +2 -2
  86. package/dist/cli/chunks/{agent-memory-branch-Q7LLBA7C.js → agent-memory-branch-VIXQ3DAR.js} +2 -2
  87. package/dist/cli/chunks/aqe-learning-engine-W4WW7SQW.js +2 -0
  88. package/dist/cli/chunks/{audit-YRLKHJLX.js → audit-FWTGLQHH.js} +2 -2
  89. package/dist/cli/chunks/base-UQKFTHOY.js +2 -0
  90. package/dist/cli/chunks/{better-sqlite3-XFGOGICB.js → better-sqlite3-TYI3CCWU.js} +2 -2
  91. package/dist/cli/chunks/{brain-handler-KIUSNVSS.js → brain-handler-45ZGBLSB.js} +3 -3
  92. package/dist/cli/chunks/{branch-enumerator-VKZ4L3FH.js → branch-enumerator-ZBXELCQA.js} +2 -2
  93. package/dist/cli/chunks/{browser-GZVIYFIB.js → browser-2KM5IKEX.js} +2 -2
  94. package/dist/cli/chunks/browser-workflow-NMOEM3HW.js +2 -0
  95. package/dist/cli/chunks/{chunk-7PHNHFZI.js → chunk-226DSROQ.js} +3 -3
  96. package/dist/cli/chunks/{chunk-MGX2BZWE.js → chunk-27B575K6.js} +2 -2
  97. package/dist/cli/chunks/{chunk-P7APAQD6.js → chunk-2IJFZW3N.js} +12 -12
  98. package/dist/cli/chunks/{chunk-TWDWDKOI.js → chunk-32OB4ZYQ.js} +1 -1
  99. package/dist/cli/chunks/{chunk-E4D36LGH.js → chunk-335CCAOL.js} +1 -1
  100. package/dist/cli/chunks/{chunk-Q5PARJC6.js → chunk-34WI4QNF.js} +2 -2
  101. package/dist/cli/chunks/chunk-3A4BL62O.js +2 -0
  102. package/dist/cli/chunks/{chunk-6ZMM7MXA.js → chunk-3AG647MY.js} +2 -2
  103. package/dist/cli/chunks/{chunk-LPRHYSXN.js → chunk-3HIDCXW3.js} +1 -1
  104. package/dist/cli/chunks/{chunk-HN7HYUW6.js → chunk-4EKWEDHA.js} +9 -9
  105. package/dist/cli/chunks/{chunk-JCROLOP6.js → chunk-4FU6YNDP.js} +2 -2
  106. package/dist/cli/chunks/{chunk-A4DJMFDM.js → chunk-4LOJJ4VX.js} +1 -1
  107. package/dist/cli/chunks/{chunk-I25KIHQE.js → chunk-4VOGUZW5.js} +1 -1
  108. package/dist/cli/chunks/{chunk-KJZU3E5G.js → chunk-4ZR5G4MZ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-W45FANJG.js → chunk-52ZHPZVX.js} +2 -2
  110. package/dist/cli/chunks/{chunk-LOANEFGZ.js → chunk-53G3OCGS.js} +2 -2
  111. package/dist/cli/chunks/{chunk-TZMKO6PC.js → chunk-54TZA65H.js} +2 -2
  112. package/dist/cli/chunks/{chunk-GHJRX7PV.js → chunk-5QKTLOGO.js} +1 -1
  113. package/dist/cli/chunks/{chunk-76UL224Z.js → chunk-5TATJQ3Z.js} +2 -2
  114. package/dist/cli/chunks/{chunk-OGFGNAKQ.js → chunk-5V6DRRLO.js} +2 -2
  115. package/dist/cli/chunks/{chunk-BXMIQRF3.js → chunk-6X7WKNDF.js} +2 -2
  116. package/dist/cli/chunks/chunk-7FWZHYYE.js +2 -0
  117. package/dist/cli/chunks/{chunk-R2LWLZ3Y.js → chunk-A2ULGMMG.js} +1 -1
  118. package/dist/cli/chunks/{chunk-AVKDT3UL.js → chunk-A53XKLEA.js} +8 -8
  119. package/dist/cli/chunks/{chunk-GOPE5OB5.js → chunk-A5OIXFFL.js} +1 -1
  120. package/dist/cli/chunks/{chunk-I7OH6RAC.js → chunk-ACNL4NFI.js} +2 -2
  121. package/dist/cli/chunks/{chunk-PBPOSPTY.js → chunk-AE6Y5CNJ.js} +2 -2
  122. package/dist/cli/chunks/{chunk-TN72MXLI.js → chunk-AO4HDN62.js} +2 -2
  123. package/dist/cli/chunks/{chunk-IHJXFWUL.js → chunk-AOA454FC.js} +2 -2
  124. package/dist/cli/chunks/{chunk-N2L7RWNX.js → chunk-B2QVWL5R.js} +2 -2
  125. package/dist/cli/chunks/{chunk-7CFEGUEH.js → chunk-B3L3CT4X.js} +2 -2
  126. package/dist/cli/chunks/{chunk-XVXSQOQG.js → chunk-B4AFVIOA.js} +2 -2
  127. package/dist/cli/chunks/{chunk-S72TSJS4.js → chunk-BCSCJBYQ.js} +2 -2
  128. package/dist/cli/chunks/{chunk-UAI5NPPQ.js → chunk-BIV6HWMT.js} +2 -2
  129. package/dist/cli/chunks/{chunk-XPL3BXLM.js → chunk-BNNH3KZP.js} +1 -1
  130. package/dist/cli/chunks/{chunk-JK6JBNGL.js → chunk-C234RGWZ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-4EAAHMVM.js → chunk-C55GEYDA.js} +2 -2
  132. package/dist/cli/chunks/{chunk-Y67OXEUM.js → chunk-CEBZHZ4O.js} +1 -1
  133. package/dist/cli/chunks/{chunk-A2QLTNN5.js → chunk-CFQHIWWH.js} +1 -1
  134. package/dist/cli/chunks/{chunk-KMGAJRQ6.js → chunk-CJO2V2FB.js} +1 -1
  135. package/dist/cli/chunks/{chunk-5TGK7VTS.js → chunk-CQNXIYQW.js} +2 -2
  136. package/dist/cli/chunks/{chunk-IP2Z4Z6X.js → chunk-D2A4TGZY.js} +1 -1
  137. package/dist/cli/chunks/{chunk-VVNR4R22.js → chunk-DG2OYKUQ.js} +2 -2
  138. package/dist/cli/chunks/{chunk-ELZ5SKEN.js → chunk-DPYCHODC.js} +2 -2
  139. package/dist/cli/chunks/{chunk-WUCWFDBE.js → chunk-E4YKNKQL.js} +2 -2
  140. package/dist/cli/chunks/{chunk-ZCKNGICX.js → chunk-EEWTTYRC.js} +1 -1
  141. package/dist/cli/chunks/{chunk-IFIYNCT2.js → chunk-EGIYLRW5.js} +2 -2
  142. package/dist/cli/chunks/{chunk-DLKRK2GU.js → chunk-EHGTNSJ2.js} +1 -1
  143. package/dist/cli/chunks/{chunk-IIYXSWJN.js → chunk-EJNASXOY.js} +2 -2
  144. package/dist/cli/chunks/{chunk-ZJ4PMOIZ.js → chunk-F7HRGQRS.js} +2 -2
  145. package/dist/cli/chunks/{chunk-2QI5RYVR.js → chunk-FF7TSDO4.js} +2 -2
  146. package/dist/cli/chunks/{chunk-DDDEGBBJ.js → chunk-FIQNVPYY.js} +2 -2
  147. package/dist/cli/chunks/{chunk-F5VLJFVU.js → chunk-FJOBKT7N.js} +1 -1
  148. package/dist/cli/chunks/{chunk-JNJYWWBG.js → chunk-FYI52MFF.js} +6 -6
  149. package/dist/cli/chunks/{chunk-UOSKMAAY.js → chunk-GCNTU3QJ.js} +1 -1
  150. package/dist/cli/chunks/{chunk-4GMV6Z7Y.js → chunk-H56YBNXW.js} +2 -2
  151. package/dist/cli/chunks/{chunk-HTL2WT64.js → chunk-HJMLJNCB.js} +1 -1
  152. package/dist/cli/chunks/chunk-I3IRIJOT.js +2 -0
  153. package/dist/cli/chunks/chunk-IEQ2VYMO.js +3 -0
  154. package/dist/cli/chunks/{chunk-PG7CZ6Q4.js → chunk-IGRKFVFD.js} +2 -2
  155. package/dist/cli/chunks/{chunk-SQ6XZGR4.js → chunk-IJPE6OGD.js} +10 -10
  156. package/dist/cli/chunks/{chunk-AYKMWP7F.js → chunk-IJUL2UMO.js} +1 -1
  157. package/dist/cli/chunks/{chunk-JVH7753D.js → chunk-ISZJAZ2D.js} +1 -1
  158. package/dist/cli/chunks/{chunk-NCXVOOA7.js → chunk-ITDYTODU.js} +2 -2
  159. package/dist/cli/chunks/{chunk-RGCCSAHI.js → chunk-JHUEBBSX.js} +2 -2
  160. package/dist/cli/chunks/{chunk-TDPHLQ2M.js → chunk-JN3CC2TX.js} +2 -2
  161. package/dist/cli/chunks/{chunk-TSDTRJOG.js → chunk-JOEEGNNX.js} +2 -2
  162. package/dist/cli/chunks/{chunk-QVGSD25D.js → chunk-JQX2DHQT.js} +1 -1
  163. package/dist/cli/chunks/{chunk-VHZ653XS.js → chunk-JRG4AFUR.js} +3 -3
  164. package/dist/cli/chunks/{chunk-SP3ZBJ63.js → chunk-JRMNQWRL.js} +3 -3
  165. package/dist/cli/chunks/{chunk-EKDFIYV5.js → chunk-JXDJMVIG.js} +2 -2
  166. package/dist/cli/chunks/{chunk-3WOQMFTD.js → chunk-JYPW22JV.js} +2 -2
  167. package/dist/cli/chunks/{chunk-WJDOOT2M.js → chunk-KK3KVYE7.js} +2 -2
  168. package/dist/cli/chunks/{chunk-4KX6TMKB.js → chunk-KSRAA6ZD.js} +3 -3
  169. package/dist/cli/chunks/chunk-KUCU5ML6.js +6 -0
  170. package/dist/cli/chunks/{chunk-MVW7AACO.js → chunk-KXXLMLMJ.js} +2 -2
  171. package/dist/cli/chunks/{chunk-HE2NWYHK.js → chunk-LKCFJC4Q.js} +1 -1
  172. package/dist/cli/chunks/{chunk-237NNDKL.js → chunk-LODXDV4G.js} +2 -2
  173. package/dist/cli/chunks/{chunk-W4IRWGGR.js → chunk-M4CYXAVP.js} +4 -4
  174. package/dist/cli/chunks/{chunk-R4VOIXJQ.js → chunk-MOLMS6MA.js} +2 -2
  175. package/dist/cli/chunks/{chunk-SDMGF3KD.js → chunk-NBTM2J4B.js} +2 -2
  176. package/dist/cli/chunks/{chunk-X66IXWSO.js → chunk-NIFVFUCU.js} +2 -2
  177. package/dist/cli/chunks/{chunk-266SKKFM.js → chunk-OOHKW3UE.js} +2 -2
  178. package/dist/cli/chunks/{chunk-WXEDVKJS.js → chunk-ORA6NIXN.js} +2 -2
  179. package/dist/cli/chunks/{chunk-ECYDMBDA.js → chunk-OSD55UO7.js} +2 -2
  180. package/dist/cli/chunks/{chunk-SSURIMCL.js → chunk-OWQRMH3G.js} +2 -2
  181. package/dist/cli/chunks/chunk-QFUINEBN.js +2 -0
  182. package/dist/cli/chunks/{chunk-HYACMUUR.js → chunk-RE2IBX7Z.js} +2 -2
  183. package/dist/cli/chunks/{chunk-2V5VKOJ2.js → chunk-RMQQ5UHM.js} +2 -2
  184. package/dist/cli/chunks/{chunk-U62WL3WZ.js → chunk-ROEMVTXC.js} +3 -3
  185. package/dist/cli/chunks/{chunk-YOKRSFGA.js → chunk-SMTAZQJ3.js} +2 -2
  186. package/dist/cli/chunks/{chunk-OZTSMI7P.js → chunk-TO4NGP3E.js} +1 -1
  187. package/dist/cli/chunks/{chunk-LFEBTWFS.js → chunk-TTXYZUTQ.js} +2 -2
  188. package/dist/cli/chunks/{chunk-IZTUAI5T.js → chunk-U4NODKRR.js} +2 -2
  189. package/dist/cli/chunks/{chunk-JD3GH47Z.js → chunk-U635PSAW.js} +2 -2
  190. package/dist/cli/chunks/{chunk-6DBYVKGA.js → chunk-UBT7VCKQ.js} +2 -2
  191. package/dist/cli/chunks/{chunk-YSUMQBMY.js → chunk-UETM5XDO.js} +1 -1
  192. package/dist/cli/chunks/{chunk-BZB5D4BO.js → chunk-URXG7FMO.js} +4 -3
  193. package/dist/cli/chunks/{chunk-M2JBQVBP.js → chunk-VIWDVS24.js} +2 -2
  194. package/dist/cli/chunks/{chunk-6A4FEIE2.js → chunk-VNKCUKUJ.js} +3 -3
  195. package/dist/cli/chunks/{chunk-6KWX7A3R.js → chunk-VXIXHZCN.js} +2 -2
  196. package/dist/cli/chunks/{chunk-YIJDCZVX.js → chunk-WFEXEDMC.js} +2 -2
  197. package/dist/cli/chunks/{chunk-CG3HIYF4.js → chunk-WLX57ULC.js} +2 -2
  198. package/dist/cli/chunks/{chunk-FKODRXOU.js → chunk-WVQZGLCT.js} +2 -2
  199. package/dist/cli/chunks/{chunk-677V67MR.js → chunk-WW5DZ6BU.js} +1 -1
  200. package/dist/cli/chunks/{chunk-7L64UC5U.js → chunk-X364AIY6.js} +1 -1
  201. package/dist/cli/chunks/{chunk-UGJNR52C.js → chunk-XH7D6EGE.js} +1 -1
  202. package/dist/cli/chunks/{chunk-66DCG6RO.js → chunk-XICRAXUR.js} +4 -4
  203. package/dist/cli/chunks/{chunk-ETXK25IY.js → chunk-XMAV7AIC.js} +1 -1
  204. package/dist/cli/chunks/{chunk-NHXFAXEV.js → chunk-XSUPK7FI.js} +1 -1
  205. package/dist/cli/chunks/{chunk-3ZAGYTEC.js → chunk-XSWOB74I.js} +2 -2
  206. package/dist/cli/chunks/chunk-YPIZMTTA.js +14 -0
  207. package/dist/cli/chunks/{chunk-YDW522M7.js → chunk-YT6KBEXE.js} +2 -2
  208. package/dist/cli/chunks/{chunk-P2H5ARHM.js → chunk-ZENLP5LF.js} +1 -1
  209. package/dist/cli/chunks/{ci-A5ZXOEC4.js → ci-WS32HBBS.js} +2 -2
  210. package/dist/cli/chunks/{ci-output-S47BMRYC.js → ci-output-67R5MSLL.js} +2 -2
  211. package/dist/cli/chunks/circuit-breaker-MA562FT7.js +2 -0
  212. package/dist/cli/chunks/{claude-flow-setup-F5WBEBVK.js → claude-flow-setup-4QKGSRS7.js} +2 -2
  213. package/dist/cli/chunks/client-XQGZKXOB.js +2 -0
  214. package/dist/cli/chunks/{cline-installer-HLKR4QDR.js → cline-installer-6VSROHRY.js} +2 -2
  215. package/dist/cli/chunks/{code-MTZWS6JT.js → code-FBPBHVV3.js} +2 -2
  216. package/dist/cli/chunks/{code-index-extractor-BALTZ2WQ.js → code-index-extractor-62F622V2.js} +2 -2
  217. package/dist/cli/chunks/{codex-installer-LI2VIGET.js → codex-installer-LSR6DVCU.js} +2 -2
  218. package/dist/cli/chunks/{completions-TOF4GTNF.js → completions-56QOICBN.js} +2 -2
  219. package/dist/cli/chunks/{complexity-analyzer-IPFXIT6T.js → complexity-analyzer-SDH4NWIS.js} +2 -2
  220. package/dist/cli/chunks/{continuedev-installer-KWI66RBI.js → continuedev-installer-S7ZPL3VC.js} +2 -2
  221. package/dist/cli/chunks/{copilot-installer-REFOE6UF.js → copilot-installer-25GNNKNL.js} +2 -2
  222. package/dist/cli/chunks/{cost-tracker-M2MZQXCN.js → cost-tracker-73J4Y2RS.js} +2 -2
  223. package/dist/cli/chunks/{coverage-UR2XSJCR.js → coverage-WEE2AZ5F.js} +3 -3
  224. package/dist/cli/chunks/cross-domain-router-C2ZFCSXJ.js +2 -0
  225. package/dist/cli/chunks/{cursor-installer-X4PXCVYH.js → cursor-installer-DHQ644T3.js} +2 -2
  226. package/dist/cli/chunks/{daemon-5R6ZEEBB.js → daemon-3WUJ5E3X.js} +3 -3
  227. package/dist/cli/chunks/{dag-attention-scheduler-RUY2RJZA.js → dag-attention-scheduler-IRLAM43H.js} +2 -2
  228. package/dist/cli/chunks/{detect-PX2AYBHM.js → detect-DTSB4T4R.js} +2 -2
  229. package/dist/cli/chunks/{domain-handler-5JXWEO3E.js → domain-handler-DDN2Z5XC.js} +2 -2
  230. package/dist/cli/chunks/{domain-transfer-6M2YLBJY.js → domain-transfer-3RRG4S6R.js} +2 -2
  231. package/dist/cli/chunks/dream-JSZZ67OO.js +2 -0
  232. package/dist/cli/chunks/esm-node-X4TES6NX.js +2 -0
  233. package/dist/cli/chunks/{eval-L6ZBG462.js → eval-UXEP425X.js} +2 -2
  234. package/dist/cli/chunks/{fast-paths-WIFDALFK.js → fast-paths-4XLHS2VN.js} +2 -2
  235. package/dist/cli/chunks/{feature-flags-YLBXFUCN.js → feature-flags-6C2HD76K.js} +2 -2
  236. package/dist/cli/chunks/{feature-flags-GRHF5MTK.js → feature-flags-KXXHAEYF.js} +2 -2
  237. package/dist/cli/chunks/{file-discovery-4HXUB4HN.js → file-discovery-YSDUIZO4.js} +2 -2
  238. package/dist/cli/chunks/{fleet-RPLJXOEP.js → fleet-TYDG5DWK.js} +3 -3
  239. package/dist/cli/chunks/{gnn-wrapper-2D5IOGAT.js → gnn-wrapper-GJVYRPHB.js} +2 -2
  240. package/dist/cli/chunks/{heartbeat-handler-D5SWZZGA.js → heartbeat-handler-X63CM35O.js} +4 -4
  241. package/dist/cli/chunks/{heartbeat-scheduler-WSG4Y3M2.js → heartbeat-scheduler-NYH4CMVM.js} +2 -2
  242. package/dist/cli/chunks/hnsw-adapter-SQCVEHB5.js +2 -0
  243. package/dist/cli/chunks/hnsw-index-UGVC5IDK.js +2 -0
  244. package/dist/cli/chunks/{hnsw-legacy-bridge-UH6RWE74.js → hnsw-legacy-bridge-YDVUZTJI.js} +2 -2
  245. package/dist/cli/chunks/{hnswlib-node-BJ4ZJPMP.js → hnswlib-node-TLBDFWA6.js} +2 -2
  246. package/dist/cli/chunks/{hooks-KGDQNB5T.js → hooks-B6PVGP7D.js} +6 -6
  247. package/dist/cli/chunks/hybrid-router-YZEBKUZJ.js +2 -0
  248. package/dist/cli/chunks/{hypergraph-engine-LARQCK7V.js → hypergraph-engine-OQ2ZEG53.js} +2 -2
  249. package/dist/cli/chunks/{hypergraph-handler-RACF4AOX.js → hypergraph-handler-VPD424MI.js} +3 -3
  250. package/dist/cli/chunks/impact-analyzer-ZIXSRWED.js +2 -0
  251. package/dist/cli/chunks/{init-handler-64AOFMJD.js → init-handler-5WYP6NJW.js} +6 -6
  252. package/dist/cli/chunks/init-wizard-MO6PCXPX.js +2 -0
  253. package/dist/cli/chunks/kernel-P54KQB2F.js +2 -0
  254. package/dist/cli/chunks/{kilocode-installer-4ICIP6QN.js → kilocode-installer-YVY4EVMY.js} +2 -2
  255. package/dist/cli/chunks/{kiro-installer-J2GOV2OB.js → kiro-installer-GNT4BN3A.js} +2 -2
  256. package/dist/cli/chunks/knowledge-graph-GU57FQAQ.js +2 -0
  257. package/dist/cli/chunks/{learning-QD4JVH3K.js → learning-LD2RSBRS.js} +3 -3
  258. package/dist/cli/chunks/llm-router-ALKXFKLQ.js +36 -0
  259. package/dist/cli/chunks/{load-EXKUJMBK.js → load-XAOTGZYB.js} +2 -2
  260. package/dist/cli/chunks/load-test-5RFBTSS7.js +2 -0
  261. package/dist/cli/chunks/{mcp-NSNDZSMH.js → mcp-WDAJHGH4.js} +2 -2
  262. package/dist/cli/chunks/{memory-63JTNVZN.js → memory-M7QD57JD.js} +5 -5
  263. package/dist/cli/chunks/memory-backend-GPOP3IR4.js +2 -0
  264. package/dist/cli/chunks/memory-handlers-2NHGZLQM.js +2 -0
  265. package/dist/cli/chunks/multi-model-executor-2XZQK2IN.js +14 -0
  266. package/dist/cli/chunks/{opencode-installer-244LFSPN.js → opencode-installer-ASCVY3GG.js} +2 -2
  267. package/dist/cli/chunks/{orchestrator-TZB457J6.js → orchestrator-GOZICWN3.js} +22 -19
  268. package/dist/cli/chunks/{pipeline-YLBD2Z5Q.js → pipeline-YHQRJWV3.js} +2 -2
  269. package/dist/cli/chunks/{platform-53PWFZSE.js → platform-4NESYFHN.js} +2 -2
  270. package/dist/cli/chunks/{plugin-6GUQEFJU.js → plugin-E24I2RVB.js} +2 -2
  271. package/dist/cli/chunks/{prime-radiant-advanced-wasm-VCOK7FV5.js → prime-radiant-advanced-wasm-CDVSLR7R.js} +2 -2
  272. package/dist/cli/chunks/protocol-executor-M5IONISJ.js +2 -0
  273. package/dist/cli/chunks/{protocol-handler-25UEGTE2.js → protocol-handler-TGTDKSZB.js} +2 -2
  274. package/dist/cli/chunks/{prove-CTOU5F6G.js → prove-WUKDAMSE.js} +2 -2
  275. package/dist/cli/chunks/provider-manager-BTKK6W7M.js +24 -0
  276. package/dist/cli/chunks/qe-reasoning-bank-WIEXCBVE.js +2 -0
  277. package/dist/cli/chunks/{quality-PB7H5UEF.js → quality-RTIOIS2K.js} +2 -2
  278. package/dist/cli/chunks/queen-coordinator-ZFK6DANW.js +2 -0
  279. package/dist/cli/chunks/{real-embeddings-RWWYCIE5.js → real-embeddings-4JJKAEMO.js} +2 -2
  280. package/dist/cli/chunks/{roocode-installer-U4AGYVKL.js → roocode-installer-XU2IXRBM.js} +2 -2
  281. package/dist/cli/chunks/router-TOFBEI2Q.js +2 -0
  282. package/dist/cli/chunks/routing-feedback-RC2VDP6W.js +2 -0
  283. package/dist/cli/chunks/{routing-handler-NTDKDEBE.js → routing-handler-3KBOCIEN.js} +2 -2
  284. package/dist/cli/chunks/{ruvector-commands-RQKOLQSW.js → ruvector-commands-HHE2ZPX7.js} +2 -2
  285. package/dist/cli/chunks/{rvf-dual-writer-6EZ7S7OG.js → rvf-dual-writer-GAWM2BUZ.js} +2 -2
  286. package/dist/cli/chunks/{rvf-migration-adapter-EBTV6FV2.js → rvf-migration-adapter-HQPEC4BN.js} +2 -2
  287. package/dist/cli/chunks/{rvf-migration-coordinator-MERU7VLY.js → rvf-migration-coordinator-A4K45EFU.js} +2 -2
  288. package/dist/cli/chunks/rvf-native-adapter-ZOQDH3JY.js +2 -0
  289. package/dist/cli/chunks/safe-db-RIP3X32S.js +2 -0
  290. package/dist/cli/chunks/schedule-Q6KZRLWS.js +2 -0
  291. package/dist/cli/chunks/scheduler-SJO5QPAU.js +2 -0
  292. package/dist/cli/chunks/{security-JPDLGHMC.js → security-UIKUNOXB.js} +3 -3
  293. package/dist/cli/chunks/shared-rvf-adapter-JJCR3AWU.js +2 -0
  294. package/dist/cli/chunks/{shared-rvf-dual-writer-7OGLQE5Y.js → shared-rvf-dual-writer-ZUWSLFPH.js} +2 -2
  295. package/dist/cli/chunks/sqlite-persistence-HK2S6XAI.js +2 -0
  296. package/dist/cli/chunks/{status-handler-3TI3DHEL.js → status-handler-E3VSWGA6.js} +2 -2
  297. package/dist/cli/chunks/{structural-health-WCZKXVWS.js → structural-health-Y22H4BOU.js} +2 -2
  298. package/dist/cli/chunks/{sync-AM5T4GYO.js → sync-CA4KWZFS.js} +2 -2
  299. package/dist/cli/chunks/{task-handler-VHDTXPVP.js → task-handler-3EZPIAMD.js} +2 -2
  300. package/dist/cli/chunks/task-handlers-6UVAQAGP.js +2 -0
  301. package/dist/cli/chunks/{test-G6P5XGHM.js → test-Q5DOFSJI.js} +4 -4
  302. package/dist/cli/chunks/{test-scheduling-37RBUN4E.js → test-scheduling-BSXWCIMQ.js} +3 -3
  303. package/dist/cli/chunks/token-bootstrap-XGEZU2CS.js +2 -0
  304. package/dist/cli/chunks/{token-usage-5XGVBLFR.js → token-usage-BZX5TCG6.js} +2 -2
  305. package/dist/cli/chunks/{transformers-JTKWAZJU.js → transformers-7ITQPXAU.js} +2 -2
  306. package/dist/cli/chunks/{tree-sitter-wasm-parser-KW2GWIIQ.js → tree-sitter-wasm-parser-ZYBBNYR3.js} +2 -2
  307. package/dist/cli/chunks/{types-7R72BACI.js → types-ACZ5VVRC.js} +2 -2
  308. package/dist/cli/chunks/unified-memory-EXO6WK33.js +2 -0
  309. package/dist/cli/chunks/unified-memory-hnsw-7HPSTFVV.js +2 -0
  310. package/dist/cli/chunks/unified-persistence-WC3O4WOJ.js +2 -0
  311. package/dist/cli/chunks/{validate-TYB4ZTUL.js → validate-IQL6OVXD.js} +2 -2
  312. package/dist/cli/chunks/{validate-swarm-3TFI6PLT.js → validate-swarm-J52J2K5X.js} +2 -2
  313. package/dist/cli/chunks/{vibium-3YELURJT.js → vibium-XSE76PXE.js} +2 -2
  314. package/dist/cli/chunks/visual-security-COW3OCEE.js +2 -0
  315. package/dist/cli/chunks/{web-tree-sitter-7Q77A27Y.js → web-tree-sitter-YM6QXUIY.js} +2 -2
  316. package/dist/cli/chunks/{windsurf-installer-ASARRM2X.js → windsurf-installer-M27DVL4H.js} +2 -2
  317. package/dist/cli/chunks/{witness-chain-WZ6PNXEY.js → witness-chain-NB5LP73S.js} +2 -2
  318. package/dist/cli/chunks/witness-chain-XQXF3RSP.js +2 -0
  319. package/dist/cli/chunks/{workflow-JDTEE6TY.js → workflow-5DODQ6XS.js} +4 -4
  320. package/dist/cli/chunks/workflow-orchestrator-HSIZEKZM.js +2 -0
  321. package/dist/cli/chunks/{wrappers-X7WZLBZD.js → wrappers-K7HHCIYD.js} +2 -2
  322. package/dist/cli/commands/llm-router.js +252 -0
  323. package/dist/coordination/queen-task-management.js +8 -1
  324. package/dist/init/browser-engine-installer.d.ts +60 -0
  325. package/dist/init/browser-engine-installer.js +92 -0
  326. package/dist/init/init-wizard-steps.js +9 -0
  327. package/dist/init/phases/09-assets.d.ts +2 -0
  328. package/dist/init/phases/09-assets.js +65 -0
  329. package/dist/init/phases/12-verification.js +8 -0
  330. package/dist/init/skills-installer.js +1 -0
  331. package/dist/kernel/unified-memory-schemas.d.ts +1 -1
  332. package/dist/kernel/unified-memory-schemas.js +2 -1
  333. package/dist/mcp/bundle.js +47 -44
  334. package/dist/mcp/protocol-server.js +87 -0
  335. package/dist/routing/advisor/circuit-breaker.d.ts +56 -0
  336. package/dist/routing/advisor/circuit-breaker.js +128 -0
  337. package/dist/routing/advisor/domain-prompts.d.ts +14 -0
  338. package/dist/routing/advisor/domain-prompts.js +53 -0
  339. package/dist/routing/advisor/index.d.ts +10 -0
  340. package/dist/routing/advisor/index.js +9 -0
  341. package/dist/routing/advisor/multi-model-executor.d.ts +60 -0
  342. package/dist/routing/advisor/multi-model-executor.js +176 -0
  343. package/dist/routing/advisor/redaction.d.ts +40 -0
  344. package/dist/routing/advisor/redaction.js +187 -0
  345. package/dist/routing/advisor/types.d.ts +101 -0
  346. package/dist/routing/advisor/types.js +9 -0
  347. package/dist/routing/queen-integration.d.ts +3 -0
  348. package/dist/routing/queen-integration.js +7 -1
  349. package/dist/routing/routing-feedback.d.ts +7 -1
  350. package/dist/routing/routing-feedback.js +57 -11
  351. package/dist/routing/tiny-dancer-router.d.ts +35 -1
  352. package/dist/routing/tiny-dancer-router.js +33 -0
  353. package/dist/routing/types.d.ts +12 -0
  354. package/package.json +1 -1
  355. package/dist/cli/chunks/adapter-D4XQUIJD.js +0 -2
  356. package/dist/cli/chunks/aqe-learning-engine-CGIWYLIP.js +0 -2
  357. package/dist/cli/chunks/base-BYVP2STR.js +0 -2
  358. package/dist/cli/chunks/browser-workflow-PC4N5TKL.js +0 -2
  359. package/dist/cli/chunks/chunk-2K3DJ3EK.js +0 -7
  360. package/dist/cli/chunks/chunk-JBQ4WGB4.js +0 -14
  361. package/dist/cli/chunks/chunk-OT4JADWW.js +0 -2
  362. package/dist/cli/chunks/client-56BU3GAX.js +0 -2
  363. package/dist/cli/chunks/cross-domain-router-XQT52BTB.js +0 -2
  364. package/dist/cli/chunks/dream-LFZCN5WK.js +0 -2
  365. package/dist/cli/chunks/esm-node-EBDIEPKS.js +0 -2
  366. package/dist/cli/chunks/hnsw-adapter-BMXTVGZB.js +0 -2
  367. package/dist/cli/chunks/hnsw-index-YX6XLICT.js +0 -2
  368. package/dist/cli/chunks/impact-analyzer-MGSI2WBK.js +0 -2
  369. package/dist/cli/chunks/init-wizard-TBDWRRMC.js +0 -2
  370. package/dist/cli/chunks/kernel-NV7TO2FK.js +0 -2
  371. package/dist/cli/chunks/knowledge-graph-7REGYH6A.js +0 -2
  372. package/dist/cli/chunks/llm-router-4K4IT2PQ.js +0 -30
  373. package/dist/cli/chunks/load-test-RYQK44TT.js +0 -2
  374. package/dist/cli/chunks/memory-backend-3EBE2DEX.js +0 -2
  375. package/dist/cli/chunks/memory-handlers-2335MVQJ.js +0 -2
  376. package/dist/cli/chunks/protocol-executor-MR37S7GX.js +0 -2
  377. package/dist/cli/chunks/qe-reasoning-bank-DANGLPTH.js +0 -2
  378. package/dist/cli/chunks/queen-coordinator-4YJPYF5F.js +0 -2
  379. package/dist/cli/chunks/router-F4IPY4RQ.js +0 -2
  380. package/dist/cli/chunks/routing-feedback-VGHFIJ5S.js +0 -2
  381. package/dist/cli/chunks/rvf-native-adapter-2P75WF5A.js +0 -2
  382. package/dist/cli/chunks/safe-db-47NEO2RS.js +0 -2
  383. package/dist/cli/chunks/schedule-L5GJW25Z.js +0 -2
  384. package/dist/cli/chunks/scheduler-NGGGSZMO.js +0 -2
  385. package/dist/cli/chunks/shared-rvf-adapter-NKNTYGHO.js +0 -2
  386. package/dist/cli/chunks/sqlite-persistence-TE2ZRHKA.js +0 -2
  387. package/dist/cli/chunks/task-handlers-GEJ36WNB.js +0 -2
  388. package/dist/cli/chunks/token-bootstrap-JPE3LWXQ.js +0 -2
  389. package/dist/cli/chunks/unified-memory-KSBLUZT4.js +0 -2
  390. package/dist/cli/chunks/unified-memory-hnsw-V3EOMQIZ.js +0 -2
  391. package/dist/cli/chunks/unified-persistence-URIRJ4BM.js +0 -2
  392. package/dist/cli/chunks/visual-security-DJOOVCBZ.js +0 -2
  393. package/dist/cli/chunks/witness-chain-ZWJUCXCJ.js +0 -2
  394. package/dist/cli/chunks/workflow-orchestrator-5CKA6Q74.js +0 -2
@@ -1 +1 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");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.10");process.exit(0)}
@@ -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.8");process.exit(0)}
2
- import{a as T}from"./chunk-OT4JADWW.js";import{c as S}from"./chunk-CG3HIYF4.js";import{b as C,d as P}from"./chunk-VVNR4R22.js";import{a as w,c as $}from"./chunk-PG7CZ6Q4.js";import{a as b,d as M}from"./chunk-IHJXFWUL.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
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.10");process.exit(0)}
2
+ import{a as T}from"./chunk-7FWZHYYE.js";import{c as S}from"./chunk-WLX57ULC.js";import{b as C,d as P}from"./chunk-DG2OYKUQ.js";import{a as w,c as $}from"./chunk-IGRKFVFD.js";import{a as b,d as M}from"./chunk-AOA454FC.js";$();M();import{randomUUID as D}from"crypto";var V={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...V,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${D().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+b()*100,s=.85+b()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=w(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function A(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as L,writeFileSync as N,existsSync as E}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,x)=>v+x,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!E(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(L(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},N(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
3
3
 
4
4
  > ${c} Generated: ${e.timestamp.toISOString()}
5
5
  > Run ID: ${e.runId}
@@ -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.8");process.exit(0)}
2
- import{a as S}from"./chunk-OT4JADWW.js";import{c as g}from"./chunk-CG3HIYF4.js";import{S as T,b as l}from"./chunk-TZMKO6PC.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.10");process.exit(0)}
2
+ import{a as S}from"./chunk-7FWZHYYE.js";import{c as g}from"./chunk-WLX57ULC.js";import{S as T,b as l}from"./chunk-54TZA65H.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,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.8");process.exit(0)}
2
- import{k as p,o as N}from"./chunk-BZB5D4BO.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.10");process.exit(0)}
2
+ import{k as p,o as N}from"./chunk-URXG7FMO.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.8");process.exit(0)}
2
- import{c as t}from"./chunk-E4D36LGH.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{c as t}from"./chunk-335CCAOL.js";import{randomInt as o}from"node:crypto";function a(){return Math.random()}function m(n,e){return o(n,e)}function c(n,e){return n+Math.random()*(e-n)}var r=t(()=>{"use strict"});export{a,m as b,c,r as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{a as g}from"./chunk-76UL224Z.js";import{b as p,c}from"./chunk-R2LWLZ3Y.js";import{a as x,b as f,c as w}from"./chunk-PG7CZ6Q4.js";import{f as v}from"./chunk-IP2Z4Z6X.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{a as g}from"./chunk-5TATJQ3Z.js";import{b as p,c}from"./chunk-A2ULGMMG.js";import{a as x,b as f,c as w}from"./chunk-IGRKFVFD.js";import{f as v}from"./chunk-D2A4TGZY.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- var e=null,f=null,t=null,u=!1;async function M(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-2P75WF5A.js");if(!d())return null;let{getUnifiedMemory:v}=await import("./unified-memory-KSBLUZT4.js"),l=v().getDatabase();if(!l)return null;let{RvfDualWriter:p}=await import("./rvf-dual-writer-6EZ7S7OG.js"),o=new p(l,{rvfPath:".agentic-qe/brain.rvf",mode:"dual-write",dimensions:384});await o.initialize(),e=o;try{let{getRvfMigrationStage:g}=await import("./feature-flags-GRHF5MTK.js"),n=g();if(n>=2){let{RvfMigrationAdapter:m}=await import("./rvf-migration-adapter-EBTV6FV2.js"),s=new m({stage:n});s.setSqliteDb(l);let{getSharedRvfAdapter:R}=await import("./shared-rvf-adapter-NKNTYGHO.js"),i=R();if(i){let y={ingest:a=>i.ingest(a),search:(a,D)=>i.search(a,D).map(c=>({id:c.id,score:c.score})),delete:a=>i.delete(a),status:()=>i.status(),close:()=>{}};s.setRvfStore(y)}f=s,console.log(`[RVF] Migration adapter active at stage ${n} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][n]})`)}}catch{}return o}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-BYVP2STR.js").then(({registerRvfResetFn:r})=>r(h)).catch(()=>{})}})(),t)}function w(){return e}function W(){return f}function h(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{M as a,w as b,W as c,h as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ var e=null,f=null,t=null,u=!1;async function M(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-ZOQDH3JY.js");if(!d())return null;let{getUnifiedMemory:v}=await import("./unified-memory-EXO6WK33.js"),l=v().getDatabase();if(!l)return null;let{RvfDualWriter:p}=await import("./rvf-dual-writer-GAWM2BUZ.js"),o=new p(l,{rvfPath:".agentic-qe/brain.rvf",mode:"dual-write",dimensions:384});await o.initialize(),e=o;try{let{getRvfMigrationStage:g}=await import("./feature-flags-KXXHAEYF.js"),n=g();if(n>=2){let{RvfMigrationAdapter:m}=await import("./rvf-migration-adapter-HQPEC4BN.js"),s=new m({stage:n});s.setSqliteDb(l);let{getSharedRvfAdapter:R}=await import("./shared-rvf-adapter-JJCR3AWU.js"),i=R();if(i){let y={ingest:a=>i.ingest(a),search:(a,D)=>i.search(a,D).map(c=>({id:c.id,score:c.score})),delete:a=>i.delete(a),status:()=>i.status(),close:()=>{}};s.setRvfStore(y)}f=s,console.log(`[RVF] Migration adapter active at stage ${n} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][n]})`)}}catch{}return o}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-UQKFTHOY.js").then(({registerRvfResetFn:r})=>r(h)).catch(()=>{})}})(),t)}function w(){return e}function W(){return f}function h(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{M as a,w as b,W as c,h as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.8");process.exit(0)}
2
- import{c as h}from"./chunk-E4D36LGH.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{c as h}from"./chunk-335CCAOL.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m 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.8");process.exit(0)}
2
- import{k as K,o as ot}from"./chunk-BZB5D4BO.js";import{a as rt}from"./chunk-OT4JADWW.js";import{c as U}from"./chunk-CG3HIYF4.js";import{a as j,c as et}from"./chunk-PG7CZ6Q4.js";import{a as G,d as at}from"./chunk-IHJXFWUL.js";import{a as nt,b as it}from"./chunk-MVW7AACO.js";import{c as H,e as V,g as w}from"./chunk-E4D36LGH.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-2D5IOGAT.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{k as K,o as ot}from"./chunk-URXG7FMO.js";import{a as rt}from"./chunk-7FWZHYYE.js";import{c as U}from"./chunk-WLX57ULC.js";import{a as j,c as et}from"./chunk-IGRKFVFD.js";import{a as G,d as at}from"./chunk-AOA454FC.js";import{a as nt,b as it}from"./chunk-KXXLMLMJ.js";import{c as H,e as V,g as w}from"./chunk-335CCAOL.js";var Z={};V(Z,{DotProductAttention:()=>yt,FlashAttention:()=>ft,HyperbolicAttention:()=>bt,LinearAttention:()=>vt,MoEAttention:()=>Et,MultiHeadAttention:()=>At,RuvectorLayer:()=>ut,SonaEngine:()=>P,TensorCompress:()=>mt,default:()=>ct,differentiableSearch:()=>ht,getCompressionLevel:()=>pt,hierarchicalForward:()=>dt,init:()=>gt,pipeline:()=>Ft});import{createRequire as st}from"module";var lt,$,ct,ut,mt,ht,dt,pt,gt,ft,yt,At,bt,vt,Et,P,Ft,k=H(()=>{lt=st(import.meta.url),$=lt("@ruvector/sona"),ct=$,{RuvectorLayer:ut,TensorCompress:mt,differentiableSearch:ht,hierarchicalForward:dt,getCompressionLevel:pt,init:gt,FlashAttention:ft,DotProductAttention:yt,MultiHeadAttention:At,HyperbolicAttention:bt,LinearAttention:vt,MoEAttention:Et,SonaEngine:P,pipeline:Ft}=$||{}});var N={};V(N,{DotProductAttention:()=>It,FlashAttention:()=>zt,HyperbolicAttention:()=>_t,LinearAttention:()=>Ht,MoEAttention:()=>Vt,MultiHeadAttention:()=>qt,RuvectorLayer:()=>Qt,SonaEngine:()=>jt,TensorCompress:()=>Nt,default:()=>xt,differentiableSearch:()=>Ot,getCompressionLevel:()=>Wt,hierarchicalForward:()=>Dt,init:()=>Bt,pipeline:()=>Ut});import{createRequire as kt}from"module";var Rt,X,xt,Qt,Nt,Ot,Dt,Wt,Bt,zt,It,qt,_t,Ht,Vt,jt,Ut,O=H(()=>{Rt=kt(import.meta.url),X=Rt("@ruvector/attention"),xt=X,{RuvectorLayer:Qt,TensorCompress:Nt,differentiableSearch:Ot,hierarchicalForward:Dt,getCompressionLevel:Wt,init:Bt,FlashAttention:zt,DotProductAttention:It,MultiHeadAttention:qt,HyperbolicAttention:_t,LinearAttention:Ht,MoEAttention:Vt,SonaEngine:jt,pipeline:Ut}=X||{}});k();at();import{randomUUID as Ct}from"crypto";rt();import{createRequire as wt}from"module";var f=U.create("sona-three-loop"),S=wt(import.meta.url),M=null,J=!1;function St(){if(J)return M;J=!0;try{let l=S("@ruvector/learning-wasm"),t=S("fs"),e=S("path"),r=e.join(e.dirname(S.resolve("@ruvector/learning-wasm")),"ruvector_learning_wasm_bg.wasm");l.initSync({module:t.readFileSync(r)}),M=l,f.info("WASM MicroLoRA loaded from @ruvector/learning-wasm (6.4x faster than TS)")}catch{M=null,f.debug("@ruvector/learning-wasm not available, using TypeScript MicroLoRA")}return M}var Mt={dimension:384,microLoraLr:.001,consolidationInterval:100,ewcLambda:1e3,taskBoundaryZScoreThreshold:2.5,fisherDecay:.9,fisherSampleSize:200,importanceThreshold:.01},R=class{adaptationVector;baseWeights;lr;adaptationCount=0;constructor(t,e=.001){this.adaptationVector=new Float32Array(t),this.baseWeights=new Float32Array(t),this.lr=e}adapt(t){let e=this.baseWeights.length,r=new Float32Array(e),a=Math.min(t.length,e);for(let n=0;n<e;n++){let o=n<a?t[n]:0;r[n]=this.baseWeights[n]+this.adaptationVector[n]+this.lr*o}for(let n=0;n<a;n++)this.adaptationVector[n]+=this.lr*t[n];return this.adaptationCount++,r}consolidate(){let t=this.adaptationCount,e=this.baseWeights.length;for(let r=0;r<e;r++)this.baseWeights[r]+=this.adaptationVector[r],this.adaptationVector[r]=0;return this.adaptationCount=0,t}getAdaptationCount(){return this.adaptationCount}getEffectiveWeights(){let t=this.baseWeights.length,e=new Float32Array(t);for(let r=0;r<t;r++)e[r]=this.baseWeights[r]+this.adaptationVector[r];return e}getAdaptationMagnitude(){let t=0;for(let e=0;e<this.adaptationVector.length;e++)t+=this.adaptationVector[e]*this.adaptationVector[e];return Math.sqrt(t)}resetAdaptation(){this.adaptationVector.fill(0),this.adaptationCount=0}},x=class{fisherMatrix;optimalParams;lambda;fisherDecay;zScoreThreshold;importanceThreshold;gradientHistory=[];gradientMean=0;gradientVariance=0;taskBoundaryCount=0;consolidationCount=0;constructor(t,e=1e3,r=.9,a=2.5,n=.01){this.fisherMatrix=new Float32Array(t),this.optimalParams=new Float32Array(t),this.lambda=e,this.fisherDecay=r,this.zScoreThreshold=a,this.importanceThreshold=n}detectTaskBoundary(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i]*t[i];if(e=Math.sqrt(e),this.gradientHistory.length<5)return this.gradientHistory.push(e),this.updateGradientStats(),!1;let r=Math.sqrt(this.gradientVariance),a=0,n=Math.abs(e-this.gradientMean);return r>1e-10?a=n/r:n>1e-10&&this.gradientMean>1e-10&&(a=n/(this.gradientMean*.01+1e-10)),this.gradientHistory.push(e),this.gradientHistory.length>100&&this.gradientHistory.shift(),this.updateGradientStats(),a>this.zScoreThreshold?(this.taskBoundaryCount++,!0):!1}computeLoss(t){let e=0,r=Math.min(t.length,this.fisherMatrix.length,this.optimalParams.length);for(let a=0;a<r;a++){let n=t[a]-this.optimalParams[a];e+=this.fisherMatrix[a]*n*n}return this.lambda/2*e}updateFisher(t,e){if(t.length===0)return;let r=this.fisherMatrix.length,a=new Float32Array(r);for(let s of t){let u=Math.min(s.length,r);for(let c=0;c<u;c++)a[c]+=s[c]*s[c]}let n=t.length;for(let s=0;s<r;s++)a[s]/=n;let o=this.fisherDecay;for(let s=0;s<r;s++)this.fisherMatrix[s]=o*this.fisherMatrix[s]+(1-o)*a[s];let i=Math.min(e.length,r);for(let s=0;s<i;s++)this.optimalParams[s]=e[s];this.consolidationCount++}getMetrics(){let t=this.fisherMatrix.length,e=0,r=0,a=0;for(let n=0;n<t;n++)e+=this.fisherMatrix[n],this.fisherMatrix[n]>r&&(r=this.fisherMatrix[n]),this.fisherMatrix[n]>this.importanceThreshold&&a++;return{regularizationLoss:0,taskBoundariesDetected:this.taskBoundaryCount,fisherTrace:e,avgFisherImportance:t>0?e/t:0,maxFisherImportance:r,protectedParams:a,consolidationCycles:this.consolidationCount,lambda:this.lambda}}getTaskBoundaryCount(){return this.taskBoundaryCount}getFisherDiagonal(){return new Float32Array(this.fisherMatrix)}getOptimalParams(){return new Float32Array(this.optimalParams)}loadFisher(t,e){let r=this.fisherMatrix.length,a=Math.min(t.length,r),n=Math.min(e.length,r);for(let o=0;o<a;o++)this.fisherMatrix[o]=t[o];for(let o=0;o<n;o++)this.optimalParams[o]=e[o]}updateGradientStats(){let t=this.gradientHistory.length;if(t===0)return;let e=0;for(let a of this.gradientHistory)e+=a;e/=t;let r=0;for(let a of this.gradientHistory){let n=a-e;r+=n*n}r=t>1?r/(t-1):0,this.gradientMean=e,this.gradientVariance=r}},C=class{config;microLora;ewc;nativeEngine;wasmLora=null;requestCount=0;lastConsolidationRequest=0;peerStates=new Map;gradientBuffer=[];lastFeatures=null;constructor(t={},e){this.config={...Mt,...t},this.nativeEngine=e??null,this.microLora=new R(this.config.dimension,this.config.microLoraLr),this.ewc=new x(this.config.dimension,this.config.ewcLambda,this.config.fisherDecay,this.config.taskBoundaryZScoreThreshold,this.config.importanceThreshold);let r=St();if(r)try{this.wasmLora=new r.WasmMicroLoRA(this.config.dimension,1,this.config.microLoraLr),f.info("SONA Three-Loop using WASM MicroLoRA (0.07us/adapt)")}catch(a){f.debug("WASM MicroLoRA creation failed, falling back",{error:String(a)}),this.wasmLora=null}!this.wasmLora&&this.nativeEngine&&f.info("SONA Three-Loop using native @ruvector/sona engine for MicroLoRA delegation")}instantAdapt(t){let e=performance.now(),r;if(this.wasmLora)try{let o=new Float32Array(t),i=this.wasmLora.adapt(o);i&&i.length>0?(r=i,this.microLora.adapt(t)):r=this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else if(this.nativeEngine)try{let o=this.nativeEngine.applyMicroLora(t);r=new Float32Array(o),this.microLora.adapt(t)}catch{r=this.microLora.adapt(t)}else r=this.microLora.adapt(t);let a=this.microLora.getAdaptationMagnitude();this.requestCount++,this.lastFeatures=[...t];let n=(performance.now()-e)*1e3;return{adaptedWeights:r,latencyUs:n,applied:!0,magnitude:a,requestIndex:this.requestCount}}recordOutcome(t,e){if(this.lastFeatures===null){f.warn("recordOutcome called without a preceding instantAdapt()");return}let r=this.lastFeatures.length,a=new Float32Array(r);for(let n=0;n<r;n++)a[n]=t*this.lastFeatures[n];this.gradientBuffer.push(a),this.gradientBuffer.length>this.config.fisherSampleSize&&this.gradientBuffer.shift(),this.lastFeatures=null}backgroundConsolidate(){let t=performance.now();if(this.nativeEngine)try{this.nativeEngine.forceLearn(),this.nativeEngine.tick()}catch(i){f.warn("Native SONA background learning failed, continuing with TypeScript",{error:String(i)})}let e=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),r=!1;if(this.gradientBuffer.length>0){let i=this.gradientBuffer[this.gradientBuffer.length-1];r=this.ewc.detectTaskBoundary(i)}if(r&&this.gradientBuffer.length>0&&(this.ewc.updateFisher(this.gradientBuffer,this.microLora.getEffectiveWeights()),f.info("Task boundary detected, Fisher updated",{boundaries:this.ewc.getTaskBoundaryCount(),requestCount:this.requestCount})),this.gradientBuffer.length>1){let i=!1,s=this.gradientBuffer[0];for(let u=1;u<this.gradientBuffer.length&&!i;u++)for(let c=0;c<s.length;c++)if(Math.abs(this.gradientBuffer[u][c]-s[c])>1e-8){i=!0;break}i||f.warn("All gradient samples identical \u2014 Fisher estimate may be poor. Ensure recordOutcome() is called with diverse rewards.")}let a=this.microLora.consolidate();this.applyEWCRegularization();let n=this.ewc.computeLoss(this.microLora.getEffectiveWeights());this.lastConsolidationRequest=this.requestCount,this.gradientBuffer=[];let o=performance.now()-t;return{consolidated:a>0||r,adaptationsMerged:a,ewcLossBefore:e,ewcLossAfter:n,taskBoundaryDetected:r,durationMs:o}}shouldConsolidate(){return this.requestCount-this.lastConsolidationRequest>=this.config.consolidationInterval}syncWithPeers(t){if(t.length===0)return;for(let i of t)this.peerStates.set(i.peerId,i);let e=this.config.dimension,r=new Float32Array(e),a=new Float32Array(e),n=this.ewc.getFisherDiagonal(),o=this.microLora.adaptationVector;for(let i=0;i<e;i++){let s=n[i]+1e-10;r[i]+=s*o[i],a[i]+=s}for(let i of t){let s=Math.min(i.adaptationVector.length,e);for(let u=0;u<s;u++){let c=(u<i.fisherDiagonal.length?i.fisherDiagonal[u]:0)+1e-10;r[u]+=c*i.adaptationVector[u],a[u]+=c}}for(let i=0;i<e;i++)this.microLora.adaptationVector[i]=r[i]/a[i];f.debug("Synced with peers",{peerCount:t.length,peersStored:this.peerStates.size})}getLocalPeerState(t,e){return{peerId:t,domain:e,adaptationVector:new Float32Array(this.microLora.adaptationVector),fisherDiagonal:this.ewc.getFisherDiagonal(),requestCount:this.requestCount,lastUpdateMs:Date.now()}}getEWCMetrics(){let t=this.ewc.getMetrics();return t.regularizationLoss=this.ewc.computeLoss(this.microLora.getEffectiveWeights()),t}getFisherDiagonal(){return this.ewc.getFisherDiagonal()}getOptimalParams(){return this.ewc.getOptimalParams()}loadFisher(t,e){this.ewc.loadFisher(t,e)}getBaseWeights(){return new Float32Array(this.microLora.baseWeights)}setBaseWeights(t){let e=Math.min(t.length,this.microLora.baseWeights.length);for(let r=0;r<e;r++)this.microLora.baseWeights[r]=t[r]}getEffectiveWeights(){return this.microLora.getEffectiveWeights()}getRequestCount(){return this.requestCount}getConfig(){return{...this.config}}getPeerStates(){return new Map(this.peerStates)}getMicroLoRA(){return this.microLora}getEWC(){return this.ewc}applyEWCRegularization(){let t=this.config.dimension,e=this.ewc.fisherMatrix,r=this.ewc.optimalParams,a=this.microLora.baseWeights,n=.01;for(let o=0;o<t;o++)if(e[o]>this.config.importanceThreshold){let i=a[o]-r[o];a[o]-=n*e[o]*i}}persistFisher(t,e){let r=this.ewc.getMetrics();t(e,this.ewc.getFisherDiagonal(),this.ewc.getOptimalParams(),this.getBaseWeights(),{taskBoundaries:r.taskBoundariesDetected,consolidationCycles:r.consolidationCycles,requestCount:this.requestCount,ewcLambda:r.lambda}),f.info("Fisher matrix persisted to SQLite",{domain:e,requestCount:this.requestCount,taskBoundaries:r.taskBoundariesDetected})}restoreFisher(t){this.ewc.loadFisher(t.fisherDiagonal,t.optimalParams),t.baseWeights&&this.setBaseWeights(t.baseWeights),this.requestCount=t.requestCount,f.info("Fisher matrix restored from SQLite",{requestCount:t.requestCount,dimension:t.fisherDiagonal.length})}};var Lt={hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,microLoraLr:.001,baseLoraLr:1e-4,ewcLambda:1e3,patternClusters:50,trajectoryCapacity:1e4,backgroundIntervalMs:36e5,qualityThreshold:.5,enableSimd:!0,minConfidence:.5,maxPatterns:1e4},Q=class{patterns;trajectoryMap;maxPatterns;constructor(t=1e4){this.patterns=new Map,this.trajectoryMap=new Map,this.maxPatterns=t}register(t){if(this.patterns.size>=this.maxPatterns&&!this.patterns.has(t.id)){let e=Array.from(this.patterns.entries()).sort(([,r],[,a])=>(r.lastUsedAt?.getTime()??r.createdAt.getTime())-(a.lastUsedAt?.getTime()??a.createdAt.getTime()))[0];e&&this.patterns.delete(e[0])}this.patterns.set(t.id,t)}get(t){return this.patterns.get(t)}getByTrajectory(t){let e=this.trajectoryMap.get(t);return e?this.patterns.get(e):void 0}associateTrajectory(t,e){this.trajectoryMap.set(t,e)}update(t,e){let r=this.patterns.get(t);return r?(this.patterns.set(t,{...r,...e}),!0):!1}getAll(){return Array.from(this.patterns.values())}getByType(t){return Array.from(this.patterns.values()).filter(e=>e.type===t)}getByDomain(t){return Array.from(this.patterns.values()).filter(e=>e.domain===t)}clear(){this.patterns.clear(),this.trajectoryMap.clear()}size(){return this.patterns.size}},v=class{engine;registry;config;adaptationTimes=[];cacheHits=0;totalAdaptations=0;threeLoopEngine=null;fisherPersistFn=null;fisherDomain="default";constructor(t={}){this.config={...Lt,...t};let e={hiddenDim:this.config.hiddenDim,embeddingDim:this.config.embeddingDim,microLoraRank:this.config.microLoraRank,baseLoraRank:this.config.baseLoraRank,microLoraLr:this.config.microLoraLr,baseLoraLr:this.config.baseLoraLr,ewcLambda:this.config.ewcLambda,patternClusters:this.config.patternClusters,trajectoryCapacity:this.config.trajectoryCapacity,backgroundIntervalMs:this.config.backgroundIntervalMs,qualityThreshold:this.config.qualityThreshold,enableSimd:this.config.enableSimd};this.engine=P.withConfig(e),this.registry=new Q(this.config.maxPatterns??1e4)}async adaptPattern(t,e,r){let a=performance.now();try{let n=this.createStateEmbedding(t),o=this.engine.findPatterns(n,5),i=[];for(let m of o){let g=this.findByRawPattern(m);if(g||(g=this.createQEPatternFromRaw(m,e,r)),g.type===e&&g.domain===r&&g.confidence>=(this.config.minConfidence??.5)){let h=this.calculateSimilarity(n,m.centroid);i.push({pattern:g,similarity:h})}}if(i.length===0){let m=performance.now()-a;return this.recordAdaptation(m),{success:!1,pattern:null,adaptationTimeMs:m,similarity:0,reasoning:"No suitable pattern found"}}let s=i[0],u={...s.pattern,usageCount:s.pattern.usageCount+1,lastUsedAt:new Date};this.registry.update(u.id,u);let c=performance.now()-a;return this.recordAdaptation(c),{success:!0,pattern:u,adaptationTimeMs:c,similarity:s.similarity,reasoning:`Pattern adapted from @ruvector/sona with ${s.similarity.toFixed(3)} similarity`}}catch(n){let o=performance.now()-a;return this.recordAdaptation(o),{success:!1,pattern:null,adaptationTimeMs:o,similarity:0,reasoning:`Adaptation failed: ${n.message}`}}}recallPattern(t,e,r){let a=this.createStateEmbedding(t),n=this.engine.findPatterns(a,1);for(let o of n){let i=this.findByRawPattern(o);if(i&&i.type===e&&i.domain===r)return i}return null}storePattern(t){this.registry.register(t);let e=this.engine.beginTrajectory(t.stateEmbedding),r=this.createActionEmbedding(t.action),a=new Array(r.length).fill(1),n=t.outcome.success?t.outcome.quality:-t.outcome.quality;this.engine.addTrajectoryStep(e,r,a,n),this.engine.endTrajectory(e,t.outcome.quality),this.registry.associateTrajectory(e,t.id)}storePatternsBatch(t){for(let e of t)this.storePattern(e)}createPattern(t,e,r,a,n,o){let i={id:`qesona-${Date.now()}-${Ct().slice(0,7)}`,type:a,domain:n,stateEmbedding:this.createStateEmbedding(t),action:e,outcome:r,confidence:.5,usageCount:0,createdAt:new Date,metadata:o};return this.storePattern(i),i}updatePattern(t,e,r){let a=this.registry.get(t);if(!a)return!1;let n=e?r:-r,i=a.confidence+.1*(n-a.confidence),s={...a,confidence:Math.max(0,Math.min(1,i)),usageCount:a.usageCount+1,lastUsedAt:new Date};return this.registry.update(t,s)}applyMicroLora(t){return this.engine.applyMicroLora(t)}applyBaseLora(t,e){return this.engine.applyBaseLora(t,e)}forceLearn(){return this.engine.forceLearn()}tick(){return this.engine.tick()}getAllPatterns(){return this.registry.getAll()}getPatternsByType(t){return this.registry.getByType(t)}getPatternsByDomain(t){return this.registry.getByDomain(t)}getStats(){let t=this.registry.getAll(),e=this.engine.getStats(),r={"test-generation":0,"defect-prediction":0,"coverage-optimization":0,"quality-assessment":0,"resource-allocation":0};for(let a of t)r[a.type]++;return{totalPatterns:t.length,patternsByType:r,avgAdaptationTimeMs:this.avgAdaptationTime(),minAdaptationTimeMs:this.minAdaptationTime(),maxAdaptationTimeMs:this.maxAdaptationTime(),totalAdaptations:this.totalAdaptations,cacheHitRate:this.totalAdaptations>0?this.cacheHits/this.totalAdaptations:0,engineStats:e}}clear(){this.registry.clear(),this.adaptationTimes=[],this.cacheHits=0,this.totalAdaptations=0}exportPatterns(){return this.registry.getAll()}importPatterns(t){this.clear(),this.storePatternsBatch(t)}getConfig(){return{...this.config}}setEnabled(t){this.engine.setEnabled(t)}isEnabled(){return this.engine.isEnabled()}createStateEmbedding(t){let e=t.features;if(e.length===0)return new Array(this.config.embeddingDim??384).fill(0);let r=Math.max(...e.map(Math.abs));if(r===0)return[...e];let a=e.map(o=>o/r),n=this.config.embeddingDim??384;return a.length>=n?a.slice(0,n):[...a,...new Array(n-a.length).fill(0)]}createActionEmbedding(t){let e=[],r=this.hashCode(t.type);if(e.push(r%1e3/1e3),typeof t.value=="number")e.push(Math.min(1,Math.max(-1,t.value)));else if(typeof t.value=="string"){let n=this.hashCode(t.value);e.push(n%1e3/1e3)}else if(Array.isArray(t.value))for(let n of t.value.slice(0,10))typeof n=="number"&&e.push(Math.min(1,Math.max(-1,n)));let a=this.config.embeddingDim??384;for(;e.length<a;)e.push(0);return e.slice(0,a)}findByRawPattern(t){let e=this.registry.getAll();for(let r of e)if(r.rawPattern?.patternType===t.id)return r}createQEPatternFromRaw(t,e,r){let a={centroid:t.centroid,clusterSize:1,totalWeight:1,avgQuality:t.avgQuality,createdAt:new Date().toISOString(),lastAccessed:new Date().toISOString(),accessCount:0,patternType:t.patternType};return{id:`qesona-${t.id}`,type:e,domain:r,stateEmbedding:t.centroid,action:{type:"learned",value:t.patternType},outcome:{reward:t.avgQuality,success:t.avgQuality>.5,quality:t.avgQuality},confidence:t.avgQuality,usageCount:0,createdAt:new Date,rawPattern:a}}calculateSimilarity(t,e){let r=Math.min(t.length,e.length),a=0,n=0,o=0;for(let s=0;s<r;s++)a+=t[s]*e[s],n+=t[s]*t[s],o+=e[s]*e[s];return(a/(Math.sqrt(n)*Math.sqrt(o)+1e-10)+1)/2}hashCode(t){let e=0;for(let r=0;r<t.length;r++)e=(e<<5)-e+t.charCodeAt(r),e=e|0;return Math.abs(e)}recordAdaptation(t){this.adaptationTimes.push(t),this.totalAdaptations++,this.adaptationTimes.length>1e3&&this.adaptationTimes.shift()}avgAdaptationTime(){return this.adaptationTimes.length===0?0:this.adaptationTimes.reduce((e,r)=>e+r,0)/this.adaptationTimes.length}minAdaptationTime(){return this.adaptationTimes.length===0?0:Math.min(...this.adaptationTimes)}maxAdaptationTime(){return this.adaptationTimes.length===0?0:Math.max(...this.adaptationTimes)}initThreeLoopEngine(t){this.threeLoopEngine=new C({dimension:this.config.embeddingDim??384,microLoraLr:this.config.microLoraLr??.001,ewcLambda:this.config.ewcLambda??1e3,...t},this.engine)}getThreeLoopEngine(){return this.threeLoopEngine}instantAdapt(t){return this.threeLoopEngine?this.threeLoopEngine.instantAdapt(t):null}recordOutcome(t,e){this.threeLoopEngine&&this.threeLoopEngine.recordOutcome(t,e)}backgroundConsolidate(){if(!this.threeLoopEngine)return null;let t=this.threeLoopEngine.backgroundConsolidate();if(t&&(t.consolidated||t.taskBoundaryDetected)&&this.fisherPersistFn)try{this.threeLoopEngine.persistFisher(this.fisherPersistFn,this.fisherDomain)}catch(e){console.warn("[QESONA] Fisher persistence failed:",e instanceof Error?e.message:e)}return t}setFisherPersistence(t,e){this.fisherPersistFn=t,this.fisherDomain=e}syncWithPeers(t){this.threeLoopEngine&&this.threeLoopEngine.syncWithPeers(t)}getEWCMetrics(){return this.threeLoopEngine?this.threeLoopEngine.getEWCMetrics():null}shouldConsolidate(){return this.threeLoopEngine?this.threeLoopEngine.shouldConsolidate():!1}getLocalPeerState(t,e){return this.threeLoopEngine?this.threeLoopEngine.getLocalPeerState(t,e):null}isThreeLoopEnabled(){return this.threeLoopEngine!==null}async verifyPerformance(t=1e3){let e=[],r={id:"test-state",features:new Array(384).fill(0).map(()=>G())};for(let s=0;s<t;s++){let u=performance.now();await this.adaptPattern(r,"test-generation","test-generation");let c=performance.now();e.push({iteration:s,timeMs:c-u})}let a=e.map(s=>s.timeMs),n=a.reduce((s,u)=>s+u,0)/a.length,o=Math.min(...a),i=Math.max(...a);return{targetMet:n<.05,avgTimeMs:n,minTimeMs:o,maxTimeMs:i,details:e}}};function Tt(l){return new v(l)}function Pt(l,t){return new v({...t,maxPatterns:t?.maxPatterns||5e3})}ot();et();var F=null,D=null,W=null,B=null,z=null,I=null,q=!1;try{let l=(O(),w(N));F=l.FlashAttention,D=l.DotProductAttention,W=l.MultiHeadAttention,B=l.HyperbolicAttention,z=l.LinearAttention,I=l.MoEAttention,q=!0}catch{}function Gt(){return q}function A(){if(!q)throw new Error("@ruvector/attention native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var T={"test-similarity":{dim:384,strategy:"flash",blockSize:64},"code-embedding":{dim:512,strategy:"flash",blockSize:128},"defect-matching":{dim:384,strategy:"flash",blockSize:64},"coverage-analysis":{dim:384,strategy:"flash",blockSize:256},"pattern-adaptation":{dim:256,strategy:"flash",blockSize:32}},Kt={"test-similarity":{enabled:!0,microLoRARank:4,targetAdaptationMs:.05,patternCacheSize:1e3},"code-embedding":{enabled:!0,microLoRARank:2,targetAdaptationMs:.03,patternCacheSize:5e3},"defect-matching":{enabled:!0,microLoRARank:8,targetAdaptationMs:.05,patternCacheSize:2e3},"coverage-analysis":{enabled:!1,microLoRARank:2,targetAdaptationMs:.01,patternCacheSize:100},"pattern-adaptation":{enabled:!0,microLoRARank:2,targetAdaptationMs:.05,patternCacheSize:1e4}},$t={"test-similarity":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:1e3}},"code-embedding":{latency:{before:50,after:15},memory:{before:200,after:80},throughput:{min:2e3}},"defect-matching":{latency:{before:20,after:5},memory:{before:150,after:50},throughput:{min:500}},"coverage-analysis":{latency:{before:100,after:1},memory:{before:100,after:30},throughput:{min:1e4}},"pattern-adaptation":{latency:{before:2,after:.05},memory:{before:50,after:20},throughput:{min:2e4}}};function Zt(l){return l<=128?{queryChunkSize:128,kvChunkSize:128}:l<=256?{queryChunkSize:256,kvChunkSize:256}:l<=512?{queryChunkSize:512,kvChunkSize:512}:l<=1024?{queryChunkSize:1024,kvChunkSize:1024}:{queryChunkSize:1024,kvChunkSize:2048}}var E=class{static create(t){switch(A(),t.strategy){case"flash":return new F(t.dim,t.blockSize);case"dot-product":return new D(t.dim);case"multi-head":return new W(t.dim,t.numHeads??8);case"hyperbolic":return new B(t.dim,t.curvature);case"linear":return new z(t.dim,t.features);case"moe":return I.simple(t.dim,t.moeConfig?.numExperts??8,t.moeConfig?.topK??2);default:return new F(t.dim,t.blockSize)}}},L=class l{attention;config;workload;metrics=[];db=null;persistCount=0;static KV_NAMESPACE="attention-metrics";static KV_TTL=3600;static PERSIST_INTERVAL=10;constructor(t,e){this.workload=t;let r=T[t];this.config={...r,...e},this.attention=E.create(this.config)}async initialize(){try{this.db=K(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[QEFlashAttention] DB init failed, using memory-only:",j(t)),this.db=null}}async computeFlashAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=this.toFloat32Array(t,a,n),u=this.splitMatrix(e,a,n),c=this.splitMatrix(r,a,n),m,g=this.attention;typeof g.compute=="function"?m=g.compute(s,u,c):(A(),m=new F(this.config.dim).compute(s,u,c));let h=performance.now(),d=process.memoryUsage().heapUsed/1024/1024;return this.metrics.push({timeMs:h-o,memoryMB:d-i,speedup:1,throughput:a*a/((h-o)/1e3),peakMemoryMB:d}),this.maybePersistToKv(),m}async computeBaselineAttention(t,e,r,a,n){let o=performance.now(),i=process.memoryUsage().heapUsed/1024/1024,s=new Float32Array(a*a),u=1/Math.sqrt(n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=0;for(let p=0;p<n;p++)b+=t[h*n+p]*e[d*n+p];s[h*a+d]=b*u}for(let h=0;h<a;h++){let d=h*a,b=d+a,p=s.subarray(d,b),tt=Math.max(...p),_=0;for(let y=0;y<a;y++)p[y]=Math.exp(p[y]-tt),_+=p[y];for(let y=0;y<a;y++)p[y]/=_}let c=new Float32Array(a*n);for(let h=0;h<a;h++)for(let d=0;d<a;d++){let b=s[h*a+d];for(let p=0;p<n;p++)c[h*n+p]+=b*r[d*n+p]}let m=performance.now(),g=process.memoryUsage().heapUsed/1024/1024;return c}async computeTestSimilarity(t,e,r=5){let a=e.length,n=t.length,o=new Float32Array(a*n),i=new Float32Array(a*n);for(let m=0;m<a;m++)o.set(t,m*n),i.set(e[m],m*n);let s=new Float32Array(a*n),u=await this.computeFlashAttention(o,i,s,a,n),c=[];for(let m=0;m<a;m++)c.push({index:m,similarity:u[m*n]});return c.sort((m,g)=>g.similarity-m.similarity),c.slice(0,r)}async generateCodeEmbedding(t,e){let r=t.length/e.length,a=e.length;return await this.computeFlashAttention(t,e,t,r,a)}async matchDefectPattern(t,e){let r=e.length,a=t.length,n=new Float32Array(r*a),o=new Float32Array(r*a);for(let c=0;c<r;c++)n.set(t,c*a),o.set(e[c],c*a);let i=new Float32Array(r*a),s=await this.computeFlashAttention(n,o,i,r,a),u=[];for(let c=0;c<r;c++)u.push({pattern:c,score:s[c*a]});return u.sort((c,m)=>m.score-c.score),u}getMetrics(){return[...this.metrics]}getAverageSpeedup(){return this.metrics.length===0?1:this.metrics.reduce((t,e)=>t+e.speedup,0)/this.metrics.length}getConfig(){return{...this.config}}updateConfig(t){this.config={...this.config,...t},this.attention=E.create(this.config)}changeStrategy(t){this.config.strategy=t,this.attention=E.create(this.config)}resetMetrics(){this.metrics=[]}getWorkload(){return this.workload}dispose(){this.metrics=[]}async persistToKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e={workload:this.workload,metrics:this.metrics.slice(-50),savedAt:Date.now()};await this.db.kvSet(t,e,l.KV_NAMESPACE,l.KV_TTL)}async loadFromKv(){if(!this.db)return;let t=`attention-metrics-${this.workload}`,e=await this.db.kvGet(t,l.KV_NAMESPACE);e?.metrics?.length&&(this.metrics=e.metrics)}maybePersistToKv(){this.persistCount++,this.persistCount>=l.PERSIST_INTERVAL&&(this.persistCount=0,this.persistToKv().catch(()=>{}))}toFloat32Array(t,e,r){return t.slice(0,r)}splitMatrix(t,e,r){let a=[];for(let n=0;n<e;n++)a.push(t.slice(n*r,(n+1)*r));return a}};async function Y(l,t){let e=new L(l,t);return await e.initialize(),e}function Jt(l){return{...T[l]}}function Xt(){return Object.keys(T)}function Yt(){return A(),F}function te(){return A(),D}function ee(){return A(),W}function re(){return A(),B}function ae(){return A(),z}function ne(){return A(),I}function ie(l){return l instanceof Float32Array?l:new Float32Array(l)}function oe(l){return Array.from(l)}async function se(l,t,e,r){let a=await Y(l),n=[],o=t[0].length,i=e.length;for(let s of t){let u=new Float32Array(i*o),c=new Float32Array(i*o),m=new Float32Array(i*o);u.set(s,0);for(let h=0;h<i;h++)c.set(e[h],h*o),m.set(r[h],h*o);let g=await a.computeFlashAttention(u,c,m,i,o);n.push(g.slice(0,o))}return a.dispose(),n}function We(){return{"@ruvector/sona":"^0.1.5","@ruvector/attention":"^0.1.4","@ruvector/gnn":"^0.1.22"}}function Be(){let l={sona:!1,attention:!1,gnn:!1,all:!1};try{k(),l.sona=!0}catch{}try{O(),l.attention=!0}catch{}try{let t=(it(),w(nt));t.init();let e=new Float32Array([.1,.2,.3]),r=[new Float32Array([.1,.2,.3]),new Float32Array([.4,.5,.6])],a=t.differentiableSearch(e,r,1,1);a&&Array.isArray(a.indices)&&Array.isArray(a.weights)&&(l.gnn=!0)}catch{}return l.all=l.sona&&l.attention&&l.gnn,l}async function ze(){let{initGNN:l}=await import("./gnn-wrapper-GJVYRPHB.js");return[l(),"SONA: Ready (no initialization required)","Attention: Ready (no initialization required)"]}export{v as a,Tt as b,Pt as c,Gt as d,T as e,Kt as f,$t as g,Zt as h,L as i,Y as j,Jt as k,Xt as l,Yt as m,te as n,ee as o,re as p,ae as q,ne as r,ie as s,oe as t,se as u,We as v,Be as w,ze as x};
@@ -1,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.8");process.exit(0)}
2
- import{a as I}from"./chunk-76UL224Z.js";import{n as F,o as q}from"./chunk-BZB5D4BO.js";import{a as A,b as m,c as d}from"./chunk-R2LWLZ3Y.js";import{a as b,b as W,c as O}from"./chunk-PG7CZ6Q4.js";import{f as D}from"./chunk-IP2Z4Z6X.js";import{g as T}from"./chunk-E4D36LGH.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
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.10");process.exit(0)}
2
+ import{a as I}from"./chunk-5TATJQ3Z.js";import{n as F,o as q}from"./chunk-URXG7FMO.js";import{a as A,b as m,c as d}from"./chunk-A2ULGMMG.js";import{a as b,b as W,c as O}from"./chunk-IGRKFVFD.js";import{f as D}from"./chunk-D2A4TGZY.js";import{g as T}from"./chunk-335CCAOL.js";O();var w={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},E={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};function S(){try{let{getUnifiedMemory:s}=(q(),T(F)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var N={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,n=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,o=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||n===null||o===null){let p=S();if(p)try{if(r===null&&(r=p.prepare("SELECT after_lines FROM coverage_sessions ORDER BY created_at DESC LIMIT 1").get()?.after_lines??0),n===null){let y=p.prepare(`SELECT COUNT(*) as total,
3
3
  SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
4
4
  FROM test_outcomes
5
5
  WHERE created_at > datetime('now', '-7 days')`).get();n=y&&y.total>0?y.passed/y.total*100:0}o===null&&(o=p.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
@@ -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.8");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.10");process.exit(0)}
2
2
  var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{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.8");process.exit(0)}
2
- import{a as I,b as H,c as C,e as S,f as L}from"./chunk-LFEBTWFS.js";import{b as T,d as P}from"./chunk-VVNR4R22.js";import{a as f,c as O}from"./chunk-PG7CZ6Q4.js";import{f as x}from"./chunk-IP2Z4Z6X.js";L();P();var v=["function","module","test","file","class"],w=["calls","imports","tests","depends_on","covers"],E=class{ensureSchema(e){e.transaction(()=>{e.exec(I),e.exec(H),e.exec(C)})()}schemaExists(e){return S(e)}getNodeTypes(){return v}getEdgeTypes(){return w}isValidNodeType(e){return v.includes(e)}isValidEdgeType(e){return w.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function N(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?M(n.embedding):null}}function l(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?T(n.metadata):void 0,embedding:n.embedding?F(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function A(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function b(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?T(n.properties):void 0,createdAt:n.created_at}}function _(n,e,t){return`${n}--${t}-->${e}`}function M(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function F(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}O();var z={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},y=class{config;schemaManager;initialized=!1;constructor(e){this.config={...z,...e},this.schemaManager=new E}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=x(),r={id:t,...e},i=N(r);return this.config.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{a as I,b as H,c as C,e as S,f as L}from"./chunk-TTXYZUTQ.js";import{b as T,d as P}from"./chunk-DG2OYKUQ.js";import{a as f,c as O}from"./chunk-IGRKFVFD.js";import{f as x}from"./chunk-D2A4TGZY.js";L();P();var v=["function","module","test","file","class"],w=["calls","imports","tests","depends_on","covers"],E=class{ensureSchema(e){e.transaction(()=>{e.exec(I),e.exec(H),e.exec(C)})()}schemaExists(e){return S(e)}getNodeTypes(){return v}getEdgeTypes(){return w}isValidNodeType(e){return v.includes(e)}isValidEdgeType(e){return w.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function N(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?M(n.embedding):null}}function l(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?T(n.metadata):void 0,embedding:n.embedding?F(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function A(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function b(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?T(n.properties):void 0,createdAt:n.created_at}}function _(n,e,t){return`${n}--${t}-->${e}`}function M(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function F(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}O();var z={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},y=class{config;schemaManager;initialized=!1;constructor(e){this.config={...z,...e},this.schemaManager=new E}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=x(),r={id:t,...e},i=N(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(i.id,i.type,i.name,i.file_path,i.line_start,i.line_end,i.complexity,i.coverage,i.metadata,i.embedding),t}async addEdge(e){this.ensureInitialized();let t=_(e.sourceId,e.targetId,e.type),r={id:t,...e},i=A(r);return this.config.db.prepare(`
@@ -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.8");process.exit(0)}
2
- import{a as G}from"./chunk-XPL3BXLM.js";import{a as q,e as C,f as z}from"./chunk-JCROLOP6.js";import{a as I}from"./chunk-A4DJMFDM.js";import{a as H,b as _,c as U,d as j}from"./chunk-ZCKNGICX.js";import{a as A,b as W,f as N,i as O}from"./chunk-UGJNR52C.js";import{d as B}from"./chunk-LOANEFGZ.js";import{b as v,d as L,f as M,g as P}from"./chunk-X66IXWSO.js";import{a as K}from"./chunk-OT4JADWW.js";import{c as D}from"./chunk-CG3HIYF4.js";import{b as w,d as Y}from"./chunk-VVNR4R22.js";import{b as f,c as h}from"./chunk-R2LWLZ3Y.js";import{a as Q,b,c as J}from"./chunk-PG7CZ6Q4.js";import{f as T}from"./chunk-IP2Z4Z6X.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=B(this.qeConfig.sqlite),this.asymmetricEngine=new G}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-BJ4ZJPMP.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{a as G}from"./chunk-BNNH3KZP.js";import{a as q,e as C,f as z}from"./chunk-4FU6YNDP.js";import{a as I}from"./chunk-4LOJJ4VX.js";import{a as H,b as _,c as U,d as j}from"./chunk-EEWTTYRC.js";import{a as A,b as W,f as N,i as O}from"./chunk-XH7D6EGE.js";import{d as B}from"./chunk-53G3OCGS.js";import{b as v,d as L,f as M,g as P}from"./chunk-NIFVFUCU.js";import{a as K}from"./chunk-7FWZHYYE.js";import{c as D}from"./chunk-WLX57ULC.js";import{b as w,d as Y}from"./chunk-DG2OYKUQ.js";import{b as f,c as h}from"./chunk-A2ULGMMG.js";import{a as Q,b,c as J}from"./chunk-IGRKFVFD.js";import{f as T}from"./chunk-D2A4TGZY.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=B(this.qeConfig.sqlite),this.asymmetricEngine=new G}qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-TLBDFWA6.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -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.8");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.10");process.exit(0)}
2
2
  import{createRequire as t}from"module";var o=t(import.meta.url),e=o("hnswlib-node"),i=e,{RuvectorLayer:r,TensorCompress:a,differentiableSearch:c,hierarchicalForward:l,getCompressionLevel:s,init:p,FlashAttention:d,DotProductAttention:m,MultiHeadAttention:u,HyperbolicAttention:A,LinearAttention:h,MoEAttention:f,SonaEngine:_,pipeline:b}=e||{};export{i as a,r as b,a as c,c as d,l as e,s as f,p as g,d as h,m as i,u as j,A as k,h as l,f as m,_ as n,b as o};
@@ -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.8");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.10");process.exit(0)}
2
2
  var h={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},g=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let s={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.config.stage<4,o=this.config.stage>=2;if(n&&this.db){let i=performance.now();try{let r=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', datetime('now'))
@@ -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.8");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.10");process.exit(0)}
2
2
  import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l 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.8");process.exit(0)}
2
- import{a as L}from"./chunk-R2LWLZ3Y.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{a as L}from"./chunk-A2ULGMMG.js";import*as w from"fs";var R={"aqe test generate":{domain:"test-generation",action:"generateTests"},"aqe test execute":{domain:"test-execution",action:"execute"},"aqe coverage analyze":{domain:"coverage-analysis",action:"analyze"},"aqe coverage gaps":{domain:"coverage-analysis",action:"detectGaps"},"aqe quality gate":{domain:"quality-assessment",action:"evaluateGate"},"aqe quality assess":{domain:"quality-assessment",action:"analyzeQuality"},"aqe security scan":{domain:"security-compliance",action:"runSASTScan"},"aqe security audit":{domain:"security-compliance",action:"runAudit"},"aqe defect predict":{domain:"defect-intelligence",action:"predictDefects"},"aqe code index":{domain:"code-intelligence",action:"index"},"aqe code impact":{domain:"code-intelligence",action:"analyzeImpact"},"aqe contract validate":{domain:"contract-testing",action:"validateContract"},"aqe chaos test":{domain:"chaos-resilience",action:"runChaosTest"},"aqe requirements validate":{domain:"requirements-validation",action:"validateRequirements"},"aqe visual test":{domain:"visual-accessibility",action:"runVisualTest"},"aqe accessibility test":{domain:"visual-accessibility",action:"runAccessibilityTest"},"aqe learn optimize":{domain:"learning-optimization",action:"optimizeAllStrategies"}},D={daily:"0 0 * * *",weekly:"0 0 * * 0",hourly:"0 * * * *",minutely:"* * * * *"},S=1e4,x=20,M=1e4,W=["__proto__","constructor","prototype"];function v(t){return!W.includes(t)}function C(t){let n=t.split(`
3
3
  `);if(n.length>S)throw new Error(`YAML content exceeds maximum allowed lines (${S}). File has ${n.length} lines.`);for(let i=0;i<n.length;i++)if(n[i].length>M)throw new Error(`YAML line ${i+1} exceeds maximum allowed length (${M} characters).`);let a={};for(let i=0;i<n.length;i++){let e=n[i];if(e.trim()===""||e.trim().startsWith("#")||e.search(/\S/)!==0)continue;let o=e.match(/^([\w_-]+):\s*(.+)$/);if(o){let[,c,u]=o;v(c)&&(a[c]=f(u))}}let r=["tags","stages","triggers"];for(let i of r){let e=new RegExp(`^${i}:\\s*$`),s=-1;for(let l=0;l<n.length;l++){let d=n[l];if(!(d.trim()===""||d.trim().startsWith("#"))&&e.test(d.trim())){s=l;break}}if(s===-1)continue;let o=[];a[i]=o;let c=n[s].search(/\S/),u=s+1;for(;u<n.length;){let l=n[u];if(l.trim()===""||l.trim().startsWith("#")){u++;continue}let d=l.search(/\S/),p=l.trim();if(d<=c&&!p.startsWith("-"))break;if(p.startsWith("- ")){let m=p.slice(2).trim();if(!m.includes(":")){o.push(f(m)),u++;continue}let g={},k=m.match(/^([\w_-]+):\s*(.*)$/);if(k){let[,h,y]=k;g[h]=f(y)}let T=d;for(u++;u<n.length;){let h=n[u];if(h.trim()===""||h.trim().startsWith("#")){u++;continue}let y=h.search(/\S/),q=h.trim();if(y<=T)break;let _=q.match(/^([\w_-]+):\s*(.*)$/);if(_){let[,A,$]=_;if($===""){let b=E(n,u+1,y,1);g[A]=b.value,u=b.nextLine;continue}else g[A]=f($)}u++}o.push(g)}else u++}}return a}function E(t,n,a,r=0){if(r>x)throw new Error(`YAML nesting exceeds maximum allowed depth (${x}).`);let i={},e=null,s=null,o=n;for(;o<t.length;){let u=t[o];if(u.trim()===""||u.trim().startsWith("#")){o++;continue}let l=u.search(/\S/),d=u.trim();if(l<=a)break;if(d.startsWith("- ")){let m=d.slice(2).trim();s&&!Array.isArray(i[s])&&(i[s]=[]),s?i[s].push(f(m)):(e||(e=[]),e.push(f(m))),o++;continue}let p=d.match(/^([\w_-]+):\s*(.*)$/);if(p){let[,m,g]=p;if(!v(m)){o++;continue}g===""?(s=m,i[m]=[]):(i[m]=f(g),s=null)}o++}if(e&&Object.keys(i).length===0)return{value:e,nextLine:o};let c=Object.keys(i);return c.length===1&&Array.isArray(i[c[0]])?{value:i[c[0]],nextLine:o}:{value:i,nextLine:o}}function f(t){if(t==="")return"";if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="~")return null;let n=Number(t);return!isNaN(n)&&t!==""?n:t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1).split(",").map(r=>f(r.trim())):t}function K(t){let n=[];if(!w.existsSync(t))return{success:!1,errors:[`File not found: ${t}`]};let a;try{a=w.readFileSync(t,"utf-8")}catch(r){return{success:!1,errors:[`Failed to read file: ${r}`]}}return Y(a,t)}function Y(t,n){let a=[],r;try{r=C(t)}catch(s){return{success:!1,errors:[`Invalid YAML syntax: ${s}`]}}if((!r.name||typeof r.name!="string")&&a.push('Pipeline must have a "name" field'),(!r.stages||!Array.isArray(r.stages))&&a.push('Pipeline must have a "stages" array'),a.length>0)return{success:!1,errors:a};let i={name:r.name,description:r.description,version:r.version||"1.0.0",schedule:r.schedule,stages:r.stages.map((s,o)=>{let c=s;return{name:c.name||`stage-${o}`,command:c.command,params:c.params,depends_on:c.depends_on,condition:c.condition,timeout:c.timeout,retry:c.retry,continue_on_failure:c.continue_on_failure}}),triggers:r.triggers,tags:r.tags,timeout:r.timeout};for(let s=0;s<i.stages.length;s++){let o=i.stages[s];o.command||a.push(`Stage ${s+1} (${o.name}) must have a "command" field`)}if(a.length>0)return{success:!1,pipeline:i,errors:a};let e=O(i,n);return{success:!0,pipeline:i,workflow:e,errors:[]}}function O(t,n){let a=`pipeline-${t.name.replace(/\s+/g,"-").toLowerCase()}`,r=t.stages.map((e,s)=>{let o=P(e.command),c={};if(e.params)for(let[l,d]of Object.entries(e.params))v(l)&&(c[l]=`input.${l}`);let u={id:`stage-${e.name.replace(/\s+/g,"-").toLowerCase()}`,name:e.name,domain:o.domain,action:o.action,inputMapping:Object.keys(c).length>0?c:void 0,dependsOn:e.depends_on?.map(l=>`stage-${l.replace(/\s+/g,"-").toLowerCase()}`),timeout:e.timeout?e.timeout*1e3:void 0,continueOnFailure:e.continue_on_failure};return e.condition&&(u.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),e.retry&&(u.retry={maxAttempts:e.retry.max_attempts||3,backoffMs:(e.retry.backoff_seconds||1)*1e3}),u}),i=t.triggers?.map(e=>{let s={eventType:I(e),sourceDomain:e.source_domain};return e.condition&&(s.condition={path:e.condition.path,operator:e.condition.operator,value:e.condition.value}),s});return{id:a,name:t.name,description:t.description||`Pipeline from ${n||"inline YAML"}`,version:t.version||"1.0.0",steps:r,triggers:i,tags:t.tags,timeout:t.timeout?t.timeout*1e3:void 0}}function P(t){let n=t.trim().replace(/\s+/g," ").toLowerCase();for(let[a,r]of Object.entries(R))if(n.startsWith(a.toLowerCase()))return r;return n.includes("test")&&n.includes("generate")?{domain:"test-generation",action:"generateTests"}:n.includes("test")&&(n.includes("execute")||n.includes("run"))?{domain:"test-execution",action:"execute"}:n.includes("coverage")?{domain:"coverage-analysis",action:"analyze"}:n.includes("quality")||n.includes("gate")?{domain:"quality-assessment",action:"evaluateGate"}:n.includes("security")||n.includes("scan")?{domain:"security-compliance",action:"runSASTScan"}:n.includes("defect")||n.includes("predict")?{domain:"defect-intelligence",action:"predictDefects"}:{domain:"learning-optimization",action:"runLearningCycle"}}function I(t){let n=t.event.toLowerCase();return n==="push"?"code-intelligence.CodePushed":n==="pull_request"||n==="pr"?"code-intelligence.PullRequestOpened":n==="schedule"?"workflow.ScheduleTrigger":n==="quality_gate"?"quality-assessment.QualityGateEvaluated":n==="test_complete"?"test-execution.TestRunCompleted":n}function F(t){let n=[],a=[];if(t.name||n.push({path:"name",message:"Pipeline name is required",severity:"error"}),!t.stages||t.stages.length===0)n.push({path:"stages",message:"Pipeline must have at least one stage",severity:"error"});else{let r=new Set;for(let e=0;e<t.stages.length;e++){let s=t.stages[e],o=`stages[${e}]`;if(r.has(s.name)&&n.push({path:`${o}.name`,message:`Duplicate stage name: ${s.name}`,severity:"error"}),r.add(s.name),s.command?P(s.command).domain==="learning-optimization"&&!s.command.toLowerCase().includes("learn")&&a.push({path:`${o}.command`,message:`Command "${s.command}" not recognized, will default to learning-optimization domain`,severity:"warning"}):n.push({path:`${o}.command`,message:"Stage must have a command",severity:"error"}),s.depends_on)for(let c of s.depends_on)t.stages.some(u=>u.name===c)||n.push({path:`${o}.depends_on`,message:`Unknown dependency: ${c}`,severity:"error"});s.timeout!==void 0&&s.timeout<=0&&n.push({path:`${o}.timeout`,message:"Timeout must be a positive number",severity:"error"}),s.retry&&s.retry.max_attempts!==void 0&&s.retry.max_attempts<1&&n.push({path:`${o}.retry.max_attempts`,message:"max_attempts must be at least 1",severity:"error"})}let i=N(t.stages);i&&n.push({path:"stages",message:`Circular dependency detected: ${i}`,severity:"error"})}if(t.schedule&&(z(t.schedule)||n.push({path:"schedule",message:`Invalid cron expression: ${t.schedule}`,severity:"error"})),t.triggers)for(let r=0;r<t.triggers.length;r++){let i=t.triggers[r],e=`triggers[${r}]`;i.event||n.push({path:`${e}.event`,message:"Trigger must have an event type",severity:"error"}),i.source_domain&&!L.includes(i.source_domain)&&a.push({path:`${e}.source_domain`,message:`Unknown domain: ${i.source_domain}`,severity:"warning"})}return{valid:n.length===0,errors:n,warnings:a}}function N(t){let n=new Set,a=new Set,r=(i,e)=>{if(a.has(i))return[...e,i].join(" -> ");if(n.has(i))return null;n.add(i),a.add(i);let s=t.find(o=>o.name===i);if(s?.depends_on)for(let o of s.depends_on){let c=r(o,[...e,i]);if(c)return c}return a.delete(i),null};for(let i of t){let e=r(i.name,[]);if(e)return e}return null}function z(t){if(Object.keys(D).includes(t))return!0;let n=t.trim().split(/\s+/);if(n.length!==5)return!1;let a=[/^(\*|[0-5]?\d)(-[0-5]?\d)?(\/\d+)?$/,/^(\*|1?\d|2[0-3])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|[12]\d|3[01])(-\d+)?(\/\d+)?$/,/^(\*|[1-9]|1[0-2])(-\d+)?(\/\d+)?$/,/^(\*|[0-7])(-[0-7])?(\/\d+)?$/];for(let r=0;r<5;r++){let i=n[r].split(",");for(let e of i)if(!a[r].test(e)&&e!=="*")return!1}return!0}function G(t){let n={"@daily":"Daily at midnight","@weekly":"Weekly on Sunday at midnight","@hourly":"Every hour","@minutely":"Every minute"};if(n[t])return n[t];if(Object.keys(D).includes(t))return{daily:"Daily at midnight",weekly:"Weekly on Sunday at midnight",hourly:"Every hour",minutely:"Every minute"}[t]||t;let a=t.trim().split(/\s+/);if(a.length!==5)return t;let[r,i,e,s,o]=a;return r==="0"&&i==="0"&&e==="*"&&s==="*"&&o==="*"?"Daily at midnight":r==="0"&&e==="*"&&s==="*"&&o==="*"?`Daily at ${i}:00`:r!=="*"&&i!=="*"&&e==="*"&&s==="*"?`Daily at ${i}:${r.padStart(2,"0")}`:i==="*"&&r==="0"?"Every hour":r!=="*"&&i==="*"?`Every hour at minute ${r}`:t}function H(t,n=new Date){let a=t.trim().split(/\s+/);if(a.length!==5)return new Date(n.getTime()+1440*60*1e3);let[r,i]=a,e=new Date(n);return i!=="*"&&r!=="*"?(e.setHours(parseInt(i,10),parseInt(r,10),0,0),e<=n&&e.setDate(e.getDate()+1)):i!=="*"?(e.setHours(parseInt(i,10),0,0,0),e<=n&&e.setDate(e.getDate()+1)):r!=="*"?(e.setMinutes(parseInt(r,10),0,0),e<=n&&e.setHours(e.getHours()+1)):(e.setSeconds(0,0),e.setMinutes(e.getMinutes()+1)),e}export{C as a,K as b,F as c,G as d,H as e};
@@ -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.8");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.10");process.exit(0)}
2
2
  import T from"crypto";var h=new Uint8Array(256),y=h.length;function s(){return y>h.length-16&&(T.randomFillSync(h),y=0),h.slice(y,y+=16)}var A=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function q(r){return typeof r=="string"&&A.test(r)}var u=q;var o=[];for(let r=0;r<256;++r)o.push((r+256).toString(16).slice(1));function p(r,e=0){return o[r[e+0]]+o[r[e+1]]+o[r[e+2]]+o[r[e+3]]+"-"+o[r[e+4]]+o[r[e+5]]+"-"+o[r[e+6]]+o[r[e+7]]+"-"+o[r[e+8]]+o[r[e+9]]+"-"+o[r[e+10]]+o[r[e+11]]+o[r[e+12]]+o[r[e+13]]+o[r[e+14]]+o[r[e+15]]}function N(r,e=0){let t=p(r,e);if(!u(t))throw TypeError("Stringified UUID is invalid");return t}var _=N;var E,U,I=0,w=0;function R(r,e,t){let n=e&&t||0,f=e||new Array(16);r=r||{};let d=r.node||E,l=r.clockseq!==void 0?r.clockseq:U;if(d==null||l==null){let a=r.random||(r.rng||s)();d==null&&(d=E=[a[0]|1,a[1],a[2],a[3],a[4],a[5]]),l==null&&(l=U=(a[6]<<8|a[7])&16383)}let c=r.msecs!==void 0?r.msecs:Date.now(),x=r.nsecs!==void 0?r.nsecs:w+1,i=c-I+(x-w)/1e4;if(i<0&&r.clockseq===void 0&&(l=l+1&16383),(i<0||c>I)&&r.nsecs===void 0&&(x=0),x>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");I=c,w=x,U=l,c+=122192928e5;let m=((c&268435455)*1e4+x)%4294967296;f[n++]=m>>>24&255,f[n++]=m>>>16&255,f[n++]=m>>>8&255,f[n++]=m&255;let v=c/4294967296*1e4&268435455;f[n++]=v>>>8&255,f[n++]=v&255,f[n++]=v>>>24&15|16,f[n++]=v>>>16&255,f[n++]=l>>>8|128,f[n++]=l&255;for(let a=0;a<6;++a)f[n+a]=d[a];return e||p(f)}var C=R;function H(r){if(!u(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var D=H;function L(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var M="6ba7b810-9dad-11d1-80b4-00c04fd430c8",P="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function g(r,e,t){function n(f,d,l,c){var x;if(typeof f=="string"&&(f=L(f)),typeof d=="string"&&(d=D(d)),((x=d)===null||x===void 0?void 0:x.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let i=new Uint8Array(16+f.length);if(i.set(d),i.set(f,d.length),i=t(i),i[6]=i[6]&15|e,i[8]=i[8]&63|128,l){c=c||0;for(let m=0;m<16;++m)l[c+m]=i[m];return l}return p(i)}try{n.name=r}catch{}return n.DNS=M,n.URL=P,n}import F from"crypto";function G(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),F.createHash("md5").update(r).digest()}var k=G;var X=g("v3",48,k),$=X;import j from"crypto";var S={randomUUID:j.randomUUID};function z(r,e,t){if(S.randomUUID&&!e&&!r)return S.randomUUID();r=r||{};let n=r.random||(r.rng||s)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){t=t||0;for(let f=0;f<16;++f)e[t+f]=n[f];return e}return p(n)}var J=z;import K from"crypto";function O(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),K.createHash("sha1").update(r).digest()}var B=O;var Q=g("v5",80,B),V=Q;var W="00000000-0000-0000-0000-000000000000";function Y(r){if(!u(r))throw TypeError("Invalid UUID");return parseInt(r.slice(14,15),16)}var Z=Y;export{u as a,_ as b,C as c,D as d,$ as e,J as f,V as g,W as h,Z 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.8");process.exit(0)}
2
- import{c as w,d as E,f as T}from"./chunk-E4D36LGH.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.10");process.exit(0)}
2
+ import{c as w,d as E,f as T}from"./chunk-335CCAOL.js";var d=E((b,u)=>{"use strict";var _=typeof Buffer<"u",a=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,l=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function p(r,t,e){e==null&&t!==null&&typeof t=="object"&&(e=t,t=void 0),_&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let o=JSON.parse(r,t);if(o===null||typeof o!="object")return o;let n=e&&e.protoAction||"error",c=e&&e.constructorAction||"error";if(n==="ignore"&&c==="ignore")return o;if(n!=="ignore"&&c!=="ignore"){if(a.test(r)===!1&&l.test(r)===!1)return o}else if(n!=="ignore"&&c==="ignore"){if(a.test(r)===!1)return o}else if(l.test(r)===!1)return o;return y(o,{protoAction:n,constructorAction:c,safe:e&&e.safe})}function y(r,{protoAction:t="error",constructorAction:e="error",safe:o}={}){let n=[r];for(;n.length;){let c=n;n=[];for(let s of c){if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"__proto__")){if(o===!0)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.__proto__}if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(s,"constructor")&&s.constructor!==null&&typeof s.constructor=="object"&&Object.prototype.hasOwnProperty.call(s.constructor,"prototype")){if(o===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete s.constructor}for(let h in s){let f=s[h];f&&typeof f=="object"&&n.push(f)}}}return r}function i(r,t,e){let{stackTraceLimit:o}=Error;Error.stackTraceLimit=0;try{return p(r,t,e)}finally{Error.stackTraceLimit=o}}function m(r,t){let{stackTraceLimit:e}=Error;Error.stackTraceLimit=0;try{return p(r,t,{safe:!0})}catch{return}finally{Error.stackTraceLimit=e}}u.exports=i;u.exports.default=i;u.exports.parse=i;u.exports.safeParse=m;u.exports.scan=y});function F(r){return g.default.parse(r,void 0,{protoAction:"remove",constructorAction:"remove"})}function j(r,t){try{return F(r)}catch(e){throw new Error(`Invalid JSON in --${t}: ${e instanceof Error?e.message:"Parse error"}`)}}var g,O=w(()=>{"use strict";g=T(d(),1)});export{d as a,F as b,j as c,O as d};