agentic-qe 3.10.6 → 3.10.7

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 (441) hide show
  1. package/.claude/hooks/aqe-hook.cjs +38 -2
  2. package/.claude/skills/.validation/examples/chaos-engineering-output.example.json +1 -1
  3. package/.claude/skills/.validation/examples/performance-testing-output.example.json +1 -1
  4. package/.claude/skills/.validation/examples/security-testing-output.example.json +1 -1
  5. package/.claude/skills/.validation/examples/testability-scoring-output.example.json +1 -1
  6. package/.claude/skills/.validation/schemas/skill-eval.schema.json +2 -4
  7. package/.claude/skills/.validation/schemas/skill-frontmatter.schema.json +1 -1
  8. package/.claude/skills/.validation/schemas/skill-output.template.json +1 -1
  9. package/.claude/skills/.validation/templates/eval.template.yaml +3 -3
  10. package/.claude/skills/.validation/templates/security-testing-eval.template.yaml +3 -2
  11. package/.claude/skills/.validation/templates/skill-frontmatter.example.yaml +2 -2
  12. package/.claude/skills/a11y-ally/evals/a11y-ally.yaml +2 -2
  13. package/.claude/skills/accessibility-testing/evals/accessibility-testing.yaml +2 -3
  14. package/.claude/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -3
  15. package/.claude/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +3 -3
  16. package/.claude/skills/cicd-pipeline-qe-orchestrator/evals/cicd-pipeline-qe-orchestrator.yaml +2 -2
  17. package/.claude/skills/compatibility-testing/evals/compatibility-testing.yaml +2 -2
  18. package/.claude/skills/compliance-testing/evals/compliance-testing.yaml +2 -3
  19. package/.claude/skills/contract-testing/evals/contract-testing.yaml +2 -3
  20. package/.claude/skills/database-testing/evals/database-testing.yaml +2 -3
  21. package/.claude/skills/enterprise-integration-testing/evals/enterprise-integration-testing.yaml +2 -2
  22. package/.claude/skills/localization-testing/evals/localization-testing.yaml +2 -2
  23. package/.claude/skills/middleware-testing-patterns/evals/middleware-testing-patterns.yaml +2 -2
  24. package/.claude/skills/mobile-testing/evals/mobile-testing.yaml +2 -2
  25. package/.claude/skills/mutation-testing/evals/mutation-testing.yaml +2 -3
  26. package/.claude/skills/mutation-testing/test-data/sample-output.json +1 -1
  27. package/.claude/skills/n8n-expression-testing/evals/n8n-expression-testing.yaml +2 -2
  28. package/.claude/skills/n8n-integration-testing-patterns/evals/n8n-integration-testing-patterns.yaml +2 -2
  29. package/.claude/skills/n8n-security-testing/evals/n8n-security-testing.yaml +3 -2
  30. package/.claude/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +2 -2
  31. package/.claude/skills/n8n-workflow-testing-fundamentals/evals/n8n-workflow-testing-fundamentals.yaml +2 -2
  32. package/.claude/skills/observability-testing-patterns/evals/observability-testing-patterns.yaml +2 -2
  33. package/.claude/skills/pentest-validation/evals/pentest-validation.yaml +3 -3
  34. package/.claude/skills/performance-testing/evals/performance-testing.yaml +2 -3
  35. package/.claude/skills/qcsd-cicd-swarm/evals/qcsd-cicd-swarm.yaml +2 -2
  36. package/.claude/skills/qcsd-development-swarm/evals/qcsd-development-swarm.yaml +2 -2
  37. package/.claude/skills/qcsd-ideation-swarm/evals/qcsd-ideation-swarm.yaml +2 -2
  38. package/.claude/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +2 -2
  39. package/.claude/skills/qcsd-refinement-swarm/evals/qcsd-refinement-swarm.yaml +2 -2
  40. package/.claude/skills/qe-browser/evals/qe-browser.yaml +2 -2
  41. package/.claude/skills/qe-chaos-resilience/evals/qe-chaos-resilience.yaml +3 -2
  42. package/.claude/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +2 -2
  43. package/.claude/skills/qe-coverage-analysis/evals/qe-coverage-analysis.yaml +2 -2
  44. package/.claude/skills/qe-defect-intelligence/evals/qe-defect-intelligence.yaml +3 -2
  45. package/.claude/skills/qe-learning-optimization/evals/qe-learning-optimization.yaml +4 -4
  46. package/.claude/skills/qe-quality-assessment/evals/qe-quality-assessment.yaml +2 -2
  47. package/.claude/skills/qe-requirements-validation/evals/qe-requirements-validation.yaml +2 -2
  48. package/.claude/skills/qe-test-execution/evals/qe-test-execution.yaml +2 -2
  49. package/.claude/skills/qe-test-generation/evals/qe-test-generation.yaml +2 -2
  50. package/.claude/skills/qe-visual-accessibility/evals/qe-visual-accessibility.yaml +2 -2
  51. package/.claude/skills/quality-metrics/evals/quality-metrics.yaml +2 -2
  52. package/.claude/skills/regression-testing/evals/regression-testing.yaml +2 -2
  53. package/.claude/skills/risk-based-testing/evals/risk-based-testing.yaml +2 -2
  54. package/.claude/skills/security-testing/evals/security-testing.yaml +3 -3
  55. package/.claude/skills/security-visual-testing/evals/security-visual-testing.yaml +3 -2
  56. package/.claude/skills/shift-left-testing/evals/shift-left-testing.yaml +2 -2
  57. package/.claude/skills/shift-right-testing/evals/shift-right-testing.yaml +2 -2
  58. package/.claude/skills/skills-manifest.json +1 -1
  59. package/.claude/skills/test-automation-strategy/evals/test-automation-strategy.yaml +2 -2
  60. package/.claude/skills/test-data-management/evals/test-data-management.yaml +2 -2
  61. package/.claude/skills/test-design-techniques/evals/test-design-techniques.yaml +2 -2
  62. package/.claude/skills/test-reporting-analytics/evals/test-reporting-analytics.yaml +2 -2
  63. package/.claude/skills/testability-scoring/evals/testability-scoring.yaml +2 -3
  64. package/.claude/skills/validation-pipeline/evals/validation-pipeline.yaml +2 -2
  65. package/.claude/skills/verification-quality/evals/verification-quality.yaml +2 -2
  66. package/.claude/skills/visual-testing-advanced/evals/visual-testing-advanced.yaml +2 -2
  67. package/.claude/skills/wms-testing-patterns/evals/wms-testing-patterns.yaml +2 -1
  68. package/CHANGELOG.md +41 -0
  69. package/assets/skills/.validation/examples/chaos-engineering-output.example.json +1 -1
  70. package/assets/skills/.validation/examples/performance-testing-output.example.json +1 -1
  71. package/assets/skills/.validation/examples/security-testing-output.example.json +1 -1
  72. package/assets/skills/.validation/examples/testability-scoring-output.example.json +1 -1
  73. package/assets/skills/.validation/schemas/skill-eval.schema.json +2 -4
  74. package/assets/skills/.validation/schemas/skill-frontmatter.schema.json +1 -1
  75. package/assets/skills/.validation/schemas/skill-output.template.json +1 -1
  76. package/assets/skills/.validation/templates/eval.template.yaml +3 -3
  77. package/assets/skills/.validation/templates/security-testing-eval.template.yaml +3 -2
  78. package/assets/skills/.validation/templates/skill-frontmatter.example.yaml +2 -2
  79. package/assets/skills/a11y-ally/evals/a11y-ally.yaml +2 -2
  80. package/assets/skills/accessibility-testing/evals/accessibility-testing.yaml +2 -3
  81. package/assets/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -3
  82. package/assets/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +3 -3
  83. package/assets/skills/cicd-pipeline-qe-orchestrator/evals/cicd-pipeline-qe-orchestrator.yaml +2 -2
  84. package/assets/skills/compatibility-testing/evals/compatibility-testing.yaml +2 -2
  85. package/assets/skills/compliance-testing/evals/compliance-testing.yaml +2 -3
  86. package/assets/skills/contract-testing/evals/contract-testing.yaml +2 -3
  87. package/assets/skills/database-testing/evals/database-testing.yaml +2 -3
  88. package/assets/skills/enterprise-integration-testing/evals/enterprise-integration-testing.yaml +2 -2
  89. package/assets/skills/localization-testing/evals/localization-testing.yaml +2 -2
  90. package/assets/skills/middleware-testing-patterns/evals/middleware-testing-patterns.yaml +2 -2
  91. package/assets/skills/mobile-testing/evals/mobile-testing.yaml +2 -2
  92. package/assets/skills/mutation-testing/evals/mutation-testing.yaml +2 -3
  93. package/assets/skills/mutation-testing/test-data/sample-output.json +1 -1
  94. package/assets/skills/n8n-expression-testing/evals/n8n-expression-testing.yaml +2 -2
  95. package/assets/skills/n8n-integration-testing-patterns/evals/n8n-integration-testing-patterns.yaml +2 -2
  96. package/assets/skills/n8n-security-testing/evals/n8n-security-testing.yaml +3 -2
  97. package/assets/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +2 -2
  98. package/assets/skills/n8n-workflow-testing-fundamentals/evals/n8n-workflow-testing-fundamentals.yaml +2 -2
  99. package/assets/skills/observability-testing-patterns/evals/observability-testing-patterns.yaml +2 -2
  100. package/assets/skills/pentest-validation/evals/pentest-validation.yaml +3 -3
  101. package/assets/skills/performance-testing/evals/performance-testing.yaml +2 -3
  102. package/assets/skills/qcsd-cicd-swarm/evals/qcsd-cicd-swarm.yaml +2 -2
  103. package/assets/skills/qcsd-development-swarm/evals/qcsd-development-swarm.yaml +2 -2
  104. package/assets/skills/qcsd-ideation-swarm/evals/qcsd-ideation-swarm.yaml +2 -2
  105. package/assets/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +2 -2
  106. package/assets/skills/qcsd-refinement-swarm/evals/qcsd-refinement-swarm.yaml +2 -2
  107. package/assets/skills/qe-browser/evals/qe-browser.yaml +2 -2
  108. package/assets/skills/qe-chaos-resilience/evals/qe-chaos-resilience.yaml +3 -2
  109. package/assets/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +2 -2
  110. package/assets/skills/qe-coverage-analysis/evals/qe-coverage-analysis.yaml +2 -2
  111. package/assets/skills/qe-defect-intelligence/evals/qe-defect-intelligence.yaml +3 -2
  112. package/assets/skills/qe-learning-optimization/evals/qe-learning-optimization.yaml +4 -4
  113. package/assets/skills/qe-quality-assessment/evals/qe-quality-assessment.yaml +2 -2
  114. package/assets/skills/qe-requirements-validation/evals/qe-requirements-validation.yaml +2 -2
  115. package/assets/skills/qe-test-execution/evals/qe-test-execution.yaml +2 -2
  116. package/assets/skills/qe-test-generation/evals/qe-test-generation.yaml +2 -2
  117. package/assets/skills/qe-visual-accessibility/evals/qe-visual-accessibility.yaml +2 -2
  118. package/assets/skills/quality-metrics/evals/quality-metrics.yaml +2 -2
  119. package/assets/skills/regression-testing/evals/regression-testing.yaml +2 -2
  120. package/assets/skills/risk-based-testing/evals/risk-based-testing.yaml +2 -2
  121. package/assets/skills/security-testing/evals/security-testing.yaml +3 -3
  122. package/assets/skills/security-visual-testing/evals/security-visual-testing.yaml +3 -2
  123. package/assets/skills/shift-left-testing/evals/shift-left-testing.yaml +2 -2
  124. package/assets/skills/shift-right-testing/evals/shift-right-testing.yaml +2 -2
  125. package/assets/skills/test-automation-strategy/evals/test-automation-strategy.yaml +2 -2
  126. package/assets/skills/test-data-management/evals/test-data-management.yaml +2 -2
  127. package/assets/skills/test-design-techniques/evals/test-design-techniques.yaml +2 -2
  128. package/assets/skills/test-reporting-analytics/evals/test-reporting-analytics.yaml +2 -2
  129. package/assets/skills/testability-scoring/evals/testability-scoring.yaml +2 -3
  130. package/assets/skills/validation-pipeline/evals/validation-pipeline.yaml +2 -2
  131. package/assets/skills/verification-quality/evals/verification-quality.yaml +2 -2
  132. package/assets/skills/visual-testing-advanced/evals/visual-testing-advanced.yaml +2 -2
  133. package/assets/skills/wms-testing-patterns/evals/wms-testing-patterns.yaml +2 -1
  134. package/dist/cli/bundle.js +5 -5
  135. package/dist/cli/chunks/adapter-TTIBYXH2.js +2 -0
  136. package/dist/cli/chunks/{agent-booster-wasm-J5CITTTV.js → agent-booster-wasm-6I3JMU2M.js} +2 -2
  137. package/dist/cli/chunks/{agent-handler-HMN4ZBZ6.js → agent-handler-XWI7YM6R.js} +2 -2
  138. package/dist/cli/chunks/{agent-memory-branch-SCAKN4DU.js → agent-memory-branch-QFZKQN2L.js} +2 -2
  139. package/dist/cli/chunks/aqe-learning-engine-CTV5OLSN.js +2 -0
  140. package/dist/cli/chunks/{arena-CJOLCHZW.js → arena-5HNPVTBZ.js} +4 -4
  141. package/dist/cli/chunks/{arena-FVBTSGKS.js → arena-P4IUBKZP.js} +2 -2
  142. package/dist/cli/chunks/{audit-SOF6L5RY.js → audit-PBSH25VZ.js} +2 -2
  143. package/dist/cli/chunks/base-ISNCJZ7A.js +2 -0
  144. package/dist/cli/chunks/{hnswlib-node-LFVNGGCL.js → better-sqlite3-F262IAGH.js} +2 -2
  145. package/dist/cli/chunks/{brain-handler-D2ZQQI2J.js → brain-handler-EVYRCKXI.js} +3 -3
  146. package/dist/cli/chunks/{branch-enumerator-QQXOCGOR.js → branch-enumerator-SUDGYJQJ.js} +2 -2
  147. package/dist/cli/chunks/{browser-XASHKIEN.js → browser-4UKMW2RE.js} +2 -2
  148. package/dist/cli/chunks/browser-workflow-OD32QTTI.js +2 -0
  149. package/dist/cli/chunks/{chunk-F72A356B.js → chunk-222ZQTL5.js} +2 -2
  150. package/dist/cli/chunks/{chunk-NKEGEQ3J.js → chunk-262F3EMN.js} +2 -2
  151. package/dist/cli/chunks/{chunk-5QTUGFFP.js → chunk-2J4ZUUU5.js} +2 -2
  152. package/dist/cli/chunks/{chunk-2I5RXDNO.js → chunk-2JWFS2K2.js} +2 -2
  153. package/dist/cli/chunks/{chunk-K32AUACO.js → chunk-2MLISLRR.js} +1 -1
  154. package/dist/cli/chunks/{chunk-J2SMTP2L.js → chunk-32E2OPIE.js} +3 -3
  155. package/dist/cli/chunks/{chunk-Q5432RIH.js → chunk-34NT5NBZ.js} +2 -2
  156. package/dist/cli/chunks/{chunk-TWH3ZL6B.js → chunk-3IJS52OS.js} +2 -2
  157. package/dist/cli/chunks/{chunk-T6CUKJHS.js → chunk-3O4Q4GAX.js} +1 -1
  158. package/dist/cli/chunks/{chunk-Z3RPA3RD.js → chunk-3W6QASVB.js} +2 -2
  159. package/dist/cli/chunks/{chunk-GXNNKM7F.js → chunk-3XEL7XCA.js} +1 -1
  160. package/dist/cli/chunks/{chunk-TNVOINYC.js → chunk-4I6FK67T.js} +3 -3
  161. package/dist/cli/chunks/{chunk-UQYDFT6I.js → chunk-4MJQJQLY.js} +2 -2
  162. package/dist/cli/chunks/{chunk-H6UPZFI6.js → chunk-4RGV6Z2H.js} +2 -2
  163. package/dist/cli/chunks/{chunk-4N4TU7ST.js → chunk-4W5QWFU4.js} +1 -1
  164. package/dist/cli/chunks/{chunk-ELC6JIXL.js → chunk-5QMIVHFT.js} +2 -2
  165. package/dist/cli/chunks/{chunk-X5R6SUWM.js → chunk-64BSODHA.js} +2 -2
  166. package/dist/cli/chunks/{chunk-J3WUBGLQ.js → chunk-6A2HRMTD.js} +2 -2
  167. package/dist/cli/chunks/{chunk-LEDF3LGZ.js → chunk-6F5KPT6U.js} +1 -1
  168. package/dist/cli/chunks/{chunk-BHD6THT5.js → chunk-6OLPKIYU.js} +1 -1
  169. package/dist/cli/chunks/{chunk-6DHJPKAH.js → chunk-6QBD64W3.js} +2 -2
  170. package/dist/cli/chunks/{chunk-7RTI5WT4.js → chunk-6RG7ZJ2H.js} +2 -2
  171. package/dist/cli/chunks/{chunk-Q4LYWIEX.js → chunk-76JYG426.js} +2 -2
  172. package/dist/cli/chunks/{chunk-TFA5UETW.js → chunk-76SUEI7S.js} +1 -1
  173. package/dist/cli/chunks/{chunk-B3H2TTYT.js → chunk-7NK2H7H5.js} +2 -2
  174. package/dist/cli/chunks/{chunk-7SFCZ3AE.js → chunk-AKL5A3IZ.js} +1 -1
  175. package/dist/cli/chunks/{chunk-HMHQOEU7.js → chunk-AKSCYNFH.js} +2 -2
  176. package/dist/cli/chunks/{chunk-QZSNYXYC.js → chunk-AW3LGLC3.js} +2 -2
  177. package/dist/cli/chunks/{chunk-ZMCMSDXR.js → chunk-AY4IEMRI.js} +2 -2
  178. package/dist/cli/chunks/{chunk-XOYTW6LI.js → chunk-B5ZJV7GZ.js} +2 -2
  179. package/dist/cli/chunks/{chunk-KVMY2ABO.js → chunk-BLFZFKT6.js} +2 -2
  180. package/dist/cli/chunks/{chunk-ESZDW6G7.js → chunk-BPC6X6VR.js} +2 -2
  181. package/dist/cli/chunks/{chunk-HDEFCRHI.js → chunk-BRYYQQUV.js} +1 -1
  182. package/dist/cli/chunks/{chunk-CH7KUYGO.js → chunk-BU2I77YW.js} +3 -3
  183. package/dist/cli/chunks/{chunk-NEIJP6TG.js → chunk-C5CY5NSW.js} +2 -2
  184. package/dist/cli/chunks/{chunk-H4Q36ILL.js → chunk-CGBEI7UH.js} +2 -2
  185. package/dist/cli/chunks/{chunk-VFFIMJWT.js → chunk-CJTDQJ7E.js} +1 -1
  186. package/dist/cli/chunks/{chunk-XKRJQIGP.js → chunk-CW7JQVXV.js} +2 -2
  187. package/dist/cli/chunks/chunk-DF7V6X3N.js +2 -0
  188. package/dist/cli/chunks/{chunk-6ZLVQTQ5.js → chunk-DPT37UHR.js} +4 -4
  189. package/dist/cli/chunks/{chunk-IB3QQDC4.js → chunk-DU7Y54JI.js} +1 -1
  190. package/dist/cli/chunks/{chunk-TUFU3BAK.js → chunk-DYNO72WD.js} +2 -2
  191. package/dist/cli/chunks/{chunk-LOQMQEKN.js → chunk-DYSRMAZP.js} +1 -1
  192. package/dist/cli/chunks/{chunk-RTFFD263.js → chunk-EWNJK2BU.js} +1 -1
  193. package/dist/cli/chunks/{chunk-JPL53G4V.js → chunk-F5RZSNHI.js} +2 -2
  194. package/dist/cli/chunks/{chunk-RH3I4Q23.js → chunk-FK4JHBG4.js} +2 -2
  195. package/dist/cli/chunks/{chunk-DAUQIXHW.js → chunk-FQBNPSV2.js} +2 -2
  196. package/dist/cli/chunks/{chunk-LHA4OQ7G.js → chunk-FWLXK6AH.js} +2 -2
  197. package/dist/cli/chunks/{chunk-UVWOIF6P.js → chunk-G7ISGLKP.js} +1 -1
  198. package/dist/cli/chunks/{chunk-EYKID5HA.js → chunk-GUDOOOO6.js} +1 -1
  199. package/dist/cli/chunks/{chunk-SA5FTDRS.js → chunk-HARYQMWN.js} +2 -2
  200. package/dist/cli/chunks/{chunk-RA7HEY5G.js → chunk-HBWAMCVB.js} +2 -2
  201. package/dist/cli/chunks/{chunk-NUCJS3Z7.js → chunk-HDLF6LGO.js} +3 -3
  202. package/dist/cli/chunks/{chunk-XLFYVBOD.js → chunk-HELQ7CXL.js} +1 -1
  203. package/dist/cli/chunks/{chunk-USPBUR6P.js → chunk-HI4DA7Z3.js} +2 -2
  204. package/dist/cli/chunks/{chunk-PIIBVLFC.js → chunk-I64BLAFS.js} +2 -2
  205. package/dist/cli/chunks/{chunk-AQPFTDGS.js → chunk-I7M574IO.js} +2 -2
  206. package/dist/cli/chunks/{chunk-JP2YXWJD.js → chunk-INI3AGF5.js} +2 -2
  207. package/dist/cli/chunks/{chunk-ZY4G7O7Y.js → chunk-ISLI6D4K.js} +2 -2
  208. package/dist/cli/chunks/{chunk-T6SCQVWH.js → chunk-IXAABYGS.js} +2 -2
  209. package/dist/cli/chunks/{chunk-2IC2I525.js → chunk-IYZWEYWJ.js} +1 -1
  210. package/dist/cli/chunks/{chunk-M4OYZMXE.js → chunk-J5ETX2DG.js} +2 -2
  211. package/dist/cli/chunks/{chunk-XOGBTPJI.js → chunk-JJELOEIY.js} +4 -4
  212. package/dist/cli/chunks/{chunk-EDPVATNH.js → chunk-JNQVPTOM.js} +2 -2
  213. package/dist/cli/chunks/{chunk-5VTRPOYL.js → chunk-JNXPRDNV.js} +3 -3
  214. package/dist/cli/chunks/{chunk-7OK5H6ML.js → chunk-K6A3AWUI.js} +1 -1
  215. package/dist/cli/chunks/{chunk-ULEVKOWQ.js → chunk-K6IU2MV4.js} +1 -1
  216. package/dist/cli/chunks/{chunk-SHVTMMJB.js → chunk-KXENXRZE.js} +1 -1
  217. package/dist/cli/chunks/{chunk-HWKFBRMX.js → chunk-L2ZSYIDA.js} +1 -1
  218. package/dist/cli/chunks/{chunk-RTAGNKCV.js → chunk-L3EQQMFI.js} +2 -2
  219. package/dist/cli/chunks/{chunk-S574AFAT.js → chunk-L5UUUSSB.js} +1 -1
  220. package/dist/cli/chunks/{chunk-5V4IFRG5.js → chunk-L6NB4UHR.js} +2 -2
  221. package/dist/cli/chunks/{chunk-2UI5LQ7C.js → chunk-LEZ2MGHM.js} +3 -3
  222. package/dist/cli/chunks/{chunk-NN35QH6X.js → chunk-LFSQSLNP.js} +2 -2
  223. package/dist/cli/chunks/{chunk-L2IMTNZF.js → chunk-LHZYTNOQ.js} +2 -2
  224. package/dist/cli/chunks/{chunk-JADBRSQN.js → chunk-LJHCPN4E.js} +2 -2
  225. package/dist/cli/chunks/{chunk-UNDPB5SS.js → chunk-LRRQEAP5.js} +1 -1
  226. package/dist/cli/chunks/{chunk-ZBSEXVEI.js → chunk-LSHUPEQQ.js} +2 -2
  227. package/dist/cli/chunks/{chunk-HZGOVRZ6.js → chunk-LUZH2IZY.js} +2 -2
  228. package/dist/cli/chunks/{chunk-UWDC3TZP.js → chunk-M7SO5KNJ.js} +2 -2
  229. package/dist/cli/chunks/{chunk-KQOJYO5Z.js → chunk-MDVJVY4C.js} +4 -4
  230. package/dist/cli/chunks/{chunk-TFJDJVPC.js → chunk-MK73CCKO.js} +2 -2
  231. package/dist/cli/chunks/{chunk-JXCIRWLQ.js → chunk-MMR23KAO.js} +2 -2
  232. package/dist/cli/chunks/{chunk-ROXH622K.js → chunk-MOI74MMX.js} +2 -2
  233. package/dist/cli/chunks/{chunk-MSJGDIRP.js → chunk-MRLGQX7Y.js} +2 -2
  234. package/dist/cli/chunks/{chunk-2RQSFRON.js → chunk-MWRKNBSY.js} +2 -2
  235. package/dist/cli/chunks/{chunk-BXOGLZGU.js → chunk-NKYMHEHY.js} +2 -2
  236. package/dist/cli/chunks/{chunk-MJLDZSFB.js → chunk-O4B6FFC5.js} +1 -1
  237. package/dist/cli/chunks/{chunk-JX7HZMW5.js → chunk-OAXDI4XM.js} +1 -1
  238. package/dist/cli/chunks/{chunk-PFSBUTDA.js → chunk-OMDV6GFP.js} +1 -1
  239. package/dist/cli/chunks/{chunk-OBLAWVXM.js → chunk-OPLLH67G.js} +1 -1
  240. package/dist/cli/chunks/{chunk-LAGNWKAD.js → chunk-OSETFZVE.js} +2 -2
  241. package/dist/cli/chunks/{chunk-OU4HRUVV.js → chunk-OW4LJ5HE.js} +2 -2
  242. package/dist/cli/chunks/{chunk-NHC635LL.js → chunk-PY3HWJRJ.js} +2 -2
  243. package/dist/cli/chunks/{chunk-DFBVWMX3.js → chunk-QBVFONWU.js} +2 -2
  244. package/dist/cli/chunks/{chunk-7BPYFDWY.js → chunk-QBVS4CXM.js} +1 -1
  245. package/dist/cli/chunks/{chunk-O2H5WYFK.js → chunk-QDBFB4XD.js} +2 -2
  246. package/dist/cli/chunks/{chunk-X3YWLJGT.js → chunk-QLVZEEPR.js} +2 -2
  247. package/dist/cli/chunks/{chunk-4B22URZJ.js → chunk-QMGNYRR5.js} +3 -3
  248. package/dist/cli/chunks/{chunk-MCMVRPNG.js → chunk-R2B6EQQF.js} +2 -2
  249. package/dist/cli/chunks/{chunk-VQM2TC2V.js → chunk-R7KIC6TL.js} +1 -1
  250. package/dist/cli/chunks/{chunk-HFU3LTQX.js → chunk-RJBCIN2G.js} +2 -2
  251. package/dist/cli/chunks/{chunk-PIJ5XOMM.js → chunk-RLXCFURS.js} +2 -2
  252. package/dist/cli/chunks/{chunk-WNAFMYND.js → chunk-S423UHYM.js} +2 -2
  253. package/dist/cli/chunks/{chunk-GWHDPEBT.js → chunk-S4NNQE4L.js} +1 -1
  254. package/dist/cli/chunks/{chunk-AJ2VDNPB.js → chunk-S7FNTWFM.js} +2 -2
  255. package/dist/cli/chunks/{chunk-H73FLSBV.js → chunk-SFW6IDMR.js} +10 -10
  256. package/dist/cli/chunks/{chunk-QUQA4NNZ.js → chunk-SG6O3PXZ.js} +2 -2
  257. package/dist/cli/chunks/{chunk-P7EOYGR2.js → chunk-SLASYVNX.js} +2 -2
  258. package/dist/cli/chunks/{chunk-A2DCROAN.js → chunk-TIUC5LRA.js} +2 -2
  259. package/dist/cli/chunks/{chunk-LHZOIXJ6.js → chunk-TTLAWPEN.js} +2 -2
  260. package/dist/cli/chunks/{chunk-QNIL3D6E.js → chunk-TXXRBNOB.js} +1 -1
  261. package/dist/cli/chunks/{chunk-6RFPELCD.js → chunk-TY7XPI6R.js} +2 -2
  262. package/dist/cli/chunks/{chunk-QJXZ4SU7.js → chunk-U7EGKKN3.js} +2 -2
  263. package/dist/cli/chunks/{chunk-I7ADT6AZ.js → chunk-UPDPD43T.js} +2 -2
  264. package/dist/cli/chunks/{chunk-RBZWUWUG.js → chunk-UURGDFGU.js} +1 -1
  265. package/dist/cli/chunks/{chunk-MQN3HYFX.js → chunk-UVUVWA4B.js} +1 -1
  266. package/dist/cli/chunks/{chunk-2CZQA3NN.js → chunk-V3KNHI5B.js} +2 -2
  267. package/dist/cli/chunks/{chunk-ELTN4F4R.js → chunk-V7WBNB2S.js} +2 -2
  268. package/dist/cli/chunks/{chunk-4XEUJH2M.js → chunk-VPBXVZWE.js} +1 -1
  269. package/dist/cli/chunks/{chunk-3XUPDWMA.js → chunk-WCXQA24H.js} +8 -8
  270. package/dist/cli/chunks/{chunk-CSM4LXTH.js → chunk-X3HRJV65.js} +1 -1
  271. package/dist/cli/chunks/{chunk-DF4Z7TKZ.js → chunk-X6OJFP7G.js} +2 -2
  272. package/dist/cli/chunks/{chunk-M3APJ7VS.js → chunk-XCYPVJ34.js} +2 -2
  273. package/dist/cli/chunks/{chunk-LWUIK5DH.js → chunk-XK7P7OXO.js} +2 -2
  274. package/dist/cli/chunks/{chunk-O4MNYX4X.js → chunk-XWPUCPYW.js} +2 -2
  275. package/dist/cli/chunks/{chunk-EJWAKPZD.js → chunk-YB4GXJJG.js} +1 -1
  276. package/dist/cli/chunks/{chunk-SUGQZCNI.js → chunk-YBM4LUSF.js} +2 -2
  277. package/dist/cli/chunks/{chunk-C75ODWRP.js → chunk-YLXUF5KW.js} +3 -3
  278. package/dist/cli/chunks/{chunk-ULV5K4V5.js → chunk-YMBPKBKG.js} +1 -1
  279. package/dist/cli/chunks/{chunk-7NXVVIJZ.js → chunk-Z44VJC5U.js} +2 -2
  280. package/dist/cli/chunks/{ci-COQUVZH6.js → ci-OO42YBET.js} +2 -2
  281. package/dist/cli/chunks/{ci-output-KVUHUEOT.js → ci-output-YXMTEX7Q.js} +2 -2
  282. package/dist/cli/chunks/{circuit-breaker-O4JNXAYH.js → circuit-breaker-EHA4N643.js} +2 -2
  283. package/dist/cli/chunks/{claude-flow-setup-J65U34NA.js → claude-flow-setup-E6G6SLYI.js} +2 -2
  284. package/dist/cli/chunks/client-N4FQ6SMD.js +2 -0
  285. package/dist/cli/chunks/{cline-installer-ZTG234Z2.js → cline-installer-6JPWD64G.js} +2 -2
  286. package/dist/cli/chunks/{code-5GWPY4IX.js → code-Q3U6XDOO.js} +2 -2
  287. package/dist/cli/chunks/{code-index-extractor-TWNKG4VS.js → code-index-extractor-BK2DC4MO.js} +2 -2
  288. package/dist/cli/chunks/{codex-installer-4TM4BLAE.js → codex-installer-DA3GBMLN.js} +2 -2
  289. package/dist/cli/chunks/{completions-BBNHQXMV.js → completions-TZ5F33TA.js} +2 -2
  290. package/dist/cli/chunks/{complexity-analyzer-2SCI2VGH.js → complexity-analyzer-N7U4V7ID.js} +2 -2
  291. package/dist/cli/chunks/{continuedev-installer-CTIORASU.js → continuedev-installer-DDDJGW26.js} +2 -2
  292. package/dist/cli/chunks/{copilot-installer-4R2V4IYB.js → copilot-installer-JVFCE6GT.js} +2 -2
  293. package/dist/cli/chunks/core-handlers-SFD5HCA3.js +2 -0
  294. package/dist/cli/chunks/{cost-tracker-KDBYQBKG.js → cost-tracker-ZTIDLUFW.js} +2 -2
  295. package/dist/cli/chunks/{coverage-QQJQVDPZ.js → coverage-6G7T7TRQ.js} +3 -3
  296. package/dist/cli/chunks/cross-domain-router-7HGRUNLT.js +2 -0
  297. package/dist/cli/chunks/{cursor-installer-5WEZCESZ.js → cursor-installer-JFNYGSDD.js} +2 -2
  298. package/dist/cli/chunks/{daemon-M4DKHEEA.js → daemon-5A4GD6XA.js} +3 -3
  299. package/dist/cli/chunks/{daemon-Y7H3ZUXQ.js → daemon-KTXGJJRI.js} +4 -4
  300. package/dist/cli/chunks/{dag-attention-scheduler-SD2UIADT.js → dag-attention-scheduler-4CUEQZD6.js} +2 -2
  301. package/dist/cli/chunks/{detect-WONWUXFH.js → detect-I32JUSUE.js} +2 -2
  302. package/dist/cli/chunks/{dist-node-Q5GQN2R6.js → dist-node-7ITNV6QS.js} +2 -2
  303. package/dist/cli/chunks/{domain-handler-EMXE2XQW.js → domain-handler-LIFCXSZ4.js} +2 -2
  304. package/dist/cli/chunks/{domain-transfer-QATUJJRP.js → domain-transfer-67UWLHSK.js} +2 -2
  305. package/dist/cli/chunks/dream-HPGD5TLD.js +2 -0
  306. package/dist/cli/chunks/{embed-and-insert-pattern-AAFHLBEJ.js → embed-and-insert-pattern-4WC5RUD6.js} +2 -2
  307. package/dist/cli/chunks/{eval-73BDNLSK.js → eval-DLS2UAQ2.js} +3 -3
  308. package/dist/cli/chunks/{experience-capture-middleware-YPAPVSYY.js → experience-capture-middleware-VG5E6OJA.js} +3 -3
  309. package/dist/cli/chunks/{fast-paths-33ZKMNYY.js → fast-paths-262IVHDN.js} +2 -2
  310. package/dist/cli/chunks/{feature-flags-QKO5YYDU.js → feature-flags-JJ3FHZGD.js} +2 -2
  311. package/dist/cli/chunks/{feature-flags-F3DVW4ST.js → feature-flags-L3K7DBN3.js} +2 -2
  312. package/dist/cli/chunks/{file-discovery-YYVZLRYD.js → file-discovery-Q3PBKVUW.js} +2 -2
  313. package/dist/cli/chunks/{fleet-EJX6BXLR.js → fleet-LQ5S2YHG.js} +3 -3
  314. package/dist/cli/chunks/{gnn-wrapper-TBNLYPTM.js → gnn-wrapper-I33Z537H.js} +2 -2
  315. package/dist/cli/chunks/{heartbeat-handler-HPRTS6SI.js → heartbeat-handler-RYIRAGZ7.js} +4 -4
  316. package/dist/cli/chunks/heartbeat-scheduler-O6TI5E4P.js +2 -0
  317. package/dist/cli/chunks/hnsw-adapter-TOVTN23J.js +2 -0
  318. package/dist/cli/chunks/hnsw-index-KCZ75V7K.js +2 -0
  319. package/dist/cli/chunks/{hnsw-legacy-bridge-Z6V6TOF5.js → hnsw-legacy-bridge-SSENBBPR.js} +2 -2
  320. package/dist/cli/chunks/{better-sqlite3-5G7LRX7Q.js → hnswlib-node-ILDTCGLZ.js} +2 -2
  321. package/dist/cli/chunks/{hooks-GG2Z3BDB.js → hooks-LR5KQMN5.js} +10 -10
  322. package/dist/cli/chunks/hybrid-router-4JEPC4JZ.js +2 -0
  323. package/dist/cli/chunks/{hypergraph-engine-X4Q2TTET.js → hypergraph-engine-NDZA2DKP.js} +2 -2
  324. package/dist/cli/chunks/{hypergraph-handler-6BZWV5PL.js → hypergraph-handler-ADMWVHBT.js} +3 -3
  325. package/dist/cli/chunks/impact-analyzer-3MHIU3SE.js +2 -0
  326. package/dist/cli/chunks/{init-handler-EKUS7U6L.js → init-handler-MGCYDX62.js} +6 -6
  327. package/dist/cli/chunks/init-wizard-ERBO5JNA.js +2 -0
  328. package/dist/cli/chunks/kernel-XJPIIWET.js +2 -0
  329. package/dist/cli/chunks/{kilocode-installer-BWAVVSQG.js → kilocode-installer-DQVWZUKP.js} +2 -2
  330. package/dist/cli/chunks/{kiro-installer-UADO53E5.js → kiro-installer-TINLYZ22.js} +2 -2
  331. package/dist/cli/chunks/knowledge-graph-NTJEG6ZE.js +2 -0
  332. package/dist/cli/chunks/{learning-HMUTCYQM.js → learning-KBT3S5WW.js} +3 -3
  333. package/dist/cli/chunks/{llm-router-453TBDUY.js → llm-router-2MX5LUAB.js} +4 -4
  334. package/dist/cli/chunks/llm-router-service-4T66BGB5.js +2 -0
  335. package/dist/cli/chunks/{load-DBBSNP6T.js → load-IQWTGMLZ.js} +2 -2
  336. package/dist/cli/chunks/load-test-PM674TSK.js +2 -0
  337. package/dist/cli/chunks/{mcp-PK3SAKRF.js → mcp-GCTTJUBZ.js} +2 -2
  338. package/dist/cli/chunks/{memory-63NHVBXS.js → memory-XQVPI4UT.js} +5 -5
  339. package/dist/cli/chunks/memory-backend-53NQ5CG7.js +2 -0
  340. package/dist/cli/chunks/{memory-handlers-YIKKORRY.js → memory-handlers-XD7MSFUN.js} +2 -2
  341. package/dist/cli/chunks/{multi-model-executor-HUGRXJ6D.js → multi-model-executor-JC63UCWG.js} +2 -2
  342. package/dist/cli/chunks/{opencode-installer-A6IXNF26.js → opencode-installer-6VJGEBIU.js} +2 -2
  343. package/dist/cli/chunks/{orchestrator-KDFYDNE3.js → orchestrator-B75QWJUF.js} +5 -5
  344. package/dist/cli/chunks/pattern-null-store-IF2RG2ON.js +2 -0
  345. package/dist/cli/chunks/{pipeline-HSPRKEYE.js → pipeline-TCBQ2UTZ.js} +2 -2
  346. package/dist/cli/chunks/{platform-X74IBN2H.js → platform-T43AYI3Z.js} +2 -2
  347. package/dist/cli/chunks/{plugin-KDJZ7VFD.js → plugin-MSI3ZU3Z.js} +2 -2
  348. package/dist/cli/chunks/{prime-radiant-advanced-wasm-2YZGKQE7.js → prime-radiant-advanced-wasm-V62CWI6M.js} +2 -2
  349. package/dist/cli/chunks/protocol-executor-7AS75ZWT.js +2 -0
  350. package/dist/cli/chunks/{protocol-handler-I2SDHC7B.js → protocol-handler-OH2INET2.js} +2 -2
  351. package/dist/cli/chunks/{prove-JQJDNIZH.js → prove-6PTMXMUL.js} +2 -2
  352. package/dist/cli/chunks/provider-manager-AU2C4AET.js +2 -0
  353. package/dist/cli/chunks/qe-reasoning-bank-WATQRCFO.js +2 -0
  354. package/dist/cli/chunks/{quality-2P7KHVY3.js → quality-PLNQN5GU.js} +2 -2
  355. package/dist/cli/chunks/queen-coordinator-IOCC4VQH.js +2 -0
  356. package/dist/cli/chunks/{real-embeddings-L7NMMNDO.js → real-embeddings-OW4OKR77.js} +2 -2
  357. package/dist/cli/chunks/{roocode-installer-LA4QN5AG.js → roocode-installer-C32LCYAJ.js} +2 -2
  358. package/dist/cli/chunks/router-SCJMX6WA.js +2 -0
  359. package/dist/cli/chunks/routing-feedback-RWC7F553.js +2 -0
  360. package/dist/cli/chunks/{routing-handler-B5CDEZF3.js → routing-handler-CKFXXPMI.js} +2 -2
  361. package/dist/cli/chunks/{ruvector-commands-SOVCRLJ6.js → ruvector-commands-GERRPTJL.js} +2 -2
  362. package/dist/cli/chunks/{rvf-dual-writer-M6WI2KFB.js → rvf-dual-writer-5FAB2QPA.js} +2 -2
  363. package/dist/cli/chunks/{rvf-migration-adapter-YDMZGPMA.js → rvf-migration-adapter-46COKWYB.js} +2 -2
  364. package/dist/cli/chunks/{rvf-migration-coordinator-TFGQ5EO4.js → rvf-migration-coordinator-AJVRWSNC.js} +2 -2
  365. package/dist/cli/chunks/rvf-native-adapter-W2RT6PTO.js +2 -0
  366. package/dist/cli/chunks/safe-db-HO2LCAO3.js +2 -0
  367. package/dist/cli/chunks/schedule-XENCR4MR.js +2 -0
  368. package/dist/cli/chunks/scheduler-WKZ3O2SS.js +2 -0
  369. package/dist/cli/chunks/{security-R3IXQXDA.js → security-Q622IVRB.js} +3 -3
  370. package/dist/cli/chunks/{shared-rvf-adapter-GZX7LSQZ.js → shared-rvf-adapter-EST24R3R.js} +2 -2
  371. package/dist/cli/chunks/{shared-rvf-dual-writer-YT7SJX7K.js → shared-rvf-dual-writer-CP6EXKBT.js} +2 -2
  372. package/dist/cli/chunks/sqlite-persistence-IN6BOSCX.js +2 -0
  373. package/dist/cli/chunks/{status-handler-7PZSPBHJ.js → status-handler-LLRQB4E2.js} +2 -2
  374. package/dist/cli/chunks/{structural-health-UMJS6IVR.js → structural-health-BUFWTNN2.js} +2 -2
  375. package/dist/cli/chunks/{sync-UIREA3UG.js → sync-JDG4SNT5.js} +2 -2
  376. package/dist/cli/chunks/{sync-HA5SLSBA.js → sync-RDL2RUOV.js} +2 -2
  377. package/dist/cli/chunks/{task-handler-NV4HGMEG.js → task-handler-KPP6ZXA6.js} +2 -2
  378. package/dist/cli/chunks/{task-handlers-RXYWWOSU.js → task-handlers-MRK2BQWI.js} +3 -3
  379. package/dist/cli/chunks/{test-2Y6OXGEU.js → test-7NYFTHRY.js} +4 -4
  380. package/dist/cli/chunks/{test-scheduling-N55VFOYT.js → test-scheduling-LGPKDMWD.js} +3 -3
  381. package/dist/cli/chunks/{token-bootstrap-FW3ZVMRP.js → token-bootstrap-H5JHB7TD.js} +2 -2
  382. package/dist/cli/chunks/{token-usage-YXKOB3U6.js → token-usage-TWPDS5U3.js} +2 -2
  383. package/dist/cli/chunks/{transformers-GBRSFAVA.js → transformers-GRNPPUHM.js} +2 -2
  384. package/dist/cli/chunks/{tree-sitter-wasm-parser-FJHMEHJS.js → tree-sitter-wasm-parser-DOH5F6TO.js} +2 -2
  385. package/dist/cli/chunks/{types-NVMRVSBH.js → types-NYV3YKE3.js} +2 -2
  386. package/dist/cli/chunks/unified-memory-6MXOYRXZ.js +2 -0
  387. package/dist/cli/chunks/unified-memory-hnsw-HY3JJD5Z.js +2 -0
  388. package/dist/cli/chunks/unified-persistence-LKQNQYRY.js +2 -0
  389. package/dist/cli/chunks/{upgrade-L2OTYHD3.js → upgrade-GDJMRYAT.js} +2 -2
  390. package/dist/cli/chunks/{validate-3NWRQYTP.js → validate-SIRFOPPM.js} +2 -2
  391. package/dist/cli/chunks/{validate-swarm-MDURRWXK.js → validate-swarm-XGMJYR6X.js} +2 -2
  392. package/dist/cli/chunks/{vibium-SZX7RB4H.js → vibium-NP6ENRKV.js} +2 -2
  393. package/dist/cli/chunks/visual-security-7TBWICHP.js +2 -0
  394. package/dist/cli/chunks/{web-tree-sitter-LGQT7JRD.js → web-tree-sitter-YDBWPYZD.js} +2 -2
  395. package/dist/cli/chunks/{windsurf-installer-EYYGHPPX.js → windsurf-installer-MFI6EAPH.js} +2 -2
  396. package/dist/cli/chunks/witness-chain-24SVOWQL.js +2 -0
  397. package/dist/cli/chunks/{witness-chain-YYYA2CU3.js → witness-chain-YHLBWQQ3.js} +2 -2
  398. package/dist/cli/chunks/{workflow-UD45FQAH.js → workflow-TA6RY7R5.js} +4 -4
  399. package/dist/cli/chunks/workflow-orchestrator-XBDXCTLY.js +2 -0
  400. package/dist/cli/chunks/{wrappers-JXD3KNSR.js → wrappers-DS77IK4H.js} +2 -2
  401. package/dist/cli/commands/eval.js +2 -2
  402. package/dist/mcp/bundle.js +1 -1
  403. package/package.json +2 -2
  404. package/dist/cli/chunks/adapter-AMIHQ243.js +0 -2
  405. package/dist/cli/chunks/aqe-learning-engine-LRG2UG6P.js +0 -2
  406. package/dist/cli/chunks/base-WDL3FANJ.js +0 -2
  407. package/dist/cli/chunks/browser-workflow-W7S4IKWD.js +0 -2
  408. package/dist/cli/chunks/chunk-434VUSZP.js +0 -2
  409. package/dist/cli/chunks/client-VJNNIAMG.js +0 -2
  410. package/dist/cli/chunks/core-handlers-MV5CAR7O.js +0 -2
  411. package/dist/cli/chunks/cross-domain-router-ULY4NIML.js +0 -2
  412. package/dist/cli/chunks/dream-PIGWXWE4.js +0 -2
  413. package/dist/cli/chunks/heartbeat-scheduler-5BBLZP6R.js +0 -2
  414. package/dist/cli/chunks/hnsw-adapter-FMEBL5T4.js +0 -2
  415. package/dist/cli/chunks/hnsw-index-K2R24V4Z.js +0 -2
  416. package/dist/cli/chunks/hybrid-router-LVF6N345.js +0 -2
  417. package/dist/cli/chunks/impact-analyzer-CCVVMGWE.js +0 -2
  418. package/dist/cli/chunks/init-wizard-KDPMO4G3.js +0 -2
  419. package/dist/cli/chunks/kernel-PBYNK5VA.js +0 -2
  420. package/dist/cli/chunks/knowledge-graph-C7LVHHLN.js +0 -2
  421. package/dist/cli/chunks/llm-router-service-LMTRJCPP.js +0 -2
  422. package/dist/cli/chunks/load-test-FHMZXTXD.js +0 -2
  423. package/dist/cli/chunks/memory-backend-UZHPCQTB.js +0 -2
  424. package/dist/cli/chunks/pattern-null-store-5PS4JN6V.js +0 -2
  425. package/dist/cli/chunks/protocol-executor-2GTGIOFD.js +0 -2
  426. package/dist/cli/chunks/provider-manager-VH6YTBB3.js +0 -2
  427. package/dist/cli/chunks/qe-reasoning-bank-47JSO76G.js +0 -2
  428. package/dist/cli/chunks/queen-coordinator-C7EDY7IS.js +0 -2
  429. package/dist/cli/chunks/router-7DVH66WB.js +0 -2
  430. package/dist/cli/chunks/routing-feedback-4I2MF235.js +0 -2
  431. package/dist/cli/chunks/rvf-native-adapter-UN3ESMMW.js +0 -2
  432. package/dist/cli/chunks/safe-db-Y2ZXKWBK.js +0 -2
  433. package/dist/cli/chunks/schedule-PG2NVRGA.js +0 -2
  434. package/dist/cli/chunks/scheduler-CNH6WWU2.js +0 -2
  435. package/dist/cli/chunks/sqlite-persistence-WWT4DRRP.js +0 -2
  436. package/dist/cli/chunks/unified-memory-PXEJKKMN.js +0 -2
  437. package/dist/cli/chunks/unified-memory-hnsw-M7OI5WUU.js +0 -2
  438. package/dist/cli/chunks/unified-persistence-WR4VDTAF.js +0 -2
  439. package/dist/cli/chunks/visual-security-CKSZZHKG.js +0 -2
  440. package/dist/cli/chunks/witness-chain-IOQX3XFG.js +0 -2
  441. package/dist/cli/chunks/workflow-orchestrator-Z2ZJRWIN.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");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.10.7");process.exit(0)}
2
2
  var l=class m{vertices=new Map;edges=new Map;adjacencyList=new Map;totalWeight=0;addVertex(e){if(this.vertices.has(e.id)){this.vertices.set(e.id,e);return}this.vertices.set(e.id,e),this.adjacencyList.set(e.id,[])}removeVertex(e){if(!this.vertices.has(e))return!1;let t=this.adjacencyList.get(e)||[];for(let r of t)this.removeEdge(e,r.neighborId);for(let[,r]of this.adjacencyList){let n=r.findIndex(i=>i.neighborId===e);n!==-1&&(this.totalWeight-=r[n].weight,r.splice(n,1))}return this.vertices.delete(e),this.adjacencyList.delete(e),!0}getVertex(e){return this.vertices.get(e)}hasVertex(e){return this.vertices.has(e)}getVertices(){return Array.from(this.vertices.values())}getVertexIds(){return Array.from(this.vertices.keys())}getVerticesByDomain(e){return this.getVertices().filter(t=>t.domain===e)}getVerticesByType(e){return this.getVertices().filter(t=>t.type===e)}addEdge(e){if(!this.vertices.has(e.source))throw new Error(`Source vertex ${e.source} does not exist`);if(!this.vertices.has(e.target))throw new Error(`Target vertex ${e.target} does not exist`);let t=this.edgeKey(e.source,e.target);if(this.edges.has(t)){let r=this.edges.get(t);this.totalWeight-=r.weight,this.removeFromAdjacency(e.source,e.target),r.bidirectional&&this.removeFromAdjacency(e.target,e.source)}this.edges.set(t,e),this.totalWeight+=e.weight,this.addToAdjacency(e.source,e.target,e.weight,e),e.bidirectional&&this.addToAdjacency(e.target,e.source,e.weight,e)}removeEdge(e,t){let r=this.edgeKey(e,t),n=this.edges.get(r);return n?(this.totalWeight-=n.weight,this.edges.delete(r),this.removeFromAdjacency(e,t),n.bidirectional&&this.removeFromAdjacency(t,e),!0):!1}getEdge(e,t){return this.edges.get(this.edgeKey(e,t))}hasEdge(e,t){return this.edges.has(this.edgeKey(e,t))}getEdges(){return Array.from(this.edges.values())}getEdgesForVertex(e){return(this.adjacencyList.get(e)||[]).map(r=>r.edge)}degree(e){return this.adjacencyList.get(e)?.length||0}weightedDegree(e){let t=this.adjacencyList.get(e);return t?t.reduce((r,n)=>r+n.weight,0):0}neighbors(e){return(this.adjacencyList.get(e)||[]).map(r=>({vertex:this.vertices.get(r.neighborId),weight:r.weight})).filter(r=>r.vertex!==void 0)}neighborIds(e){return(this.adjacencyList.get(e)||[]).map(r=>r.neighborId)}getStats(){let e=this.vertices.size,t=this.edges.size,r=0;for(let[,s]of this.adjacencyList)r+=s.length;let n=e>0?r/e:0,i=e>1?e*(e-1)/2:0,a=i>0?t/i:0,o=this.countConnectedComponents(),c=o===1&&e>0;return{vertexCount:e,edgeCount:t,totalWeight:this.totalWeight,averageDegree:n,density:a,isConnected:c,componentCount:o}}countConnectedComponents(){let e=new Set,t=0;for(let r of this.vertices.keys())e.has(r)||(this.dfs(r,e),t++);return t}dfs(e,t){t.add(e);let r=this.adjacencyList.get(e)||[];for(let n of r)t.has(n.neighborId)||this.dfs(n.neighborId,t)}isConnected(){if(this.vertices.size===0||this.vertices.size===1)return!0;let e=new Set,t=this.vertices.keys().next().value;return t===void 0?!0:(this.dfs(t,e),e.size===this.vertices.size)}getConnectedComponent(e){if(!this.vertices.has(e))return[];let t=new Set;return this.dfs(e,t),Array.from(t)}snapshot(){return{timestamp:new Date,vertices:this.getVertices(),edges:this.getEdges(),stats:this.getStats()}}clone(){let e=new m;for(let t of this.vertices.values())e.addVertex({...t});for(let t of this.edges.values())e.addEdge({...t});return e}static fromSnapshot(e){let t=new m;for(let r of e.vertices)t.addVertex(r);for(let r of e.edges)t.addEdge(r);return t}clear(){this.vertices.clear(),this.edges.clear(),this.adjacencyList.clear(),this.totalWeight=0}get vertexCount(){return this.vertices.size}get edgeCount(){return this.edges.size}isEmpty(){return this.vertices.size===0}edgeKey(e,t){return e<t?`${e}:${t}`:`${t}:${e}`}addToAdjacency(e,t,r,n){let i=this.adjacencyList.get(e);i&&(i.find(o=>o.neighborId===t)||i.push({neighborId:t,weight:r,edge:n}))}removeFromAdjacency(e,t){let r=this.adjacencyList.get(e);if(r){let n=r.findIndex(i=>i.neighborId===t);n!==-1&&r.splice(n,1)}}};function p(){return new l}var f=class{approxMinCut(e){let t=Date.now();if(e.isEmpty())return this.emptyResult(t,"weighted-degree");let r=e.getVertexIds(),n=1/0,i=null;for(let o of r){let c=e.weightedDegree(o);c<n&&(n=c,i=o)}if(i===null||r.length===1)return this.emptyResult(t,"weighted-degree");let a=e.getEdgesForVertex(i);return{value:n,sourceSide:[i],targetSide:r.filter(o=>o!==i),cutEdges:a,calculatedAt:new Date,algorithm:"weighted-degree",durationMs:Date.now()-t}}findWeakVertices(e,t){if(e.isEmpty())return[];let r=e.getVertices(),n=[],i=new Map,a=0;for(let g of r){let h=e.weightedDegree(g.id);i.set(g.id,h),a+=h}let o=a/r.length,c=0;for(let g of i.values())c+=(g-o)**2;let s=Math.sqrt(c/r.length),d=1/0;for(let g of i.values())g<d&&(d=g);let u=t??o-s;for(let g of r){let h=i.get(g.id);if(h<=u){let w=this.calculateRiskScore(h,o,s,d),y=this.determineWeakReason(g,h,o,e),v=this.generateStrengtheningActions(g,e,h);n.push({vertexId:g.id,vertex:g,weightedDegree:h,riskScore:w,reason:y,suggestions:v})}}return n.sort((g,h)=>h.riskScore-g.riskScore),n}getMinCutValue(e){if(e.isEmpty())return 0;let t=1/0;for(let r of e.getVertexIds()){let n=e.weightedDegree(r);n<t&&(t=n)}return t===1/0?0:t}isConnectivityCritical(e,t){return this.getMinCutValue(e)<t}getMinDegreeVertex(e){if(e.isEmpty())return null;let t=1/0,r=null;for(let n of e.getVertexIds()){let i=e.weightedDegree(n);i<t&&(t=i,r=n)}return r?{vertexId:r,degree:t}:null}getLocalMinCut(e,t){return e.hasVertex(t)?e.weightedDegree(t):0}findPartitioningPoints(e){if(e.isEmpty()||e.vertexCount<2)return[];let t=this.findArticulationPoints(e),r=[];for(let n of e.getVertices()){let i=this.getLocalMinCut(e,n.id);r.push({vertexId:n.id,localMinCut:i,wouldDisconnect:t.has(n.id)&&e.vertexCount>2})}return r.sort((n,i)=>n.localMinCut-i.localMinCut),r}findArticulationPoints(e){let t=new Map,r=new Map,n=new Map,i=new Set,a=0,o=e.getVertexIds();for(let s of o)t.set(s,-1),r.set(s,-1),n.set(s,null);let c=s=>{let d=0;t.set(s,a),r.set(s,a),a++;for(let u of e.neighborIds(s))t.get(u)===-1?(d++,n.set(u,s),c(u),r.set(s,Math.min(r.get(s),r.get(u))),n.get(s)===null&&d>1&&i.add(s),n.get(s)!==null&&r.get(u)>=t.get(s)&&i.add(s)):u!==n.get(s)&&r.set(s,Math.min(r.get(s),t.get(u)))};for(let s of o)t.get(s)===-1&&c(s);return i}suggestEdgeAdditions(e,t){let r=this.findWeakVertices(e),n=[],i=0,a=e.getVertices().map(o=>({vertex:o,degree:e.weightedDegree(o.id)})).sort((o,c)=>c.degree-o.degree);for(let o of r){if(i>=t)break;let c=new Set(e.neighborIds(o.vertexId));for(let{vertex:s}of a){if(s.id===o.vertexId||c.has(s.id))continue;let d={source:o.vertexId,target:s.id,weight:1,type:"coordination",bidirectional:!0};n.push(d),i+=1;break}}return n}emptyResult(e,t){return{value:0,sourceSide:[],targetSide:[],cutEdges:[],calculatedAt:new Date,algorithm:t,durationMs:Date.now()-e}}calculateRiskScore(e,t,r,n){if(r===0)return .5;let i=(t-e)/r,a=1/(1+Math.exp(-i)),o=n>0?n/e:1;return Math.min(1,a*o)}determineWeakReason(e,t,r,n){return t===0?"Isolated vertex with no connections":n.degree(e.id)===1?"Single connection point (leaf node)":t<r*.5?`Low connectivity (${(t/r*100).toFixed(0)}% of average)`:"Below average connectivity threshold"}generateStrengtheningActions(e,t,r){let n=[],i=new Set(t.neighborIds(e.id)),a=t.getStats().averageDegree,o=Math.max(a,3),c=Math.ceil(o-r),s=t.getVertices().filter(d=>d.id!==e.id&&!i.has(d.id)).sort((d,u)=>t.weightedDegree(u.id)-t.weightedDegree(d.id)).slice(0,c);for(let d of s)n.push({type:"add_edge",targetVertex:d.id,priority:"high",estimatedImprovement:1});return e.type==="agent"&&e.domain&&r<1&&n.push({type:"spawn_agent",domain:e.domain,priority:"critical",estimatedImprovement:2}),i.size>0&&i.size<3&&n.push({type:"increase_weight",weightDelta:.5,priority:"medium",estimatedImprovement:.5*i.size}),n}};function x(){return new f}export{l as a,p as b,f as c,x 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.10.6");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.10.7");process.exit(0)}
2
2
  var u={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:["claude-haiku-4-5-20251001","gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:["claude-sonnet-4-6","gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:["claude-sonnet-4-6"],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:["claude-opus-4-7","gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},d={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},y={budgetConfig:d,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",1:"claude-haiku-4-5-20251001",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}},r=class extends Error{constructor(e,t,l){super(e);this.code=t;this.cause=l;this.name="ModelRouterError"}code;cause},a=class extends r{constructor(e,t,l){super(e,"BUDGET_EXCEEDED");this.tier=t;this.usage=l;this.name="BudgetExceededError"}tier;usage},i=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},s=class extends r{constructor(e,t){super(e,"ROUTING_TIMEOUT");this.timeoutMs=t;this.name="RoutingTimeoutError"}timeoutMs};export{u as a,d as b,y as c,r as d,a as e,i as f,s as g};
@@ -1,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.10.6");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.10.7");process.exit(0)}
2
2
  function c(r,e,o){let n=new Error(r);return n.name="LLMError",n.code=e,n.provider=o?.provider,n.model=o?.model,n.retryable=o?.retryable??!1,n.retryAfterMs=o?.retryAfterMs,n.cause=o?.cause,n}function p(r){return r instanceof Error&&"code"in r&&typeof r.code=="string"}var a={"claude-sonnet-4-5":{canonical:"Claude Sonnet 4.5",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-5-20250929",openrouter:"anthropic/claude-sonnet-4.5",bedrock:"anthropic.claude-sonnet-4-5-v2:0"}},"claude-opus-4":{canonical:"Claude Opus 4",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-20250514",openrouter:"anthropic/claude-opus-4",bedrock:"anthropic.claude-opus-4-v1:0"}},"claude-opus-4-5":{canonical:"Claude Opus 4.5",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-5-20251101",openrouter:"anthropic/claude-opus-4.5",bedrock:"anthropic.claude-opus-4-5-v1:0"}},"claude-haiku-3-5":{canonical:"Claude Haiku 3.5",family:"claude",tier:"economy",providers:{anthropic:"claude-3-5-haiku-20241022",openrouter:"anthropic/claude-3.5-haiku",bedrock:"anthropic.claude-3-5-haiku-v1:0"}},"claude-sonnet-4":{canonical:"Claude Sonnet 4",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-20250514",openrouter:"anthropic/claude-sonnet-4",bedrock:"anthropic.claude-sonnet-4-v1:0"}},"claude-opus-4-7":{canonical:"Claude Opus 4.7",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"}},"claude-sonnet-4-6":{canonical:"Claude Sonnet 4.6",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"}},"claude-haiku-4-5":{canonical:"Claude Haiku 4.5",family:"claude",tier:"economy",providers:{anthropic:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"}},"gpt-4o":{canonical:"GPT-4o",family:"gpt",tier:"standard",providers:{openai:"gpt-4o",azure:"gpt-4o",openrouter:"openai/gpt-4o"}},"gpt-4o-mini":{canonical:"GPT-4o Mini",family:"gpt",tier:"economy",providers:{openai:"gpt-4o-mini",azure:"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"}},"gpt-4-turbo":{canonical:"GPT-4 Turbo",family:"gpt",tier:"premium",providers:{openai:"gpt-4-turbo",azure:"gpt-4-turbo",openrouter:"openai/gpt-4-turbo"}},"gpt-4":{canonical:"GPT-4",family:"gpt",tier:"premium",providers:{openai:"gpt-4",azure:"gpt-4",openrouter:"openai/gpt-4"}},o1:{canonical:"OpenAI o1",family:"gpt",tier:"flagship",providers:{openai:"o1",azure:"o1",openrouter:"openai/o1"}},"o1-mini":{canonical:"OpenAI o1 Mini",family:"gpt",tier:"standard",providers:{openai:"o1-mini",azure:"o1-mini",openrouter:"openai/o1-mini"}},"gemini-pro":{canonical:"Gemini Pro",family:"gemini",tier:"standard",providers:{gemini:"gemini-pro",openrouter:"google/gemini-pro"}},"gemini-pro-1.5":{canonical:"Gemini Pro 1.5",family:"gemini",tier:"standard",providers:{gemini:"gemini-1.5-pro",openrouter:"google/gemini-pro-1.5"}},"gemini-flash-1.5":{canonical:"Gemini Flash 1.5",family:"gemini",tier:"economy",providers:{gemini:"gemini-1.5-flash",openrouter:"google/gemini-flash-1.5"}},"gemini-ultra":{canonical:"Gemini Ultra",family:"gemini",tier:"flagship",providers:{gemini:"gemini-ultra",openrouter:"google/gemini-ultra"}},llama3:{canonical:"Llama 3",family:"llama",tier:"economy",providers:{ollama:"llama3",openrouter:"meta-llama/llama-3-8b-instruct"}},"llama3.1":{canonical:"Llama 3.1",family:"llama",tier:"economy",providers:{ollama:"llama3.1",openrouter:"meta-llama/llama-3.1-8b-instruct"}},codellama:{canonical:"CodeLlama",family:"llama",tier:"economy",providers:{ollama:"codellama",openrouter:"meta-llama/codellama-34b-instruct"}},mistral:{canonical:"Mistral",family:"mistral",tier:"economy",providers:{ollama:"mistral",openrouter:"mistralai/mistral-7b-instruct"}},mixtral:{canonical:"Mixtral",family:"mistral",tier:"standard",providers:{ollama:"mixtral",openrouter:"mistralai/mixtral-8x7b-instruct"}},phi3:{canonical:"Phi-3",family:"phi",tier:"economy",providers:{ollama:"phi3",azure:"phi-3-mini-128k-instruct"}},qwen2:{canonical:"Qwen 2",family:"qwen",tier:"economy",providers:{ollama:"qwen2",openrouter:"qwen/qwen-2-7b-instruct"}}};function l(){let r=new Map;for(let[e,o]of Object.entries(a)){r.set(e,e),r.set(e.toLowerCase(),e);for(let[n,t]of Object.entries(o.providers))t&&(r.set(t,e),r.set(t.toLowerCase(),e),r.set(`${n}/${t}`,e),r.set(`${n}/${t}`.toLowerCase(),e))}return r}var i=l();function m(r,e){let o=s(r),n=a[o];if(!n)throw new Error(`Unknown model: ${r}`);let t=n.providers[e];if(!t)throw new Error(`Model '${o}' (${n.canonical}) is not available on provider '${e}'`);return t}function s(r){let e=i.get(r);if(e||(e=i.get(r.toLowerCase()),e))return e;let o=[/^anthropic\//i,/^openai\//i,/^google\//i,/^meta-llama\//i,/^mistralai\//i,/^qwen\//i];for(let n of o){let t=r.replace(n,"");if(e=i.get(t),e||(e=i.get(t.toLowerCase()),e))return e}throw new Error(`Unknown model ID: ${r}`)}function d(r){try{let e=s(r);return a[e]}catch{return}}export{c as a,p as b,m as c,s as d,d as e};
@@ -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.10.6");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as z}from"./chunk-UQYDFT6I.js";import{b as S,d as $}from"./chunk-DFBVWMX3.js";import{a as N,c as F}from"./chunk-O4MNYX4X.js";import{i as v}from"./chunk-BHD6THT5.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(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.10.7");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as z}from"./chunk-4MJQJQLY.js";import{b as S,d as $}from"./chunk-QBVFONWU.js";import{a as N,c as F}from"./chunk-XWPUCPYW.js";import{i as v}from"./chunk-6OLPKIYU.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(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(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");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.10.7");process.exit(0)}
2
2
  import{existsSync as c,readFileSync as f}from"fs";import{join as p,dirname as i}from"path";import{fileURLToPath as s}from"url";function u(o,a=10){let t=i(s(o));for(let r=0;r<a;r++){let n=p(t,"package.json");if(c(n))try{if(JSON.parse(f(n,"utf-8")).name==="agentic-qe")return t}catch{}let e=i(t);if(e===t)break;t=e}return null}export{u as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-UNDPB5SS.js";var g={};o(g,{DotProductAttention:()=>u,FlashAttention:()=>m,HyperbolicAttention:()=>h,LinearAttention:()=>f,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>r,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>d,pipeline:()=>L});import{createRequire as n}from"module";var i,e,r,a,c,l,s,p,d,m,u,A,h,f,_,b,L,q=t(()=>{i=n(import.meta.url),e=i("hnswlib-node"),r=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:d,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:A,HyperbolicAttention:h,LinearAttention:f,MoEAttention:_,SonaEngine:b,pipeline:L}=e||{}});export{r as a,a as b,c,l as d,s as e,p as f,d as g,m as h,u as i,A as j,h as k,f as l,_ as m,b as n,L as o,g as p,q};
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.10.7");process.exit(0)}
2
+ import{c as t,e as o}from"./chunk-LRRQEAP5.js";var g={};o(g,{DotProductAttention:()=>u,FlashAttention:()=>m,HyperbolicAttention:()=>h,LinearAttention:()=>f,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>r,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>d,pipeline:()=>L});import{createRequire as n}from"module";var i,e,r,a,c,l,s,p,d,m,u,A,h,f,_,b,L,q=t(()=>{i=n(import.meta.url),e=i("hnswlib-node"),r=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:d,FlashAttention:m,DotProductAttention:u,MultiHeadAttention:A,HyperbolicAttention:h,LinearAttention:f,MoEAttention:_,SonaEngine:b,pipeline:L}=e||{}});export{r as a,a as b,c,l as d,s as e,p as f,d as g,m as h,u as i,A as j,h as k,f as l,_ as m,b as n,L as o,g as p,q};
@@ -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.10.6");process.exit(0)}
2
- import{b as pe}from"./chunk-GXNNKM7F.js";import{a as gt}from"./chunk-RTFFD263.js";import{a as dt,b as mt}from"./chunk-M4OYZMXE.js";import{a as lt,b as ut}from"./chunk-Z3RPA3RD.js";import{j as I}from"./chunk-NKEGEQ3J.js";import{a as nt}from"./chunk-VQM2TC2V.js";import{a as st,b as ot,c as ct}from"./chunk-DAUQIXHW.js";import{b as at}from"./chunk-ULEVKOWQ.js";import{a as ge}from"./chunk-LEDF3LGZ.js";import{i as w,m as me}from"./chunk-RA7HEY5G.js";import{a as sn}from"./chunk-434VUSZP.js";import{c as it}from"./chunk-F72A356B.js";import{b as M,d as rt}from"./chunk-DFBVWMX3.js";import{a as T,b as C,c as f}from"./chunk-K32AUACO.js";import{a as p,b as tt,c as k}from"./chunk-O4MNYX4X.js";import{i as y}from"./chunk-BHD6THT5.js";import{R as on,S as cn}from"./chunk-Q4LYWIEX.js";import{c as z,e as an,g as et}from"./chunk-UNDPB5SS.js";function ft(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(dn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):mn.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>gn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var vt={};an(vt,{NeuralTinyDancerRouter:()=>q,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(s){return new q(s)}var hn,fn,yn,Tn,vn,Cn,bn,kn,q,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},q=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Tt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Cn[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=Tt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=kn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),h=this.argmax(m),b=1-m[u];this.calibrationScores.push(b),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as bt}from"perf_hooks";function kt(s){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(s)}var F,ve=z(()=>{"use strict";yt();F=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},G=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(s){return new G(s)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=y();return this.memory.getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
2
+ import{b as pe}from"./chunk-3XEL7XCA.js";import{a as gt}from"./chunk-EWNJK2BU.js";import{a as dt,b as mt}from"./chunk-J5ETX2DG.js";import{a as lt,b as ut}from"./chunk-3W6QASVB.js";import{j as I}from"./chunk-262F3EMN.js";import{a as nt}from"./chunk-R7KIC6TL.js";import{a as st,b as ot,c as ct}from"./chunk-FQBNPSV2.js";import{b as at}from"./chunk-K6IU2MV4.js";import{a as ge}from"./chunk-6F5KPT6U.js";import{i as w,m as me}from"./chunk-HBWAMCVB.js";import{a as sn}from"./chunk-DF7V6X3N.js";import{c as it}from"./chunk-222ZQTL5.js";import{b as M,d as rt}from"./chunk-QBVFONWU.js";import{a as T,b as C,c as f}from"./chunk-2MLISLRR.js";import{a as p,b as tt,c as k}from"./chunk-XWPUCPYW.js";import{i as y}from"./chunk-6OLPKIYU.js";import{R as on,S as cn}from"./chunk-76JYG426.js";import{c as z,e as an,g as et}from"./chunk-LRRQEAP5.js";function ft(s){let e=[],t=0;if(s.fileCount!==void 0&&(s.fileCount>20?(t+=25,e.push({name:"very-high-file-count",weight:25,description:`Task involves ${s.fileCount} files (>20)`})):s.fileCount>10?(t+=20,e.push({name:"high-file-count",weight:20,description:`Task involves ${s.fileCount} files (>10)`})):s.fileCount>5&&(t+=10,e.push({name:"moderate-file-count",weight:10,description:`Task involves ${s.fileCount} files (>5)`}))),s.domain&&(dn.includes(s.domain)?(t+=30,e.push({name:"complex-domain",weight:30,description:`Domain '${s.domain}' requires complex reasoning`})):mn.includes(s.domain)&&(t+=15,e.push({name:"moderate-domain",weight:15,description:`Domain '${s.domain}' has moderate complexity`}))),s.crossComponent&&(t+=25,e.push({name:"cross-component",weight:25,description:"Task spans multiple components/modules"})),s.priority==="critical"?(t+=25,e.push({name:"critical-priority",weight:25,description:"Critical priority requires careful attention"})):s.priority==="high"&&(t+=15,e.push({name:"high-priority",weight:15,description:"High priority task"})),s.requiredCapabilities){let r=s.requiredCapabilities.filter(a=>gn.includes(a)).length;if(r>0){let a=Math.min(20,r*10);t+=a,e.push({name:"complex-capabilities",weight:a,description:`Requires ${r} complex capabilit${r===1?"y":"ies"}`})}}s.requiresExternalApis&&(t+=10,e.push({name:"external-apis",weight:10,description:"Requires external API integration"})),s.involvesDatabaseOps&&(t+=10,e.push({name:"database-ops",weight:10,description:"Involves database operations"})),s.timeSensitive&&(t+=5,e.push({name:"time-sensitive",weight:5,description:"Time-sensitive task"})),s.estimatedLinesAffected!==void 0&&(s.estimatedLinesAffected>500?(t+=15,e.push({name:"large-change",weight:15,description:`Estimated ${s.estimatedLinesAffected} lines affected (>500)`})):s.estimatedLinesAffected>200&&(t+=10,e.push({name:"medium-change",weight:10,description:`Estimated ${s.estimatedLinesAffected} lines affected (>200)`}))),(s.type==="security-scan"||s.type==="vulnerability-assessment")&&(t+=20,e.push({name:"security-task",weight:20,description:"Security-related task requires careful analysis"}));let n=t>=S.critical?"critical":t>=S.complex?"complex":t>=S.moderate?"moderate":"simple",i=pn[n];return{complexity:n,recommendedModel:i,factors:e,score:t,timestamp:new Date}}var dn,mn,gn,S,pn,yt=z(()=>{"use strict";dn=["security-compliance","chaos-resilience","defect-intelligence"],mn=["code-intelligence","contract-testing","quality-assessment","learning-optimization"],gn=["sast","dast","vulnerability","owasp","chaos-testing","resilience","fault-injection","mutation-testing"],S={critical:70,complex:45,moderate:20},pn={critical:"opus",complex:"sonnet",moderate:"sonnet",simple:"haiku"}});var R,Te=z(()=>{"use strict";R=class{weightsInputHidden;weightsHiddenOutput;biasHidden;biasOutput;learningRate;constructor(e=.01){this.learningRate=e,this.weightsInputHidden=this.xavierInit(4,32),this.weightsHiddenOutput=this.xavierInit(32,3),this.biasHidden=new Float32Array(32),this.biasOutput=new Float32Array(3)}xavierInit(e,t){let n=Math.sqrt(2/(e+t)),i=new Float32Array(e*t);for(let r=0;r<i.length;r++){let a=Math.random(),o=Math.random(),l=Math.sqrt(-2*Math.log(Math.max(a,1e-10)))*Math.cos(2*Math.PI*o);i[r]=l*n}return i}forward(e){if(e.length!==4)throw new Error(`Expected 4 features, got ${e.length}`);let t=new Float32Array(32);for(let i=0;i<32;i++){let r=this.biasHidden[i];for(let a=0;a<4;a++)r+=e[a]*this.weightsInputHidden[a*32+i];t[i]=Math.max(0,r)}let n=new Float32Array(3);for(let i=0;i<3;i++){let r=this.biasOutput[i];for(let a=0;a<32;a++)r+=t[a]*this.weightsHiddenOutput[a*3+i];n[i]=r}return this.softmax(n)}softmax(e){let t=Math.max(...e),n=new Float32Array(e.length),i=0;for(let a=0;a<e.length;a++)n[a]=Math.exp(e[a]-t),i+=n[a];let r=[];for(let a=0;a<e.length;a++)r.push(n[a]/i);return r}updateWeights(e,t,n){let i=new Float32Array(32);for(let c=0;c<32;c++){let u=this.biasHidden[c];for(let d=0;d<4;d++)u+=e[d]*this.weightsInputHidden[d*32+c];i[c]=Math.max(0,u)}let r=new Float32Array(3);for(let c=0;c<3;c++){let u=this.biasOutput[c];for(let d=0;d<32;d++)u+=i[d]*this.weightsHiddenOutput[d*3+c];r[c]=u}let a=this.softmax(r),o=new Float32Array(3);for(let c=0;c<3;c++)o[c]=(c===t?1:0)-a[c],o[c]*=n*this.learningRate;for(let c=0;c<32;c++)for(let u=0;u<3;u++)this.weightsHiddenOutput[c*3+u]+=i[c]*o[u];for(let c=0;c<3;c++)this.biasOutput[c]+=o[c];let l=new Float32Array(32);for(let c=0;c<32;c++){if(i[c]<=0)continue;let u=0;for(let d=0;d<3;d++)u+=o[d]*this.weightsHiddenOutput[c*3+d];l[c]=u}for(let c=0;c<4;c++)for(let u=0;u<32;u++)this.weightsInputHidden[c*32+u]+=e[c]*l[u];for(let c=0;c<32;c++)this.biasHidden[c]+=l[c]}serialize(){return{weightsInputHidden:Array.from(this.weightsInputHidden),weightsHiddenOutput:Array.from(this.weightsHiddenOutput),biasHidden:Array.from(this.biasHidden),biasOutput:Array.from(this.biasOutput)}}deserialize(e){e.weightsInputHidden.length===128&&(this.weightsInputHidden=new Float32Array(e.weightsInputHidden)),e.weightsHiddenOutput.length===96&&(this.weightsHiddenOutput=new Float32Array(e.weightsHiddenOutput)),e.biasHidden.length===32&&(this.biasHidden=new Float32Array(e.biasHidden)),e.biasOutput.length===3&&(this.biasOutput=new Float32Array(e.biasOutput))}}});var vt={};an(vt,{NeuralTinyDancerRouter:()=>q,SimpleNeuralRouter:()=>R,createNeuralTinyDancerRouter:()=>Sn});import{performance as Tt}from"perf_hooks";function Sn(s){return new q(s)}var hn,fn,yn,Tn,vn,Cn,bn,kn,q,Ct=z(()=>{"use strict";ve();Te();Te();hn=1e3,fn=.1,yn=.2,Tn=50,vn=.01,Cn=["haiku","sonnet","opus"],bn={haiku:0,sonnet:1,opus:2},kn={"test-generation":.1,"test-execution":.15,"coverage-analysis":.2,"quality-assessment":.3,"requirements-validation":.35,"code-intelligence":.4,"contract-testing":.45,"visual-accessibility":.5,"learning-optimization":.55,"defect-intelligence":.7,"chaos-resilience":.8,"security-compliance":.9},q=class{ruleRouter;neuralNet;circuitBreakerThreshold;shadowModeDecisionLimit;shadowModeMaxDisagreement;shadowModeActive;shadowDecisions=[];shadowDisagreements=0;circuitBreakerTripped=!1;recentOutcomes=[];totalNeuralDecisions=0;totalWeightUpdates=0;neuralPrimary=!1;calibrationScores=[];maxCalibrationScores=500;domainSuccessRates=new Map;config;nativeRouterAvailable=!1;constructor(e={}){this.config=e,this.ruleRouter=new F(e),this.neuralNet=new R(e.learningRate??vn),this.circuitBreakerThreshold=e.circuitBreakerThreshold??yn,this.shadowModeDecisionLimit=e.shadowModeDecisions??hn,this.shadowModeMaxDisagreement=e.shadowModeMaxDisagreement??fn,e.forceShadowMode!==void 0?(this.shadowModeActive=e.forceShadowMode,this.neuralPrimary=!e.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1),this.tryLoadNativeRouter()}tryLoadNativeRouter(){this.nativeRouterAvailable=!1}async route(e){let t=Tt.now(),n=await this.ruleRouter.route(e);if(this.circuitBreakerTripped)return n;let i=this.extractFeatures(e,n.classification),r;try{r=this.neuralNet.forward(i)}catch{return this.tripCircuitBreaker(),n}let a=this.argmax(r),o=Cn[a],l=r[a];if(this.totalNeuralDecisions++,this.shadowModeActive){let m=n.model===o;return m||this.shadowDisagreements++,this.shadowDecisions.push({taskDescription:e.description.slice(0,100),ruleDecision:n.model,neuralDecision:o,agreed:m,neuralConfidence:l,timestamp:new Date}),this.evaluateShadowModeExit(),n}let c=Tt.now()-t,u=this.computeEmpiricalConfidenceBounds(r);return l<.3||u.calibrationScore>.8?n:{model:o,confidence:l,uncertainty:1-l,triggerMultiModel:n.triggerMultiModel,triggerHumanReview:n.triggerHumanReview,complexity:n.complexity,classification:n.classification,latencyMs:c,reasoning:this.buildNeuralReasoning(o,l,r,n,u)}}extractFeatures(e,t){let n=Math.min(1,t.score/100),i=e.description.length,r=e.context?.code?.length??0,a=(i+r)/4,o=Math.min(1,a/1e4),l=e.domain??"",c=kn[l]??.25,u=this.domainSuccessRates.get(l),d=u?u.success/Math.max(1,u.total):.7;return[n,o,c,d]}recordNeuralOutcome(e,t,n,i=n?1:0,r=t.model,a=0){this.ruleRouter.recordOutcome(e,t,n,i,r,a);let o=e.domain??"unknown",l=this.domainSuccessRates.get(o)??{success:0,total:0};l.total++,n&&l.success++,this.domainSuccessRates.set(o,l),this.recentOutcomes.push(n),this.recentOutcomes.length>Tn&&this.recentOutcomes.shift(),this.checkCircuitBreaker();let c=this.extractFeatures(e,t.classification),u=bn[r],d=(i-.5)*2;try{this.neuralNet.updateWeights(c,u,d),this.totalWeightUpdates++}catch{}let m=this.neuralNet.forward(c),h=this.argmax(m),b=1-m[u];this.calibrationScores.push(b),this.calibrationScores.length>this.maxCalibrationScores&&this.calibrationScores.shift()}computeEmpiricalConfidenceBounds(e){let n=Math.max(...e),i=1-n;if(this.calibrationScores.length<10)return{lower:0,upper:1,coverageLevel:.9,calibrationScore:i};let r=[...this.calibrationScores].sort((l,c)=>l-c),a=Math.ceil(.9*r.length)-1,o=r[Math.min(a,r.length-1)];return{lower:Math.max(0,n-o),upper:Math.min(1,n+o),coverageLevel:.9,calibrationScore:i}}computeConformalBounds(e){return this.computeEmpiricalConfidenceBounds(e)}evaluateShadowModeExit(){if(!this.shadowModeActive||this.config.forceShadowMode===!0)return;let e=this.shadowDecisions.length;if(e<this.shadowModeDecisionLimit)return;this.shadowDisagreements/e<=this.shadowModeMaxDisagreement&&(this.shadowModeActive=!1,this.neuralPrimary=!0)}checkCircuitBreaker(){if(this.recentOutcomes.length<10)return;let t=this.recentOutcomes.filter(n=>!n).length/this.recentOutcomes.length;t>this.circuitBreakerThreshold?this.tripCircuitBreaker():this.circuitBreakerTripped&&t<this.circuitBreakerThreshold*.5&&(this.circuitBreakerTripped=!1)}tripCircuitBreaker(){this.circuitBreakerTripped=!0,this.neuralPrimary=!1}buildNeuralReasoning(e,t,n,i,r){let a=[];return a.push(`[Neural] Routing to ${e.toUpperCase()}`),a.push(`with ${(t*100).toFixed(0)}% neural confidence.`),a.push(`Tier probabilities: haiku=${(n[0]*100).toFixed(0)}%,`),a.push(`sonnet=${(n[1]*100).toFixed(0)}%,`),a.push(`opus=${(n[2]*100).toFixed(0)}%.`),e!==i.model&&a.push(`Rule-based would choose ${i.model.toUpperCase()}.`),a.push(`Empirical bounds: [${r.lower.toFixed(2)}, ${r.upper.toFixed(2)}]`),a.push(`at ${(r.coverageLevel*100).toFixed(0)}% coverage.`),a.join(" ")}argmax(e){let t=0,n=e[0];for(let i=1;i<e.length;i++)e[i]>n&&(n=e[i],t=i);return t}getNeuralStats(){let e=this.shadowDecisions.length,t=e>0?this.shadowDisagreements/e:0,n=this.recentOutcomes.filter(r=>!r).length,i=this.recentOutcomes.length>0?n/this.recentOutcomes.length:0;return{shadowModeActive:this.shadowModeActive,shadowDecisions:e,disagreementRate:t,circuitBreakerTripped:this.circuitBreakerTripped,recentErrorRate:i,totalNeuralDecisions:this.totalNeuralDecisions,totalWeightUpdates:this.totalWeightUpdates,neuralPrimary:this.neuralPrimary}}getShadowDecisionLogs(){return this.shadowDecisions}getRuleRouter(){return this.ruleRouter}getNeuralNet(){return this.neuralNet}isNativeRouterAvailable(){return this.nativeRouterAvailable}isShadowModeActive(){return this.shadowModeActive}isNeuralPrimary(){return this.neuralPrimary}isCircuitBreakerTripped(){return this.circuitBreakerTripped}resetCircuitBreaker(){this.circuitBreakerTripped=!1,this.recentOutcomes=[]}getStats(){return this.ruleRouter.getStats()}getConfig(){return this.ruleRouter.getConfig()}reset(){this.ruleRouter.reset(),this.shadowDecisions=[],this.shadowDisagreements=0,this.circuitBreakerTripped=!1,this.recentOutcomes=[],this.totalNeuralDecisions=0,this.totalWeightUpdates=0,this.calibrationScores=[],this.domainSuccessRates.clear(),this.config.forceShadowMode!==void 0?(this.shadowModeActive=this.config.forceShadowMode,this.neuralPrimary=!this.config.forceShadowMode):(this.shadowModeActive=!0,this.neuralPrimary=!1)}}});import{performance as bt}from"perf_hooks";function kt(s){try{let{getRuVectorFeatureFlags:e}=(cn(),et(on));if(e().useNeuralRouting){let{NeuralTinyDancerRouter:n}=(Ct(),et(vt));return new n(s)}}catch(e){process.env.DEBUG&&console.debug("[Router] Neural router unavailable, using rule-based:",e instanceof Error?e.message:e)}return new F(s)}var F,ve=z(()=>{"use strict";yt();F=class{confidenceThreshold;uncertaintyThreshold;securityConfidenceThreshold;enableLearning;verbose;executor;totalRouted=0;routesByModel={haiku:0,sonnet:0,opus:0};routesByComplexity={simple:0,moderate:0,complex:0,critical:0};multiModelTriggers=0;humanReviewTriggers=0;advisorConsultations=0;totalConfidence=0;totalLatencyMs=0;outcomes=[];maxOutcomes=1e3;constructor(e={}){this.confidenceThreshold=e.confidenceThreshold??.8,this.uncertaintyThreshold=e.uncertaintyThreshold??.2,this.securityConfidenceThreshold=e.securityConfidenceThreshold??.85,this.enableLearning=e.enableLearning??!0,this.verbose=e.verbose??!1,this.executor=e.executor}hasExecutor(){return this.executor!==void 0}async routeWithAdvisor(e,t){let n=await this.route(e);if(!n.triggerMultiModel||!this.executor||!t)return{route:n};let i=await this.executor.consult(t,{agentName:e.agentId??e.id??"unknown",triggerReason:`tiny_dancer.confidence=${n.confidence.toFixed(2)}<${this.confidenceThreshold}`});return this.advisorConsultations++,{route:n,advisor:i}}async route(e){let t=bt.now(),n=ft(e),i=this.calculateConfidence(n),r=1-i,a=this.isSecurityTask(e),o=a&&i<this.securityConfidenceThreshold||i<this.confidenceThreshold&&n.complexity!=="simple",l=r>this.uncertaintyThreshold||a&&n.complexity==="critical",c=bt.now()-t,u=this.buildReasoning(n,i,a,o,l),d={model:n.recommendedModel,confidence:i,uncertainty:r,triggerMultiModel:o,triggerHumanReview:l,complexity:n.complexity,classification:n,latencyMs:c,reasoning:u};return this.updateStats(d),this.verbose&&console.log(`[TinyDancer] Route: ${n.recommendedModel} (complexity=${n.complexity}, confidence=${(i*100).toFixed(1)}%)`),d}calculateConfidence(e){let{score:t,complexity:n}=e;if(n==="simple"&&t<10)return .9;if(n==="critical"&&t>85)return .92;let i=[S.moderate,S.complex,S.critical],r=1/0;for(let d of i){let m=Math.abs(t-d);m<r&&(r=m)}let a=.55,o=.35,l=Math.min(r/25,1),c=a+l*o,u=n!=="simple"?Math.min(.05,e.factors.length*.01):0;return Math.min(.95,c+u)}isSecurityTask(e){let t=e;if(t.type==="security-scan"||t.type==="vulnerability-assessment"||e.domain==="security-compliance")return!0;let n=["sast","dast","vulnerability","owasp","security-scanning"];if(e.requiredCapabilities?.some(a=>n.includes(a)))return!0;let i=["security","vulnerability","cve","owasp","exploit","injection"],r=e.description.toLowerCase();return!!i.some(a=>r.includes(a))}buildReasoning(e,t,n,i,r){let a=[];if(a.push(`Routing to ${e.recommendedModel.toUpperCase()}`),a.push(`(complexity: ${e.complexity}, score: ${e.score})`),a.push(`with ${(t*100).toFixed(0)}% confidence.`),e.factors.length>0){let o=e.factors.slice(0,3).map(l=>l.name).join(", ");a.push(`Key factors: ${o}.`)}return n&&a.push("Security-sensitive task detected."),i&&a.push("Multi-model verification recommended due to uncertainty."),r&&a.push("Human review flagged due to high uncertainty or criticality."),a.join(" ")}updateStats(e){this.totalRouted++,this.routesByModel[e.model]++,this.routesByComplexity[e.complexity]++,this.totalConfidence+=e.confidence,this.totalLatencyMs+=e.latencyMs,e.triggerMultiModel&&this.multiModelTriggers++,e.triggerHumanReview&&this.humanReviewTriggers++}recordOutcome(e,t,n,i=n?1:0,r=t.model,a=0){if(!this.enableLearning)return;let o={task:e,routeResult:t,success:n,qualityScore:i,actualModelUsed:r,durationMs:a,timestamp:new Date};this.outcomes.push(o),this.outcomes.length>this.maxOutcomes&&this.outcomes.shift(),this.verbose&&console.log(`[TinyDancer] Recorded outcome: success=${n}, quality=${(i*100).toFixed(0)}%, model=${r}`)}getStats(){return{totalRouted:this.totalRouted,routesByModel:{...this.routesByModel},routesByComplexity:{...this.routesByComplexity},multiModelTriggers:this.multiModelTriggers,advisorConsultations:this.advisorConsultations,humanReviewTriggers:this.humanReviewTriggers,avgConfidence:this.totalRouted>0?this.totalConfidence/this.totalRouted:0,avgLatencyMs:this.totalRouted>0?this.totalLatencyMs/this.totalRouted:0,outcomesRecorded:this.outcomes.length}}getOutcomes(){return this.outcomes}getSuccessRateByModel(){let e={haiku:{success:0,total:0},sonnet:{success:0,total:0},opus:{success:0,total:0}};for(let t of this.outcomes){let n=t.actualModelUsed;e[n].total++,t.success&&e[n].success++}return{haiku:e.haiku.total>0?e.haiku.success/e.haiku.total:0,sonnet:e.sonnet.total>0?e.sonnet.success/e.sonnet.total:0,opus:e.opus.total>0?e.opus.success/e.opus.total:0}}reset(){this.totalRouted=0,this.routesByModel={haiku:0,sonnet:0,opus:0},this.routesByComplexity={simple:0,moderate:0,complex:0,critical:0},this.multiModelTriggers=0,this.advisorConsultations=0,this.humanReviewTriggers=0,this.totalConfidence=0,this.totalLatencyMs=0,this.outcomes=[]}getConfig(){return{confidenceThreshold:this.confidenceThreshold,uncertaintyThreshold:this.uncertaintyThreshold,securityConfidenceThreshold:this.securityConfidenceThreshold,enableLearning:this.enableLearning,verbose:this.verbose}}}});var ln={enableConsoleLog:!0,maxEntries:1e3,logPrefix:"[TASK]"},G=class{entries=[];config;constructor(e={}){this.config={...ln,...e}}log(e,t,n){let i={timestamp:new Date,operation:e,taskId:t,agentId:n?.agentId,domain:n?.domain,details:n?.details};if(this.entries.push(i),this.entries.length>this.config.maxEntries&&this.entries.splice(0,this.entries.length-this.config.maxEntries),this.config.enableConsoleLog){let r=n?.agentId?` by ${n.agentId}`:"",a=n?.domain?` (${n.domain})`:"";console.log(`${this.config.logPrefix} ${e.toUpperCase()} ${t}${r}${a}`)}}logSubmit(e,t){this.log("submit",e,{details:t})}logAssign(e,t,n){this.log("assign",e,{agentId:t,domain:n})}logReassign(e,t,n,i){this.log("reassign",e,{agentId:n,domain:i,details:{fromAgent:t}})}logComplete(e,t){this.log("complete",e,{agentId:t})}logFail(e,t,n){this.log("fail",e,{agentId:t,details:n?{error:n}:void 0})}logCancel(e){this.log("cancel",e)}logSteal(e,t,n){this.log("steal",e,{domain:n,details:{fromDomain:t}})}logQueue(e,t){this.log("queue",e,{details:{position:t}})}logDequeue(e){this.log("dequeue",e)}getEntries(e){let t=[...this.entries];e&&(e.operation&&(t=t.filter(i=>i.operation===e.operation)),e.taskId&&(t=t.filter(i=>i.taskId===e.taskId)),e.agentId&&(t=t.filter(i=>i.agentId===e.agentId)),e.domain&&(t=t.filter(i=>i.domain===e.domain)),e.fromTimestamp&&(t=t.filter(i=>i.timestamp>=e.fromTimestamp)),e.toTimestamp&&(t=t.filter(i=>i.timestamp<=e.toTimestamp)));let n=e?.limit??t.length;return t.slice(-n)}getStatistics(){let e={submit:0,assign:0,reassign:0,complete:0,fail:0,cancel:0,steal:0,queue:0,dequeue:0},t=new Set,n=new Set;for(let i of this.entries)e[i.operation]++,t.add(i.taskId),i.agentId&&n.add(i.agentId);return{totalEntries:this.entries.length,operationCounts:e,taskCount:t.size,agentCount:n.size}}clear(){this.entries.length=0}};function he(s){return new G(s)}me();rt();var fe=class{memory;initialized=!1;constructor(e){this.memory=e??w()}async initialize(){this.initialized||(this.memory.isInitialized()||await this.memory.initialize(),this.initialized=!0)}async saveSnapshot(e){this.ensureInitialized();let t=y();return this.memory.getDatabase().prepare(`
3
3
  INSERT INTO mincut_snapshots (
4
4
  id, timestamp, vertex_count, edge_count, total_weight,
5
5
  is_connected, component_count, vertices_json, edges_json
@@ -177,4 +177,4 @@ import{b as pe}from"./chunk-GXNNKM7F.js";import{a as gt}from"./chunk-RTFFD263.js
177
177
  `;let i=this.getRecommendations(n);if(i.length>0){t+=`**Recommendations:**
178
178
  `;for(let r of i)t+=`- ${r}
179
179
  `;t+=`
180
- `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await pe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},Ge=null;function qt(s){return Ge||(Ge=new qe(s)),Ge}function jt(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await si(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await oi(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await ci(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await li(s,a)});return t.push(r),t}async function si(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function oi(s,e){let{taskId:t,result:n}=e.payload,i=s.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;s.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(r),s.auditLogger.logComplete(t,i.assignedAgents[0]);try{let a=qt(),o=i.assignedAgents[0];o&&await a.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(a){console.warn("[QueenCoordinator] Cross-phase hook error:",a)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(a){console.warn("[QueenCoordinator] Governance tracking error:",a)}if(s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),s.traceCollector){let a=s.taskTraceContexts.get(t);a&&(s.traceCollector.completeSpan(a.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let a=typeof n=="object"&&n!==null?n:null;if(a===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(a,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:a,metrics:o,duration:r,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(a){console.warn("[QueenCoordinator] Pattern training setup error:",a)}}await s.processQueue()}async function ci(s,e){let{taskId:t,error:n}=e.payload,i=s.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let r=s.taskTraceContexts.get(t);r&&(s.traceCollector.failSpan(r.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}if(i.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};s.tasks.set(t,r),s.enqueueTask(i.task)}else{s.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(s.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",a=s.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(a.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),s.hypothesisManager.addHypothesis(a.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${a.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await s.processQueue()}async function li(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function ui(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function Wt(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}var di=mt();function Vt(s,e,t){let n=s.get(t.priority);n&&dt(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function je(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;try{await Ve(s,n)}catch(i){throw s.runningTaskCounter--,i}if(s.runningTaskCounter>=s.config.maxConcurrentTasks)return}}}function Kt(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ve(s,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?Ke(s,e,n):f(new Error("No healthy domain available for task"))}async function Ke(s,e,t){let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:c[e.priority]};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r),o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await c.executeTask(u,m=>mi(s,m));return d.success?C(e.id):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),f(d.error))}if(c)try{await c.handleEvent({id:y(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return C(e.id)}async function mi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,n),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await s.agentCoordinator.stop(i);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(s)}function Yt(s,e){return(P[e.type]||[]).includes(s)}k();async function Zt(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();s.removeFromQueues(l),s.auditLogger.logSteal(l.id,i,c),await s.assignTaskToDomain(l,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,p(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function Ze(s){return typeof s.setMinCutBridge=="function"}function Xt(s,e){for(let[t,n]of s)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(s,e,t){try{let n=await s.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:864e5,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function Xe(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=it.create("QueenCoordinator");zt(T);var Je=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new j(this.config.routing)),T.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new nt(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Rt(t),this.availableMcpServers=gt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-PXEJKKMN.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:T}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await en(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${y()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),C(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return f(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),C(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return T.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return T.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let a=r.dependencies.mcpServers;if(!a||a.length===0)continue;let o=a.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(this.domainPlugins,T);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map,t=0;for(let l of T){let c=this.getDomainLoad(l);e.set(l,c),t+=c}let n=this.agentCoordinator.listAgents(),i=n.filter(l=>l.status==="running").length,r=n.length>0?i/n.length:0,a=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:a,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Ze(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new se(e);this.taskCompletedHook=new ae({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),T)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:y(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),C(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Ot(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>We(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function uo(s,e,t,n,i,r){return new Je(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo as d};
180
+ `}}return t}getRecommendations(e){switch(e.loopType){case"strategic":return[...e.recommendations.forRiskAssessor,...e.recommendations.forQualityCriteria];case"tactical":return e.recommendations.forProductFactorsAssessor;case"operational":return[...e.recommendations.forTestArchitect,...e.recommendations.antiPatterns];case"quality-criteria":return e.recommendations.forRequirementsValidator;default:return[]}}filterManagedHooks(e){if(process.env.AQE_HOOKS_MANAGED_ONLY!=="true")return e;let t=e.filter(([n])=>n.startsWith("managed:"));return t.length<e.length&&console.log(`[CrossPhaseHooks] AQE_HOOKS_MANAGED_ONLY: filtered ${e.length-t.length} non-managed hooks`),t}async isBlockedUrl(e){if(!e.includes("://"))return!1;let t=await pe(e);return t.safe?!1:(console.warn(`[CrossPhaseHooks] SSRF blocked: ${t.reason}`),!0)}checkConditions(e,t){return!e||e.length===0?!0:e.every(n=>this.evaluateCondition(n,t))}evaluateCondition(e,t){try{let n=e.split(/\s*(>|<|>=|<=|==|!=)\s*/);if(n.length!==3)return!1;let[i,r,a]=n,o=this.getValueFromPath(t,i),l=isNaN(Number(a))?a:Number(a),c=typeof o=="number"?o:Number(o),u=typeof l=="number"?l:Number(l);switch(r){case">":return c>u;case"<":return c<u;case">=":return c>=u;case"<=":return c<=u;case"==":return o==l;case"!=":return o!=l;default:return!1}}catch{return!1}}getValueFromPath(e,t){return t.split(".").reduce((n,i)=>{if(n&&typeof n=="object"&&i in n)return n[i]},e)}extractFromContext(e,t){let n={};for(let[i,r]of Object.entries(e))n[i]=this.getValueFromPath(t,r);return n}parseMaxAge(e){let t=e.match(/^(\d+)(d|h|m|s)$/);if(!t)return 0;let[,n,i]=t,r=parseInt(n,10);switch(i){case"d":return r*24*60*60*1e3;case"h":return r*60*60*1e3;case"m":return r*60*1e3;case"s":return r*1e3;default:return 0}}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){this.listeners.get(e)?.forEach(n=>n(t))}async runCleanup(){if(!this.config?.cleanup.enabled)return;console.log("[CrossPhaseHooks] Running cleanup...");let e=await this.memory.cleanupExpired();console.log(`[CrossPhaseHooks] Cleanup complete: ${e.deleted} signals deleted`)}},Ge=null;function qt(s){return Ge||(Ge=new qe(s)),Ge}function jt(s,e){let t=[];for(let a of e){let o=s.router.subscribeToDoamin(a,async l=>{await si(s,l)});t.push(o)}let n=s.router.subscribeToEventType("TaskCompleted",async a=>{await oi(s,a)});t.push(n);let i=s.router.subscribeToEventType("TaskFailed",async a=>{await ci(s,a)});t.push(i);let r=s.router.subscribeToEventType("AgentStatusChanged",async a=>{await li(s,a)});return t.push(r),t}async function si(s,e){s.domainLastActivity.set(e.source,new Date),await s.processQueue()}async function oi(s,e){let{taskId:t,result:n}=e.payload,i=s.tasks.get(t);if(i){(i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1));let r=i.startedAt?Date.now()-i.startedAt.getTime():0;s.tasks.set(t,{...i,status:"completed",completedAt:new Date,result:n}),s.tasksCompleted++,s.taskDurations.push(r),s.auditLogger.logComplete(t,i.assignedAgents[0]);try{let a=qt(),o=i.assignedAgents[0];o&&await a.onAgentComplete(o,{taskId:t,taskType:i.task.type,domain:i.assignedDomain,result:n,duration:r})}catch(a){console.warn("[QueenCoordinator] Cross-phase hook error:",a)}try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!0,0,0)}catch(a){console.warn("[QueenCoordinator] Governance tracking error:",a)}if(s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordSuccess(),s.traceCollector){let a=s.taskTraceContexts.get(t);a&&(s.traceCollector.completeSpan(a.spanId),s.taskTraceContexts.delete(t))}if(s.taskCompletedHook)try{let a=typeof n=="object"&&n!==null?n:null;if(a===null)console.error(`[QueenCoordinator] Pattern training skipped for task ${t}: result is not an object (got ${typeof n})`);else{let o=ui(a,t);if(o){let l={taskId:t,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",type:i.task.type,status:"completed",output:a,metrics:o,duration:r,timestamp:Date.now()};s.taskCompletedHook.onTaskCompleted(l).catch(c=>{console.warn("[QueenCoordinator] Pattern training error:",c)})}}}catch(a){console.warn("[QueenCoordinator] Pattern training setup error:",a)}}await s.processQueue()}async function ci(s,e){let{taskId:t,error:n}=e.payload,i=s.tasks.get(t);if(i){if((i.status==="running"||i.status==="assigned")&&(s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1)),s.domainBreakerRegistry&&i.assignedDomain&&s.domainBreakerRegistry.getBreaker(i.assignedDomain).recordFailure(new Error(n||"Task failed")),s.traceCollector){let r=s.taskTraceContexts.get(t);r&&(s.traceCollector.failSpan(r.spanId,n||"Task failed"),s.taskTraceContexts.delete(t))}if(i.retryCount<s.config.taskRetryLimit){s.auditLogger.logFail(t,i.assignedAgents[0],n);let r={...i,status:"queued",retryCount:i.retryCount+1,error:n};s.tasks.set(t,r),s.enqueueTask(i.task)}else{s.tasks.set(t,{...i,status:"failed",completedAt:new Date,error:n}),s.tasksFailed++,s.auditLogger.logFail(t,i.assignedAgents[0],n);try{await I.afterTaskExecution({taskId:t,taskType:i.task.type,agentId:i.assignedAgents[0]||"unknown",domain:i.assignedDomain||"test-generation",priority:i.task.priority},!1,0,0)}catch(r){console.warn("[QueenCoordinator] Governance tracking error:",r)}if(s.hypothesisManager&&(i.task.priority==="p0"||i.task.priority==="p1"))try{let r=i.assignedDomain||"test-generation",a=s.hypothesisManager.createInvestigation(t,r,`Root cause analysis for ${i.task.type} failure: ${n}`);s.hypothesisManager.addHypothesis(a.id,`Infrastructure failure in domain '${r}' caused task ${t} to fail`,"log-analysis",`${r}-lead`),s.hypothesisManager.addHypothesis(a.id,`Logic/configuration error in task payload caused ${i.task.type} to fail: ${n}`,"code-analysis",i.assignedAgents[0]||"unknown"),console.log(`[QueenCoordinator] Competing hypotheses investigation created: ${a.id}`)}catch(r){console.warn("[QueenCoordinator] Hypothesis creation error:",r)}}}await s.processQueue()}async function li(s,e){let{agentId:t,status:n,domain:i}=e.payload;s.domainLastActivity.set(i,new Date),(n==="completed"||n==="failed")&&await s.processQueue()}function ui(s,e){if("metrics"in s&&typeof s.metrics=="object"&&s.metrics!==null){let t=s.metrics;return{testsPassed:typeof t.testsPassed=="number"?t.testsPassed:void 0,testsFailed:typeof t.testsFailed=="number"?t.testsFailed:void 0,coverageChange:typeof t.coverageChange=="number"?t.coverageChange:void 0,securityIssues:typeof t.securityIssues=="number"?t.securityIssues:void 0,performanceMs:typeof t.performanceMs=="number"?t.performanceMs:void 0,linesChanged:typeof t.linesChanged=="number"?t.linesChanged:void 0}}return"testsPassed"in s||"testsFailed"in s?{testsPassed:typeof s.testsPassed=="number"?s.testsPassed:void 0,testsFailed:typeof s.testsFailed=="number"?s.testsFailed:void 0,coverageChange:typeof s.coverageChange=="number"?s.coverageChange:void 0,securityIssues:typeof s.securityIssues=="number"?s.securityIssues:void 0,performanceMs:typeof s.performanceMs=="number"?s.performanceMs:void 0,linesChanged:typeof s.linesChanged=="number"?s.linesChanged:void 0}:(console.error(`[QueenCoordinator] Pattern training skipped for task ${e}: result object has no recognizable metrics shape (keys: ${Object.keys(s).join(", ")})`),null)}function Wt(s,e,t){let n=s.listAgents({domain:e}),i=n.filter(l=>l.status==="running").length,r=n.filter(l=>l.status==="idle").length,a=n.filter(l=>l.status==="failed").length,o;return a>0&&a>=n.length/2?o="unhealthy":a>0?o="degraded":i>0?o="healthy":o="idle",{status:o,agents:{total:n.length,active:i,idle:r,failed:a},lastActivity:t,errors:[]}}var di=mt();function Vt(s,e,t){let n=s.get(t.priority);n&&dt(n,t,di);for(let i of t.targetDomains){let r=e.get(i);r&&r.push(t)}}function de(s,e,t){let n=s.get(t.priority);if(n){let i=n.findIndex(r=>r.id===t.id);i!==-1&&n.splice(i,1)}for(let i of t.targetDomains){let r=e.get(i);if(r){let a=r.findIndex(o=>o.id===t.id);a!==-1&&r.splice(a,1)}}}function je(s,e){let t=0;for(let n of["p0","p1","p2","p3"]){let i=s.get(n);if(i){if(n===e.priority){t+=i.findIndex(r=>r.id===e.id);break}t+=i.length}}return t}async function We(s){if(!(s.runningTaskCounter>=s.config.maxConcurrentTasks))for(let e of["p0","p1","p2","p3"]){let t=s.taskQueue.get(e);if(!t||t.length===0)continue;let n=t.shift();if(n){de(s.taskQueue,s.domainQueues,n),s.runningTaskCounter++;try{await Ve(s,n)}catch(i){throw s.runningTaskCounter--,i}if(s.runningTaskCounter>=s.config.maxConcurrentTasks)return}}}function Kt(s,e){let t=Array.from(s.values());return e&&(e.status&&(t=t.filter(n=>n.status===e.status)),e.domain&&(t=t.filter(n=>n.assignedDomain===e.domain)),e.priority&&(t=t.filter(n=>n.task.priority===e.priority)),e.type&&(t=t.filter(n=>n.task.type===e.type)),e.fromDate&&(t=t.filter(n=>n.task.createdAt>=e.fromDate)),e.toDate&&(t=t.filter(n=>n.task.createdAt<=e.toDate))),t}async function Ve(s,e){let t=e.targetDomains.length>0?e.targetDomains:P[e.type]||[];if(t.length===0)return f(new Error(`No domains configured for task type: ${e.type}`));let n,i=1/0;for(let r of t){let a=s.getDomainLoad(r);s.getDomainHealth(r)?.status!=="unhealthy"&&a<i&&(i=a,n=r)}return n?Ke(s,e,n):f(new Error("No healthy domain available for task"))}async function Ke(s,e,t){let n;if(s.tinyDancerRouter){let c={p0:"critical",p1:"high",p2:"normal",p3:"low"},u={description:`${e.type}: ${JSON.stringify(e.payload).slice(0,200)}`,type:e.type,domain:t,priority:c[e.priority]};n=await s.tinyDancerRouter.route(u),s.config.enableMetrics&&console.log(`[Queen] TinyDancer routing: ${e.type} \u2192 tier=${n.tier}, model=${n.model}, cost=$${n.estimatedCost.toFixed(4)}`)}if(s.domainBreakerRegistry&&!s.domainBreakerRegistry.canExecuteInDomain(t))return f(new Error(`Domain '${t}' circuit breaker is open \u2014 too many recent failures`));if(s.domainTeamManager)try{if(!s.domainTeamManager.getDomainTeam(t)){let u=`${t}-lead`;s.domainTeamManager.createDomainTeam(t,u)}}catch(c){console.warn(`[Queen] Domain team setup for '${t}' failed (continuing):`,c)}let i=n?.tier||"task-worker",r=["task-execution",e.type,...n?[`model:${n.model}`]:[],...n?.triggerMultiModel?["advisor:triggerMultiModel"]:[]],a=await s.requestAgentSpawn(t,i,r),o=[];a.success&&o.push(a.value);let l={taskId:e.id,task:e,status:"running",assignedDomain:t,assignedAgents:o,startedAt:new Date,retryCount:0};s.tasks.set(e.id,l),s.domainLastActivity.set(t,new Date);for(let c of o)s.auditLogger.logAssign(e.id,c,t);if(await s.publishEvent("TaskAssigned",{taskId:e.id,domain:t,agentIds:o}),s.domainPlugins){let c=s.domainPlugins.get(t);if(c?.executeTask&&c.canHandleTask?.(e.type)){let u={taskId:e.id,taskType:e.type,payload:e.payload,priority:e.priority,timeout:e.timeout,correlationId:e.correlationId},d=await c.executeTask(u,m=>mi(s,m));return d.success?C(e.id):(s.tasks.set(e.id,{...l,status:"failed",error:d.error.message,completedAt:new Date}),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.tasksFailed++,s.auditLogger.logFail(e.id,o[0],d.error.message),f(d.error))}if(c)try{await c.handleEvent({id:y(),type:"TaskAssigned",timestamp:new Date,source:"queen-coordinator",correlationId:e.correlationId,payload:{task:e}}),console.warn(`[Queen] Domain ${t} has no executeTask handler, using event fallback`)}catch(u){console.warn(`[Queen] Failed to invoke domain ${t} event handler:`,u)}}return C(e.id)}async function mi(s,e){let t=s.tasks.get(e.taskId);if(!t){console.warn(`[Queen] Received completion for unknown task: ${e.taskId}`);return}let n={...t,status:e.success?"completed":"failed",completedAt:new Date,result:e.data,error:e.error};if(s.tasks.set(e.taskId,n),e.success?(s.tasksCompleted++,s.taskDurations.push(e.duration),s.auditLogger.logComplete(e.taskId,t.assignedAgents[0])):(s.tasksFailed++,s.auditLogger.logFail(e.taskId,t.assignedAgents[0],e.error||"Unknown error")),s.runningTaskCounter=Math.max(0,s.runningTaskCounter-1),s.coExecutionRepo&&t.assignedAgents.length>=2)try{s.coExecutionRepo.recordSwarmCoExecution(t.assignedAgents,t.assignedDomain||"unknown",e.success,t.task.type)}catch{}for(let i of t.assignedAgents)await s.agentCoordinator.stop(i);await s.publishEvent(e.success?"TaskCompleted":"TaskFailed",{taskId:e.taskId,domain:t.assignedDomain,result:e.data,error:e.error,duration:e.duration}),await We(s)}function Yt(s,e){return(P[e.type]||[]).includes(s)}k();async function Zt(s){let e=0,t=s.getIdleDomains(),n=s.getBusyDomains();if(t.length===0||n.length===0)return 0;n.sort((i,r)=>s.getDomainLoad(r)-s.getDomainLoad(i));for(let i of n){if(t.length===0)break;let r=s.domainQueues.get(i)||[],a=Math.min(r.length,s.config.workStealing.stealBatchSize);for(let o=0;o<a&&t.length>0;o++){let l=r.find(c=>Yt(t[0],c));if(l){let c=t.shift();s.removeFromQueues(l),s.auditLogger.logSteal(l.id,i,c),await s.assignTaskToDomain(l,c),e++,s.tasksStolen++,await s.publishEvent("TaskStolen",{taskId:l.id,fromDomain:i,toDomain:c})}}}return e}function Ye(s,e){let t=0,n=10,i=setInterval(async()=>{try{await e(),t=0}catch(r){t++;let a=Math.min(1e3*Math.pow(2,t),3e4);if(console.warn(`[QueenCoordinator] Work-stealing failed (attempt ${t}), backing off ${a}ms`,p(r)),t>n){console.error(`[QueenCoordinator] Work-stealing exceeded ${n} consecutive failures, stopping interval`),clearInterval(i);return}await new Promise(o=>setTimeout(o,a))}},s.workStealing.checkInterval);return i}function Ze(s){return typeof s.setMinCutBridge=="function"}function Xt(s,e){for(let[t,n]of s)Ze(n)&&(n.setMinCutBridge(e),console.log(`[QueenCoordinator] MinCut bridge injected into ${t}`))}async function Jt(s,e,t){try{let n=await s.get("queen:state");if(n)for(let[i,r]of n.tasks)r.status==="queued"&&(e.set(i,r),t(r.task))}catch(n){console.debug("[QueenCoordinator] State loading failed:",n instanceof Error?n.message:n)}}async function en(s,e){let t=Array.from(e.entries()).filter(([,n])=>n.status==="queued");await s.set("queen:state",{tasks:t},{namespace:"queen-coordinator",persist:!0})}function tn(s){return setInterval(async()=>{let e=s.getMetrics();if(await s.publishEvent("MetricsCollected",{metrics:e}),await s.memory.set(`queen:metrics:${Date.now()}`,e,{ttl:864e5,namespace:"queen-coordinator"}),s.dynamicScaler)try{let t=s.getAverageTaskDuration(),n={queueDepth:s.getQueuedTaskCount(),activeAgents:s.getActiveAgentCount(),idleAgents:s.getIdleAgentCount(),avgTaskDurationMs:t,errorRate:s.getTasksReceived()>0?s.getTasksFailed()/s.getTasksReceived():0,throughput:e.uptime>0?s.getTasksCompleted()/(e.uptime/1e3):0,timestamp:Date.now()};s.dynamicScaler.recordMetrics(n);let i=s.dynamicScaler.evaluate();i&&i.action!=="maintain"&&(console.log(`[QueenCoordinator] Dynamic scaler: ${i.action} to ${i.targetAgents} agents \u2014 ${i.reason}`),s.dynamicScaler.execute(i).catch(r=>{console.warn("[QueenCoordinator] Dynamic scaling execution error:",r)}))}catch(t){console.warn("[QueenCoordinator] Dynamic scaler metrics error:",t)}},s.config.metricsInterval)}function Xe(s,e,t=36e5){let n=Date.now(),i=0;for(let[a,o]of s)if(o.status==="completed"||o.status==="failed"||o.status==="cancelled"){let l=o.completedAt?.getTime()||o.startedAt?.getTime()||0;l>0&&n-l>t&&(s.delete(a),e.delete(a),i++)}let r=1e4;if(e.size>r){let a=e.size-r,o=e.keys();for(let l=0;l<a;l++){let c=o.next().value;c!==void 0&&e.delete(c)}console.log(`[QueenCoordinator] Evicted ${a} oldest trace contexts (max: ${r})`)}return i>0&&console.log(`[QueenCoordinator] Cleaned up ${i} old tasks (retention: ${t}ms)`),i}function nn(s,e){return s&&s.size>0?Array.from(s.keys()):[...e]}var g=it.create("QueenCoordinator");zt(T);var Je=class{constructor(e,t,n,i,r,a,o,l={}){this.eventBus=e;this.agentCoordinator=t;this.memory=n;this.router=i;this.protocolExecutor=r;this.workflowExecutor=a;this.domainPlugins=o;this.config={...Ut,...l},this.auditLogger=he({enableConsoleLog:this.config.enableMetrics,maxEntries:1e3,logPrefix:"[QUEEN]"}),["p0","p1","p2","p3"].forEach(c=>{this.taskQueue.set(c,[])}),this.config.enableRouting!==!1&&(this.tinyDancerRouter=new j(this.config.routing)),T.forEach(c=>{this.domainQueues.set(c,[]),this.domainLastActivity.set(c,new Date)})}eventBus;agentCoordinator;memory;router;protocolExecutor;workflowExecutor;domainPlugins;config;tasks=new Map;taskQueue=new Map;domainQueues=new Map;domainLastActivity=new Map;initialized=!1;workStealingTimer=null;metricsTimer=null;cleanupTimer=null;startTime=new Date;eventSubscriptionIds=[];runningTaskCounter=0;tasksReceived=0;tasksCompleted=0;tasksFailed=0;tasksStolen=0;taskDurations=new nt(1e3);protocolsExecuted=0;workflowsExecuted=0;auditLogger;minCutBridge=null;tinyDancerRouter=null;domainBreakerRegistry=null;domainTeamManager=null;agentTeamsAdapter=null;tierSelector=null;taskCompletedHook=null;traceCollector=null;taskTraceContexts=new Map;hypothesisManager=null;federationMailbox=null;dynamicScaler=null;coExecutionRepo=null;dependencyGraph=null;availableMcpServers=[];async initialize(){if(!this.initialized){this.startTime=new Date,await this.router.initialize(),this.subscribeToEvents(),this.config.workStealing.enabled&&(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{}))),this.config.enableMetrics&&(this.metricsTimer=tn(this.createMetricsContext())),this.cleanupTimer=setInterval(()=>{Xe(this.tasks,this.taskTraceContexts,36e5)},3e5),this.cleanupTimer.unref(),await Jt(this.memory,this.tasks,e=>this.enqueueTaskInternal(e)),this.minCutBridge=ht(this.eventBus,this.agentCoordinator,{autoUpdateFromEvents:!0,persistData:!0,includeInQueenHealth:!0,sharedGraph:ct()}),await this.minCutBridge.initialize(),this.domainPlugins&&Xt(this.domainPlugins,this.minCutBridge);try{await I.initialize(),g.info("Governance adapter initialized")}catch(e){g.warn("Governance initialization failed (continuing)",{error:e})}this.initializeSubsystems();try{let{join:e}=await import("path"),t=e(process.cwd(),".claude","agents","v3");this.dependencyGraph=Rt(t),this.availableMcpServers=gt(process.cwd());let{getUnifiedMemory:n}=await import("./unified-memory-6MXOYRXZ.js"),i=n();await i.initialize(),this.coExecutionRepo=wt(),this.coExecutionRepo.initialize(i.getDatabase()),this.dependencyGraph.warnings.length>0&&g.warn(`Dependency graph: ${this.dependencyGraph.warnings.length} warning(s)`,{warnings:this.dependencyGraph.warnings.slice(0,5)}),g.info("Dependency intelligence initialized",{agents:this.dependencyGraph.nodes.size,mcpServers:this.availableMcpServers.length})}catch(e){g.warn("Dependency intelligence initialization failed (continuing)",{error:e})}await this.publishEvent("QueenInitialized",{timestamp:new Date,config:this.config,domains:T}),this.initialized=!0}}async dispose(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null),this.metricsTimer&&(clearInterval(this.metricsTimer),this.metricsTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.minCutBridge&&(await this.minCutBridge.dispose(),this.minCutBridge=null),this.domainTeamManager&&(this.domainTeamManager.dispose(),this.domainTeamManager=null),this.agentTeamsAdapter&&(this.agentTeamsAdapter.shutdown(),this.agentTeamsAdapter=null),this.domainBreakerRegistry=null,this.tierSelector=null,this.traceCollector&&(this.traceCollector.dispose(),this.traceCollector=null),this.hypothesisManager&&(this.hypothesisManager.dispose(),this.hypothesisManager=null),this.federationMailbox&&(this.federationMailbox.dispose(),this.federationMailbox=null),this.dynamicScaler&&(this.dynamicScaler.dispose(),this.dynamicScaler=null),await en(this.memory,this.tasks);for(let[e,t]of this.tasks)(t.status==="queued"||t.status==="running")&&await this.cancelTask(e);await this.publishEvent("QueenShutdown",{timestamp:new Date,metrics:this.getMetrics()});for(let e of this.eventSubscriptionIds)this.router.unsubscribe(e);this.eventSubscriptionIds=[],await this.router.dispose(),this.initialized=!1}async submitTask(e){if(!this.initialized)return f(new Error("Queen Coordinator not initialized"));let t=`task_${y()}`,n={...e,id:t,createdAt:new Date,timeout:e.timeout||this.config.defaultTaskTimeout},i={taskId:n.id,taskType:n.type,agentId:n.requester||"unknown",domain:n.targetDomains[0]||"test-generation",priority:n.priority,payload:n.payload};try{let r=await I.beforeTaskExecution(i);if(!r.allowed)return this.auditLogger.logFail(t,"governance",r.reason||"Governance check failed"),await this.publishEvent("TaskRejected",{taskId:t,reason:r.reason,escalate:r.escalate}),f(new Error(`Task blocked by governance: ${r.reason}`))}catch(r){g.warn("Governance check error (continuing)",{error:r})}this.runningTaskCounter++;try{if(this.runningTaskCounter>this.config.maxConcurrentTasks)return this.runningTaskCounter--,this.queueTask(n);this.auditLogger.logSubmit(t,{type:n.type,priority:n.priority}),this.selectFleetTier(n),this.startTaskTrace(n,t);let r=await Ve(this.createTaskContext(),n);return r.success?(this.tasksReceived++,await this.publishEvent("TaskSubmitted",{taskId:t,task:n}),C(t)):(this.runningTaskCounter--,r)}catch(r){throw this.runningTaskCounter--,r}}async cancelTask(e){let t=this.tasks.get(e);if(!t)return f(new Error(`Task not found: ${e}`));if(t.status==="completed"||t.status==="failed")return f(new Error(`Task already finished: ${e}`));(t.status==="running"||t.status==="assigned")&&(this.runningTaskCounter=Math.max(0,this.runningTaskCounter-1)),this.tasks.set(e,{...t,status:"cancelled",completedAt:new Date}),de(this.taskQueue,this.domainQueues,t.task);for(let n of t.assignedAgents)await this.agentCoordinator.stop(n);return this.auditLogger.logCancel(e),await this.publishEvent("TaskCancelled",{taskId:e}),C(void 0)}getTaskStatus(e){return this.tasks.get(e)}listTasks(e){return Kt(this.tasks,e)}getDomainHealth(e){if(this.domainPlugins){let t=this.domainPlugins.get(e);if(t)return t.getHealth()}return Wt(this.agentCoordinator,e,this.domainLastActivity.get(e))}getDomainLoad(e){let t=this.domainQueues.get(e)||[],n=Array.from(this.tasks.values()).filter(i=>i.assignedDomain===e&&i.status==="running");return t.length+n.length}getIdleDomains(){let e=Date.now(),t=this.config.workStealing.idleThreshold;return T.filter(n=>{let i=this.domainLastActivity.get(n);return this.getDomainLoad(n)===0&&i&&e-i.getTime()>t})}getBusyDomains(){return T.filter(e=>this.getDomainLoad(e)>this.config.workStealing.loadThreshold)}getSpawnPlan(e){return this.dependencyGraph?_t(e,this.dependencyGraph):{phases:[e],warnings:[],unsatisfiedHardDeps:[]}}getDependencyGraph(){return this.dependencyGraph}enableWorkStealing(){this.workStealingTimer||(this.workStealingTimer=Ye(this.config,()=>this.triggerWorkStealing().then(()=>{})))}disableWorkStealing(){this.workStealingTimer&&(clearInterval(this.workStealingTimer),this.workStealingTimer=null)}async triggerWorkStealing(){return Zt(this.createWorkStealingContext())}listAllAgents(){return this.agentCoordinator.listAgents()}getAgentsByDomain(e){return this.agentCoordinator.listAgents({domain:e})}async requestAgentSpawn(e,t,n){if(!this.agentCoordinator.canSpawn())return f(new Error("Maximum concurrent agents reached (15)"));if(this.dependencyGraph&&this.availableMcpServers.length>0)try{for(let[,r]of this.dependencyGraph.nodes){let a=r.dependencies.mcpServers;if(!a||a.length===0)continue;let o=a.filter(l=>l.required&&!this.availableMcpServers.includes(l.name));if(o.length>0){g.warn(`Pre-spawn MCP advisory: ${r.agentName} needs ${o.map(l=>l.name).join(", ")}`,{agent:r.agentName,domain:e,missing:o.map(l=>l.name)});break}}}catch{}let i=await this.agentCoordinator.spawn({name:`${e}-${t}-${Date.now()}`,domain:e,type:t,capabilities:n});if(i.success){if(this.domainLastActivity.set(e,new Date),this.domainTeamManager&&typeof this.domainTeamManager.getDomainTeam=="function")try{if(this.domainTeamManager.getDomainTeam(e))this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full)`);else try{this.domainTeamManager.createDomainTeam(e,i.value)}catch{this.domainTeamManager.addTeammate(e,i.value)||g.warn(`Agent ${i.value} could not join ${e} team (full or max teams reached)`)}}catch(r){g.warn(`Auto-team-wiring failed for ${i.value}`,{error:r})}await this.publishEvent("AgentSpawned",{agentId:i.value,domain:e,type:t,capabilities:n})}return i}getHealth(){let e=new Map,t=[],n=0,i=0,r=nn(this.domainPlugins,T);for(let u of r){let d=this.getDomainHealth(u);d&&(e.set(u,d),d.status==="unhealthy"?(n++,t.push({domain:u,severity:"high",message:`Domain ${u} is unhealthy`,timestamp:new Date})):d.status==="degraded"&&(i++,t.push({domain:u,severity:"medium",message:`Domain ${u} is degraded`,timestamp:new Date})))}let a=this.agentCoordinator.listAgents(),o=a.filter(u=>u.status==="running").length,l="healthy";n>0?l="unhealthy":i>r.length/2&&(l="degraded");let c={status:l,domainHealth:e,totalAgents:a.length,activeAgents:o,pendingTasks:this.getQueuedTaskCount(),runningTasks:this.getRunningTaskCount(),workStealingActive:this.workStealingTimer!==null,lastHealthCheck:new Date,issues:t};return this.minCutBridge?this.minCutBridge.extendQueenHealth(c):c}getMetrics(){let e=new Map,t=0;for(let l of T){let c=this.getDomainLoad(l);e.set(l,c),t+=c}let n=this.agentCoordinator.listAgents(),i=n.filter(l=>l.status==="running").length,r=n.length>0?i/n.length:0,a=this.taskDurations.average(),o={tasksReceived:this.tasksReceived,tasksCompleted:this.tasksCompleted,tasksFailed:this.tasksFailed,tasksStolen:this.tasksStolen,averageTaskDuration:a,domainUtilization:e,agentUtilization:r,protocolsExecuted:this.protocolsExecuted,workflowsExecuted:this.workflowsExecuted,uptime:Date.now()-this.startTime.getTime()};return this.minCutBridge?this.minCutBridge.extendQueenMetrics(o):o}getMinCutBridge(){return this.minCutBridge}injectMinCutBridgeIntoDomain(e){if(!this.minCutBridge)return g.warn("Cannot inject MinCut bridge: bridge not initialized"),!1;if(!this.domainPlugins)return g.warn("Cannot inject MinCut bridge: no domain plugins registered"),!1;let t=this.domainPlugins.get(e);return t?Ze(t)?(t.setMinCutBridge(this.minCutBridge),g.info(`MinCut bridge injected into ${e} (late binding)`),!0):(g.warn(`Domain ${e} does not support MinCut integration`),!1):(g.warn(`Cannot inject MinCut bridge: domain ${e} not found`),!1)}getTinyDancerRouter(){return this.tinyDancerRouter}getDomainBreakerRegistry(){return this.domainBreakerRegistry}getDomainTeamManager(){return this.domainTeamManager}getAgentTeamsAdapter(){return this.agentTeamsAdapter}getTierSelector(){return this.tierSelector}getTraceCollector(){return this.traceCollector}getHypothesisManager(){return this.hypothesisManager}getFederationMailbox(){return this.federationMailbox}getDynamicScaler(){return this.dynamicScaler}connectReasoningBank(e){let t=new se(e);this.taskCompletedHook=new ae({},t),g.info("ReasoningBank connected for pattern training")}async executeProtocol(e,t){if(!this.protocolExecutor)return f(new Error("Protocol executor not configured"));let n=await this.protocolExecutor.execute(e,t);return n.success?(this.protocolsExecuted++,await this.publishEvent("ProtocolExecuted",{protocolId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}async executeWorkflow(e,t){if(!this.workflowExecutor)return f(new Error("Workflow executor not configured"));let n=await this.workflowExecutor.execute(e,t);return n.success?(this.workflowsExecuted++,await this.publishEvent("WorkflowExecuted",{workflowId:e,executionId:n.value.executionId}),C(n.value.executionId)):n}cleanupCompletedTasks(e=36e5){return Xe(this.tasks,this.taskTraceContexts,e)}subscribeToEvents(){this.eventSubscriptionIds=jt(this.createEventHandlerContext(),T)}enqueueTaskInternal(e){Vt(this.taskQueue,this.domainQueues,e)}async publishEvent(e,t){await this.eventBus.publish({id:y(),type:`Queen${e}`,timestamp:new Date,source:"queen-coordinator",payload:t})}queueTask(e){this.enqueueTaskInternal(e);let t={taskId:e.id,task:e,status:"queued",assignedAgents:[],retryCount:0};return this.tasks.set(e.id,t),this.tasksReceived++,this.auditLogger.logSubmit(e.id,{type:e.type,priority:e.priority}),this.auditLogger.logQueue(e.id,je(this.taskQueue,e)),this.publishEvent("TaskQueued",{taskId:e.id,task:e,position:je(this.taskQueue,e)}),C(e.id)}selectFleetTier(e){if(this.tierSelector)try{let t={trigger:e.payload?.trigger??"manual",changedFiles:e.payload?.changedFiles,affectedDomains:e.targetDomains,severity:e.priority==="p0"?"critical":e.priority==="p1"?"high":void 0,isHotfix:e.payload?.isHotfix},n=this.tierSelector.selectTier(t);return g.info(`Fleet tier: ${n.selectedTier} (${n.reason})`),n.selectedTier}catch(t){g.warn("Tier selection error (continuing)",{error:t});return}}startTaskTrace(e,t){if(this.traceCollector)try{let{context:n}=this.traceCollector.startTrace({operationName:e.type,agentId:e.requester||"queen",domain:e.targetDomains[0]||"test-generation",tags:{taskId:t,priority:e.priority}});if(this.taskTraceContexts.size>=1e4){let r=this.taskTraceContexts.keys().next().value;r!==void 0&&this.taskTraceContexts.delete(r)}this.taskTraceContexts.set(t,n)}catch(n){g.warn("Trace start error (continuing)",{error:n})}}getRunningTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="running"||e.status==="assigned").length}getQueuedTaskCount(){return Array.from(this.tasks.values()).filter(e=>e.status==="queued").length}initializeSubsystems(){if(this.config.enableCircuitBreakers!==!1)try{this.domainBreakerRegistry=Ot(),g.info("Domain circuit breaker registry initialized")}catch(e){g.warn("Circuit breaker initialization failed (continuing)",{error:e})}if(this.config.enableDomainTeams!==!1)try{this.agentTeamsAdapter=Ae(),this.agentTeamsAdapter.initialize(),this.domainTeamManager=Ee(this.agentTeamsAdapter),g.info("Domain team manager initialized")}catch(e){g.warn("Domain team manager initialization failed (continuing)",{error:e})}if(this.config.enableFleetTiers!==!1)try{this.tierSelector=Re(),g.info("Fleet tier selector initialized")}catch(e){g.warn("Tier selector initialization failed (continuing)",{error:e})}try{this.traceCollector=xe(),g.info("Trace collector initialized")}catch(e){g.warn("Trace collector initialization failed (continuing)",{error:e})}try{this.hypothesisManager=Fe(),this.federationMailbox=Oe(),this.dynamicScaler=Le(),g.info("Phase 4 modules initialized (hypotheses, federation, scaling)")}catch(e){g.warn("Phase 4 initialization failed (continuing)",{error:e})}}createEventHandlerContext(){let e=this;return{config:e.config,tasks:e.tasks,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,router:e.router,agentCoordinator:e.agentCoordinator,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get domainBreakerRegistry(){return e.domainBreakerRegistry},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get taskCompletedHook(){return e.taskCompletedHook},get hypothesisManager(){return e.hypothesisManager},processQueue:()=>We(e.createTaskContext()),enqueueTask:t=>e.enqueueTaskInternal(t)}}createTaskContext(){let e=this;return{config:e.config,tasks:e.tasks,taskQueue:e.taskQueue,domainQueues:e.domainQueues,domainLastActivity:e.domainLastActivity,auditLogger:e.auditLogger,agentCoordinator:e.agentCoordinator,domainPlugins:e.domainPlugins,get runningTaskCounter(){return e.runningTaskCounter},set runningTaskCounter(t){e.runningTaskCounter=t},get tasksReceived(){return e.tasksReceived},set tasksReceived(t){e.tasksReceived=t},get tasksCompleted(){return e.tasksCompleted},set tasksCompleted(t){e.tasksCompleted=t},get tasksFailed(){return e.tasksFailed},set tasksFailed(t){e.tasksFailed=t},taskDurations:e.taskDurations,get tinyDancerRouter(){return e.tinyDancerRouter},get domainBreakerRegistry(){return e.domainBreakerRegistry},get domainTeamManager(){return e.domainTeamManager},get tierSelector(){return e.tierSelector},get traceCollector(){return e.traceCollector},taskTraceContexts:e.taskTraceContexts,get coExecutionRepo(){return e.coExecutionRepo},requestAgentSpawn:(t,n,i)=>e.requestAgentSpawn(t,n,i),publishEvent:(t,n)=>e.publishEvent(t,n),getDomainLoad:t=>e.getDomainLoad(t),getDomainHealth:t=>e.getDomainHealth(t)}}createWorkStealingContext(){let e=this;return{config:e.config,domainQueues:e.domainQueues,auditLogger:e.auditLogger,get tasksStolen(){return e.tasksStolen},set tasksStolen(t){e.tasksStolen=t},getIdleDomains:()=>e.getIdleDomains(),getBusyDomains:()=>e.getBusyDomains(),getDomainLoad:t=>e.getDomainLoad(t),removeFromQueues:t=>de(e.taskQueue,e.domainQueues,t),assignTaskToDomain:(t,n)=>Ke(e.createTaskContext(),t,n).then(()=>{}),publishEvent:(t,n)=>e.publishEvent(t,n)}}createMetricsContext(){let e=this;return{config:e.config,memory:e.memory,get dynamicScaler(){return e.dynamicScaler},getMetrics:()=>e.getMetrics(),publishEvent:(t,n)=>e.publishEvent(t,n),getQueuedTaskCount:()=>e.getQueuedTaskCount(),getActiveAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="running").length,getIdleAgentCount:()=>e.agentCoordinator.listAgents().filter(t=>t.status==="idle").length,getAverageTaskDuration:()=>e.taskDurations.average(),getTasksReceived:()=>e.tasksReceived,getTasksFailed:()=>e.tasksFailed,getTasksCompleted:()=>e.tasksCompleted}}};function uo(s,e,t,n,i,r){return new Je(s.eventBus,s.coordinator,s.memory,e,t,n,i,r)}export{ei as a,P as b,Je as c,uo as d};
@@ -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.10.6");process.exit(0)}
2
- import{i as c}from"./chunk-LEDF3LGZ.js";import{a as p}from"./chunk-434VUSZP.js";import{c as m}from"./chunk-F72A356B.js";import{b as g,d as E}from"./chunk-DFBVWMX3.js";import{a as l,b as _}from"./chunk-7NXVVIJZ.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&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.10.7");process.exit(0)}
2
+ import{i as c}from"./chunk-6F5KPT6U.js";import{a as p}from"./chunk-DF7V6X3N.js";import{c as m}from"./chunk-222ZQTL5.js";import{b as g,d as E}from"./chunk-QBVFONWU.js";import{a as l,b as _}from"./chunk-Z44VJC5U.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -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.10.6");process.exit(0)}
2
- import{a as C,b as E}from"./chunk-5QTUGFFP.js";import{a as T}from"./chunk-XOGBTPJI.js";import{a as _}from"./chunk-LEDF3LGZ.js";import{l as D,m as F}from"./chunk-RA7HEY5G.js";import{a as R,c as A}from"./chunk-O4MNYX4X.js";import{g as O}from"./chunk-UNDPB5SS.js";import{createHash as M}from"crypto";var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function S(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return"["+o.map(i=>S(i)).join(",")+"]";let e=o;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+S(e[i])).join(",")+"}"}var x=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=S({action:t,domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=w();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
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.10.7");process.exit(0)}
2
+ import{a as C,b as E}from"./chunk-2J4ZUUU5.js";import{a as T}from"./chunk-JJELOEIY.js";import{a as _}from"./chunk-6F5KPT6U.js";import{l as D,m as F}from"./chunk-HBWAMCVB.js";import{a as R,c as A}from"./chunk-XWPUCPYW.js";import{g as O}from"./chunk-LRRQEAP5.js";import{createHash as M}from"crypto";var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function S(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return"["+o.map(i=>S(i)).join(",")+"]";let e=o;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+S(e[i])).join(",")+"}"}var x=class{cache=new Map;config;hits=0;misses=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=S({action:t,domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=w();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=w();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
@@ -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.10.6");process.exit(0)}
2
- import{a as I}from"./chunk-JXCIRWLQ.js";import{l as F,m as q}from"./chunk-RA7HEY5G.js";import{a as A,b as m,c as d}from"./chunk-K32AUACO.js";import{a as b,b as W,c as O}from"./chunk-O4MNYX4X.js";import{i as D}from"./chunk-BHD6THT5.js";import{g as T}from"./chunk-UNDPB5SS.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.10.7");process.exit(0)}
2
+ import{a as I}from"./chunk-MMR23KAO.js";import{l as F,m as q}from"./chunk-HBWAMCVB.js";import{a as A,b as m,c as d}from"./chunk-2MLISLRR.js";import{a as b,b as W,c as O}from"./chunk-XWPUCPYW.js";import{i as D}from"./chunk-6OLPKIYU.js";import{g as T}from"./chunk-LRRQEAP5.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.10.6");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.10.7");process.exit(0)}
2
2
  var h=Object.create;var e=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),n=a=>b=>{var c=a[b];if(c)return c();throw new Error("Module not found in bundle: "+b)};var o=(a,b)=>()=>(a&&(b=a(a=0)),b);var p=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports),q=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of j(b))!l.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=i(b,d))||f.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(e({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f,s as g};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-UWDC3TZP.js";import{i as g,m as P}from"./chunk-RA7HEY5G.js";import{a as d,b as y,c as R}from"./chunk-O4MNYX4X.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,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.10.7");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-M7SO5KNJ.js";import{i as g,m as P}from"./chunk-HBWAMCVB.js";import{a as d,b as y,c as R}from"./chunk-XWPUCPYW.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.6");process.exit(0)}
2
- import{p as O,q}from"./chunk-5V4IFRG5.js";import{i as T,m as U}from"./chunk-RA7HEY5G.js";import{i as b}from"./chunk-BHD6THT5.js";import{b as M,c as H}from"./chunk-LHZOIXJ6.js";import{g as C}from"./chunk-UNDPB5SS.js";U();var _=null;function w(){if(_)return _;let E=(q(),C(O));if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function L(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=L(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=(H(),C(M)),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=w(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=w(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var W={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...W,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=T();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.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.10.7");process.exit(0)}
2
+ import{p as O,q}from"./chunk-L6NB4UHR.js";import{i as T,m as U}from"./chunk-HBWAMCVB.js";import{i as b}from"./chunk-6OLPKIYU.js";import{b as M,c as H}from"./chunk-TTLAWPEN.js";import{g as C}from"./chunk-LRRQEAP5.js";U();var _=null;function w(){if(_)return _;let E=(q(),C(O));if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function L(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=L(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=(H(),C(M)),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=w(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=w(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var W={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...W,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=T();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
3
3
  SELECT id, task, domain, quality, success, application_count,
4
4
  consolidation_count, reuse_success_count, reuse_failure_count,
5
5
  embedding, embedding_dimension, started_at
@@ -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.10.6");process.exit(0)}
2
- import{a as _}from"./chunk-4N4TU7ST.js";import{e as E}from"./chunk-LEDF3LGZ.js";import{a as b}from"./chunk-434VUSZP.js";import{c as h}from"./chunk-F72A356B.js";import{b as p,d as S}from"./chunk-DFBVWMX3.js";import{S as A,j as g}from"./chunk-Q4LYWIEX.js";S();b();A();var d=h.create("pattern-lifecycle"),D={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},y=5,L=.9,R=2;function v(u,e){return e<y||!Number.isFinite(u)?0:Math.min(Math.max(u,0),1)}var f=class{constructor(e,t={}){this.db=e;this.config={...D,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.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.10.7");process.exit(0)}
2
+ import{a as _}from"./chunk-4W5QWFU4.js";import{e as E}from"./chunk-6F5KPT6U.js";import{a as b}from"./chunk-DF7V6X3N.js";import{c as h}from"./chunk-222ZQTL5.js";import{b as p,d as S}from"./chunk-QBVFONWU.js";import{S as A,j as g}from"./chunk-76JYG426.js";S();b();A();var d=h.create("pattern-lifecycle"),D={promotionRewardThreshold:.7,promotionMinOccurrences:E,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3,maxAgeForActivePatterns:90,promotionActivityWindowDays:30,asymmetricLearning:{}},y=5,L=.9,R=2;function v(u,e){return e<y||!Number.isFinite(u)?0:Math.min(Math.max(u,0),1)}var f=class{constructor(e,t={}){this.db=e;this.config={...D,...t},this.asymmetricEngine=new _(this.config.asymmetricLearning),this.ensureSchema()}db;config;asymmetricEngine;_witnessChain=null;set witnessChain(e){this._witnessChain=e}_compressionService=null;set compressionService(e){this._compressionService=e}ensureSchema(){try{this.db.prepare(`
3
3
  SELECT deprecated_at FROM qe_patterns LIMIT 1
4
4
  `).get()}catch(e){d.debug("Adding missing deprecated_at column",{error:e instanceof Error?e.message:String(e)}),this.db.exec(`
5
5
  ALTER TABLE qe_patterns ADD COLUMN deprecated_at TEXT DEFAULT NULL