agentic-qe 3.14.3 → 3.14.5

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 (786) hide show
  1. package/.claude/agents/v3/qe-coverage-specialist.md +1 -1
  2. package/.claude/agents/v3/qe-fleet-commander.md +1 -1
  3. package/.claude/agents/v3/qe-pentest-validator.md +1 -1
  4. package/.claude/agents/v3/qe-queen-coordinator.md +1 -1
  5. package/.claude/agents/v3/qe-risk-assessor.md +1 -1
  6. package/.claude/agents/v3/qe-root-cause-analyzer.md +1 -1
  7. package/.claude/agents/v3/qe-security-auditor.md +1 -1
  8. package/.claude/agents/v3/qe-test-architect.md +1 -1
  9. package/.claude/commands/aqe-costs.md +10 -10
  10. package/.claude/helpers/advisor-call.cjs +3 -3
  11. package/.claude/helpers/v3/advisor-call.cjs +3 -3
  12. package/.claude/skills/.validation/examples/chaos-engineering-output.example.json +1 -1
  13. package/.claude/skills/.validation/examples/performance-testing-output.example.json +1 -1
  14. package/.claude/skills/.validation/examples/security-testing-output.example.json +1 -1
  15. package/.claude/skills/.validation/examples/testability-scoring-output.example.json +1 -1
  16. package/.claude/skills/.validation/schemas/skill-eval.schema.json +4 -1
  17. package/.claude/skills/.validation/schemas/skill-frontmatter.schema.json +1 -1
  18. package/.claude/skills/.validation/schemas/skill-output.template.json +1 -1
  19. package/.claude/skills/.validation/templates/eval.template.yaml +1 -1
  20. package/.claude/skills/.validation/templates/security-testing-eval.template.yaml +1 -1
  21. package/.claude/skills/.validation/templates/skill-frontmatter.example.yaml +1 -1
  22. package/.claude/skills/.validation/test-data/sample-output.json +1 -1
  23. package/.claude/skills/a11y-ally/SKILL.md +1 -1
  24. package/.claude/skills/a11y-ally/evals/a11y-ally.yaml +1 -1
  25. package/.claude/skills/accessibility-testing/evals/accessibility-testing.yaml +1 -1
  26. package/.claude/skills/api-testing-patterns/evals/api-testing-patterns.yaml +1 -1
  27. package/.claude/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +1 -1
  28. package/.claude/skills/cicd-pipeline-qe-orchestrator/evals/cicd-pipeline-qe-orchestrator.yaml +1 -1
  29. package/.claude/skills/compatibility-testing/evals/compatibility-testing.yaml +1 -1
  30. package/.claude/skills/compliance-testing/evals/compliance-testing.yaml +1 -1
  31. package/.claude/skills/contract-testing/evals/contract-testing.yaml +1 -1
  32. package/.claude/skills/database-testing/evals/database-testing.yaml +1 -1
  33. package/.claude/skills/enterprise-integration-testing/evals/enterprise-integration-testing.yaml +1 -1
  34. package/.claude/skills/localization-testing/evals/localization-testing.yaml +1 -1
  35. package/.claude/skills/middleware-testing-patterns/evals/middleware-testing-patterns.yaml +1 -1
  36. package/.claude/skills/mobile-testing/evals/mobile-testing.yaml +1 -1
  37. package/.claude/skills/mutation-testing/evals/mutation-testing.yaml +1 -1
  38. package/.claude/skills/mutation-testing/test-data/sample-output.json +1 -1
  39. package/.claude/skills/n8n-expression-testing/evals/n8n-expression-testing.yaml +1 -1
  40. package/.claude/skills/n8n-integration-testing-patterns/evals/n8n-integration-testing-patterns.yaml +1 -1
  41. package/.claude/skills/n8n-security-testing/evals/n8n-security-testing.yaml +1 -1
  42. package/.claude/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +1 -1
  43. package/.claude/skills/n8n-workflow-testing-fundamentals/evals/n8n-workflow-testing-fundamentals.yaml +1 -1
  44. package/.claude/skills/observability-testing-patterns/evals/observability-testing-patterns.yaml +1 -1
  45. package/.claude/skills/pentest-validation/evals/pentest-validation.yaml +1 -1
  46. package/.claude/skills/performance-testing/evals/performance-testing.yaml +1 -1
  47. package/.claude/skills/qcsd-cicd-swarm/evals/qcsd-cicd-swarm.yaml +1 -1
  48. package/.claude/skills/qcsd-development-swarm/evals/qcsd-development-swarm.yaml +1 -1
  49. package/.claude/skills/qcsd-ideation-swarm/evals/qcsd-ideation-swarm.yaml +1 -1
  50. package/.claude/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +1 -1
  51. package/.claude/skills/qcsd-refinement-swarm/evals/qcsd-refinement-swarm.yaml +1 -1
  52. package/.claude/skills/qe-browser/evals/qe-browser.yaml +1 -1
  53. package/.claude/skills/qe-chaos-resilience/evals/qe-chaos-resilience.yaml +1 -1
  54. package/.claude/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +1 -1
  55. package/.claude/skills/qe-coverage-analysis/evals/qe-coverage-analysis.yaml +1 -1
  56. package/.claude/skills/qe-defect-intelligence/evals/qe-defect-intelligence.yaml +1 -1
  57. package/.claude/skills/qe-learning-optimization/evals/qe-learning-optimization.yaml +2 -2
  58. package/.claude/skills/qe-quality-assessment/evals/qe-quality-assessment.yaml +1 -1
  59. package/.claude/skills/qe-requirements-validation/evals/qe-requirements-validation.yaml +1 -1
  60. package/.claude/skills/qe-test-execution/evals/qe-test-execution.yaml +1 -1
  61. package/.claude/skills/qe-test-generation/evals/qe-test-generation.yaml +1 -1
  62. package/.claude/skills/qe-visual-accessibility/evals/qe-visual-accessibility.yaml +1 -1
  63. package/.claude/skills/quality-metrics/evals/quality-metrics.yaml +1 -1
  64. package/.claude/skills/regression-testing/evals/regression-testing.yaml +1 -1
  65. package/.claude/skills/risk-based-testing/evals/risk-based-testing.yaml +1 -1
  66. package/.claude/skills/security-testing/evals/security-testing.yaml +1 -1
  67. package/.claude/skills/security-visual-testing/evals/security-visual-testing.yaml +1 -1
  68. package/.claude/skills/shift-left-testing/evals/shift-left-testing.yaml +1 -1
  69. package/.claude/skills/shift-right-testing/evals/shift-right-testing.yaml +1 -1
  70. package/.claude/skills/skills-manifest.json +1 -1
  71. package/.claude/skills/test-automation-strategy/evals/test-automation-strategy.yaml +1 -1
  72. package/.claude/skills/test-data-management/evals/test-data-management.yaml +1 -1
  73. package/.claude/skills/test-design-techniques/evals/test-design-techniques.yaml +1 -1
  74. package/.claude/skills/test-reporting-analytics/evals/test-reporting-analytics.yaml +1 -1
  75. package/.claude/skills/testability-scoring/evals/testability-scoring.yaml +1 -1
  76. package/.claude/skills/validation-pipeline/evals/validation-pipeline.yaml +1 -1
  77. package/.claude/skills/verification-quality/evals/verification-quality.yaml +1 -1
  78. package/.claude/skills/visual-testing-advanced/evals/visual-testing-advanced.yaml +1 -1
  79. package/.claude/skills/wms-testing-patterns/evals/wms-testing-patterns.yaml +1 -1
  80. package/.opencode/agents/collective-intelligence-coordinator.yaml +1 -1
  81. package/.opencode/agents/ddd-domain-expert.yaml +1 -1
  82. package/.opencode/agents/memory-specialist.yaml +1 -1
  83. package/.opencode/agents/performance-engineer.yaml +1 -1
  84. package/.opencode/agents/qe-accessibility-auditor.yaml +1 -1
  85. package/.opencode/agents/qe-api-contract-validator.yaml +1 -1
  86. package/.opencode/agents/qe-bdd-generator.yaml +1 -1
  87. package/.opencode/agents/qe-chaos-engineer.yaml +1 -1
  88. package/.opencode/agents/qe-code-complexity.yaml +1 -1
  89. package/.opencode/agents/qe-code-intelligence.yaml +1 -1
  90. package/.opencode/agents/qe-coverage-analyzer.yaml +1 -1
  91. package/.opencode/agents/qe-defect-predictor.yaml +1 -1
  92. package/.opencode/agents/qe-dependency-mapper.yaml +1 -1
  93. package/.opencode/agents/qe-deployment-advisor.yaml +1 -1
  94. package/.opencode/agents/qe-devils-advocate.yaml +1 -1
  95. package/.opencode/agents/qe-flaky-hunter.yaml +1 -1
  96. package/.opencode/agents/qe-fleet-commander.yaml +1 -1
  97. package/.opencode/agents/qe-gap-detector.yaml +1 -1
  98. package/.opencode/agents/qe-graphql-tester.yaml +1 -1
  99. package/.opencode/agents/qe-impact-analyzer.yaml +1 -1
  100. package/.opencode/agents/qe-integration-architect.yaml +1 -1
  101. package/.opencode/agents/qe-integration-tester.yaml +1 -1
  102. package/.opencode/agents/qe-kg-builder.yaml +1 -1
  103. package/.opencode/agents/qe-learning-coordinator.yaml +1 -1
  104. package/.opencode/agents/qe-load-tester.yaml +1 -1
  105. package/.opencode/agents/qe-message-broker-tester.yaml +1 -1
  106. package/.opencode/agents/qe-metrics-optimizer.yaml +1 -1
  107. package/.opencode/agents/qe-middleware-validator.yaml +1 -1
  108. package/.opencode/agents/qe-mutation-tester.yaml +1 -1
  109. package/.opencode/agents/qe-odata-contract-tester.yaml +1 -1
  110. package/.opencode/agents/qe-parallel-executor.yaml +1 -1
  111. package/.opencode/agents/qe-pattern-learner.yaml +1 -1
  112. package/.opencode/agents/qe-pentest-validator.yaml +1 -1
  113. package/.opencode/agents/qe-performance-tester.yaml +1 -1
  114. package/.opencode/agents/qe-product-factors-assessor.yaml +1 -1
  115. package/.opencode/agents/qe-property-tester.yaml +1 -1
  116. package/.opencode/agents/qe-quality-criteria-recommender.yaml +1 -1
  117. package/.opencode/agents/qe-quality-gate.yaml +1 -1
  118. package/.opencode/agents/qe-queen-coordinator.yaml +1 -1
  119. package/.opencode/agents/qe-qx-partner.yaml +1 -1
  120. package/.opencode/agents/qe-regression-analyzer.yaml +1 -1
  121. package/.opencode/agents/qe-requirements-validator.yaml +1 -1
  122. package/.opencode/agents/qe-responsive-tester.yaml +1 -1
  123. package/.opencode/agents/qe-retry-handler.yaml +1 -1
  124. package/.opencode/agents/qe-risk-assessor.yaml +1 -1
  125. package/.opencode/agents/qe-root-cause-analyzer.yaml +1 -1
  126. package/.opencode/agents/qe-sap-idoc-tester.yaml +1 -1
  127. package/.opencode/agents/qe-sap-rfc-tester.yaml +1 -1
  128. package/.opencode/agents/qe-security-auditor.yaml +1 -1
  129. package/.opencode/agents/qe-security-scanner.yaml +1 -1
  130. package/.opencode/agents/qe-soap-tester.yaml +1 -1
  131. package/.opencode/agents/qe-sod-analyzer.yaml +1 -1
  132. package/.opencode/agents/qe-tdd-specialist.yaml +1 -1
  133. package/.opencode/agents/qe-test-generator.yaml +1 -1
  134. package/.opencode/agents/qe-test-idea-rewriter.yaml +1 -1
  135. package/.opencode/agents/qe-transfer-specialist.yaml +1 -1
  136. package/.opencode/agents/qe-visual-tester.yaml +1 -1
  137. package/.opencode/agents/security-architect.yaml +1 -1
  138. package/.opencode/agents/security-auditor.yaml +1 -1
  139. package/CHANGELOG.md +204 -0
  140. package/README.md +7 -2
  141. package/assets/agents/v3/helpers/advisor-call.cjs +3 -3
  142. package/assets/agents/v3/qe-coverage-specialist.md +1 -1
  143. package/assets/agents/v3/qe-fleet-commander.md +1 -1
  144. package/assets/agents/v3/qe-pentest-validator.md +1 -1
  145. package/assets/agents/v3/qe-queen-coordinator.md +1 -1
  146. package/assets/agents/v3/qe-risk-assessor.md +1 -1
  147. package/assets/agents/v3/qe-root-cause-analyzer.md +1 -1
  148. package/assets/agents/v3/qe-security-auditor.md +1 -1
  149. package/assets/agents/v3/qe-test-architect.md +1 -1
  150. package/assets/skills/.validation/examples/chaos-engineering-output.example.json +1 -1
  151. package/assets/skills/.validation/examples/performance-testing-output.example.json +1 -1
  152. package/assets/skills/.validation/examples/security-testing-output.example.json +1 -1
  153. package/assets/skills/.validation/examples/testability-scoring-output.example.json +1 -1
  154. package/assets/skills/.validation/schemas/skill-eval.schema.json +4 -1
  155. package/assets/skills/.validation/schemas/skill-frontmatter.schema.json +1 -1
  156. package/assets/skills/.validation/schemas/skill-output.template.json +1 -1
  157. package/assets/skills/.validation/templates/eval.template.yaml +1 -1
  158. package/assets/skills/.validation/templates/security-testing-eval.template.yaml +1 -1
  159. package/assets/skills/.validation/templates/skill-frontmatter.example.yaml +1 -1
  160. package/assets/skills/.validation/test-data/sample-output.json +1 -1
  161. package/assets/skills/a11y-ally/SKILL.md +1 -1
  162. package/assets/skills/a11y-ally/evals/a11y-ally.yaml +1 -1
  163. package/assets/skills/accessibility-testing/evals/accessibility-testing.yaml +1 -1
  164. package/assets/skills/api-testing-patterns/evals/api-testing-patterns.yaml +1 -1
  165. package/assets/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +1 -1
  166. package/assets/skills/cicd-pipeline-qe-orchestrator/evals/cicd-pipeline-qe-orchestrator.yaml +1 -1
  167. package/assets/skills/compatibility-testing/evals/compatibility-testing.yaml +1 -1
  168. package/assets/skills/compliance-testing/evals/compliance-testing.yaml +1 -1
  169. package/assets/skills/contract-testing/evals/contract-testing.yaml +1 -1
  170. package/assets/skills/database-testing/evals/database-testing.yaml +1 -1
  171. package/assets/skills/enterprise-integration-testing/evals/enterprise-integration-testing.yaml +1 -1
  172. package/assets/skills/localization-testing/evals/localization-testing.yaml +1 -1
  173. package/assets/skills/middleware-testing-patterns/evals/middleware-testing-patterns.yaml +1 -1
  174. package/assets/skills/mobile-testing/evals/mobile-testing.yaml +1 -1
  175. package/assets/skills/mutation-testing/evals/mutation-testing.yaml +1 -1
  176. package/assets/skills/mutation-testing/test-data/sample-output.json +1 -1
  177. package/assets/skills/n8n-expression-testing/evals/n8n-expression-testing.yaml +1 -1
  178. package/assets/skills/n8n-integration-testing-patterns/evals/n8n-integration-testing-patterns.yaml +1 -1
  179. package/assets/skills/n8n-security-testing/evals/n8n-security-testing.yaml +1 -1
  180. package/assets/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +1 -1
  181. package/assets/skills/n8n-workflow-testing-fundamentals/evals/n8n-workflow-testing-fundamentals.yaml +1 -1
  182. package/assets/skills/observability-testing-patterns/evals/observability-testing-patterns.yaml +1 -1
  183. package/assets/skills/pentest-validation/evals/pentest-validation.yaml +1 -1
  184. package/assets/skills/performance-testing/evals/performance-testing.yaml +1 -1
  185. package/assets/skills/qcsd-cicd-swarm/evals/qcsd-cicd-swarm.yaml +1 -1
  186. package/assets/skills/qcsd-development-swarm/evals/qcsd-development-swarm.yaml +1 -1
  187. package/assets/skills/qcsd-ideation-swarm/evals/qcsd-ideation-swarm.yaml +1 -1
  188. package/assets/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +1 -1
  189. package/assets/skills/qcsd-refinement-swarm/evals/qcsd-refinement-swarm.yaml +1 -1
  190. package/assets/skills/qe-browser/evals/qe-browser.yaml +1 -1
  191. package/assets/skills/qe-chaos-resilience/evals/qe-chaos-resilience.yaml +1 -1
  192. package/assets/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +1 -1
  193. package/assets/skills/qe-coverage-analysis/evals/qe-coverage-analysis.yaml +1 -1
  194. package/assets/skills/qe-defect-intelligence/evals/qe-defect-intelligence.yaml +1 -1
  195. package/assets/skills/qe-learning-optimization/evals/qe-learning-optimization.yaml +2 -2
  196. package/assets/skills/qe-quality-assessment/evals/qe-quality-assessment.yaml +1 -1
  197. package/assets/skills/qe-requirements-validation/evals/qe-requirements-validation.yaml +1 -1
  198. package/assets/skills/qe-test-execution/evals/qe-test-execution.yaml +1 -1
  199. package/assets/skills/qe-test-generation/evals/qe-test-generation.yaml +1 -1
  200. package/assets/skills/qe-visual-accessibility/evals/qe-visual-accessibility.yaml +1 -1
  201. package/assets/skills/quality-metrics/evals/quality-metrics.yaml +1 -1
  202. package/assets/skills/regression-testing/evals/regression-testing.yaml +1 -1
  203. package/assets/skills/risk-based-testing/evals/risk-based-testing.yaml +1 -1
  204. package/assets/skills/security-testing/evals/security-testing.yaml +1 -1
  205. package/assets/skills/security-visual-testing/evals/security-visual-testing.yaml +1 -1
  206. package/assets/skills/shift-left-testing/evals/shift-left-testing.yaml +1 -1
  207. package/assets/skills/shift-right-testing/evals/shift-right-testing.yaml +1 -1
  208. package/assets/skills/skills-manifest.json +1 -1
  209. package/assets/skills/test-automation-strategy/evals/test-automation-strategy.yaml +1 -1
  210. package/assets/skills/test-data-management/evals/test-data-management.yaml +1 -1
  211. package/assets/skills/test-design-techniques/evals/test-design-techniques.yaml +1 -1
  212. package/assets/skills/test-reporting-analytics/evals/test-reporting-analytics.yaml +1 -1
  213. package/assets/skills/testability-scoring/evals/testability-scoring.yaml +1 -1
  214. package/assets/skills/validation-pipeline/evals/validation-pipeline.yaml +1 -1
  215. package/assets/skills/verification-quality/evals/verification-quality.yaml +1 -1
  216. package/assets/skills/visual-testing-advanced/evals/visual-testing-advanced.yaml +1 -1
  217. package/assets/skills/wms-testing-patterns/evals/wms-testing-patterns.yaml +1 -1
  218. package/dist/audit/witness-chain.d.ts +1 -1
  219. package/dist/audit/witness-chain.js +29 -22
  220. package/dist/cli/bundle.js +13 -10
  221. package/dist/cli/chunks/adapter-IYC62SXA.js +2 -0
  222. package/dist/cli/chunks/{agent-booster-wasm-TQOMLWWX.js → agent-booster-wasm-EDNKP3SP.js} +2 -2
  223. package/dist/cli/chunks/{agent-handler-Q3SEMMI2.js → agent-handler-V6CZ7Q6S.js} +2 -2
  224. package/dist/cli/chunks/{agent-memory-branch-SJXAQSZI.js → agent-memory-branch-ZMD6ULC3.js} +2 -2
  225. package/dist/cli/chunks/aqe-learning-engine-LLOU2IXD.js +2 -0
  226. package/dist/cli/chunks/{arena-7RC7TBGW.js → arena-4UPAEHFT.js} +4 -4
  227. package/dist/cli/chunks/{arena-UPB7TKUY.js → arena-QLSBESC7.js} +2 -2
  228. package/dist/cli/chunks/{audit-IXN5R4WB.js → audit-CVZQMF55.js} +3 -3
  229. package/dist/cli/chunks/base-P3Z4IKCT.js +2 -0
  230. package/dist/cli/chunks/{better-sqlite3-RP4DEGK3.js → better-sqlite3-4DSBPDRH.js} +2 -2
  231. package/dist/cli/chunks/brain-handler-GBY4EZ4P.js +94 -0
  232. package/dist/cli/chunks/{branch-enumerator-VPRWDGFJ.js → branch-enumerator-XYBVXCNO.js} +2 -2
  233. package/dist/cli/chunks/{browser-B6E7JPPJ.js → browser-32F6MREU.js} +2 -2
  234. package/dist/cli/chunks/browser-workflow-YYHQQ25X.js +2 -0
  235. package/dist/cli/chunks/{chunk-HOQQCY2K.js → chunk-2JGEZHWY.js} +2 -2
  236. package/dist/cli/chunks/{chunk-NN76NTOX.js → chunk-2KJQ2UQE.js} +1 -1
  237. package/dist/cli/chunks/{chunk-D4Z2N74A.js → chunk-2OMLTYQK.js} +1 -1
  238. package/dist/cli/chunks/chunk-37TUN44F.js +4 -0
  239. package/dist/cli/chunks/{chunk-LVLBIKJD.js → chunk-3DDXWYMO.js} +1 -1
  240. package/dist/cli/chunks/{chunk-UHQY3GK7.js → chunk-3EZ5DR2R.js} +3 -3
  241. package/dist/cli/chunks/{chunk-3P6NCFI2.js → chunk-3KDL6QDK.js} +2 -2
  242. package/dist/cli/chunks/{chunk-SG47AXJG.js → chunk-3VIXOHMS.js} +1 -1
  243. package/dist/cli/chunks/{chunk-7FYMDKQH.js → chunk-3YUB5HER.js} +165 -167
  244. package/dist/cli/chunks/chunk-4FWTLJEP.js +16 -0
  245. package/dist/cli/chunks/{chunk-PI74GOE4.js → chunk-52L77RMG.js} +2 -2
  246. package/dist/cli/chunks/{chunk-LS3EUMBP.js → chunk-5D36YHS3.js} +5 -5
  247. package/dist/cli/chunks/{chunk-EY4OQHU3.js → chunk-5WOSWNDN.js} +1 -1
  248. package/dist/cli/chunks/{chunk-F67AV5P2.js → chunk-67YV75XP.js} +2 -2
  249. package/dist/cli/chunks/{chunk-IP7NSFQQ.js → chunk-6A44AOGN.js} +2 -2
  250. package/dist/cli/chunks/{chunk-3ABRGG3C.js → chunk-6CR4VQBQ.js} +2 -2
  251. package/dist/cli/chunks/chunk-6ITZZIQX.js +2 -0
  252. package/dist/cli/chunks/{chunk-7BUERZYL.js → chunk-6LKDHEBY.js} +2 -2
  253. package/dist/cli/chunks/{chunk-FKG5OQFT.js → chunk-6TU7FEMD.js} +1 -1
  254. package/dist/cli/chunks/{chunk-KF63AYXD.js → chunk-6VAZAHQG.js} +2 -2
  255. package/dist/cli/chunks/{chunk-XXCYQXK3.js → chunk-73EI4C2E.js} +2 -2
  256. package/dist/cli/chunks/chunk-75QJ5HWE.js +14 -0
  257. package/dist/cli/chunks/{chunk-72UJXEKQ.js → chunk-7CD7PBHY.js} +2 -2
  258. package/dist/cli/chunks/chunk-7DETTOPZ.js +14 -0
  259. package/dist/cli/chunks/{chunk-7JQHPANT.js → chunk-7JZJJA7U.js} +3 -3
  260. package/dist/cli/chunks/{chunk-5Y5TC6BY.js → chunk-7VFY7TUR.js} +2 -2
  261. package/dist/cli/chunks/chunk-7X7JYWT4.js +27 -0
  262. package/dist/cli/chunks/chunk-AF4XKLXO.js +2 -0
  263. package/dist/cli/chunks/{chunk-7SLAZAVU.js → chunk-AFEDJ3RU.js} +2 -2
  264. package/dist/cli/chunks/{chunk-ZUG5MOUB.js → chunk-AMMQOV35.js} +2 -2
  265. package/dist/cli/chunks/{chunk-ZN3J6TZD.js → chunk-BHFR2EXL.js} +1 -1
  266. package/dist/cli/chunks/{chunk-HXE5NBJG.js → chunk-BJPL6THQ.js} +1 -1
  267. package/dist/cli/chunks/{chunk-37BASGWC.js → chunk-BXVAVFGU.js} +2 -2
  268. package/dist/cli/chunks/{chunk-VWNHKYK7.js → chunk-BYG36QC5.js} +2 -2
  269. package/dist/cli/chunks/chunk-C3HQL6S4.js +2 -0
  270. package/dist/cli/chunks/{chunk-OY7MLMEX.js → chunk-C3Z4VVHP.js} +5 -5
  271. package/dist/cli/chunks/{chunk-CB5JPRIZ.js → chunk-CPC7FN52.js} +2 -2
  272. package/dist/cli/chunks/{chunk-OVDKWCD7.js → chunk-CVMNJSCB.js} +2 -2
  273. package/dist/cli/chunks/{chunk-N4H2QOT5.js → chunk-CYE2TJFV.js} +2 -2
  274. package/dist/cli/chunks/{chunk-YCBDE2N7.js → chunk-CZO4BJG5.js} +2 -2
  275. package/dist/cli/chunks/{chunk-YEXPFHV6.js → chunk-D6OUCB2H.js} +2 -2
  276. package/dist/cli/chunks/{chunk-JRYZKBY2.js → chunk-DDCIYOGT.js} +2 -2
  277. package/dist/cli/chunks/{chunk-XX7HUSX2.js → chunk-DKUBQQFG.js} +2 -2
  278. package/dist/cli/chunks/{chunk-SGXSB7YO.js → chunk-DLF5BOJD.js} +1 -1
  279. package/dist/cli/chunks/{chunk-5BLFXQEB.js → chunk-DO6EI5KB.js} +1 -1
  280. package/dist/cli/chunks/{chunk-33VPWGCM.js → chunk-DPBRWP4J.js} +3 -3
  281. package/dist/cli/chunks/{chunk-H6XBM2LY.js → chunk-E3W6XQ57.js} +2 -2
  282. package/dist/cli/chunks/{chunk-KPMGTVB4.js → chunk-E4AZXCT5.js} +1 -1
  283. package/dist/cli/chunks/chunk-E4EYPYR3.js +2 -0
  284. package/dist/cli/chunks/{chunk-TFHQE6NK.js → chunk-EFV4ADMO.js} +4 -4
  285. package/dist/cli/chunks/{chunk-VIDBBB6F.js → chunk-ELBZON4V.js} +2 -2
  286. package/dist/cli/chunks/chunk-EOR2UT72.js +2 -0
  287. package/dist/cli/chunks/{chunk-H5ZRV5K5.js → chunk-F34OAHOM.js} +2 -2
  288. package/dist/cli/chunks/{chunk-UMENRGHK.js → chunk-FUNGTIF2.js} +2 -2
  289. package/dist/cli/chunks/{chunk-DBA3N742.js → chunk-G3L5L6YQ.js} +1 -1
  290. package/dist/cli/chunks/{chunk-ELU4IC3I.js → chunk-G3W6BMVJ.js} +1 -1
  291. package/dist/cli/chunks/{chunk-RTJ2M6V6.js → chunk-GTKCGPJZ.js} +3 -3
  292. package/dist/cli/chunks/chunk-HBCGYMQU.js +2 -0
  293. package/dist/cli/chunks/{chunk-YL7T3VV7.js → chunk-HSVKZ5KI.js} +4 -4
  294. package/dist/cli/chunks/{chunk-MXMFGSWR.js → chunk-HVU64GP5.js} +2 -2
  295. package/dist/cli/chunks/chunk-HVXJC3OC.js +2 -0
  296. package/dist/cli/chunks/chunk-HYEJJJY3.js +4 -0
  297. package/dist/cli/chunks/{chunk-CR3QGHVN.js → chunk-I2NENQ44.js} +2 -2
  298. package/dist/cli/chunks/{chunk-GNTVFN7D.js → chunk-I6X3EGJI.js} +1 -1
  299. package/dist/cli/chunks/{chunk-2GNRW3OD.js → chunk-IGBEJ4UJ.js} +2 -2
  300. package/dist/cli/chunks/{chunk-UYJHYMEQ.js → chunk-IIAR5S7Q.js} +2 -2
  301. package/dist/cli/chunks/{chunk-YAKS3CAB.js → chunk-IJHCIXJC.js} +2 -2
  302. package/dist/cli/chunks/{chunk-YDNSLLBS.js → chunk-IUDWEOLX.js} +2 -2
  303. package/dist/cli/chunks/chunk-IUHB5GVS.js +3 -0
  304. package/dist/cli/chunks/{chunk-4UDZLD42.js → chunk-IYTLXUBO.js} +2 -2
  305. package/dist/cli/chunks/chunk-J27F4NSB.js +2 -0
  306. package/dist/cli/chunks/{chunk-HRUU7E3D.js → chunk-J5UNP6W3.js} +2 -2
  307. package/dist/cli/chunks/{chunk-E3FBW6G2.js → chunk-JES6R5KP.js} +1 -1
  308. package/dist/cli/chunks/chunk-JROVR6YS.js +11 -0
  309. package/dist/cli/chunks/chunk-JSZ663MU.js +2 -0
  310. package/dist/cli/chunks/{chunk-FUE6LL72.js → chunk-JVQBWYHW.js} +2 -2
  311. package/dist/cli/chunks/{chunk-G6ZHTF42.js → chunk-K27SU3RE.js} +2 -2
  312. package/dist/cli/chunks/chunk-K7NJHFLZ.js +54 -0
  313. package/dist/cli/chunks/{chunk-MDZ6RRLX.js → chunk-KEY43ANX.js} +2 -2
  314. package/dist/cli/chunks/chunk-KIP6WZGV.js +13 -0
  315. package/dist/cli/chunks/{chunk-SQ3PPISY.js → chunk-KKHYJF5U.js} +1 -1
  316. package/dist/cli/chunks/{chunk-TJEIOE7F.js → chunk-KLTP5IDB.js} +1 -1
  317. package/dist/cli/chunks/{chunk-IKIITGU5.js → chunk-KO4FNAUR.js} +4 -4
  318. package/dist/cli/chunks/{chunk-DX3C5HPN.js → chunk-KYA5LARK.js} +1 -1
  319. package/dist/cli/chunks/{chunk-ZHXWGNYM.js → chunk-LSUILON7.js} +1 -1
  320. package/dist/cli/chunks/chunk-LULD4JV2.js +15 -0
  321. package/dist/cli/chunks/{chunk-MWWAMDHI.js → chunk-M23ZOZVY.js} +1 -1
  322. package/dist/cli/chunks/{chunk-RKJZWWB7.js → chunk-M5AEL7IS.js} +2 -2
  323. package/dist/cli/chunks/chunk-MI5Q55DG.js +65 -0
  324. package/dist/cli/chunks/chunk-N7H767TP.js +4 -0
  325. package/dist/cli/chunks/{chunk-5F6DWHQG.js → chunk-NQI7FWCS.js} +2 -2
  326. package/dist/cli/chunks/{chunk-LLVGTEHU.js → chunk-NRE4NAVA.js} +1 -1
  327. package/dist/cli/chunks/{chunk-XA7CG3LH.js → chunk-NU7UTXMP.js} +2 -2
  328. package/dist/cli/chunks/chunk-NVYBM3R4.js +2 -0
  329. package/dist/cli/chunks/chunk-O3JTQ7N4.js +2 -0
  330. package/dist/cli/chunks/{chunk-TISSZFHO.js → chunk-OEIQTWQP.js} +1 -1
  331. package/dist/cli/chunks/{chunk-2IGT5WNQ.js → chunk-PSPKSUF6.js} +1 -1
  332. package/dist/cli/chunks/{chunk-B7SWW5A6.js → chunk-QIRL6B3C.js} +2 -2
  333. package/dist/cli/chunks/{chunk-JBB7E26R.js → chunk-QRCIZFNK.js} +2 -2
  334. package/dist/cli/chunks/{chunk-4JBFJTHJ.js → chunk-QWUXCG2L.js} +1 -1
  335. package/dist/cli/chunks/{chunk-B5XFDFBT.js → chunk-QYOGD2VW.js} +1 -1
  336. package/dist/cli/chunks/chunk-QZMUXJHZ.js +2 -0
  337. package/dist/cli/chunks/chunk-R6IU3EWP.js +2 -0
  338. package/dist/cli/chunks/{chunk-G5C2XVZC.js → chunk-R74ZKREV.js} +1 -1
  339. package/dist/cli/chunks/chunk-RD2VGOUH.js +2 -0
  340. package/dist/cli/chunks/{chunk-OV5EZO3U.js → chunk-RD6TEZ64.js} +2 -2
  341. package/dist/cli/chunks/{chunk-4C6UJIHB.js → chunk-RGGK6VZ7.js} +1 -1
  342. package/dist/cli/chunks/{chunk-4XPPMADQ.js → chunk-RIZVC4XY.js} +6 -6
  343. package/dist/cli/chunks/{chunk-4RP5VUBI.js → chunk-RKOUXVZZ.js} +2 -2
  344. package/dist/cli/chunks/{chunk-IFFZR6GY.js → chunk-RP2ZKPYV.js} +1 -1
  345. package/dist/cli/chunks/{chunk-BN7DKW5D.js → chunk-SQF6HRXR.js} +1 -1
  346. package/dist/cli/chunks/chunk-SQKW3B6B.js +2 -0
  347. package/dist/cli/chunks/{chunk-LKN7JQTW.js → chunk-SX4JLSLV.js} +2 -2
  348. package/dist/cli/chunks/{chunk-YGB6R5DW.js → chunk-TUSSPKRM.js} +1 -1
  349. package/dist/cli/chunks/{chunk-LHGNNZ76.js → chunk-TY5WC3FT.js} +3 -3
  350. package/dist/cli/chunks/{chunk-B2ZONZPZ.js → chunk-UDHVCKGA.js} +2 -2
  351. package/dist/cli/chunks/{chunk-IU4EBTA2.js → chunk-UJWAWIRV.js} +4 -4
  352. package/dist/cli/chunks/{chunk-LTBCAFTZ.js → chunk-UKGXWW64.js} +3 -3
  353. package/dist/cli/chunks/{chunk-JV4FZUE7.js → chunk-UMGFMKDW.js} +2 -2
  354. package/dist/cli/chunks/{chunk-STRDSVH3.js → chunk-URVHZPWY.js} +2 -2
  355. package/dist/cli/chunks/{chunk-PZTVH2AS.js → chunk-UTBYJ4RF.js} +2 -2
  356. package/dist/cli/chunks/{chunk-ZK5JKHP4.js → chunk-VD5IO5EO.js} +1 -1
  357. package/dist/cli/chunks/chunk-VTOVWHEM.js +2 -0
  358. package/dist/cli/chunks/{chunk-OYMLHX2B.js → chunk-W2XCZU62.js} +1 -1
  359. package/dist/cli/chunks/{chunk-T35GZXTU.js → chunk-WJHWH5D2.js} +2 -2
  360. package/dist/cli/chunks/{chunk-NBWQBQO5.js → chunk-WJTSY5MC.js} +1 -1
  361. package/dist/cli/chunks/{chunk-NTSXHZTC.js → chunk-WK7B4B6Y.js} +4 -4
  362. package/dist/cli/chunks/{chunk-2WT7AKKK.js → chunk-WLXK2KNU.js} +2 -2
  363. package/dist/cli/chunks/chunk-WOIGKU2N.js +180 -0
  364. package/dist/cli/chunks/{chunk-WYMGK5DX.js → chunk-WX6RRIGW.js} +2 -2
  365. package/dist/cli/chunks/{chunk-C46DMCWF.js → chunk-XEZIIQYJ.js} +2 -2
  366. package/dist/cli/chunks/{chunk-TTMHIOQ3.js → chunk-XFPPERA2.js} +2 -2
  367. package/dist/cli/chunks/{chunk-OVPJQWHW.js → chunk-XLAUGSW7.js} +2 -2
  368. package/dist/cli/chunks/{chunk-V4AOVDCJ.js → chunk-XQSIRBKT.js} +8 -8
  369. package/dist/cli/chunks/{chunk-4Q35TI6Z.js → chunk-XUR2M2WB.js} +2 -2
  370. package/dist/cli/chunks/{chunk-5IAB5NRZ.js → chunk-XZSMZHM2.js} +2 -2
  371. package/dist/cli/chunks/{chunk-AB4U6ZNI.js → chunk-Y5L3ES4L.js} +2 -2
  372. package/dist/cli/chunks/chunk-YDFL445W.js +2 -0
  373. package/dist/cli/chunks/{chunk-7G6UX2QN.js → chunk-YQGPQBCX.js} +2 -2
  374. package/dist/cli/chunks/{chunk-5FOZO7KM.js → chunk-YXP6BKGS.js} +46 -46
  375. package/dist/cli/chunks/chunk-ZBABIZ2D.js +2 -0
  376. package/dist/cli/chunks/{chunk-IQEJGZV6.js → chunk-ZCWERUYB.js} +4 -4
  377. package/dist/cli/chunks/ci-RACDAJMR.js +81 -0
  378. package/dist/cli/chunks/{ci-output-LK3MBXLZ.js → ci-output-EHRSZBKG.js} +2 -2
  379. package/dist/cli/chunks/{circuit-breaker-7AIXACR7.js → circuit-breaker-GBV7M5XG.js} +2 -2
  380. package/dist/cli/chunks/{claude-flow-setup-UA7EO6VN.js → claude-flow-setup-5LVJOFKP.js} +2 -2
  381. package/dist/cli/chunks/client-HUVFA5PF.js +2 -0
  382. package/dist/cli/chunks/{cline-installer-YDDCKKEV.js → cline-installer-W4NMXJSG.js} +2 -2
  383. package/dist/cli/chunks/{code-URB7UAKW.js → code-JWXJMYXB.js} +29 -29
  384. package/dist/cli/chunks/{code-index-extractor-BL6HWH4Q.js → code-index-extractor-RVI2IFTM.js} +2 -2
  385. package/dist/cli/chunks/codex-installer-3BORJINH.js +14 -0
  386. package/dist/cli/chunks/{completions-RCKBSSSS.js → completions-A55NCTAO.js} +2 -2
  387. package/dist/cli/chunks/complexity-analyzer-JCXHGGLY.js +2 -0
  388. package/dist/cli/chunks/{continuedev-installer-VOTCEBFH.js → continuedev-installer-PUVFMGYW.js} +2 -2
  389. package/dist/cli/chunks/{copilot-installer-NVTGLZX3.js → copilot-installer-4DCMYWHB.js} +2 -2
  390. package/dist/cli/chunks/core-handlers-UEXO3VAA.js +2 -0
  391. package/dist/cli/chunks/cost-tracker-5TV2GGKY.js +2 -0
  392. package/dist/cli/chunks/{coverage-ZTPJWXWE.js → coverage-NNWM7TX3.js} +3 -3
  393. package/dist/cli/chunks/cross-domain-router-ODU5IZD6.js +2 -0
  394. package/dist/cli/chunks/{cursor-installer-CMGJQMHX.js → cursor-installer-4NCHGJGK.js} +2 -2
  395. package/dist/cli/chunks/{daemon-Y2I3YVIU.js → daemon-QIKCXKWO.js} +4 -4
  396. package/dist/cli/chunks/{daemon-V456IWR3.js → daemon-T4JO4IXP.js} +3 -3
  397. package/dist/cli/chunks/{dag-attention-scheduler-ZCBBOD3D.js → dag-attention-scheduler-RPAAIDAD.js} +2 -2
  398. package/dist/cli/chunks/{detect-2GHEA4A3.js → detect-SBEEVDSN.js} +2 -2
  399. package/dist/cli/chunks/{dist-node-44AGYJCH.js → dist-node-ZHI6NCSU.js} +2 -2
  400. package/dist/cli/chunks/{domain-handler-IDLIEP6X.js → domain-handler-LBC3GJ7Z.js} +2 -2
  401. package/dist/cli/chunks/domain-plugins-H6IZ5USZ.js +2 -0
  402. package/dist/cli/chunks/{domain-transfer-KLEXGIRF.js → domain-transfer-JZA5TMW3.js} +2 -2
  403. package/dist/cli/chunks/dream-HE3OX42F.js +2 -0
  404. package/dist/cli/chunks/embed-and-insert-pattern-AHTR7CRU.js +3 -0
  405. package/dist/cli/chunks/eval-DZU2KISM.js +17 -0
  406. package/dist/cli/chunks/{experience-capture-middleware-CJJJN7CF.js → experience-capture-middleware-5IQCWKSL.js} +4 -4
  407. package/dist/cli/chunks/{fast-paths-LGLLKX6P.js → fast-paths-2KLDUWCY.js} +2 -2
  408. package/dist/cli/chunks/{feature-flags-33D3I4DD.js → feature-flags-7AC3XDZA.js} +2 -2
  409. package/dist/cli/chunks/{feature-flags-QL4NCEGW.js → feature-flags-N6UAEZY4.js} +2 -2
  410. package/dist/cli/chunks/{file-discovery-GKCYJPFZ.js → file-discovery-5SDIW4V2.js} +2 -2
  411. package/dist/cli/chunks/fleet-ZIQCAZ2Y.js +43 -0
  412. package/dist/cli/chunks/{gnn-wrapper-ELSGT67Z.js → gnn-wrapper-DUMBZJEV.js} +2 -2
  413. package/dist/cli/chunks/{heartbeat-handler-ZUI3DOOP.js → heartbeat-handler-6HVM6ZMR.js} +4 -4
  414. package/dist/cli/chunks/heartbeat-scheduler-QUIFGGLX.js +2 -0
  415. package/dist/cli/chunks/hnsw-adapter-42KB37KP.js +2 -0
  416. package/dist/cli/chunks/hnsw-index-T2PGO77J.js +2 -0
  417. package/dist/cli/chunks/{hnsw-legacy-bridge-EZMM5JWL.js → hnsw-legacy-bridge-5DRL5FLX.js} +2 -2
  418. package/dist/cli/chunks/{hnswlib-node-G4CE3EOS.js → hnswlib-node-GW67GTCL.js} +2 -2
  419. package/dist/cli/chunks/{hooks-LCVXXA55.js → hooks-QHH6FVO4.js} +10 -10
  420. package/dist/cli/chunks/hybrid-backend-FRNWYRKH.js +2 -0
  421. package/dist/cli/chunks/{hypergraph-engine-6Z7RQ3HI.js → hypergraph-engine-7XDCCVG2.js} +2 -2
  422. package/dist/cli/chunks/{hypergraph-handler-PLI2GYPK.js → hypergraph-handler-QHF7NOU5.js} +3 -3
  423. package/dist/cli/chunks/impact-analyzer-A5QYOYBR.js +2 -0
  424. package/dist/cli/chunks/{init-handler-7VH3QJ5Y.js → init-handler-5UIVOM7K.js} +6 -6
  425. package/dist/cli/chunks/init-wizard-XBU674YH.js +2 -0
  426. package/dist/cli/chunks/kernel-DV5MTNZD.js +2 -0
  427. package/dist/cli/chunks/{kilocode-installer-U3MW62DE.js → kilocode-installer-TGGV6K5Q.js} +2 -2
  428. package/dist/cli/chunks/{kiro-installer-PPEAC44T.js → kiro-installer-4XYBHZWW.js} +12 -12
  429. package/dist/cli/chunks/knowledge-graph-4ACGVJQK.js +2 -0
  430. package/dist/cli/chunks/learning-STE5W6BS.js +122 -0
  431. package/dist/cli/chunks/llm-router-NKF7J3RI.js +37 -0
  432. package/dist/cli/chunks/llm-router-service-PSMASERT.js +2 -0
  433. package/dist/cli/chunks/{load-VO7ABNHV.js → load-B2T77UJQ.js} +2 -2
  434. package/dist/cli/chunks/load-test-MRUO2VPF.js +2 -0
  435. package/dist/cli/chunks/mcp-JGSFCEMH.js +2 -0
  436. package/dist/cli/chunks/{memory-FZTT7ADM.js → memory-WRFZKG56.js} +6 -6
  437. package/dist/cli/chunks/memory-backend-2MPGI6JW.js +2 -0
  438. package/dist/cli/chunks/memory-handlers-XT4HMITB.js +2 -0
  439. package/dist/cli/chunks/multi-model-executor-26Q5BSVG.js +14 -0
  440. package/dist/cli/chunks/{opencode-installer-GQ7J5SBG.js → opencode-installer-J36EMQU7.js} +2 -2
  441. package/dist/cli/chunks/{orchestrator-66JK2OS5.js → orchestrator-D5IFV65I.js} +20 -20
  442. package/dist/cli/chunks/pattern-null-store-TGWUL237.js +2 -0
  443. package/dist/cli/chunks/{pattern-usage-recorder-O6XHM2G5.js → pattern-usage-recorder-BVMTWI3E.js} +2 -2
  444. package/dist/cli/chunks/pipeline-OWAHDUAQ.js +19 -0
  445. package/dist/cli/chunks/platform-ANGBFWBV.js +2 -0
  446. package/dist/cli/chunks/{plugin-7OFLNGOS.js → plugin-OO7ON2YW.js} +2 -2
  447. package/dist/cli/chunks/{prime-radiant-advanced-wasm-OSRDK2FW.js → prime-radiant-advanced-wasm-HFG3BXWU.js} +2 -2
  448. package/dist/cli/chunks/project-root-LNOYVTYY.js +2 -0
  449. package/dist/cli/chunks/protocol-executor-GEVH5KD6.js +2 -0
  450. package/dist/cli/chunks/{protocol-handler-WLYTX6FS.js → protocol-handler-CE3Q6LY4.js} +2 -2
  451. package/dist/cli/chunks/{prove-QVNE4V3J.js → prove-7XPN53PY.js} +2 -2
  452. package/dist/cli/chunks/qe-reasoning-bank-DJ2JL6QB.js +2 -0
  453. package/dist/cli/chunks/{quality-DNE2RKE5.js → quality-TT23JRFX.js} +2 -2
  454. package/dist/cli/chunks/{quality-gate-2K35GCSI.js → quality-gate-PPPRP255.js} +3 -3
  455. package/dist/cli/chunks/queen-coordinator-F7E3AS26.js +2 -0
  456. package/dist/cli/chunks/real-embeddings-EYNZIFJE.js +2 -0
  457. package/dist/cli/chunks/ref-validation-QQR64ZXD.js +2 -0
  458. package/dist/cli/chunks/{roocode-installer-NCEZPF5L.js → roocode-installer-UIGS7ZJD.js} +2 -2
  459. package/dist/cli/chunks/router-OZH3QSAU.js +2 -0
  460. package/dist/cli/chunks/routing-feedback-J2E3ADZB.js +2 -0
  461. package/dist/cli/chunks/{routing-handler-4MXXZRYP.js → routing-handler-6AENUIRG.js} +4 -4
  462. package/dist/cli/chunks/{ruvector-commands-WDFMMCMK.js → ruvector-commands-5AWMEV34.js} +2 -2
  463. package/dist/cli/chunks/rvf-dual-writer-HK525Y5Y.js +2 -0
  464. package/dist/cli/chunks/rvf-migration-adapter-Q7FB3BKR.js +2 -0
  465. package/dist/cli/chunks/rvf-migration-coordinator-NWRJ7C22.js +2 -0
  466. package/dist/cli/chunks/rvf-native-adapter-5ZRCGUI6.js +2 -0
  467. package/dist/cli/chunks/rvf-store-integrity-ISKRP563.js +2 -0
  468. package/dist/cli/chunks/safe-db-3OYEPVEH.js +2 -0
  469. package/dist/cli/chunks/schedule-AG4C2EIQ.js +2 -0
  470. package/dist/cli/chunks/scheduler-SQS2CZFZ.js +2 -0
  471. package/dist/cli/chunks/{security-CJJ3WJSB.js → security-325A7FMB.js} +3 -3
  472. package/dist/cli/chunks/{shared-rvf-adapter-6RGCTLHD.js → shared-rvf-adapter-NFL6QSZ6.js} +2 -2
  473. package/dist/cli/chunks/{shared-rvf-dual-writer-KIA6Q6MT.js → shared-rvf-dual-writer-THFDYS2Z.js} +2 -2
  474. package/dist/cli/chunks/sqlite-persistence-MAKDFSHC.js +2 -0
  475. package/dist/cli/chunks/standalone-memory-UD4MJ6GZ.js +2 -0
  476. package/dist/cli/chunks/{status-handler-BADQV2KA.js → status-handler-CPFTN4XL.js} +2 -2
  477. package/dist/cli/chunks/{structural-health-VMYEYRZG.js → structural-health-2MG2IVBL.js} +2 -2
  478. package/dist/cli/chunks/{sync-PXLROLHB.js → sync-EE4VVKOW.js} +2 -2
  479. package/dist/cli/chunks/{sync-ULY7T5II.js → sync-MBTW5XBF.js} +2 -2
  480. package/dist/cli/chunks/task-handler-7H5OYJG4.js +54 -0
  481. package/dist/cli/chunks/task-handlers-NH4GJHCJ.js +9 -0
  482. package/dist/cli/chunks/{test-WCLURQUT.js → test-MPHGT4T6.js} +4 -4
  483. package/dist/cli/chunks/test-scheduling-CHQ4ZLLJ.js +15 -0
  484. package/dist/cli/chunks/token-bootstrap-SSDCYEKK.js +2 -0
  485. package/dist/cli/chunks/{token-usage-DRVG6PKO.js → token-usage-EBXUJNRB.js} +2 -2
  486. package/dist/cli/chunks/{transformers-IMDDAMYQ.js → transformers-ZEKS2OJZ.js} +2 -2
  487. package/dist/cli/chunks/{tree-sitter-wasm-parser-WBZIHVFA.js → tree-sitter-wasm-parser-J6ZMAK37.js} +2 -2
  488. package/dist/cli/chunks/types-KYAA5VLV.js +2 -0
  489. package/dist/cli/chunks/unified-memory-DDWMC435.js +2 -0
  490. package/dist/cli/chunks/unified-memory-hnsw-4JA7SGBK.js +2 -0
  491. package/dist/cli/chunks/unified-persistence-F6OSNTXY.js +2 -0
  492. package/dist/cli/chunks/{upgrade-6ALSDWDD.js → upgrade-UJBJ5AYM.js} +2 -2
  493. package/dist/cli/chunks/{validate-XF4ZG3LC.js → validate-RUV6YMWS.js} +2 -2
  494. package/dist/cli/chunks/{validate-swarm-P5TAFRDA.js → validate-swarm-IVEVMGVM.js} +2 -2
  495. package/dist/cli/chunks/{vibium-2XDXKNKZ.js → vibium-HOGMFJ2Z.js} +2 -2
  496. package/dist/cli/chunks/visual-security-25SMBIYT.js +2 -0
  497. package/dist/cli/chunks/{web-tree-sitter-4JVRQPX5.js → web-tree-sitter-AVWA6HKE.js} +2 -2
  498. package/dist/cli/chunks/{windsurf-installer-WYJXVDO5.js → windsurf-installer-DAH7HI2W.js} +2 -2
  499. package/dist/cli/chunks/{witness-chain-RPZ2SE2V.js → witness-chain-PJOQPFUX.js} +2 -2
  500. package/dist/cli/chunks/witness-chain-ZW6KKUZU.js +2 -0
  501. package/dist/cli/chunks/{witness-key-manager-LXG2VBQQ.js → witness-key-manager-JSTBMG43.js} +2 -2
  502. package/dist/cli/chunks/workflow-TWOIA6LZ.js +51 -0
  503. package/dist/cli/chunks/workflow-orchestrator-UKSIDM7Q.js +2 -0
  504. package/dist/cli/chunks/{wrappers-DIJNNFU6.js → wrappers-UR7BLXKV.js} +2 -2
  505. package/dist/cli/commands/ci.js +54 -28
  506. package/dist/cli/commands/code.js +6 -0
  507. package/dist/cli/commands/eval.js +3 -2
  508. package/dist/cli/commands/fleet.js +35 -16
  509. package/dist/cli/commands/learning-snapshot.d.ts +38 -0
  510. package/dist/cli/commands/learning-snapshot.js +171 -0
  511. package/dist/cli/commands/learning.js +16 -64
  512. package/dist/cli/commands/llm-router.js +13 -12
  513. package/dist/cli/commands/mcp.js +6 -0
  514. package/dist/cli/commands/memory.d.ts +1 -1
  515. package/dist/cli/commands/memory.js +8 -8
  516. package/dist/cli/commands/pipeline.js +9 -0
  517. package/dist/cli/commands/platform.js +15 -2
  518. package/dist/cli/commands/upgrade.d.ts +3 -3
  519. package/dist/cli/commands/upgrade.js +3 -3
  520. package/dist/cli/commands/workflow.js +9 -1
  521. package/dist/cli/handlers/init-handler.d.ts +10 -0
  522. package/dist/cli/handlers/task-handler.js +43 -12
  523. package/dist/cli/helpers/domain-plugins.d.ts +5 -0
  524. package/dist/cli/helpers/domain-plugins.js +11 -0
  525. package/dist/cli/helpers/standalone-memory.d.ts +12 -0
  526. package/dist/cli/helpers/standalone-memory.js +46 -0
  527. package/dist/cli/index.js +54 -49
  528. package/dist/cli/log-gate.d.ts +66 -0
  529. package/dist/cli/log-gate.js +170 -0
  530. package/dist/cli/utils/ci-config.d.ts +3 -0
  531. package/dist/context/sources/git-source.d.ts +2 -0
  532. package/dist/context/sources/git-source.js +9 -2
  533. package/dist/coordination/cancelled-task-settlement.d.ts +11 -0
  534. package/dist/coordination/cancelled-task-settlement.js +15 -0
  535. package/dist/coordination/consensus/providers/claude-provider.d.ts +2 -2
  536. package/dist/coordination/consensus/providers/claude-provider.js +18 -25
  537. package/dist/coordination/consensus/providers/gemini-provider.d.ts +14 -4
  538. package/dist/coordination/consensus/providers/gemini-provider.js +39 -36
  539. package/dist/coordination/consensus/providers/ollama-provider.d.ts +8 -7
  540. package/dist/coordination/consensus/providers/ollama-provider.js +16 -18
  541. package/dist/coordination/consensus/providers/openai-provider.d.ts +14 -4
  542. package/dist/coordination/consensus/providers/openai-provider.js +36 -34
  543. package/dist/coordination/consensus/providers/openrouter-provider.d.ts +5 -5
  544. package/dist/coordination/consensus/providers/openrouter-provider.js +64 -37
  545. package/dist/coordination/handlers/test-execution-handlers.js +5 -3
  546. package/dist/coordination/interfaces.d.ts +2 -2
  547. package/dist/coordination/protocol-executor.js +68 -9
  548. package/dist/coordination/queen-coordinator.js +10 -4
  549. package/dist/coordination/queen-event-handlers.js +17 -0
  550. package/dist/coordination/queen-task-management.js +25 -0
  551. package/dist/coordination/queen-types.d.ts +2 -0
  552. package/dist/coordination/task-executor.js +4 -8
  553. package/dist/coordination/workflow-composition.d.ts +19 -0
  554. package/dist/coordination/workflow-composition.js +114 -0
  555. package/dist/coordination/workflow-orchestrator.d.ts +3 -2
  556. package/dist/coordination/workflow-orchestrator.js +219 -85
  557. package/dist/coordination/workflow-types.d.ts +30 -1
  558. package/dist/coordination/yaml-pipeline-loader.js +9 -5
  559. package/dist/domains/chaos-resilience/services/chaos-engineer.js +2 -7
  560. package/dist/domains/code-intelligence/services/knowledge-graph.js +2 -7
  561. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +9 -40
  562. package/dist/domains/constants.d.ts +1 -6
  563. package/dist/domains/constants.js +2 -6
  564. package/dist/domains/contract-testing/services/contract-validator.js +2 -7
  565. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +2 -12
  566. package/dist/domains/coverage-analysis/services/gap-detector.js +2 -7
  567. package/dist/domains/defect-intelligence/services/defect-predictor.js +2 -12
  568. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +2 -7
  569. package/dist/domains/learning-optimization/services/learning-coordinator.js +2 -7
  570. package/dist/domains/quality-assessment/services/deployment-advisor.js +2 -7
  571. package/dist/domains/quality-assessment/services/quality-analyzer.js +2 -7
  572. package/dist/domains/requirements-validation/services/requirements-validator.js +2 -7
  573. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +3 -7
  574. package/dist/domains/test-execution/services/flaky-detector.js +33 -3
  575. package/dist/domains/test-execution/services/retry-handler.js +22 -14
  576. package/dist/domains/test-execution/services/test-executor.js +42 -21
  577. package/dist/domains/test-generation/services/test-generator.js +2 -7
  578. package/dist/domains/visual-accessibility/services/visual-tester.js +2 -7
  579. package/dist/init/codex-installer.js +18 -6
  580. package/dist/init/init-wizard-steps.js +1 -1
  581. package/dist/init/kiro-installer.js +9 -8
  582. package/dist/init/opencode-installer.js +1 -1
  583. package/dist/init/orchestrator.js +1 -0
  584. package/dist/init/phases/07-hooks.js +4 -2
  585. package/dist/init/phases/09-assets.d.ts +10 -0
  586. package/dist/init/phases/09-assets.js +3 -0
  587. package/dist/init/phases/12-verification.js +1 -1
  588. package/dist/init/settings-merge.d.ts +10 -3
  589. package/dist/init/settings-merge.js +40 -9
  590. package/dist/init/token-bootstrap.d.ts +1 -1
  591. package/dist/init/token-bootstrap.js +12 -2
  592. package/dist/init/types.d.ts +10 -0
  593. package/dist/integrations/agentic-flow/model-router/types.js +6 -8
  594. package/dist/integrations/ruvector/brain-exporter.js +26 -15
  595. package/dist/integrations/ruvector/brain-import-audit.d.ts +20 -0
  596. package/dist/integrations/ruvector/brain-import-audit.js +22 -0
  597. package/dist/integrations/ruvector/brain-rvf-exporter.js +33 -30
  598. package/dist/integrations/ruvector/brain-shared.d.ts +5 -1
  599. package/dist/integrations/ruvector/brain-shared.js +70 -4
  600. package/dist/integrations/ruvector/rvf-dual-writer.js +42 -16
  601. package/dist/integrations/ruvector/rvf-store-integrity.d.ts +14 -9
  602. package/dist/integrations/ruvector/rvf-store-integrity.js +39 -9
  603. package/dist/integrations/ruvector/shared-rvf-adapter.js +20 -23
  604. package/dist/kernel/hybrid-backend.d.ts +6 -0
  605. package/dist/kernel/hybrid-backend.js +18 -0
  606. package/dist/kernel/kernel.js +9 -14
  607. package/dist/kernel/memory-factory.js +14 -4
  608. package/dist/kernel/project-root.d.ts +1 -1
  609. package/dist/kernel/project-root.js +33 -10
  610. package/dist/kernel/unified-memory.js +1 -1
  611. package/dist/learning/embedder-identity-store.js +4 -3
  612. package/dist/learning/local-judge-client.d.ts +6 -5
  613. package/dist/learning/local-judge-client.js +7 -6
  614. package/dist/learning/pattern-store.js +34 -12
  615. package/dist/learning/real-embeddings.d.ts +8 -0
  616. package/dist/learning/real-embeddings.js +16 -0
  617. package/dist/learning/rvf-pattern-store.js +10 -3
  618. package/dist/mcp/bundle.js +480 -480
  619. package/dist/mcp/entry.js +2 -0
  620. package/dist/mcp/handlers/index.d.ts +1 -1
  621. package/dist/mcp/handlers/index.js +1 -1
  622. package/dist/mcp/handlers/memory-handlers.d.ts +6 -1
  623. package/dist/mcp/handlers/memory-handlers.js +44 -22
  624. package/dist/mcp/handlers/pipeline-handlers.d.ts +31 -1
  625. package/dist/mcp/handlers/pipeline-handlers.js +63 -0
  626. package/dist/mcp/handlers/task-handlers.d.ts +1 -0
  627. package/dist/mcp/handlers/task-handlers.js +26 -5
  628. package/dist/mcp/protocol-server.d.ts +2 -0
  629. package/dist/mcp/protocol-server.js +105 -49
  630. package/dist/mcp/security/sampling-server.js +2 -1
  631. package/dist/mcp/services/session-store.js +5 -1
  632. package/dist/mcp/tool-annotations.js +1 -1
  633. package/dist/mcp/tools/test-execution/schedule.js +7 -0
  634. package/dist/mcp/types.d.ts +5 -1
  635. package/dist/optimization/session-cache.d.ts +5 -0
  636. package/dist/optimization/session-cache.js +23 -0
  637. package/dist/plugins/cache.d.ts +2 -0
  638. package/dist/plugins/cache.js +15 -2
  639. package/dist/plugins/lifecycle.js +15 -2
  640. package/dist/plugins/manifest.js +7 -5
  641. package/dist/plugins/resolver.d.ts +13 -22
  642. package/dist/plugins/resolver.js +169 -61
  643. package/dist/plugins/version-policy.d.ts +13 -0
  644. package/dist/plugins/version-policy.js +18 -0
  645. package/dist/routing/advisor/multi-model-executor.d.ts +4 -1
  646. package/dist/routing/advisor/multi-model-executor.js +8 -1
  647. package/dist/routing/free-tier/ladder.d.ts +2 -1
  648. package/dist/routing/free-tier/ladder.js +3 -2
  649. package/dist/routing/security/cyber-pin.d.ts +35 -11
  650. package/dist/routing/security/cyber-pin.js +76 -14
  651. package/dist/routing/value-score.js +1 -1
  652. package/dist/shared/git/index.d.ts +1 -0
  653. package/dist/shared/git/index.js +1 -0
  654. package/dist/shared/git/ref-validation.d.ts +20 -0
  655. package/dist/shared/git/ref-validation.js +43 -0
  656. package/dist/shared/llm/anthropic-params.d.ts +40 -0
  657. package/dist/shared/llm/anthropic-params.js +51 -0
  658. package/dist/shared/llm/cost-tracker.d.ts +15 -2
  659. package/dist/shared/llm/cost-tracker.js +62 -10
  660. package/dist/shared/llm/index.d.ts +2 -2
  661. package/dist/shared/llm/index.js +2 -2
  662. package/dist/shared/llm/interfaces.d.ts +1 -1
  663. package/dist/shared/llm/metrics/cost-metrics.js +5 -4
  664. package/dist/shared/llm/model-mapping.js +131 -0
  665. package/dist/shared/llm/model-registry.d.ts +37 -11
  666. package/dist/shared/llm/model-registry.js +393 -18
  667. package/dist/shared/llm/openai-params.d.ts +35 -0
  668. package/dist/shared/llm/openai-params.js +54 -0
  669. package/dist/shared/llm/provider-manager.js +4 -3
  670. package/dist/shared/llm/providers/azure-openai.d.ts +11 -0
  671. package/dist/shared/llm/providers/azure-openai.js +26 -15
  672. package/dist/shared/llm/providers/bedrock.js +11 -19
  673. package/dist/shared/llm/providers/claude.js +6 -29
  674. package/dist/shared/llm/providers/codex.js +4 -3
  675. package/dist/shared/llm/providers/gemini.d.ts +3 -2
  676. package/dist/shared/llm/providers/gemini.js +19 -10
  677. package/dist/shared/llm/providers/ollama.d.ts +2 -0
  678. package/dist/shared/llm/providers/ollama.js +30 -20
  679. package/dist/shared/llm/providers/openai.js +10 -17
  680. package/dist/shared/llm/providers/openrouter.d.ts +1 -1
  681. package/dist/shared/llm/providers/openrouter.js +57 -21
  682. package/dist/shared/llm/router/agent-router-config.js +33 -32
  683. package/dist/shared/llm/router/hybrid-router.js +21 -9
  684. package/dist/shared/llm/router/routing-rules.js +9 -8
  685. package/dist/shared/llm/router/types.js +81 -13
  686. package/dist/shared/llm/translation/message-formatter.js +4 -23
  687. package/dist/shared/types/index.d.ts +6 -0
  688. package/dist/shared/types/index.js +8 -0
  689. package/dist/shared/vitest-json-report.d.ts +7 -7
  690. package/dist/shared/vitest-json-report.js +23 -14
  691. package/dist/test-scheduling/executors/vitest-executor.d.ts +7 -2
  692. package/dist/test-scheduling/executors/vitest-executor.js +157 -47
  693. package/dist/test-scheduling/git-aware/test-selector.js +3 -0
  694. package/dist/test-scheduling/phase-scheduler.d.ts +1 -0
  695. package/dist/test-scheduling/phase-scheduler.js +23 -1
  696. package/package.json +2 -1
  697. package/dist/cli/chunks/adapter-AKQYU6UH.js +0 -2
  698. package/dist/cli/chunks/aqe-learning-engine-MICRPL3N.js +0 -2
  699. package/dist/cli/chunks/base-DZK36ITB.js +0 -2
  700. package/dist/cli/chunks/brain-handler-H5OVZ22L.js +0 -90
  701. package/dist/cli/chunks/browser-workflow-ADK54DOE.js +0 -2
  702. package/dist/cli/chunks/chunk-26GM5CWD.js +0 -13
  703. package/dist/cli/chunks/chunk-42VSQ2MX.js +0 -4
  704. package/dist/cli/chunks/chunk-44WISFTU.js +0 -2
  705. package/dist/cli/chunks/chunk-4OUPCTBS.js +0 -16
  706. package/dist/cli/chunks/chunk-4TXAP3YH.js +0 -2
  707. package/dist/cli/chunks/chunk-4W7QVUNO.js +0 -2
  708. package/dist/cli/chunks/chunk-527HQAY7.js +0 -14
  709. package/dist/cli/chunks/chunk-5DFHE4H5.js +0 -180
  710. package/dist/cli/chunks/chunk-5P3G6ZW4.js +0 -2
  711. package/dist/cli/chunks/chunk-6F2RM6X2.js +0 -2
  712. package/dist/cli/chunks/chunk-74PK3NEW.js +0 -15
  713. package/dist/cli/chunks/chunk-7Y2CEXRS.js +0 -65
  714. package/dist/cli/chunks/chunk-AWNYEAGB.js +0 -2
  715. package/dist/cli/chunks/chunk-CBOPBYPU.js +0 -2
  716. package/dist/cli/chunks/chunk-FD2JFEQC.js +0 -2
  717. package/dist/cli/chunks/chunk-G6DCESPU.js +0 -2
  718. package/dist/cli/chunks/chunk-I4NDQGKP.js +0 -2
  719. package/dist/cli/chunks/chunk-L2GKMBDP.js +0 -2
  720. package/dist/cli/chunks/chunk-QLWNXBRU.js +0 -2
  721. package/dist/cli/chunks/chunk-R2AFVFRF.js +0 -2
  722. package/dist/cli/chunks/chunk-ROX7NLS4.js +0 -14
  723. package/dist/cli/chunks/chunk-SHGKY3QB.js +0 -2
  724. package/dist/cli/chunks/chunk-SJPZSCZP.js +0 -27
  725. package/dist/cli/chunks/chunk-T62DH4GG.js +0 -11
  726. package/dist/cli/chunks/chunk-TGLAWI62.js +0 -4
  727. package/dist/cli/chunks/chunk-UMNYF5EZ.js +0 -2
  728. package/dist/cli/chunks/chunk-UTVRQEZM.js +0 -54
  729. package/dist/cli/chunks/chunk-Y2DVFVGI.js +0 -2
  730. package/dist/cli/chunks/chunk-Y5SQBI2F.js +0 -2
  731. package/dist/cli/chunks/ci-YVKDQWIX.js +0 -81
  732. package/dist/cli/chunks/client-M72GXFVQ.js +0 -2
  733. package/dist/cli/chunks/codex-installer-2AVEO4EA.js +0 -14
  734. package/dist/cli/chunks/complexity-analyzer-LEDG62YK.js +0 -2
  735. package/dist/cli/chunks/core-handlers-C32RAMVI.js +0 -2
  736. package/dist/cli/chunks/cost-tracker-GJIFB2BM.js +0 -2
  737. package/dist/cli/chunks/cross-domain-router-UGFUCPKC.js +0 -2
  738. package/dist/cli/chunks/dream-UFBBXY5W.js +0 -2
  739. package/dist/cli/chunks/embed-and-insert-pattern-DUW6K35A.js +0 -3
  740. package/dist/cli/chunks/eval-PR6YWDFM.js +0 -17
  741. package/dist/cli/chunks/fleet-QNT6X2YI.js +0 -43
  742. package/dist/cli/chunks/heartbeat-scheduler-VQWHSGTY.js +0 -2
  743. package/dist/cli/chunks/hnsw-adapter-BS3NXWGU.js +0 -2
  744. package/dist/cli/chunks/hnsw-index-JP26B4HW.js +0 -2
  745. package/dist/cli/chunks/impact-analyzer-WRE4CWPJ.js +0 -2
  746. package/dist/cli/chunks/init-wizard-OFOEYB75.js +0 -2
  747. package/dist/cli/chunks/kernel-MXNFWNUD.js +0 -2
  748. package/dist/cli/chunks/knowledge-graph-7JE2TVKJ.js +0 -2
  749. package/dist/cli/chunks/learning-7B5NITDV.js +0 -122
  750. package/dist/cli/chunks/llm-router-BNEPT5OB.js +0 -37
  751. package/dist/cli/chunks/llm-router-service-GTDVDKSU.js +0 -2
  752. package/dist/cli/chunks/load-test-JZ4CLSBF.js +0 -2
  753. package/dist/cli/chunks/mcp-THXEINCL.js +0 -2
  754. package/dist/cli/chunks/memory-backend-Q54CC5A5.js +0 -2
  755. package/dist/cli/chunks/memory-handlers-IIBJXKHZ.js +0 -2
  756. package/dist/cli/chunks/multi-model-executor-HEDVOZ6X.js +0 -14
  757. package/dist/cli/chunks/pattern-null-store-W33O7FYO.js +0 -2
  758. package/dist/cli/chunks/pipeline-UOG6UO6D.js +0 -19
  759. package/dist/cli/chunks/platform-Q7UH7FZQ.js +0 -2
  760. package/dist/cli/chunks/protocol-executor-VGN4M7XY.js +0 -2
  761. package/dist/cli/chunks/qe-reasoning-bank-7VB5LJGS.js +0 -2
  762. package/dist/cli/chunks/queen-coordinator-HIDMJMMG.js +0 -2
  763. package/dist/cli/chunks/real-embeddings-SF42ML7G.js +0 -2
  764. package/dist/cli/chunks/router-CTIJS4D7.js +0 -2
  765. package/dist/cli/chunks/routing-feedback-LFYYZS5J.js +0 -2
  766. package/dist/cli/chunks/rvf-dual-writer-MNPMIWVM.js +0 -2
  767. package/dist/cli/chunks/rvf-migration-adapter-DXOKSSNW.js +0 -2
  768. package/dist/cli/chunks/rvf-migration-coordinator-JT7ZCJY7.js +0 -2
  769. package/dist/cli/chunks/rvf-native-adapter-PZKUKA7R.js +0 -2
  770. package/dist/cli/chunks/rvf-store-integrity-Q3FGYKFT.js +0 -2
  771. package/dist/cli/chunks/safe-db-73BLFV2C.js +0 -2
  772. package/dist/cli/chunks/schedule-YVTGTTI4.js +0 -2
  773. package/dist/cli/chunks/scheduler-5DSAFIRQ.js +0 -2
  774. package/dist/cli/chunks/sqlite-persistence-LRG4IPCU.js +0 -2
  775. package/dist/cli/chunks/task-handler-L7E2I267.js +0 -49
  776. package/dist/cli/chunks/task-handlers-6DPKE4AK.js +0 -9
  777. package/dist/cli/chunks/test-scheduling-4CNJA6TW.js +0 -15
  778. package/dist/cli/chunks/token-bootstrap-GTI24JAL.js +0 -2
  779. package/dist/cli/chunks/types-TXMY5M2K.js +0 -2
  780. package/dist/cli/chunks/unified-memory-VBQ572X4.js +0 -2
  781. package/dist/cli/chunks/unified-memory-hnsw-J3L74ZRY.js +0 -2
  782. package/dist/cli/chunks/unified-persistence-EM2VYRTQ.js +0 -2
  783. package/dist/cli/chunks/visual-security-GX4S7K6O.js +0 -2
  784. package/dist/cli/chunks/witness-chain-QGKMHCNW.js +0 -2
  785. package/dist/cli/chunks/workflow-2OYNO7UU.js +0 -51
  786. package/dist/cli/chunks/workflow-orchestrator-KWHIJMFV.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.14.3");process.exit(0)}
2
- import{a as ie,b as ae}from"./chunk-IP7NSFQQ.js";import{S as oe,i as D,p as $}from"./chunk-T35GZXTU.js";import{c as g,e as ne,g as W}from"./chunk-Y2DVFVGI.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(ae(),W(ie));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();oe();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{a as ae,b as oe}from"./chunk-6A44AOGN.js";import{S as ie,i as D,p as $}from"./chunk-WJHWH5D2.js";import{b as g,d as ne,f as W}from"./chunk-JSZ663MU.js";var I,E=g(()=>{"use strict";I={dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}});function se(){if(z)return A!==null;try{let i=(oe(),W(ae));if(A=i.differentiableSearch,P=i.init,P)try{P()}catch{}return z=!0,!0}catch{return z=!0,!1}}function j(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function ce(i,e,r,t){let n=r*t;if(n===0)return 0;let a=0,o=Math.min(i.length,e.length);for(let c=0;c<o;c++)a+=i[c]*e[c];return a/n}function q(i,e){let r=0,t=Math.min(i.length,e.length);for(let n=0;n<t;n++){let a=i[n]-e[n];r+=a*a}return Math.sqrt(r)}function le(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}var A,P,z,S,B=g(()=>{"use strict";E();A=null,P=null,z=!1;S=class{config;entries=[];idToIndex=new Map;hasRuvector=!1;loaded=!1;constructor(e){this.config={...I,...e}}ensureLoaded(){this.loaded||(this.hasRuvector=se(),this.loaded=!0)}normalizeVector(e){return e.length===this.config.dimensions?e:le(e,this.config.dimensions)}add(e,r,t){this.ensureLoaded();let n=this.normalizeVector(r),a=j(n);if(this.idToIndex.has(e)){let c=this.idToIndex.get(e);this.entries[c]={id:e,vector:n,norm:a,metadata:t};return}let o=this.entries.length;this.entries.push({id:e,vector:n,norm:a,metadata:t}),this.idToIndex.set(e,o)}search(e,r){if(this.ensureLoaded(),this.entries.length===0)return[];let t=this.normalizeVector(e),n=j(t),a=Math.min(r,this.entries.length),o=this.entries.length>0?this.entries[0].vector.length:0,c=t.length===o;if(this.config.metric==="cosine")return this.bruteForcSearch(t,n,a);if(this.hasRuvector&&c&&A)try{let s=this.entries.map(u=>u.vector),l=A(t,s,a,1).indices.map(u=>{let h=this.entries[u],m=-q(t,h.vector);return{id:h.id,score:m,metadata:h.metadata}});return l.sort((u,h)=>h.score-u.score),l}catch{}return this.bruteForcSearch(t,n,a)}bruteForcSearch(e,r,t){let n=[];for(let a of this.entries){let o;this.config.metric==="cosine"?o=ce(e,a.vector,r,a.norm):o=-q(e,a.vector),n.push({id:a.id,score:o,metadata:a.metadata})}return n.sort((a,o)=>o.score-a.score),n.slice(0,t)}remove(e){let r=this.idToIndex.get(e);if(r===void 0)return!1;let t=this.entries.length-1;if(r!==t){let n=this.entries[t];this.entries[r]=n,this.idToIndex.set(n.id,r)}return this.entries.pop(),this.idToIndex.delete(e),!0}size(){return this.entries.length}dimensions(){return this.config.dimensions}recall(){return this.hasRuvector,1}isRuvectorAvailable(){return this.ensureLoaded(),this.hasRuvector}getConfig(){return{...this.config}}clear(){this.entries=[],this.idToIndex.clear()}dispose(){this.clear()}}});import{createRequire as he}from"module";function de(){if(U){if(k)return k;throw new b(O??"Unknown load error")}U=!0;try{let i=ue("hnswlib-node");if(!i.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return k=i,k}catch(i){let e=i instanceof Error?i.message:String(i);throw O=e,new b(e)}}function me(i,e){if(i.length===e)return i;let r=new Float32Array(e);if(i.length>e){let t=i.length/e;for(let n=0;n<e;n++){let a=Math.floor(n*t),o=Math.floor((n+1)*t),c=0;for(let s=a;s<o;s++)c+=i[s];r[n]=c/(o-a)}}else for(let t=0;t<i.length;t++)r[t]=i[t];return r}function K(i){let e=new Array(i.length);for(let r=0;r<i.length;r++)e[r]=i[r];return e}var ue,b,k,U,O,J,w,Q=g(()=>{"use strict";E();ue=he(import.meta.url),b=class extends Error{constructor(e){super(`Native HNSW backend unavailable: ${e}`),this.name="NativeHnswUnavailableError"}},k=null,U=!1,O=null;J=1e4,w=class{config;nativeIndex=null;currentMaxElements=J;liveIds=new Set;metadataStore=new Map;_metrics={totalSearches:0,totalAdds:0,totalRemoves:0,avgSearchLatencyMs:0,maxSearchLatencyMs:0,lastSearchLatencyMs:0,fallbackSearchCount:0,bruteForceSearchCount:0,nativeSearchCount:0,fallbackRate:0,allSearchesBruteForce:!1};constructor(e){this.config={...I,...e},this.nativeIndex=this.createFreshIndex()}createFreshIndex(){let e=de(),r=this.config.metric==="euclidean"?"l2":"cosine";try{let t=new e.HierarchicalNSW(r,this.config.dimensions);return t.initIndex(this.currentMaxElements,this.config.M,this.config.efConstruction,100,!0),t.setEf(this.config.efSearch),t}catch(t){let n=t instanceof Error?t.message:String(t);throw new b(`HierarchicalNSW init failed: ${n}`)}}add(e,r,t){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");let n=this.normalizeVector(r);if(!this.liveIds.has(e)&&this.liveIds.size>=this.currentMaxElements){let a=this.currentMaxElements*2;this.nativeIndex.resizeIndex(a),this.currentMaxElements=a}this.nativeIndex.addPoint(K(n),e,!0),this.liveIds.add(e),t?this.metadataStore.set(e,t):this.metadataStore.delete(e),this._metrics.totalAdds++}search(e,r){if(!this.nativeIndex)throw new Error("NativeHnswBackend has been disposed");if(this.liveIds.size===0||r<=0)return[];let t=performance.now(),n=this.normalizeVector(e),a=Math.min(r,this.liveIds.size),o=Math.min(this.liveIds.size,Math.max(a,this.config.efSearch)*2),c=this.nativeIndex.searchKnn(K(n),o),s=this.config.metric==="cosine",d=new Map;for(let h=0;h<c.neighbors.length;h++){let m=c.neighbors[h];if(!this.liveIds.has(m))continue;let x=c.distances[h],f=s?1-x:-x,G=d.get(m);(G===void 0||f>G.score)&&d.set(m,{id:m,score:f,metadata:this.metadataStore.get(m)})}let l=Array.from(d.values());l.sort((h,m)=>m.score-h.score),l.length>a&&(l.length=a);let u=performance.now()-t;return this.updateSearchMetrics(u),this._metrics.nativeSearchCount=this._metrics.totalSearches,u>50&&console.warn(`[NativeHNSW] search took ${u.toFixed(1)}ms (k=${r}, results=${l.length})`),l}remove(e){if(!this.nativeIndex||!this.liveIds.has(e))return!1;try{this.nativeIndex.markDelete(e)}catch{return!1}return this.liveIds.delete(e),this.metadataStore.delete(e),this._metrics.totalRemoves++,!0}size(){return this.liveIds.size}dimensions(){return this.config.dimensions}recall(){return .99}getMetrics(){return{...this._metrics}}get lastSearchLatencyMs(){return this._metrics.lastSearchLatencyMs}getConfig(){return{...this.config}}clear(){this.nativeIndex&&(this.liveIds.clear(),this.metadataStore.clear(),this.currentMaxElements=J,this.nativeIndex=this.createFreshIndex())}dispose(){this.liveIds.clear(),this.metadataStore.clear(),this.nativeIndex=null}isNativeAvailable(){return this.nativeIndex!==null}normalizeVector(e){return e.length===this.config.dimensions?e:me(e,this.config.dimensions)}updateSearchMetrics(e){this._metrics.totalSearches++,this._metrics.lastSearchLatencyMs=e,e>this._metrics.maxSearchLatencyMs&&(this._metrics.maxSearchLatencyMs=e);let r=this._metrics.totalSearches;this._metrics.avgSearchLatencyMs=this._metrics.avgSearchLatencyMs*((r-1)/r)+e/r}}});function X(i,e){let r=Array.from({length:e},()=>new Float64Array(e));for(let t=0;t<e;t++){let n=i[t].length;r[t][t]=n;for(let a of i[t])r[t][a]=-1}return r}function N(i,e){let r=e.length,t=new Float64Array(r);for(let n=0;n<r;n++){let a=i[n].length;t[n]=a*e[n];for(let o of i[n])t[n]-=e[o]}return t}function H(i){let e=0;for(let r=0;r<i.length;r++)e+=i[r]*i[r];return Math.sqrt(e)}function R(i){let e=H(i);if(e>0)for(let r=0;r<i.length;r++)i[r]/=e}function v(i,e){let r=0;for(let t=0;t<i.length;t++)r+=i[t]*e[t];for(let t=0;t<i.length;t++)i[t]-=r*e[t]}function y(i,e,r=100,t=1e-6){if(e<=1)return 0;if(e===2)return i[0].includes(1)?2:0;let n=new Float64Array(e).fill(1/Math.sqrt(e)),a=new Float64Array(e);for(let l=0;l<e;l++)a[l]=Math.random()-.5;v(a,n),R(a);let o=0;for(let l=0;l<30;l++){let u=N(i,a);if(v(u,n),o=H(u),o>0)for(let h=0;h<e;h++)a[h]=u[h]/o}if(o<t)return 0;let c=new Float64Array(e);for(let l=0;l<e;l++)c[l]=Math.random()-.5;v(c,n),R(c);let s=0;for(let l=0;l<r;l++){let u=N(i,c),h=new Float64Array(e);for(let f=0;f<e;f++)h[f]=o*c[f]-u[f];v(h,n);let m=H(h);if(m<t)break;let x=m;for(let f=0;f<e;f++)c[f]=h[f]/m;if(Math.abs(x-s)<t)break;s=x}let d=o-s;return Math.max(0,d)}function F(i,e,r=100,t=1e-6){return y(i,e,r,t)}function C(i,e,r=50,t){if(e<=1)return 0;let n=t??y(i,e);if(n<1e-10)return 1/0;let o=2*Math.max(...i.map(d=>d.length),1),s=2*(Math.log(o/n)/(o-n));return Math.max(0,s)}function M(i,e,r){let t=1-Math.exp(-i/.05),n=1-Math.exp(-e/.5),a=r===1/0?0:1/(1+r/5),o=.4*t+.3*n+.3*a;return Math.max(0,Math.min(1,o))}var _=g(()=>{"use strict"});var ee={};ne(ee,{ALERT_THRESHOLDS:()=>fe,DEFAULT_HNSW_HEALTH_CONFIG:()=>Y,HnswHealthMonitor:()=>L,_resetNativeLoader:()=>be,approximateFiedlerValue:()=>y,approximateSpectralGap:()=>F,buildAdjacencyFromIndex:()=>Z,buildLaplacian:()=>X,computeCoherenceScore:()=>M,createHnswHealthMonitor:()=>ge,deflateVector:()=>v,estimateEffectiveResistance:()=>C,laplacianMultiply:()=>N,normalizeInPlace:()=>R,vectorNorm:()=>H});function pe(){return V?T:(V=!0,T=null,null)}function be(){T=null,V=!1}function Z(i,e=16,r){let t=i.size();if(t===0)return{adjacency:[],nodeCount:0,adjacencySource:"approximate"};let n=Array.from({length:t},()=>[]),a=Math.min(e,t-1);if(a===0)return{adjacency:n,nodeCount:t,adjacencySource:"approximate"};if(r&&r.size>0){let o=Array.from(r.keys()).slice(0,t),c=new Map;for(let s=0;s<o.length;s++)c.set(o[s],s);for(let s=0;s<o.length;s++){let d=r.get(o[s]);if(!d)continue;let l=i.search(d,a+1);for(let u of l){if(u.id===o[s])continue;let h=c.get(u.id);h!==void 0&&(n[s].includes(h)||n[s].push(h),n[h].includes(s)||n[h].push(s))}}return{adjacency:n,nodeCount:t,adjacencySource:"actual-search"}}console.warn("[HnswHealthMonitor] No stored vectors provided \u2014 using approximate circular adjacency. Pass stored vectors for accurate health metrics.");for(let o=0;o<t;o++)for(let c=0;c<a;c++){let s=(o+c+1)%t;n[o].includes(s)||n[o].push(s),n[s].includes(o)||n[s].push(o)}return{adjacency:n,nodeCount:t,adjacencySource:"approximate"}}function ge(i){return new L(i)}var Y,fe,T,V,L,te=g(()=>{"use strict";_();_();Y={fiedlerThreshold:.01,spectralGapThreshold:.1,resistanceThreshold:10,coherenceThreshold:.3,maxPowerIterations:100,convergenceTolerance:1e-6,resistanceSampleSize:50,maxHistoryEntries:200,minIndexSize:3},fe={FragileIndex:.01,PoorExpansion:.1,HighResistance:10,LowCoherence:.3},T=null,V=!1;L=class{config;alerts=[];history=[];lastReport=null;useNative=!1;nativeChecked=!1;constructor(e){this.config={...Y,...e}}checkHealth(e){let r=performance.now(),t=e.size();if(t<this.config.minIndexSize)return this.createSmallIndexReport(t,performance.now()-r);this.nativeChecked||(this.nativeChecked=!0,this.useNative=pe()!==null);let{adjacency:n,nodeCount:a,adjacencySource:o}=Z(e),c=this.useNative?this.computeNativeMetrics(n):this.computeApproximateMetrics(n,a),s=this.generateAlerts(c);this.alerts.length=0,this.alerts.push(...s);let d=performance.now()-r,l={healthy:s.length===0,metrics:c,alerts:s,indexSize:t,usedNativeBackend:this.useNative,adjacencySource:o,checkDurationMs:d,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:c.coherenceScore,fiedlerValue:c.fiedlerValue,indexSize:t,healthy:l.healthy,timestamp:l.checkedAt}),this.lastReport=l,l}getAlerts(){return[...this.alerts]}getMetricsHistory(e){let r=[...this.history];return e!==void 0&&e<r.length?r.slice(-e):r}isHealthy(){return this.lastReport===null?!0:this.lastReport.healthy}getLastReport(){return this.lastReport}clearHistory(){this.history.length=0,this.alerts.length=0,this.lastReport=null}computeNativeMetrics(e){let r=T,t=r.computeFiedlerValue(e),n=r.computeSpectralGap(e),a=r.computeEffectiveResistance(e),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}computeApproximateMetrics(e,r){let t=y(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),n=F(e,r,this.config.maxPowerIterations,this.config.convergenceTolerance),a=C(e,r,this.config.resistanceSampleSize,t),o=M(t,n,a);return{fiedlerValue:t,spectralGap:n,effectiveResistance:a,coherenceScore:o}}generateAlerts(e){let r=[],t=new Date;return e.fiedlerValue<this.config.fiedlerThreshold&&r.push({type:"FragileIndex",message:`Fiedler value ${e.fiedlerValue.toFixed(6)} is below threshold ${this.config.fiedlerThreshold}. The index graph has weak algebraic connectivity.`,value:e.fiedlerValue,threshold:this.config.fiedlerThreshold,timestamp:t}),e.spectralGap<this.config.spectralGapThreshold&&r.push({type:"PoorExpansion",message:`Spectral gap ${e.spectralGap.toFixed(6)} is below threshold ${this.config.spectralGapThreshold}. The index graph has poor expansion properties.`,value:e.spectralGap,threshold:this.config.spectralGapThreshold,timestamp:t}),e.effectiveResistance>this.config.resistanceThreshold&&r.push({type:"HighResistance",message:`Average effective resistance ${e.effectiveResistance.toFixed(4)} exceeds threshold ${this.config.resistanceThreshold}. Nodes are poorly connected.`,value:e.effectiveResistance,threshold:this.config.resistanceThreshold,timestamp:t}),e.coherenceScore<this.config.coherenceThreshold&&r.push({type:"LowCoherence",message:`Coherence score ${e.coherenceScore.toFixed(4)} is below threshold ${this.config.coherenceThreshold}. Overall index health is degraded.`,value:e.coherenceScore,threshold:this.config.coherenceThreshold,timestamp:t}),r}createSmallIndexReport(e,r){let t={fiedlerValue:e>0?1:0,spectralGap:e>0?1:0,effectiveResistance:e>0?.5:0,coherenceScore:e>0?1:0},n={healthy:!0,metrics:t,alerts:[],indexSize:e,usedNativeBackend:!1,adjacencySource:"approximate",checkDurationMs:r,checkedAt:new Date};return this.addHistoryPoint({coherenceScore:t.coherenceScore,fiedlerValue:t.fiedlerValue,indexSize:e,healthy:!0,timestamp:n.checkedAt}),this.lastReport=n,n}addHistoryPoint(e){this.history.push(e),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}}});var ve,p,re,ye=g(()=>{B();Q();ie();ve={patterns:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},"qe-memory":{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"},learning:{dimensions:384,M:16,efConstruction:200,efSearch:50,metric:"cosine"},coverage:{dimensions:384,M:16,efConstruction:200,efSearch:100,metric:"cosine"}},p=new Map,re=class i{backend;_isNativeBackend;indexName;stringToNumericId=new Map;numericToStringId=new Map;nextAutoId=0;healthMonitor=null;healthMonitorLoaded=!1;operationsSinceLastCheck=0;healthCheckFrequency=100;lastHealthReport=null;constructor(e,r){this.indexName=e;let n={...ve[e]??{},...r},{backend:a,isNative:o}=i.createBackend(n);this.backend=a,this._isNativeBackend=o}add(e,r,t){this.backend.add(e,r,t),this.maybeRunHealthCheck()}search(e,r){let t=performance.now(),n=this.backend.search(e,r),a=performance.now()-t;return a>50&&console.warn(`[HNSW] search took ${a.toFixed(1)}ms (k=${r}, results=${n.length})`),this._lastSearchLatencyMs=a,n}_lastSearchLatencyMs=0;get lastSearchLatencyMs(){return this._lastSearchLatencyMs}remove(e){return this.backend.remove(e)}size(){return this.backend.size()}dimensions(){return this.backend.dimensions()}recall(){return this.backend.recall()}addByStringId(e,r){let t=this.stringToNumericId.get(e);t!==void 0?this.backend.remove(t):(t=this.nextAutoId++,this.stringToNumericId.set(e,t),this.numericToStringId.set(t,e)),this.backend.add(t,new Float32Array(r))}searchByArray(e,r){return this.backend.search(new Float32Array(e),r).map(n=>({id:this.numericToStringId.get(n.id)??String(n.id),score:n.score}))}removeByStringId(e){let r=this.stringToNumericId.get(e);if(r===void 0)return!1;let t=this.backend.remove(r);return t&&(this.stringToNumericId.delete(e),this.numericToStringId.delete(r)),t}clear(){this.backend.clear?.(),this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}dispose(){try{this.backend.dispose?.()}catch{}this.stringToNumericId.clear(),this.numericToStringId.clear(),this.nextAutoId=0}isRuvectorAvailable(){return this.backend instanceof S?this.backend.isRuvectorAvailable():this.backend instanceof w?this.backend.isNativeAvailable():!1}isNativeBackend(){return this._isNativeBackend}getName(){return this.indexName}setHealthCheckFrequency(e){this.healthCheckFrequency=Math.max(1,e)}getHealthCheckFrequency(){return this.healthCheckFrequency}getLastHealthReport(){return this.lastHealthReport}getHealthMonitor(){return this.healthMonitor}maybeRunHealthCheck(){if($()&&(this.operationsSinceLastCheck++,!(this.operationsSinceLastCheck<this.healthCheckFrequency)&&(this.operationsSinceLastCheck=0,this.ensureHealthMonitor(),this.healthMonitor)))try{this.lastHealthReport=this.healthMonitor.checkHealth(this.backend),this.lastHealthReport.healthy||console.warn(`[HNSW-Health] Index "${this.indexName}" health check failed: ${this.lastHealthReport.alerts.length} alert(s). Coherence: ${this.lastHealthReport.metrics.coherenceScore.toFixed(3)}`)}catch(e){console.warn(`[HNSW-Health] Health check error for "${this.indexName}":`,e)}}ensureHealthMonitor(){if(!this.healthMonitorLoaded){this.healthMonitorLoaded=!0;try{let e=(te(),W(ee));this.healthMonitor=e.createHnswHealthMonitor()}catch(e){process.env.DEBUG&&console.debug("[HNSW-Health] Monitor module unavailable:",e instanceof Error?e.message:e),this.healthMonitor=null}}}static createBackend(e){if(D())try{return{backend:new w(e),isNative:!0}}catch(r){r instanceof b?console.info(`[HNSW] Native backend unavailable, falling back to JS: ${r.message}`):console.warn("[HNSW] Unexpected error creating native backend, falling back to JS:",r)}return{backend:new S(e),isNative:!1}}static create(e,r){let t=p.get(e);if(t instanceof i)return t;let n=new i(e,r);return p.set(e,n),n}static get(e){let r=p.get(e);return r instanceof i?r:void 0}static close(e){let r=p.get(e);r instanceof i&&r.dispose(),p.delete(e)}static closeAll(){for(let[e]of p)i.close(e);p.clear()}static listIndexes(){return Array.from(p.keys())}}});export{re as a,ye as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{a as T}from"./chunk-L2GKMBDP.js";import{c as S}from"./chunk-72UJXEKQ.js";import{b as C,d as P}from"./chunk-YAKS3CAB.js";import{a as b,c as $}from"./chunk-HRUU7E3D.js";import{a as w,d as M}from"./chunk-5IAB5NRZ.js";$();M();import{randomUUID as A}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${A().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{b as C,d as P}from"./chunk-IJHCIXJC.js";import{a as T}from"./chunk-J27F4NSB.js";import{c as S}from"./chunk-7CD7PBHY.js";import{a as b,c as $}from"./chunk-J5UNP6W3.js";import{a as w,d as M}from"./chunk-XZSMZHM2.js";$();M();import{randomUUID as A}from"crypto";var x={topology:"hierarchical",maxConcurrentSkills:10,maxConcurrentModels:3,timeout:3e5,continueOnFailure:!0,retry:{maxRetries:2,retryDelayMs:1e3}},R=class{config;learner;skillValidator=null;workers=new Map;taskQueue=[];isRunning=!1;constructor(e,t){this.config={...x,...e},this.learner=t}setSkillValidator(e){this.skillValidator=e}async validateSkillsParallel(e,t,i){let s=Date.now(),a=i?.trustTier??3,n=i?.validationLevel??"eval",c=this.determineTopology(e.length,t.length),r=this.createValidationTasks(e,t,a,n),o=await this.executeTasksParallel(r,c),l=new Map;for(let u of o){let p=l.get(u.skill)||[];p.push(u),l.set(u.skill,p)}return await this.recordOutcomesToLearner(o,a,n),l}async validateSkillCrossModel(e,t,i){return(await this.validateSkillsParallel([e],t,i)).get(e)||[]}getSummary(e){let t=[],i=new Map,s=new Map;for(let[c,r]of e){i.set(c,r);for(let o of r){t.push(o);let l=s.get(o.model)||[];l.push(o),s.set(o.model,l)}}let a=t.filter(c=>c.errors.length===0&&c.evalPassRate>=.9).length,n=t.reduce((c,r)=>c+r.durationMs,0);return{totalSkills:i.size,totalModels:s.size,successCount:a,failureCount:t.length-a,overallPassRate:t.length>0?a/t.length:0,totalDurationMs:n,avgDurationMs:t.length>0?n/t.length:0,topology:this.config.topology,bySkill:i,byModel:s,results:t}}determineTopology(e,t){if(this.config.topology){let i=e*t;return i>20&&this.config.topology==="mesh"&&console.warn(`[SwarmSkillValidator] Large workload (${i} tasks) may be more efficient with hierarchical topology`),this.config.topology}return e>5||e>t*2?"hierarchical":t>5&&e<=3?"mesh":"hierarchical"}createValidationTasks(e,t,i,s){let a=[];for(let n of e)for(let c of t)a.push({id:`${n}-${c}-${Date.now()}-${A().slice(0,8)}`,skill:n,model:c,trustTier:i,validationLevel:s,timeout:this.config.timeout,retryCount:0});return a}async executeTasksParallel(e,t){this.isRunning=!0,this.taskQueue=[...e];let i=[],s=t==="hierarchical"?this.config.maxConcurrentSkills:Math.min(this.config.maxConcurrentSkills*this.config.maxConcurrentModels,e.length),a=[];for(let n=0;n<Math.min(s,e.length);n++){let c=`worker-${n}`;this.workers.set(c,{id:c,task:null,status:"idle"}),a.push(this.runWorker(c,i))}return await Promise.all(a),this.isRunning=!1,this.workers.clear(),i}async runWorker(e,t){let i=this.workers.get(e);if(i){for(;this.taskQueue.length>0&&this.isRunning;){let s=this.taskQueue.shift();if(!s)break;i.task=s,i.status="running",i.startTime=Date.now();try{let a=await this.executeValidationTask(s);t.push(a),i.result=a,i.status="completed"}catch(a){let n=this.createErrorResult(s,a);this.config.retry&&s.retryCount<this.config.retry.maxRetries&&this.config.continueOnFailure?(s.retryCount++,this.taskQueue.push(s),await this.delay(this.config.retry.retryDelayMs)):(t.push(n),i.result=n,i.status="failed")}}i.task=null,i.status="idle"}}async executeValidationTask(e){let t=Date.now();if(!this.skillValidator)return this.createSimulatedResult(e,t);let i=new Promise((n,c)=>{setTimeout(()=>c(new Error(`Validation timeout after ${e.timeout}ms`)),e.timeout)}),s=await Promise.race([this.skillValidator(e.skill,e.model,{trustTier:e.trustTier,validationLevel:e.validationLevel,timeout:e.timeout}),i]),a=Date.now()-t;return this.outcomeToResult(s,e,a)}outcomeToResult(e,t,i){let s=e.testCaseResults.filter(c=>c.passed).length,a=e.testCaseResults.length,n=a>0?s/a:e.score;return{skill:t.skill,model:t.model,schemaValid:e.validationLevel!=="schema"||e.passed,validatorPassed:e.validationLevel!=="validator"||e.passed,evalPassRate:n,durationMs:i,errors:e.passed?[]:["Validation failed"],trustTier:t.trustTier,validationLevel:t.validationLevel,retryCount:t.retryCount,timestamp:new Date}}createSimulatedResult(e,t){let i=Date.now()-t+w()*100,s=.85+w()*.15;return{skill:e.skill,model:e.model,schemaValid:!0,validatorPassed:s>.8,evalPassRate:s,durationMs:i,errors:s>.8?[]:["Simulated validation failure"],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}createErrorResult(e,t){let i=b(t);return{skill:e.skill,model:e.model,schemaValid:!1,validatorPassed:!1,evalPassRate:0,durationMs:0,errors:[i],trustTier:e.trustTier,validationLevel:e.validationLevel,retryCount:e.retryCount,timestamp:new Date}}async recordOutcomesToLearner(e,t,i){for(let s of e){let a={skillName:s.skill,trustTier:s.trustTier||t,validationLevel:s.validationLevel||i,model:s.model,passed:s.errors.length===0&&s.evalPassRate>=.9,score:s.evalPassRate,testCaseResults:this.createTestCaseResults(s),timestamp:s.timestamp,runId:`swarm-${Date.now()}`,metadata:{duration:s.durationMs,retryCount:s.retryCount}};await this.learner.recordValidationOutcome(a)}}createTestCaseResults(e){return[{testId:`${e.skill}-${e.model}-aggregate`,passed:e.errors.length===0,expectedPatterns:["valid-output"],actualPatterns:e.errors.length===0?["valid-output"]:[],reasoningQuality:e.evalPassRate,executionTimeMs:e.durationMs,category:"swarm-validation",priority:"high",error:e.errors.length>0?e.errors.join("; "):void 0}]}delay(e){return new Promise(t=>setTimeout(t,e))}getConfig(){return{...this.config}}isValidationRunning(){return this.isRunning}getWorkerStatus(){return Array.from(this.workers.values())}cancel(){this.isRunning=!1,this.taskQueue=[]}};function D(y,e){return new R(y,e)}var F=["security-testing","accessibility-testing","api-testing","performance-testing","visual-regression-testing","mutation-testing","contract-testing","chaos-testing","compliance-testing","penetration-testing"],I=["claude-sonnet","claude-haiku","claude-opus"];P();import{readFileSync as E,writeFileSync as L,existsSync as N}from"fs";var O={varianceThreshold:.04,regressionThreshold:.1,minSamples:3,autoUpdateManifest:!1},k=class{constructor(e,t,i={}){this.learner=e;this.manifestPath=t;this.config={...O,...i}}learner;manifestPath;config;async aggregateResults(e){let t=`agg-${Date.now()}`,i=new Date,s=this.buildSkillResultsMap(e),a=this.calculateSummary(s,e),n=await this.detectCrossModelAnomalies(e),c=await this.detectRegressions(e,this.config.regressionThreshold),r=this.generateRecommendations(s,n,c),o={timestamp:i,runId:t,summary:a,skillResults:s,crossModelAnalysis:n,regressions:c,recommendations:r,metadata:{version:"1.0.0",environment:e[0]?.metadata?.environment,generatedBy:"ValidationResultAggregator",inputs:{runIds:e.map(l=>l.runId),models:[...new Set(e.map(l=>l.model))]}}};return this.config.autoUpdateManifest&&await this.updateManifest(o),o}buildSkillResultsMap(e){let t=new Map;for(let i of e)for(let s of i.outcomes){let a=s.skillName;t.has(a)||t.set(a,{skill:a,trustTier:s.trustTier,passRateByModel:new Map,avgPassRate:0,schemaValid:!0,validatorPassed:!0,evalPassed:!0,issues:[],executionTimeMs:0,testCount:0,passedTests:0,failedTests:0});let n=t.get(a),c=s.testCaseResults.filter(r=>r.passed).length/(s.testCaseResults.length||1);n.passRateByModel.set(i.model,c),n.testCount+=s.testCaseResults.length,n.passedTests+=s.testCaseResults.filter(r=>r.passed).length,n.failedTests+=s.testCaseResults.filter(r=>!r.passed).length,n.executionTimeMs+=s.metadata?.duration||0,s.validationLevel==="schema"&&!s.passed&&(n.schemaValid=!1),s.validationLevel==="validator"&&!s.passed&&(n.validatorPassed=!1),s.validationLevel==="eval"&&!s.passed&&(n.evalPassed=!1);for(let r of s.testCaseResults)!r.passed&&r.error&&n.issues.push({skill:a,model:i.model,severity:r.priority==="critical"?"critical":r.priority==="high"?"high":r.priority==="medium"?"medium":"low",type:this.categorizeIssueType(s.validationLevel,r.error),message:r.error,testId:r.testId})}for(let i of t.values()){let s=Array.from(i.passRateByModel.values());i.avgPassRate=s.length>0?s.reduce((a,n)=>a+n,0)/s.length:0}return t}categorizeIssueType(e,t){return t.toLowerCase().includes("timeout")?"timeout":e==="schema"?"schema_failure":e==="validator"?"validator_failure":e==="eval"?"eval_failure":"error"}calculateSummary(e,t){let i=Array.from(e.values()),s=i.filter(n=>n.avgPassRate>=.9).length,a=i.length>0?i.reduce((n,c)=>n+c.avgPassRate,0)/i.length:0;return{totalSkills:i.length,passedSkills:s,failedSkills:i.length-s,avgPassRate:a,totalDurationMs:t.reduce((n,c)=>n+c.durationMs,0),totalTests:i.reduce((n,c)=>n+c.testCount,0),passedTests:i.reduce((n,c)=>n+c.passedTests,0),failedTests:i.reduce((n,c)=>n+c.failedTests,0),modelsUsed:[...new Set(t.map(n=>n.model))]}}async detectCrossModelAnomalies(e){let t=new Map,i=new Map,s=new Map;for(let d of e){t.has(d.model)||(t.set(d.model,[]),i.set(d.model,{totalTests:0,passedTests:0,skillCount:0}));for(let g of d.outcomes){let h=g.testCaseResults.filter(m=>m.passed).length/(g.testCaseResults.length||1);t.get(d.model).push(h);let f=i.get(d.model);f.totalTests+=g.testCaseResults.length,f.passedTests+=g.testCaseResults.filter(m=>m.passed).length,f.skillCount++,s.has(g.skillName)||s.set(g.skillName,{passRates:[],models:[]}),s.get(g.skillName).passRates.push(h),s.get(g.skillName).models.push(d.model)}}let a=[];for(let d of t.values())a.push(...d);let n=a.length>0?a.reduce((d,g)=>d+g,0)/a.length:0,c=a.length>1?a.reduce((d,g)=>d+Math.pow(g-n,2),0)/a.length:0,r=Math.sqrt(c),o=[],l=new Map;for(let[d,g]of t.entries()){let h=g.reduce((v,V)=>v+V,0)/g.length,f=h-n,m=i.get(d);l.set(d,{avgPassRate:h,skillCount:m.skillCount,totalTests:m.totalTests}),Math.abs(f)>this.config.varianceThreshold*2&&o.push({model:d,type:f<0?"low_performance":"high_variance",description:`Model ${d} has ${(f*100).toFixed(1)}% difference from average`,passRate:h,avgPassRate:n,deviation:Math.abs(f)})}let u=[],p=[];for(let[d,g]of s.entries()){if(g.passRates.length<2)continue;let h=g.passRates.reduce((m,v)=>m+v,0)/g.passRates.length;g.passRates.reduce((m,v)=>m+Math.pow(v-h,2),0)/g.passRates.length<this.config.varianceThreshold?u.push(d):p.push(d)}return{variance:c,stdDeviation:r,anomalies:o,consistentSkills:u,inconsistentSkills:p,modelPerformance:l}}async detectRegressions(e,t){let i=[],s=new Set;for(let a of e)for(let n of a.outcomes){let c=`${n.skillName}-${a.model}`;if(s.has(c))continue;s.add(c);let r=await this.learner.getValidationTrends(n.skillName);if(!r)continue;let o=n.testCaseResults.filter(p=>p.passed).length/(n.testCaseResults.length||1),l=r.recentPassRate,u=l-o;u>=t&&i.push({skill:n.skillName,model:a.model,previousPassRate:l,currentPassRate:o,regressionAmount:u,trend:r.overall,possibleCauses:this.analyzePossibleCauses(n,u),severity:this.categorizeRegressionSeverity(u)})}return i.sort((a,n)=>{let c={critical:0,high:1,medium:2,low:3},r=c[a.severity]-c[n.severity];return r!==0?r:n.regressionAmount-a.regressionAmount})}analyzePossibleCauses(e,t){let i=[],s=e.testCaseResults.filter(c=>!c.passed);if(s.length>0){let c=[...new Set(s.map(r=>r.category).filter(Boolean))];c.length>0&&i.push(`Failures in categories: ${c.join(", ")}`)}let a=s.filter(c=>c.priority==="critical");a.length>0&&i.push(`${a.length} critical test(s) failing`);let n=e.testCaseResults.reduce((c,r)=>c+r.reasoningQuality,0)/(e.testCaseResults.length||1);return n<.7&&i.push(`Low reasoning quality score: ${(n*100).toFixed(1)}%`),t>.3&&i.push("Possible model behavior change or prompt drift"),i.length===0&&i.push("No specific cause identified - review test details"),i}categorizeRegressionSeverity(e){return e>=.5?"critical":e>=.3?"high":e>=.15?"medium":"low"}generateRecommendations(e,t,i){let s=[];if(t.inconsistentSkills.length>0&&s.push(`Review ${t.inconsistentSkills.length} skills with inconsistent cross-model behavior: `+t.inconsistentSkills.slice(0,3).join(", ")+(t.inconsistentSkills.length>3?` and ${t.inconsistentSkills.length-3} more`:"")),t.anomalies.some(r=>r.type==="low_performance")){let r=t.anomalies.filter(o=>o.type==="low_performance").map(o=>o.model);s.push(`Investigate low performance on model(s): ${r.join(", ")}`)}let a=i.filter(r=>r.severity==="critical");a.length>0&&s.push(`URGENT: ${a.length} critical regression(s) detected - immediate review required`);let n=Array.from(e.values()).filter(r=>r.avgPassRate<.9);if(n.length>0){let r=n.filter(l=>!l.schemaValid),o=n.filter(l=>!l.validatorPassed);r.length>0&&s.push(`Fix schema validation for: ${r.map(l=>l.skill).slice(0,3).join(", ")}`),o.length>0&&s.push(`Review validator scripts for: ${o.map(l=>l.skill).slice(0,3).join(", ")}`)}return Array.from(e.values()).reduce((r,o)=>r+o.avgPassRate,0)/e.size<.8&&s.push("Overall pass rate below 80% - consider reviewing skill definitions and test expectations"),s.length===0&&s.push("All validations passing - no immediate action required"),s}async updateManifest(e){if(!N(this.manifestPath))throw new Error(`Manifest file not found: ${this.manifestPath}`);let t=C(E(this.manifestPath,"utf-8"));for(let[s,a]of e.skillResults.entries())if(t.skills&&t.skills[s]){let n=t.skills[s];n.validation||(n.validation={}),n.validation.passRate=a.avgPassRate,n.validation.lastValidated=e.timestamp.toISOString(),n.validation.status=a.avgPassRate>=.9?"passing":"failing",n.validation.passRateByModel=Object.fromEntries(a.passRateByModel)}let i=Array.from(e.skillResults.values());t.validationStatus={passing:i.filter(s=>s.avgPassRate>=.9).length,failing:i.filter(s=>s.avgPassRate<.9).length,unknown:0,skipped:t.summary?.tier0||0},t.generatedAt=new Date().toISOString(),t.lastValidationRun={runId:e.runId,timestamp:e.timestamp.toISOString(),avgPassRate:e.summary.avgPassRate,modelsUsed:e.summary.modelsUsed},L(this.manifestPath,JSON.stringify(t,null,2))}generateMarkdownReport(e){let{summary:t,crossModelAnalysis:i,regressions:s,recommendations:a,skillResults:n}=e,c=(t.avgPassRate>=.9||t.avgPassRate>=.7,"`"),r=[];if(r.push(`# Validation Report
3
3
 
4
4
  > ${c} Generated: ${e.timestamp.toISOString()}
5
5
  > Run ID: ${e.runId}
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{a as y}from"./chunk-E3FBW6G2.js";import{a as g,c as h}from"./chunk-HXE5NBJG.js";import{S as b,b as p}from"./chunk-T35GZXTU.js";b();var m=class{calculator;constructor(){this.calculator=new h}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new g;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{a as y}from"./chunk-JES6R5KP.js";import{a as g,c as h}from"./chunk-BJPL6THQ.js";import{S as b,b as p}from"./chunk-WJHWH5D2.js";b();var m=class{calculator;constructor(){this.calculator=new h}computeLambda(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);return this.calculator.getMinCutValue(e)}computeRoutingTier(t,n){let e=this.buildTaskGraphFromTopology(n),o=this.toSwarmGraph(e),s=this.calculator.getMinCutValue(o),r=Math.max(n.length-1,1),a=Math.min(s/r,1),{tier:i,label:d}=this.lambdaToTier(a),c=this.computeConfidence(o,a),l=this.buildRationale(t,a,i,n.length);return{tier:i,label:d,lambda:s,normalizedLambda:a,confidence:c,rationale:l}}getStructuralHealth(t){let n=this.maybeSparsify(t),e=this.toSwarmGraph(n);if(e.isEmpty())return this.emptyHealthReport();let o=this.calculator.getMinCutValue(e),s=e.getStats(),r=Math.max(s.vertexCount-1,1),a=Math.min(o/r,1),i=this.calculator.findWeakVertices(e),d=i.map(f=>f.vertexId),c=1-a,l=a>=.4,u=this.generateHealthSuggestions(a,i.length,s);return{lambda:o,normalizedLambda:a,healthy:l,weakPoints:d,riskScore:c,componentCount:s.componentCount,isConnected:s.isConnected,suggestions:u,analyzedAt:new Date}}maybeSparsify(t){if(!p().useSpectralSparsification||t.edges.length<=100)return t;let n=new Map;t.nodes.forEach((i,d)=>n.set(i.id,d));let e=[];for(let i of t.edges){let d=n.get(i.source),c=n.get(i.target);d!==void 0&&c!==void 0&&e.push([d,c,i.weight])}let o={nodeCount:t.nodes.length,edges:e},r=new y({epsilon:.3}).sparsify(o),a=[];for(let[i,d,c]of r.edges){let l=t.nodes[i],u=t.nodes[d];l&&u&&a.push({source:l.id,target:u.id,weight:c,edgeType:"coordination"})}return{nodes:t.nodes,edges:a}}toSwarmGraph(t){let n=new g;for(let e of t.nodes){let o={id:e.id,type:e.type==="task"||e.type==="agent"?"agent":"domain",domain:e.domain,weight:e.weight,createdAt:new Date,metadata:e.metadata};n.addVertex(o)}for(let e of t.edges)if(n.hasVertex(e.source)&&n.hasVertex(e.target)){let o={source:e.source,target:e.target,weight:e.weight,type:e.edgeType==="dependency"?"dependency":e.edgeType==="communication"?"communication":e.edgeType==="workflow"?"workflow":"coordination",bidirectional:e.edgeType!=="dependency"};n.addEdge(o)}return n}buildTaskGraphFromTopology(t){let n=t.map(r=>({id:r.id,label:r.name,type:"agent",domain:r.domain,weight:r.weight})),e=[],o=new Set(t.map(r=>r.id));for(let r of t)for(let a of r.dependsOn)o.has(a)&&e.push({source:r.id,target:a,weight:1,edgeType:"dependency"});let s=new Map;for(let r of t){let a=s.get(r.domain)||[];a.push(r.id),s.set(r.domain,a)}for(let[,r]of s)for(let a=0;a<r.length;a++)for(let i=a+1;i<r.length;i++)e.push({source:r[a],target:r[i],weight:.5,edgeType:"coordination"});return{nodes:n,edges:e}}lambdaToTier(t){return t>=.8?{tier:1,label:"Haiku"}:t>=.4?{tier:2,label:"Sonnet"}:{tier:3,label:"Opus"}}computeConfidence(t,n){let e=t.getStats();if(e.vertexCount<3)return .4;let o=Math.min(Math.abs(n-.4),Math.abs(n-.8)),s=Math.min(.95,.5+o*2.25),r=Math.min(1,e.density*2);return Math.min(.99,s*(.7+.3*r))}buildRationale(t,n,e,o){let s=t.slice(0,80),r=n>=.8?"highly connected":n>=.4?"moderately connected":"fragmented";return`Task "${s}" routed to ${e===1?"Haiku":e===2?"Sonnet":"Opus"} (Tier ${e}). Fleet topology is ${r} (lambda=${n.toFixed(3)}) across ${o} agents.`}generateHealthSuggestions(t,n,e){let o=[];return e.isConnected||o.push(`Graph has ${e.componentCount} disconnected components. Add cross-domain coordination edges to improve connectivity.`),t<.2?o.push("Critical: Fleet connectivity is very low. Consider spawning coordination agents."):t<.4&&o.push("Warning: Fleet connectivity is below healthy threshold. Reinforce weak connections."),n>0&&o.push(`${n} weak point(s) detected. Add redundant connections to these agents.`),e.vertexCount<3&&o.push("Fleet has fewer than 3 agents. MinCut analysis is most useful with larger topologies."),o}emptyHealthReport(){return{lambda:0,normalizedLambda:0,healthy:!1,weakPoints:[],riskScore:1,componentCount:0,isConnected:!0,suggestions:["No agents in fleet. Spawn agents to build a topology."],analyzedAt:new Date}}};function C(){return new m}export{C as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");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.14.5");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");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.14.5");process.exit(0)}
2
2
  import{writeFileSync as d,readFileSync as m}from"node:fs";import{resolve as f,dirname as u,join as g}from"node:path";import{mkdirSync as h}from"node:fs";import{fileURLToPath as v}from"node:url";function y(){try{let e=typeof __dirname<"u"?__dirname:u(v(import.meta.url));for(let n=0;n<5;n++){let t=g(e,"package.json");try{let o=JSON.parse(m(t,"utf-8"));if(o.version)return o.version}catch{}e=u(e)}}catch{}return"unknown"}function l(e){return e.status??e.evidence?.completeness??"unverified"}var R=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],T=["-o, --output <path>","Write output to file instead of stdout"];function w(e,n,t){if(n){let o=f(n);h(u(o),{recursive:!0}),d(o,e,"utf-8"),t&&console.log(t),console.log(`Output written to: ${o}`)}else console.log(e)}function $(e){return JSON.stringify(e,null,2)}var S="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function F(e){let n=l(e),t=s=>{switch(s.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},o=new Map,r=[];for(let s of e.vulnerabilities){let a=s.ruleId||`AQE/${s.type.replace(/\s+/g,"-").toLowerCase()}`;o.has(a)||o.set(a,{id:a,name:s.type,shortDescription:s.type,...s.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${s.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:a,level:t(s.severity),message:{text:s.message},locations:[{physicalLocation:{artifactLocation:{uri:s.file,uriBaseId:"%SRCROOT%"},region:{startLine:s.line,startColumn:1}}}],...s.cweId?{taxa:[{id:s.cweId,toolComponent:{name:"CWE"}}]}:{}})}let i={$schema:S,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:y(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(o.values()).map(s=>({id:s.id,name:s.name,shortDescription:{text:s.shortDescription},...s.helpUri?{helpUri:s.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,properties:{securityScan:{status:n,target:e.target,scanType:e.scanType,coverage:e.evidence?e.coverage:void 0,evidence:e.evidence,discovery:e.discovery,checks:e.checks}},invocations:[{executionSuccessful:n==="complete",...n==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${n}; findings do not establish complete coverage.`}}]}}]}]};return JSON.stringify(i,null,2)}function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function A(e){let n=e.tests||[],t=e.passed+e.failed+e.skipped,o=(e.duration/1e3).toFixed(3),r=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `;if(r+=`<testsuites tests="${t}" failures="${e.failed}" errors="0" time="${o}">
4
4
  `,r+=` <testsuite name="aqe-test-run" tests="${t}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${o}" id="${c(e.runId)}">
@@ -1,12 +1,12 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{a as v}from"./chunk-EY4OQHU3.js";import{a as h}from"./chunk-L2GKMBDP.js";import{c as E}from"./chunk-72UJXEKQ.js";import{a as y,c as k}from"./chunk-HRUU7E3D.js";k();h();var l=E.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function Q(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-VBQ572X4.js");o=c().getDatabase().prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{a as v}from"./chunk-5WOSWNDN.js";import{a as h}from"./chunk-J27F4NSB.js";import{c as E}from"./chunk-7CD7PBHY.js";import{a as y,c as k}from"./chunk-J5UNP6W3.js";k();h();var l=E.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function Q(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-DDWMC435.js");o=c().getDatabase().prepare(`
3
3
  SELECT u.pattern_id, u.success, u.feedback
4
4
  FROM qe_pattern_usage u
5
5
  JOIN qe_patterns p ON u.pattern_id = p.id
6
6
  WHERE p.qe_domain = 'test-generation'
7
7
  ORDER BY u.created_at DESC
8
8
  LIMIT 10
9
- `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-VBQ572X4.js");r=n().getDatabase().prepare(`
9
+ `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-DDWMC435.js");r=n().getDatabase().prepare(`
10
10
  SELECT u.pattern_id, u.success, u.feedback
11
11
  FROM qe_pattern_usage u
12
12
  JOIN qe_patterns p ON u.pattern_id = p.id
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{l as p}from"./chunk-44WISFTU.js";import{a as f,c as R}from"./chunk-HRUU7E3D.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-B6E7JPPJ.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{l as p}from"./chunk-YDFL445W.js";import{a as f,c as R}from"./chunk-J5UNP6W3.js";R();var u=class extends p{config={name:"qe/workflows/browser-load",description:"Load, validate, and prepare browser automation workflows from inline YAML or built-in templates. Returns the resolved workflow with steps and variable bindings, ready for browser execution. Templates: login-flow, form-validation, visual-regression, oauth-flow, etc.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{workflowYaml:{type:"string",description:"Inline YAML workflow definition. Mutually exclusive with templateName."},templateName:{type:"string",description:"Built-in template name to load.",enum:["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"]},variables:{type:"object",description:'Runtime variable overrides (e.g., { "baseUrl": "https://example.com" })'}}}}async execute(r,C){try{let{WorkflowLoader:n,WORKFLOW_TEMPLATES:g,WORKFLOW_DESCRIPTIONS:v,interpolateVariables:b}=await import("./browser-32F6MREU.js"),{parse:k}=await import("yaml"),d=new n,l=[...g],y=v;if(!r.workflowYaml&&!r.templateName)return{success:!0,data:{workflowName:"none",description:"No workflow specified. Use templateName or workflowYaml.",source:"none",templateUsed:null,steps:[],variables:{defined:[],provided:{}},validation:{valid:!0,errors:[],warnings:[]},availableTemplates:l,summary:`Available templates: ${l.join(", ")}`}};let e,i,t=null;r.workflowYaml?(i="inline-yaml",e=k(r.workflowYaml)):(i="template",t=r.templateName,e=await d.load(r.templateName));let a=await d.validate(e),w=(e.steps??[]).map(o=>{let s=o.config;if(r.variables){let c={};for(let[h,m]of Object.entries(s))c[h]=typeof m=="string"?b(m,r.variables):m;s=c}return{name:o.name,action:o.action,config:s,optional:o.optional??!1,assertionCount:o.assertions?.length??0}});return{success:!0,data:{workflowName:e.name||t||"custom",description:e.description||t&&y[t]||"",source:i,templateUsed:t,steps:w,variables:{defined:(e.variables??[]).map(o=>({name:o.name,type:o.type,required:o.required,hasDefault:o.default!==void 0})),provided:r.variables||{}},validation:{valid:a.valid,errors:a.errors,warnings:a.warnings},availableTemplates:l,summary:a.valid?`Workflow "${e.name}" loaded (${i}): ${w.length} steps, ${(e.variables??[]).length} variables`:`Workflow "${e.name}" has validation errors: ${a.errors.join("; ")}`}}}catch(n){return{success:!1,error:f(n)}}}};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.14.3");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.14.5");process.exit(0)}
2
2
  import{isIP as o}from"net";import{lookup as n}from"dns/promises";var f=[/^10\./,/^172\.(1[6-9]|2\d|3[01])\./,/^192\.168\./,/^127\./,/^0\./,/^169\.254\./,/^::1$/,/^fc00:/,/^fe80:/,/^fd[0-9a-f]{2}:/i];function t(r){return f.some(s=>s.test(r))}async function u(r){if(process.env.AQE_HOOKS_SSRF_DISABLED==="true")return{safe:!0};let s;try{s=new URL(r)}catch{return{safe:!1,reason:`Invalid URL: ${r}`}}let e=s.hostname.replace(/^\[|\]$/g,"");if(o(e))return t(e)?{safe:!1,reason:`Private IP blocked: ${e}`}:{safe:!0};try{let a=await n(e);if(t(a.address))return{safe:!1,reason:`DNS resolves to private IP: ${a.address}`}}catch(a){return{safe:!1,reason:`DNS lookup failed for ${e}: ${a.message}`}}return{safe:!0}}export{t as a,u as b};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{g as m,n as h}from"./chunk-R6IU3EWP.js";import{b as g}from"./chunk-JSZ663MU.js";import{randomUUID as b}from"crypto";function v(d){let t=C[d];if(t)return{input:t.input,output:t.output};let e=m(d);if(e.inputCostPerMillion>0||e.outputCostPerMillion>0)return{input:e.inputCostPerMillion,output:e.outputCostPerMillion}}function R(){return s||(s=new l),s}function P(){s&&(s.dispose(),s=void 0)}var C,l,s,k=g(()=>{h();C={"claude-sonnet-5":{input:2,output:10,provider:"claude"},"claude-opus-5":{input:5,output:25,provider:"claude"},"claude-opus-5-5":{input:4,output:20,provider:"claude"},"claude-fable-5-1":{input:10,output:50,provider:"claude"},"claude-fable-5":{input:10,output:50,provider:"claude"},"claude-opus-4-8":{input:5,output:25,provider:"claude"},"claude-opus-4-7":{input:5,output:25,provider:"claude"},"claude-sonnet-4-6":{input:3,output:15,provider:"claude"},"claude-haiku-4-5-20251001":{input:1,output:5,provider:"claude"},"claude-haiku-4-5":{input:1,output:5,provider:"claude"},"claude-opus-4-5-20251101":{input:5,output:25,provider:"claude"},"claude-opus-4-6":{input:5,output:25,provider:"claude"},"claude-sonnet-4-20250514":{input:3,output:15,provider:"claude"},"claude-3-5-haiku-20241022":{input:1,output:5,provider:"claude"},"claude-3-opus-20240229":{input:15,output:75,provider:"claude"},"claude-3-sonnet-20240229":{input:3,output:15,provider:"claude"},"claude-3-haiku-20240307":{input:.25,output:1.25,provider:"claude"},"gpt-6-astra":{input:10,output:50,provider:"openai"},"gpt-6-sol":{input:2,output:10,provider:"openai"},"gpt-6-luna":{input:.1,output:.5,provider:"openai"},"gpt-4o":{input:5,output:15,provider:"openai"},"gpt-4o-mini":{input:.15,output:.6,provider:"openai"},"gpt-4-turbo":{input:10,output:30,provider:"openai"},"gpt-4":{input:30,output:60,provider:"openai"},"gpt-3.5-turbo":{input:.5,output:1.5,provider:"openai"},llama3:{input:0,output:0,provider:"ollama"},"llama3.1":{input:0,output:0,provider:"ollama"},codellama:{input:0,output:0,provider:"ollama"},mistral:{input:0,output:0,provider:"ollama"},mixtral:{input:0,output:0,provider:"ollama"},phi3:{input:0,output:0,provider:"ollama"},qwen2:{input:0,output:0,provider:"ollama"},"anthropic/claude-sonnet-5":{input:2,output:10,provider:"openrouter"},"anthropic/claude-opus-5":{input:5,output:25,provider:"openrouter"},"anthropic/claude-opus-5.5":{input:4,output:20,provider:"openrouter"},"anthropic/claude-haiku-4.5":{input:1,output:5,provider:"openrouter"},"openai/gpt-6-sol":{input:2,output:10,provider:"openrouter"},"openai/gpt-6-luna":{input:.1,output:.5,provider:"openrouter"},"google/gemini-3.8-flash":{input:.75,output:3.75,provider:"openrouter"},"meta-llama/llama-4-maverick":{input:.1875,output:.6525,provider:"openrouter"},"openai/gpt-oss-120b":{input:.15,output:.6,provider:"openrouter"},"qwen/qwen3-coder":{input:.3,output:1,provider:"openrouter"},"anthropic/claude-3.5-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3.5-sonnet:beta":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-opus":{input:15,output:75,provider:"openrouter"},"anthropic/claude-3-sonnet":{input:3,output:15,provider:"openrouter"},"anthropic/claude-3-haiku":{input:.25,output:1.25,provider:"openrouter"},"openai/gpt-4o":{input:5,output:15,provider:"openrouter"},"openai/gpt-4o-mini":{input:.15,output:.6,provider:"openrouter"},"openai/gpt-4-turbo":{input:10,output:30,provider:"openrouter"},"openai/gpt-3.5-turbo":{input:.5,output:1.5,provider:"openrouter"},"google/gemini-pro":{input:.125,output:.375,provider:"openrouter"},"google/gemini-pro-1.5":{input:3.5,output:10.5,provider:"openrouter"},"meta-llama/llama-3.1-70b-instruct":{input:.59,output:.79,provider:"openrouter"},"meta-llama/llama-3.1-8b-instruct":{input:.06,output:.06,provider:"openrouter"},"mistralai/mistral-large":{input:2,output:6,provider:"openrouter"},"mistralai/mixtral-8x7b-instruct":{input:.24,output:.24,provider:"openrouter"},"mistralai/mistral-7b-instruct":{input:.06,output:.06,provider:"openrouter"},"anthropic.claude-opus-4-5-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-opus-4-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-sonnet-4-5-v2:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-sonnet-4-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-5-haiku-v1:0":{input:1,output:5,provider:"bedrock"},"anthropic.claude-3-opus-20240229-v1:0":{input:15,output:75,provider:"bedrock"},"anthropic.claude-3-sonnet-20240229-v1:0":{input:3,output:15,provider:"bedrock"},"anthropic.claude-3-haiku-20240307-v1:0":{input:.25,output:1.25,provider:"bedrock"},"anthropic.claude-3-5-sonnet-20241022-v2:0":{input:3,output:15,provider:"bedrock"},"azure/gpt-4o":{input:5,output:15,provider:"azure-openai"},"azure/gpt-4o-mini":{input:.15,output:.6,provider:"azure-openai"},"azure/gpt-4-turbo":{input:10,output:30,provider:"azure-openai"},"azure/gpt-4":{input:30,output:60,provider:"azure-openai"},"azure/gpt-35-turbo":{input:.5,output:1.5,provider:"azure-openai"},"azure/text-embedding-ada-002":{input:.1,output:0,provider:"azure-openai"},"azure/text-embedding-3-small":{input:.02,output:0,provider:"azure-openai"},"azure/text-embedding-3-large":{input:.13,output:0,provider:"azure-openai"},"gemini-3.8-flash":{input:.75,output:3.75,provider:"gemini"},"gemini-3.5-flash":{input:1.5,output:9,provider:"gemini"},"gemini-3.1-pro-preview":{input:2,output:12,provider:"gemini"},"gemini-2.5-flash":{input:.3,output:2.5,provider:"gemini"},"gemini-2.5-pro":{input:1.25,output:10,provider:"gemini"},"gemini-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.0-pro":{input:.5,output:1.5,provider:"gemini"},"gemini-1.5-pro":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-pro-latest":{input:3.5,output:10.5,provider:"gemini"},"gemini-1.5-flash":{input:.075,output:.3,provider:"gemini"},"gemini-1.5-flash-latest":{input:.075,output:.3,provider:"gemini"},"gemini-2.0-flash-exp":{input:.075,output:.3,provider:"gemini"},"gemini-ultra":{input:7,output:21,provider:"gemini"},"gemini-1.0-ultra":{input:7,output:21,provider:"gemini"},"text-embedding-004":{input:.025,output:0,provider:"gemini"}};l=class d{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(t=1e4){this.maxRecords=t}static calculateCost(t,e){let o=v(t);if(!o)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let i=e.promptTokens/1e6*o.input+(e.cacheReadTokens??0)/1e6*o.input*.1+(e.cacheCreationTokens??0)/1e6*o.input*1.25,r=e.completionTokens/1e6*o.output;return{inputCost:i,outputCost:r,totalCost:i+r,currency:"USD"}}static getCostPerToken(t){let e=v(t);return e?{input:e.input/1e6,output:e.output/1e6}:{input:0,output:0}}recordUsage(t,e,o,i,r){let p=d.calculateCost(e,o),n={timestamp:new Date,provider:t,model:e,usage:o,cost:p,requestId:i,metadata:r};return this.records.push(n),this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords)),this.checkAlerts(),p}getSummary(t){let e=new Date,o=this.getPeriodStart(e,t),i=e,r=this.records.filter(a=>a.timestamp>=o&&a.timestamp<=i),p={claude:0,"claude-code":0,codex:0,openai:0,ollama:0,openrouter:0,bedrock:0,"azure-openai":0,gemini:0,cognitum:0},n={},u=0,c=0;for(let a of r)u+=a.cost.totalCost,c+=a.usage.totalTokens,p[a.provider]+=a.cost.totalCost,n[a.model]=(n[a.model]||0)+a.cost.totalCost;return{period:t,periodStart:o,periodEnd:i,totalCost:u,byProvider:p,byModel:n,totalTokens:c,totalRequests:r.length}}getCurrentCost(t){return this.getSummary(t).totalCost}getTotalTokens(t){return this.getSummary(t).totalTokens}getUsageByProvider(t,e="all"){let o=this.getPeriodStart(new Date,e),i=this.records.filter(u=>u.provider===t&&u.timestamp>=o),r={},p=0,n=0;for(let u of i)p+=u.cost.totalCost,n+=u.usage.totalTokens,r[u.model]||(r[u.model]={cost:0,tokens:0,requests:0}),r[u.model].cost+=u.cost.totalCost,r[u.model].tokens+=u.usage.totalTokens,r[u.model].requests+=1;return{totalCost:p,totalTokens:n,totalRequests:i.length,models:r}}addAlert(t,e,o){let i=`alert-${Date.now()}-${b().slice(0,12)}`;return this.alerts.push({threshold:t,period:e,onThreshold:o,active:!0}),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),i}removeAlert(t){return t>=0&&t<this.alerts.length?(this.alerts.splice(t,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getRecords(){return[...this.records]}importRecords(t){for(let e of t)e.timestamp=new Date(e.timestamp),this.records.push(e);this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}clear(){this.records=[]}getRecentRequests(t=10){return this.records.slice(-t)}estimateCost(t,e,o){return d.calculateCost(t,{promptTokens:e,completionTokens:o,totalTokens:e+o})}wouldExceedLimit(t,e,o,i,r){let p=this.getCurrentCost(r),n=this.estimateCost(t,e,o);return p+n.totalCost>i}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}getPeriodStart(t,e){let o=new Date(t);switch(e){case"minute":o.setSeconds(0,0),o.setMinutes(o.getMinutes()-1);break;case"hour":o.setMinutes(0,0,0),o.setHours(o.getHours()-1);break;case"day":o.setHours(0,0,0,0);break;case"week":o.setHours(0,0,0,0),o.setDate(o.getDate()-7);break;case"month":o.setHours(0,0,0,0),o.setDate(1);break;case"all":return new Date(0)}return o}checkAlerts(){for(let t of this.alerts){if(!t.active)continue;let e=this.getSummary(t.period);if(e.totalCost>=t.threshold){t.active=!1;try{t.onThreshold(e)}catch(o){console.error("Cost alert callback error:",o)}}}}}});export{C as a,v as b,l as c,R as d,P as e,k as f};
@@ -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.14.3");process.exit(0)}
2
- import{d as j,f as ze}from"./chunk-4RP5VUBI.js";import{a as z,c as He}from"./chunk-5F6DWHQG.js";import{a as Be}from"./chunk-L2GKMBDP.js";import{c as se}from"./chunk-72UJXEKQ.js";import{a as H,b as D,c as We}from"./chunk-Y5SQBI2F.js";import{b as I,d as oe}from"./chunk-YAKS3CAB.js";import{a as X,c as ke}from"./chunk-HRUU7E3D.js";import{a as ie,b as je}from"./chunk-MXMFGSWR.js";import{a as ae,d as U,e as ce,f as Te}from"./chunk-PI74GOE4.js";import{a as b,b as re,e as qe}from"./chunk-OVDKWCD7.js";import{c as R,e as Pe}from"./chunk-Y2DVFVGI.js";import{createHash as ue}from"node:crypto";function $e(s){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(s)),e}function Ke(s){return typeof s=="string"?Buffer.from(s,"utf8"):s instanceof Uint8Array?Buffer.from(s):Buffer.from(W(s),"utf8")}function W(s){return s===null||typeof s!="object"?JSON.stringify(s)??"null":Array.isArray(s)?`[${s.map(W).join(",")}]`:`{${Object.keys(s).sort().map(t=>`${JSON.stringify(t)}:${W(s[t])}`).join(",")}}`}function _e(...s){let e=ue("sha256");for(let t of s)e.update(t);return e.digest()}function de(s,e,t){return _e(Ye,s,e,$e(t))}var Ye,Ee,O,le=R(()=>{"use strict";Ye=Buffer.from("ruvector:chain:"),Ee=ue("sha256").update("ruvector-proof-gate-v1").digest();O=class s{seq=0;prev=Ee;chain=[];payloadHashes=[];admit(e){let t=_e(Ke(e)),n=de(this.prev,t,this.seq);this.prev=n,this.chain.push(n),this.payloadHashes.push(t);let a={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:n.toString("hex")};return this.seq+=1,a}verifyReceipt(e){return e.sequence>=0&&e.sequence<this.chain.length&&this.chain[e.sequence].toString("hex")===e.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let e=Ee;for(let t=0;t<this.chain.length;t++){if(!de(e,this.payloadHashes[t],t).equals(this.chain[t]))return!1;e=this.chain[t]}return e.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(e=>e.toString("hex")),payloadHashes:this.payloadHashes.map(e=>e.toString("hex"))}}static fromJSON(e){let t=new s;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let n of e.chain)t.chain.push(Buffer.from(n,"hex"));for(let n of e.payloadHashes)t.payloadHashes.push(Buffer.from(n,"hex"));return t}}});function A(s){if(!Y.has(s))throw new Error(`Invalid table name: "${s}" is not in the allowlist`);return s}function ot(s){let e=s.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${s}" has too many parts (max: schema.table)`);for(let t of e)if(!pe.test(t))throw new Error(`Invalid SQL identifier: "${s}" \u2014 part "${t}" does not match pattern ${pe}`);return s}var Y,pe,$=R(()=>{"use strict";Y=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);pe=/^[a-z_][a-z0-9_]{0,62}$/});function me(s){s.exec(ge),s.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.14.5");process.exit(0)}
2
+ import{d as j,f as ze}from"./chunk-RKOUXVZZ.js";import{b as I,d as oe}from"./chunk-IJHCIXJC.js";import{a as z,c as He}from"./chunk-NQI7FWCS.js";import{a as H,b as D,c as We}from"./chunk-C3HQL6S4.js";import{a as qe}from"./chunk-J27F4NSB.js";import{c as re}from"./chunk-7CD7PBHY.js";import{a as X,c as ke}from"./chunk-J5UNP6W3.js";import{a as ie,b as je}from"./chunk-HVU64GP5.js";import{a as ae,d as U,e as ce,f as Te}from"./chunk-52L77RMG.js";import{a as b,b as se,e as Be}from"./chunk-CVMNJSCB.js";import{b as R,d as Pe}from"./chunk-JSZ663MU.js";import{createHash as ue}from"node:crypto";function $e(s){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(s)),e}function Ke(s){return typeof s=="string"?Buffer.from(s,"utf8"):s instanceof Uint8Array?Buffer.from(s):Buffer.from(W(s),"utf8")}function W(s){return s===null||typeof s!="object"?JSON.stringify(s)??"null":Array.isArray(s)?`[${s.map(W).join(",")}]`:`{${Object.keys(s).sort().map(t=>`${JSON.stringify(t)}:${W(s[t])}`).join(",")}}`}function _e(...s){let e=ue("sha256");for(let t of s)e.update(t);return e.digest()}function de(s,e,t){return _e(Ye,s,e,$e(t))}var Ye,Ee,O,le=R(()=>{"use strict";Ye=Buffer.from("ruvector:chain:"),Ee=ue("sha256").update("ruvector-proof-gate-v1").digest();O=class s{seq=0;prev=Ee;chain=[];payloadHashes=[];admit(e){let t=_e(Ke(e)),n=de(this.prev,t,this.seq);this.prev=n,this.chain.push(n),this.payloadHashes.push(t);let a={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:n.toString("hex")};return this.seq+=1,a}verifyReceipt(e){return e.sequence>=0&&e.sequence<this.chain.length&&this.chain[e.sequence].toString("hex")===e.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let e=Ee;for(let t=0;t<this.chain.length;t++){if(!de(e,this.payloadHashes[t],t).equals(this.chain[t]))return!1;e=this.chain[t]}return e.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(e=>e.toString("hex")),payloadHashes:this.payloadHashes.map(e=>e.toString("hex"))}}static fromJSON(e){let t=new s;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let n of e.chain)t.chain.push(Buffer.from(n,"hex"));for(let n of e.payloadHashes)t.payloadHashes.push(Buffer.from(n,"hex"));return t}}});function A(s){if(!Y.has(s))throw new Error(`Invalid table name: "${s}" is not in the allowlist`);return s}function ot(s){let e=s.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${s}" has too many parts (max: schema.table)`);for(let t of e)if(!pe.test(t))throw new Error(`Invalid SQL identifier: "${s}" \u2014 part "${t}" does not match pattern ${pe}`);return s}var Y,pe,$=R(()=>{"use strict";Y=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);pe=/^[a-z_][a-z0-9_]{0,62}$/});function me(s){s.exec(ge),s.exec(`
3
3
  INSERT OR IGNORE INTO learning_evidence_manifests (
4
4
  id, trajectory_id, trajectory_hash, manifest_hash, task_family,
5
5
  outcome, oracle_refs_json, source_kind, process_signals_json
@@ -730,7 +730,7 @@ import{d as j,f as ze}from"./chunk-4RP5VUBI.js";import{a as z,c as He}from"./chu
730
730
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
731
731
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
732
732
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
733
- `,Oe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","goap_execution_steps","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage"]});function F(s,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?s:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function a(o,T,d,E){return o!==d?o-d:T.localeCompare(E)}return{get(){return n.value},set(o,T){let d=T??Date.now();(n.timestamp===0||a(d,s,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:d,nodeId:s,version:n.version+1,lastUpdated:Date.now()})},merge(o){let T=o.getState();this.applyState(T)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||a(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return s},getTimestamp(){return n.timestamp}}}function x(s,e){let t=F(s);return t.applyState(e),t}var J=R(()=>{"use strict"});function C(s){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[s]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[s]=(e.counts[s]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[a,o]of Object.entries(t.counts)){let T=e.counts[a]||0;o>T&&(e.counts[a]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return s},getLocalCount(){return e.counts[s]||0}}}function G(s,e){let t=C(s);return t.applyState(e),t}var M=R(()=>{"use strict"});function P(s){let e=C(s),t=C(s),n=0,a=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,a=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,a=Date.now())},merge(o){let T=o.getState();this.applyState(T)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:a}},applyState(o){let T=this.get();e.applyState(o.positive),t.applyState(o.negative);let d=this.get();T!==d&&(n=Math.max(n,o.version)+1,a=Date.now())},getNodeId(){return s}}}function k(s,e){let t=P(s);return t.applyState(e),t}var Z=R(()=>{"use strict";M()});function Ve(s,e){return`${s}:${Date.now()}:${e}`}function ee(s){return typeof s=="string"?`s:${s}`:typeof s=="number"?`n:${s}`:typeof s=="boolean"?`b:${s}`:`j:${JSON.stringify(s)}`}function Qe(s){let e=s.substring(0,2),t=s.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return I(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function q(s){let e=new Map,t=new Map,n=0,a=Date.now(),o=0;function T(E){let u=e.get(E);if(!u||u.size===0)return!1;let _=t.get(E);if(!_||_.size===0)return!0;for(let m of u)if(!_.has(m))return!0;return!1}function d(E){let u=e.get(E);if(!u)return new Set;let _=t.get(E)||new Set,m=new Set;for(let p of u)_.has(p)||m.add(p);return m}return{has(E){let u=ee(E);return T(u)},values(){let E=[];for(let[u]of e)T(u)&&E.push(Qe(u));return E},size(){let E=0;for(let[u]of e)T(u)&&E++;return E},add(E){let u=ee(E),_=Ve(s,o++);e.has(u)||e.set(u,new Set),e.get(u).add(_),n++,a=Date.now()},remove(E){let u=ee(E),_=e.get(u);if(!_||_.size===0)return;t.has(u)||t.set(u,new Set);let m=t.get(u);for(let p of _)m.add(p);n++,a=Date.now()},merge(E){let u=E.getState();this.applyState(u)},getState(){let E={};for(let[_,m]of e)E[_]=Array.from(m);let u={};for(let[_,m]of t)m.size>0&&(u[_]=Array.from(m));return{elements:E,tombstones:u,version:n,lastUpdated:a}},applyState(E){let u=!1;for(let[_,m]of Object.entries(E.elements)){e.has(_)||e.set(_,new Set);let p=e.get(_);for(let l of m)p.has(l)||(p.add(l),u=!0)}for(let[_,m]of Object.entries(E.tombstones)){t.has(_)||t.set(_,new Set);let p=t.get(_);for(let l of m)p.has(l)||(p.add(l),u=!0)}u&&(n=Math.max(n,E.version)+1,a=Date.now())},getNodeId(){return s},clear(){for(let[E,u]of e){t.has(E)||t.set(E,new Set);let _=t.get(E);for(let m of u)_.add(m)}n++,a=Date.now()}}}function B(s,e){let t=q(s);return t.applyState(e),t}var te=R(()=>{"use strict";oe()});function ne(s){let e={...Je,...s},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:a}=e,o=new Map,T=new Map,d=new Map,E=new Map,u=0,_=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function l(i,r,c){let N={key:i,type:r,operation:c,timestamp:Date.now(),nodeId:t};for(let Ge of m)try{Ge(N)}catch(Me){console.error("[CRDTStore] Error in change listener:",Me)}}function g(i,r){u++,n&&p[i].add(r)}function L(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:_.length>0?_[_.length-1].toVersion:0,toVersion:u,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let c of p.registers){let N=o.get(c);N&&(r.registers[c]=N.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let c of p.gCounters){let N=T.get(c);N&&(r.gCounters[c]=N.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let c of p.pnCounters){let N=d.get(c);N&&(r.pnCounters[c]=N.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let c of p.sets){let N=E.get(c);N&&(r.sets[c]=N.getState())}p.sets.clear()}for(_.push(r);_.length>a;)_.shift()}let h={getRegister(i){return o.has(i)||o.set(i,F(t)),o.get(i)},setRegister(i,r){h.getRegister(i).set(r),g("registers",i),l(i,"lww-register","set")},hasRegister(i){return o.has(i)},deleteRegister(i){let r=o.delete(i);return r&&g("registers",i),r},getGCounter(i){return T.has(i)||T.set(i,C(t)),T.get(i)},incrementGCounter(i,r){h.getGCounter(i).increment(r),g("gCounters",i),l(i,"g-counter","increment")},hasGCounter(i){return T.has(i)},deleteGCounter(i){let r=T.delete(i);return r&&g("gCounters",i),r},getCounter(i){return d.has(i)||d.set(i,P(t)),d.get(i)},incrementCounter(i,r){h.getCounter(i).increment(r),g("pnCounters",i),l(i,"pn-counter","increment")},decrementCounter(i,r){h.getCounter(i).decrement(r),g("pnCounters",i),l(i,"pn-counter","decrement")},hasCounter(i){return d.has(i)},deleteCounter(i){let r=d.delete(i);return r&&g("pnCounters",i),r},getSet(i){return E.has(i)||E.set(i,q(t)),E.get(i)},addToSet(i,r){h.getSet(i).add(r),g("sets",i),l(i,"or-set","add")},removeFromSet(i,r){h.getSet(i).remove(r),g("sets",i),l(i,"or-set","remove")},hasSet(i){return E.has(i)},deleteSet(i){let r=E.delete(i);return r&&g("sets",i),r},merge(i){let r=i.getState();h.applyState(r)},getState(){L();let i={version:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,c]of o)i.registers[r]=c.getState();for(let[r,c]of T)i.gCounters[r]=c.getState();for(let[r,c]of d)i.pnCounters[r]=c.getState();for(let[r,c]of E)i.sets[r]=c.getState();return i},applyState(i){for(let[r,c]of Object.entries(i.registers))o.has(r)?o.get(r).applyState(c):o.set(r,x(t,c)),g("registers",r),l(r,"lww-register","merge");for(let[r,c]of Object.entries(i.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,G(t,c)),g("gCounters",r),l(r,"g-counter","merge");for(let[r,c]of Object.entries(i.pnCounters))d.has(r)?d.get(r).applyState(c):d.set(r,k(t,c)),g("pnCounters",r),l(r,"pn-counter","merge");for(let[r,c]of Object.entries(i.sets))E.has(r)?E.get(r).applyState(c):E.set(r,B(t,c)),g("sets",r),l(r,"or-set","merge");u=Math.max(u,i.version)+1},getDelta(i){if(L(),_.length===0)return i>=u,null;let r=_.filter(N=>N.toVersion>i);if(r.length===0)return null;let c={fromVersion:i,toVersion:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let N of r)N.registers&&Object.assign(c.registers,N.registers),N.gCounters&&Object.assign(c.gCounters,N.gCounters),N.pnCounters&&Object.assign(c.pnCounters,N.pnCounters),N.sets&&Object.assign(c.sets,N.sets);return Object.keys(c.registers).length===0&&delete c.registers,Object.keys(c.gCounters).length===0&&delete c.gCounters,Object.keys(c.pnCounters).length===0&&delete c.pnCounters,Object.keys(c.sets).length===0&&delete c.sets,c},applyDelta(i){if(i.registers)for(let[r,c]of Object.entries(i.registers))o.has(r)?o.get(r).applyState(c):o.set(r,x(t,c)),g("registers",r),l(r,"lww-register","merge");if(i.gCounters)for(let[r,c]of Object.entries(i.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,G(t,c)),g("gCounters",r),l(r,"g-counter","merge");if(i.pnCounters)for(let[r,c]of Object.entries(i.pnCounters))d.has(r)?d.get(r).applyState(c):d.set(r,k(t,c)),g("pnCounters",r),l(r,"pn-counter","merge");if(i.sets)for(let[r,c]of Object.entries(i.sets))E.has(r)?E.get(r).applyState(c):E.set(r,B(t,c)),g("sets",r),l(r,"or-set","merge");u=Math.max(u,i.toVersion)+1},getVersion(){return u},getNodeId(){return t},on(i,r){if(i==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${i}`)},removeAllListeners(){m.clear()},keys(i){let r=[];return(!i||i==="lww-register")&&r.push(...Array.from(o.keys())),(!i||i==="g-counter")&&r.push(...Array.from(T.keys())),(!i||i==="pn-counter")&&r.push(...Array.from(d.keys())),(!i||i==="or-set")&&r.push(...Array.from(E.keys())),r},clear(){o.clear(),T.clear(),d.clear(),E.clear(),_.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),u=0},getStats(){return{total:o.size+T.size+d.size+E.size,registers:o.size,gCounters:T.size,pnCounters:d.size,sets:E.size,version:u,nodeId:t,deltaHistorySize:_.length}}};return h}var Je,ve=R(()=>{"use strict";J();M();Z();te();Je={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var be=R(()=>{"use strict"});var De=R(()=>{"use strict";J();M();Z();te();ve();be()});var nt={};Pe(nt,{ALLOWED_TABLE_NAMES:()=>Y,BinaryHeap:()=>ae,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>we,UnifiedHnswIndex:()=>U,UnifiedMemoryManager:()=>v,clearProjectRootCache:()=>H,createHnswIndex:()=>ce,findProjectRoot:()=>D,getDefaultDbPath:()=>Ue,getResolvedDefaultConfig:()=>Fe,getUnifiedMemory:()=>xe,initializeUnifiedMemory:()=>Ze,resetUnifiedMemory:()=>et,validateTableName:()=>A});import*as f from"fs";import*as Xe from"os";import*as S from"path";function Ue(){let s=D();return S.join(s,".agentic-qe","memory.db")}function Fe(){return{...we,dbPath:Ue()}}function xe(s){return v.getInstance(s)}async function Ze(s){let e=xe(s);return await e.initialize(),e}function et(){v.resetInstance()}function tt(){if(ye)return;ye=!0;let s=()=>{try{let e=v.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",s),process.on("SIGINT",()=>{s(),process.exit(0)}),process.on("SIGTERM",()=>{s(),process.exit(0)})}var y,we,v,ye,rt=R(()=>{je();oe();ke();qe();Be();le();$();$();Te();Te();Ae();K();De();We();y=se.create("unified-memory");we={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:b.MMAP_SIZE_BYTES,cacheSize:b.CACHE_SIZE_KB,busyTimeout:b.BUSY_TIMEOUT_MS,vectorDimensions:b.DEFAULT_VECTOR_DIMENSIONS};v=class s{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new U("qe-memory");crdtStore=null;proofGate=null;proofGateEnvChecked=!1;static PROOF_NS="__proofgate__";static PROOF_KEY="chain";constructor(e){let t=Fe();if(this.config={...t,...e},process.env.AQE_MEMORY_BACKEND==="memory"){this.config.dbPath=":memory:";return}if(!S.isAbsolute(this.config.dbPath)){let n=D();this.config.dbPath=S.join(n,this.config.dbPath)}}static getInstance(e){return s.instance||(s.instance=new s(e)),s.instance}static async getInstanceAsync(e){return s.instance?.initialized?s.instance:(s.instancePromise||(s.instancePromise=(async()=>{let t=s.getInstance(e);return await t.initialize(),t})()),s.instancePromise)}static resetInstance(){s.instance&&(s.instance.close(),s.instance=null),s.instancePromise=null,H()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=this.config.dbPath===":memory:",n="",a=!1,o=0;if(!t){let T=process.env.AQE_PROJECT_ROOT;if(T){let d=S.resolve(this.config.dbPath),E=S.resolve(T);!d.startsWith(E)&&!d.startsWith(Xe.tmpdir())&&d.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${T}". Redirecting to test-safe path.`),this.config.dbPath=S.join(T,".agentic-qe","memory.db"))}if(n=S.dirname(this.config.dbPath),f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),a=f.existsSync(this.config.dbPath),a)o=f.statSync(this.config.dbPath).size;else if(f.existsSync(n)){let d=this.findRecentBackups(n);if(d.length>0){let E=d[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
733
+ `,Oe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","goap_execution_steps","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage"]});function F(s,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?s:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function a(o,T,d,E){return o!==d?o-d:T.localeCompare(E)}return{get(){return n.value},set(o,T){let d=T??Date.now();(n.timestamp===0||a(d,s,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:d,nodeId:s,version:n.version+1,lastUpdated:Date.now()})},merge(o){let T=o.getState();this.applyState(T)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||a(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return s},getTimestamp(){return n.timestamp}}}function x(s,e){let t=F(s);return t.applyState(e),t}var J=R(()=>{"use strict"});function C(s){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[s]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[s]=(e.counts[s]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[a,o]of Object.entries(t.counts)){let T=e.counts[a]||0;o>T&&(e.counts[a]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return s},getLocalCount(){return e.counts[s]||0}}}function G(s,e){let t=C(s);return t.applyState(e),t}var M=R(()=>{"use strict"});function P(s){let e=C(s),t=C(s),n=0,a=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,a=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,a=Date.now())},merge(o){let T=o.getState();this.applyState(T)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:a}},applyState(o){let T=this.get();e.applyState(o.positive),t.applyState(o.negative);let d=this.get();T!==d&&(n=Math.max(n,o.version)+1,a=Date.now())},getNodeId(){return s}}}function k(s,e){let t=P(s);return t.applyState(e),t}var Z=R(()=>{"use strict";M()});function Ve(s,e){return`${s}:${Date.now()}:${e}`}function ee(s){return typeof s=="string"?`s:${s}`:typeof s=="number"?`n:${s}`:typeof s=="boolean"?`b:${s}`:`j:${JSON.stringify(s)}`}function Qe(s){let e=s.substring(0,2),t=s.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return I(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function q(s){let e=new Map,t=new Map,n=0,a=Date.now(),o=0;function T(E){let u=e.get(E);if(!u||u.size===0)return!1;let _=t.get(E);if(!_||_.size===0)return!0;for(let m of u)if(!_.has(m))return!0;return!1}function d(E){let u=e.get(E);if(!u)return new Set;let _=t.get(E)||new Set,m=new Set;for(let p of u)_.has(p)||m.add(p);return m}return{has(E){let u=ee(E);return T(u)},values(){let E=[];for(let[u]of e)T(u)&&E.push(Qe(u));return E},size(){let E=0;for(let[u]of e)T(u)&&E++;return E},add(E){let u=ee(E),_=Ve(s,o++);e.has(u)||e.set(u,new Set),e.get(u).add(_),n++,a=Date.now()},remove(E){let u=ee(E),_=e.get(u);if(!_||_.size===0)return;t.has(u)||t.set(u,new Set);let m=t.get(u);for(let p of _)m.add(p);n++,a=Date.now()},merge(E){let u=E.getState();this.applyState(u)},getState(){let E={};for(let[_,m]of e)E[_]=Array.from(m);let u={};for(let[_,m]of t)m.size>0&&(u[_]=Array.from(m));return{elements:E,tombstones:u,version:n,lastUpdated:a}},applyState(E){let u=!1;for(let[_,m]of Object.entries(E.elements)){e.has(_)||e.set(_,new Set);let p=e.get(_);for(let l of m)p.has(l)||(p.add(l),u=!0)}for(let[_,m]of Object.entries(E.tombstones)){t.has(_)||t.set(_,new Set);let p=t.get(_);for(let l of m)p.has(l)||(p.add(l),u=!0)}u&&(n=Math.max(n,E.version)+1,a=Date.now())},getNodeId(){return s},clear(){for(let[E,u]of e){t.has(E)||t.set(E,new Set);let _=t.get(E);for(let m of u)_.add(m)}n++,a=Date.now()}}}function B(s,e){let t=q(s);return t.applyState(e),t}var te=R(()=>{"use strict";oe()});function ne(s){let e={...Je,...s},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:a}=e,o=new Map,T=new Map,d=new Map,E=new Map,u=0,_=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function l(i,r,c){let N={key:i,type:r,operation:c,timestamp:Date.now(),nodeId:t};for(let Ge of m)try{Ge(N)}catch(Me){console.error("[CRDTStore] Error in change listener:",Me)}}function g(i,r){u++,n&&p[i].add(r)}function L(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:_.length>0?_[_.length-1].toVersion:0,toVersion:u,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let c of p.registers){let N=o.get(c);N&&(r.registers[c]=N.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let c of p.gCounters){let N=T.get(c);N&&(r.gCounters[c]=N.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let c of p.pnCounters){let N=d.get(c);N&&(r.pnCounters[c]=N.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let c of p.sets){let N=E.get(c);N&&(r.sets[c]=N.getState())}p.sets.clear()}for(_.push(r);_.length>a;)_.shift()}let h={getRegister(i){return o.has(i)||o.set(i,F(t)),o.get(i)},setRegister(i,r){h.getRegister(i).set(r),g("registers",i),l(i,"lww-register","set")},hasRegister(i){return o.has(i)},deleteRegister(i){let r=o.delete(i);return r&&g("registers",i),r},getGCounter(i){return T.has(i)||T.set(i,C(t)),T.get(i)},incrementGCounter(i,r){h.getGCounter(i).increment(r),g("gCounters",i),l(i,"g-counter","increment")},hasGCounter(i){return T.has(i)},deleteGCounter(i){let r=T.delete(i);return r&&g("gCounters",i),r},getCounter(i){return d.has(i)||d.set(i,P(t)),d.get(i)},incrementCounter(i,r){h.getCounter(i).increment(r),g("pnCounters",i),l(i,"pn-counter","increment")},decrementCounter(i,r){h.getCounter(i).decrement(r),g("pnCounters",i),l(i,"pn-counter","decrement")},hasCounter(i){return d.has(i)},deleteCounter(i){let r=d.delete(i);return r&&g("pnCounters",i),r},getSet(i){return E.has(i)||E.set(i,q(t)),E.get(i)},addToSet(i,r){h.getSet(i).add(r),g("sets",i),l(i,"or-set","add")},removeFromSet(i,r){h.getSet(i).remove(r),g("sets",i),l(i,"or-set","remove")},hasSet(i){return E.has(i)},deleteSet(i){let r=E.delete(i);return r&&g("sets",i),r},merge(i){let r=i.getState();h.applyState(r)},getState(){L();let i={version:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,c]of o)i.registers[r]=c.getState();for(let[r,c]of T)i.gCounters[r]=c.getState();for(let[r,c]of d)i.pnCounters[r]=c.getState();for(let[r,c]of E)i.sets[r]=c.getState();return i},applyState(i){for(let[r,c]of Object.entries(i.registers))o.has(r)?o.get(r).applyState(c):o.set(r,x(t,c)),g("registers",r),l(r,"lww-register","merge");for(let[r,c]of Object.entries(i.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,G(t,c)),g("gCounters",r),l(r,"g-counter","merge");for(let[r,c]of Object.entries(i.pnCounters))d.has(r)?d.get(r).applyState(c):d.set(r,k(t,c)),g("pnCounters",r),l(r,"pn-counter","merge");for(let[r,c]of Object.entries(i.sets))E.has(r)?E.get(r).applyState(c):E.set(r,B(t,c)),g("sets",r),l(r,"or-set","merge");u=Math.max(u,i.version)+1},getDelta(i){if(L(),_.length===0)return i>=u,null;let r=_.filter(N=>N.toVersion>i);if(r.length===0)return null;let c={fromVersion:i,toVersion:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let N of r)N.registers&&Object.assign(c.registers,N.registers),N.gCounters&&Object.assign(c.gCounters,N.gCounters),N.pnCounters&&Object.assign(c.pnCounters,N.pnCounters),N.sets&&Object.assign(c.sets,N.sets);return Object.keys(c.registers).length===0&&delete c.registers,Object.keys(c.gCounters).length===0&&delete c.gCounters,Object.keys(c.pnCounters).length===0&&delete c.pnCounters,Object.keys(c.sets).length===0&&delete c.sets,c},applyDelta(i){if(i.registers)for(let[r,c]of Object.entries(i.registers))o.has(r)?o.get(r).applyState(c):o.set(r,x(t,c)),g("registers",r),l(r,"lww-register","merge");if(i.gCounters)for(let[r,c]of Object.entries(i.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,G(t,c)),g("gCounters",r),l(r,"g-counter","merge");if(i.pnCounters)for(let[r,c]of Object.entries(i.pnCounters))d.has(r)?d.get(r).applyState(c):d.set(r,k(t,c)),g("pnCounters",r),l(r,"pn-counter","merge");if(i.sets)for(let[r,c]of Object.entries(i.sets))E.has(r)?E.get(r).applyState(c):E.set(r,B(t,c)),g("sets",r),l(r,"or-set","merge");u=Math.max(u,i.toVersion)+1},getVersion(){return u},getNodeId(){return t},on(i,r){if(i==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${i}`)},removeAllListeners(){m.clear()},keys(i){let r=[];return(!i||i==="lww-register")&&r.push(...Array.from(o.keys())),(!i||i==="g-counter")&&r.push(...Array.from(T.keys())),(!i||i==="pn-counter")&&r.push(...Array.from(d.keys())),(!i||i==="or-set")&&r.push(...Array.from(E.keys())),r},clear(){o.clear(),T.clear(),d.clear(),E.clear(),_.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),u=0},getStats(){return{total:o.size+T.size+d.size+E.size,registers:o.size,gCounters:T.size,pnCounters:d.size,sets:E.size,version:u,nodeId:t,deltaHistorySize:_.length}}};return h}var Je,ve=R(()=>{"use strict";J();M();Z();te();Je={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var be=R(()=>{"use strict"});var De=R(()=>{"use strict";J();M();Z();te();ve();be()});var nt={};Pe(nt,{ALLOWED_TABLE_NAMES:()=>Y,BinaryHeap:()=>ae,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>we,UnifiedHnswIndex:()=>U,UnifiedMemoryManager:()=>v,clearProjectRootCache:()=>H,createHnswIndex:()=>ce,findProjectRoot:()=>D,getDefaultDbPath:()=>Ue,getResolvedDefaultConfig:()=>Fe,getUnifiedMemory:()=>xe,initializeUnifiedMemory:()=>Ze,resetUnifiedMemory:()=>et,validateTableName:()=>A});import*as f from"fs";import*as Xe from"os";import*as S from"path";function Ue(){let s=D();return S.join(s,".agentic-qe","memory.db")}function Fe(){return{...we,dbPath:Ue()}}function xe(s){return v.getInstance(s)}async function Ze(s){let e=xe(s);return await e.initialize(),e}function et(){v.resetInstance()}function tt(){if(ye)return;ye=!0;let s=()=>{try{let e=v.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",s),process.on("SIGINT",()=>{s(),process.exit(0)}),process.on("SIGTERM",()=>{s(),process.exit(0)})}var y,we,v,ye,rt=R(()=>{je();oe();ke();Be();qe();le();$();$();Te();Te();Ae();K();De();We();y=re.create("unified-memory");we={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:b.MMAP_SIZE_BYTES,cacheSize:b.CACHE_SIZE_KB,busyTimeout:b.BUSY_TIMEOUT_MS,vectorDimensions:b.DEFAULT_VECTOR_DIMENSIONS};v=class s{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new U("qe-memory");crdtStore=null;proofGate=null;proofGateEnvChecked=!1;static PROOF_NS="__proofgate__";static PROOF_KEY="chain";constructor(e){let t=Fe();if(this.config={...t,...e},process.env.AQE_MEMORY_BACKEND==="memory"){this.config.dbPath=":memory:";return}if(this.config.dbPath!==":memory:"&&!S.isAbsolute(this.config.dbPath)){let n=D();this.config.dbPath=S.join(n,this.config.dbPath)}}static getInstance(e){return s.instance||(s.instance=new s(e)),s.instance}static async getInstanceAsync(e){return s.instance?.initialized?s.instance:(s.instancePromise||(s.instancePromise=(async()=>{let t=s.getInstance(e);return await t.initialize(),t})()),s.instancePromise)}static resetInstance(){s.instance&&(s.instance.close(),s.instance=null),s.instancePromise=null,H()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=this.config.dbPath===":memory:",n="",a=!1,o=0;if(!t){let T=process.env.AQE_PROJECT_ROOT;if(T){let d=S.resolve(this.config.dbPath),E=S.resolve(T);!d.startsWith(E)&&!d.startsWith(Xe.tmpdir())&&d.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${T}". Redirecting to test-safe path.`),this.config.dbPath=S.join(T,".agentic-qe","memory.db"))}if(n=S.dirname(this.config.dbPath),f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),a=f.existsSync(this.config.dbPath),a)o=f.statSync(this.config.dbPath).size;else if(f.existsSync(n)){let d=this.findRecentBackups(n);if(d.length>0){let E=d[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
734
734
  Expected: ${this.config.dbPath}
735
735
  Found ${d.length} backup(s), newest: ${E.path} (${(E.size/1024/1024).toFixed(1)}MB)
736
736
  Restoring from backup to prevent data loss...`),f.copyFileSync(E.path,this.config.dbPath);for(let u of["-wal","-shm"]){let _=this.config.dbPath+u;f.existsSync(_)&&f.unlinkSync(_)}o=E.size}}}if(e?.throwIfAborted(),this.db=ie(this.config.dbPath,{walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,autoRestore:!0}),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.db.pragma("foreign_keys = ON"),e?.aborted){try{this.db.close()}catch{}this.db=null,e.throwIfAborted()}if(await this.runMigrations(),e?.throwIfAborted(),a&&o>1e6)try{let T=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(T&&T.cnt===0){let d=f.statSync(this.config.dbPath).size;d<o*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
@@ -792,4 +792,4 @@ import{d as j,f as ze}from"./chunk-4RP5VUBI.js";import{a as z,c as He}from"./chu
792
792
  VALUES (?, ?, ?, ?, ?, datetime('now'))
793
793
  `).run(e,n,o,t.length,T),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
794
794
  SELECT embedding, dimensions, metadata FROM vectors WHERE id = ?
795
- `).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?I(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n,a){if(this.ensureInitialized(),!Number.isInteger(t)||t<=0)return[];this.vectorsLoaded||await this.loadVectorIndex();let o=this.vectorIndex.size(),T=!!(n||a),d=Math.min(o,Math.max(T?t*2:t,1)),E=n?this.db.prepare("SELECT id, namespace, metadata FROM vectors WHERE namespace = ?").all(n):void 0,u=E?new Map(E.map(l=>[l.id,l])):void 0,_=this.vectorIndex.search(e,d);for(;T&&_.filter(l=>(!a||l.id.startsWith(a))&&(!u||u.has(l.id))).length<t&&d<o;)d=Math.min(o,d*2),_=this.vectorIndex.search(e,d);if(_.length===0)return[];let m=u??(()=>{let l=_.map(h=>h.id),g=l.map(()=>"?").join(","),L=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${g})`).all(...l);return new Map(L.map(h=>[h.id,h]))})();if(n){let l=[];for(let g of _){let L=m.get(g.id);if(L&&L.namespace===n&&(!a||g.id.startsWith(a))&&(l.push({id:g.id,score:g.score,metadata:L.metadata?I(L.metadata):void 0}),l.length>=t))break}return l}return(a?_.filter(l=>l.id.startsWith(a)).slice(0,t):_.slice(0,t)).map(l=>{let g=m.get(l.id);return{id:l.id,score:l.score,metadata:g?.metadata?I(g.metadata):void 0}})}migrateToV13EmbeddingSpace(){let e=this.db;if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_embeddings'").get()){e.exec(Q);return}e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(a=>a.name==="space_id")||e.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)")}getVectorSearchProvenance(){return this.vectorIndex.getProvider().isNativeBackend()?{backend:"native-hnsw",indexType:"hnsw",approximate:!0,estimatedRecall:this.vectorIndex.recall(),qualifiedMaxK:re.EF_SEARCH}:{backend:"progressive-hnsw",indexType:"flat",approximate:!1,estimatedRecall:1}}async vectorCount(e){return this.ensureInitialized(),e?this.db.prepare("SELECT COUNT(*) as count FROM vectors WHERE namespace = ?").get(e).count:this.db.prepare("SELECT COUNT(*) as count FROM vectors").get().count}queryCount(e){this.ensureInitialized();let t=A(e);return this.db.prepare(`SELECT COUNT(*) as c FROM ${t}`).get().c}initializeCRDT(e){if(this.crdtStore){console.warn("[UnifiedMemory] CRDT store already initialized");return}this.crdtStore=ne({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,n="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,n)}async crdtGet(e,t="crdt"){if(this.crdtStore){let n=this.crdtStore.getRegister(e);if(n)return n.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let n=this.crdtStore.getCounter(e);n||(this.crdtStore.incrementCounter(e,0),n=this.crdtStore.getCounter(e));for(let a=0;a<t;a++)this.crdtStore.incrementCounter(e)}crdtGetCounter(e){return this.crdtStore?this.crdtStore.getCounter(e)?.get()??0:0}crdtAddToSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.addToSet(e,t)}crdtRemoveFromSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.removeFromSet(e,t)}crdtGetSet(e){if(!this.crdtStore)return new Set;let t=this.crdtStore.getSet(e);return new Set(t.values())}crdtGetState(){return this.crdtStore?this.crdtStore.getState():null}crdtGetDelta(e){return this.crdtStore?this.crdtStore.getDelta(e??0):null}crdtMerge(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyState(e)}crdtApplyDelta(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyDelta(e)}async crdtPersist(){if(!this.crdtStore)return;let e=this.crdtStore.getState();await this.kvSet("__crdt_state__",e,"crdt-internal")}async crdtRestore(){if(!this.crdtStore)return!1;let e=await this.kvGet("__crdt_state__","crdt-internal");return e?(this.crdtStore.applyState(e),!0):!1}getDatabase(){if(!this.db||!this.initialized)throw new Error("UnifiedMemoryManager not initialized");return this.db}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.db)throw new Error("Database not initialized");let n=this.preparedStatements.get(e);return n||(n=this.db.prepare(t),this.preparedStatements.set(e,n)),n}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}getStats(){if(!this.db)throw new Error("Database not initialized");let e=Oe.map(a=>{try{let o=this.db.prepare(`SELECT COUNT(*) as count FROM ${a}`).get();return{name:a,rowCount:o.count}}catch(o){return y.debug("Table row count query failed",{table:a,error:o instanceof Error?o.message:String(o)}),{name:a,rowCount:0}}}),t=0,n=0;try{f.existsSync(this.config.dbPath)&&(t=f.statSync(this.config.dbPath).size);let a=this.config.dbPath+"-wal";f.existsSync(a)&&(n=f.statSync(a).size)}catch(a){console.debug("[UnifiedMemory] File stat error:",a instanceof Error?a.message:a)}return{tables:e,fileSize:t,walSize:n,vectorIndexSize:this.vectorIndex.size()}}vacuum(){if(!this.db)throw new Error("Database not initialized");this.db.exec("VACUUM")}checkpoint(){if(!this.db)throw new Error("Database not initialized");this.db.pragma("wal_checkpoint(TRUNCATE)")}close(){this.db&&(this.preparedStatements.clear(),this.vectorIndex.clear(),this.db.close(),this.db=null,this.initialized=!1,console.log("[UnifiedMemory] Database closed"))}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("UnifiedMemoryManager not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(n)}};ye=!1;tt()});export{Y as a,A as b,ot as c,$ as d,ge as e,K as f,Ue as g,we as h,Fe as i,v as j,xe as k,Ze as l,et as m,nt as n,rt as o};
795
+ `).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?I(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n,a){if(this.ensureInitialized(),!Number.isInteger(t)||t<=0)return[];this.vectorsLoaded||await this.loadVectorIndex();let o=this.vectorIndex.size(),T=!!(n||a),d=Math.min(o,Math.max(T?t*2:t,1)),E=n?this.db.prepare("SELECT id, namespace, metadata FROM vectors WHERE namespace = ?").all(n):void 0,u=E?new Map(E.map(l=>[l.id,l])):void 0,_=this.vectorIndex.search(e,d);for(;T&&_.filter(l=>(!a||l.id.startsWith(a))&&(!u||u.has(l.id))).length<t&&d<o;)d=Math.min(o,d*2),_=this.vectorIndex.search(e,d);if(_.length===0)return[];let m=u??(()=>{let l=_.map(h=>h.id),g=l.map(()=>"?").join(","),L=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${g})`).all(...l);return new Map(L.map(h=>[h.id,h]))})();if(n){let l=[];for(let g of _){let L=m.get(g.id);if(L&&L.namespace===n&&(!a||g.id.startsWith(a))&&(l.push({id:g.id,score:g.score,metadata:L.metadata?I(L.metadata):void 0}),l.length>=t))break}return l}return(a?_.filter(l=>l.id.startsWith(a)).slice(0,t):_.slice(0,t)).map(l=>{let g=m.get(l.id);return{id:l.id,score:l.score,metadata:g?.metadata?I(g.metadata):void 0}})}migrateToV13EmbeddingSpace(){let e=this.db;if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_embeddings'").get()){e.exec(Q);return}e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(a=>a.name==="space_id")||e.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)")}getVectorSearchProvenance(){return this.vectorIndex.getProvider().isNativeBackend()?{backend:"native-hnsw",indexType:"hnsw",approximate:!0,estimatedRecall:this.vectorIndex.recall(),qualifiedMaxK:se.EF_SEARCH}:{backend:"progressive-hnsw",indexType:"flat",approximate:!1,estimatedRecall:1}}async vectorCount(e){return this.ensureInitialized(),e?this.db.prepare("SELECT COUNT(*) as count FROM vectors WHERE namespace = ?").get(e).count:this.db.prepare("SELECT COUNT(*) as count FROM vectors").get().count}queryCount(e){this.ensureInitialized();let t=A(e);return this.db.prepare(`SELECT COUNT(*) as c FROM ${t}`).get().c}initializeCRDT(e){if(this.crdtStore){console.warn("[UnifiedMemory] CRDT store already initialized");return}this.crdtStore=ne({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,n="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,n)}async crdtGet(e,t="crdt"){if(this.crdtStore){let n=this.crdtStore.getRegister(e);if(n)return n.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let n=this.crdtStore.getCounter(e);n||(this.crdtStore.incrementCounter(e,0),n=this.crdtStore.getCounter(e));for(let a=0;a<t;a++)this.crdtStore.incrementCounter(e)}crdtGetCounter(e){return this.crdtStore?this.crdtStore.getCounter(e)?.get()??0:0}crdtAddToSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.addToSet(e,t)}crdtRemoveFromSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.removeFromSet(e,t)}crdtGetSet(e){if(!this.crdtStore)return new Set;let t=this.crdtStore.getSet(e);return new Set(t.values())}crdtGetState(){return this.crdtStore?this.crdtStore.getState():null}crdtGetDelta(e){return this.crdtStore?this.crdtStore.getDelta(e??0):null}crdtMerge(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyState(e)}crdtApplyDelta(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyDelta(e)}async crdtPersist(){if(!this.crdtStore)return;let e=this.crdtStore.getState();await this.kvSet("__crdt_state__",e,"crdt-internal")}async crdtRestore(){if(!this.crdtStore)return!1;let e=await this.kvGet("__crdt_state__","crdt-internal");return e?(this.crdtStore.applyState(e),!0):!1}getDatabase(){if(!this.db||!this.initialized)throw new Error("UnifiedMemoryManager not initialized");return this.db}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.db)throw new Error("Database not initialized");let n=this.preparedStatements.get(e);return n||(n=this.db.prepare(t),this.preparedStatements.set(e,n)),n}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}getStats(){if(!this.db)throw new Error("Database not initialized");let e=Oe.map(a=>{try{let o=this.db.prepare(`SELECT COUNT(*) as count FROM ${a}`).get();return{name:a,rowCount:o.count}}catch(o){return y.debug("Table row count query failed",{table:a,error:o instanceof Error?o.message:String(o)}),{name:a,rowCount:0}}}),t=0,n=0;try{f.existsSync(this.config.dbPath)&&(t=f.statSync(this.config.dbPath).size);let a=this.config.dbPath+"-wal";f.existsSync(a)&&(n=f.statSync(a).size)}catch(a){console.debug("[UnifiedMemory] File stat error:",a instanceof Error?a.message:a)}return{tables:e,fileSize:t,walSize:n,vectorIndexSize:this.vectorIndex.size()}}vacuum(){if(!this.db)throw new Error("Database not initialized");this.db.exec("VACUUM")}checkpoint(){if(!this.db)throw new Error("Database not initialized");this.db.pragma("wal_checkpoint(TRUNCATE)")}close(){this.db&&(this.preparedStatements.clear(),this.vectorIndex.clear(),this.db.close(),this.db=null,this.initialized=!1,console.log("[UnifiedMemory] Database closed"))}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("UnifiedMemoryManager not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(n)}};ye=!1;tt()});export{Y as a,A as b,ot as c,$ as d,ge as e,K as f,Ue as g,we as h,Fe as i,v as j,xe as k,Ze as l,et as m,nt as n,rt as o};
@@ -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.14.3");process.exit(0)}
2
- import{c as t,e as o}from"./chunk-Y2DVFVGI.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as 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.14.5");process.exit(0)}
2
+ import{b as t,d as o}from"./chunk-JSZ663MU.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.5");process.exit(0)}
2
+ import{b as X,c as k,d as O,e as I,f as z}from"./chunk-SQKW3B6B.js";import{g as K}from"./chunk-K7NJHFLZ.js";import{b as f,c as W,j as C,k as Q,o as Z,q as B,r as ee}from"./chunk-JROVR6YS.js";import{b as q,f as pe}from"./chunk-E4EYPYR3.js";import{a as L,b,c as J,d as ue,f as S,i as y,j as R,n as P}from"./chunk-R6IU3EWP.js";import{d as V,e as le}from"./chunk-7CD7PBHY.js";import{b as G,c as de}from"./chunk-J5UNP6W3.js";import{i as Y}from"./chunk-W2XCZU62.js";P();var te={security:{provider:"claude",model:R,temperature:.1,maxTokens:16e3,priority:100},"test-generation":{provider:"claude",model:y,temperature:.3,maxTokens:8e3,priority:90},"code-analysis":{provider:"claude",model:y,temperature:.2,maxTokens:8e3,priority:85},performance:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.2,maxTokens:4e3,priority:70},documentation:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.4,maxTokens:4e3,priority:60},learning:{provider:"claude",model:y,temperature:.3,maxTokens:8e3,priority:80},coordination:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.2,maxTokens:2e3,priority:75},simple:{provider:"openai",model:"gpt-6-luna",temperature:.3,maxTokens:2e3,priority:50},general:{provider:"claude",model:y,temperature:.3,maxTokens:4e3,priority:60}},_={"security-auditor":"security","security-architect":"security","security-scanner":"security","v3-qe-security-scanner":"security","security-manager":"security","vulnerability-scanner":"security","penetration-tester":"security","compliance-auditor":"security","threat-analyzer":"security","test-generator":"test-generation","v3-qe-test-generator":"test-generation",tester:"test-generation","tdd-specialist":"test-generation","tdd-london-swarm":"test-generation","unit-test-generator":"test-generation","integration-test-generator":"test-generation","e2e-test-generator":"test-generation","mutation-tester":"test-generation","property-based-tester":"test-generation","contract-tester":"test-generation","v3-qe-contract-tester":"test-generation","api-tester":"test-generation","visual-tester":"test-generation","v3-qe-visual-tester":"test-generation","accessibility-tester":"test-generation","code-reviewer":"code-analysis","code-analyzer":"code-analysis",reviewer:"code-analysis","v3-qe-code-intelligence":"code-analysis","v3-qe-code-analyzer":"code-analysis","coverage-analyzer":"code-analysis","v3-qe-coverage-analyzer":"code-analysis","defect-predictor":"code-analysis","v3-qe-defect-predictor":"code-analysis","static-analyzer":"code-analysis","complexity-analyzer":"code-analysis","dependency-analyzer":"code-analysis","refactoring-advisor":"code-analysis","quality-assessor":"code-analysis","v3-qe-quality-assessor":"code-analysis","test-executor":"code-analysis","v3-qe-test-executor":"code-analysis","parallel-executor":"code-analysis","flaky-test-detector":"code-analysis","test-orchestrator":"code-analysis","performance-tester":"performance","performance-engineer":"performance","perf-analyzer":"performance","performance-benchmarker":"performance","load-tester":"performance","stress-tester":"performance","v3-qe-chaos-engineer":"performance","chaos-engineer":"performance","resilience-tester":"performance","scalability-tester":"performance","api-docs":"documentation","doc-generator":"documentation","readme-generator":"documentation","changelog-generator":"documentation","specification-writer":"documentation","v3-qe-learning-optimizer":"learning","learning-optimizer":"learning","ml-developer":"learning","pattern-learner":"learning","optimization-agent":"learning","smart-agent":"learning","requirements-validator":"code-analysis","v3-qe-requirements-validator":"code-analysis","bdd-generator":"test-generation","acceptance-tester":"test-generation",coordinator:"coordination","hierarchical-coordinator":"coordination","mesh-coordinator":"coordination","adaptive-coordinator":"coordination","collective-intelligence-coordinator":"coordination","swarm-memory-manager":"coordination","byzantine-coordinator":"coordination","raft-manager":"coordination","gossip-coordinator":"coordination","consensus-builder":"coordination","crdt-synchronizer":"coordination","quorum-manager":"coordination","task-orchestrator":"coordination","memory-coordinator":"coordination",coder:"code-analysis",planner:"code-analysis",researcher:"code-analysis","backend-dev":"code-analysis","mobile-dev":"code-analysis","cicd-engineer":"code-analysis","system-architect":"code-analysis","base-template-generator":"test-generation","github-modes":"coordination","pr-manager":"coordination","code-review-swarm":"code-analysis","issue-tracker":"coordination","release-manager":"coordination","workflow-automation":"coordination","project-board-sync":"coordination","repo-architect":"code-analysis","multi-repo-swarm":"coordination","sparc-coord":"coordination","sparc-coder":"code-analysis",specification:"documentation",pseudocode:"code-analysis",architecture:"code-analysis",refinement:"code-analysis","memory-specialist":"learning","production-validator":"code-analysis"},v={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},Te={security:v.heavyweight,"test-generation":v.standard,"code-analysis":v.standard,learning:v.standard,performance:{...v.lightweight,costSensitivity:"high"},coordination:v.lightweight,general:{...v.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...v.minimal,minContextSize:16e3},simple:v.minimal};function re(l){if(l in _)return _[l];let e=l.toLowerCase();return e.includes("security")||e.includes("audit")||e.includes("vulnerab")||e.includes("penetration")||e.includes("threat")||e.includes("compliance")?"security":e.includes("test-gen")||e.includes("tdd")||e.includes("unit-test")||e.includes("e2e-test")||e.includes("integration-test")||e.includes("mutation")?"test-generation":e.includes("code-")||e.includes("coverage")||e.includes("defect")||e.includes("review")||e.includes("analyzer")||e.includes("quality")?"code-analysis":e.includes("perf")||e.includes("load")||e.includes("stress")||e.includes("benchmark")||e.includes("chaos")||e.includes("resilience")?"performance":e.includes("doc")||e.includes("readme")||e.includes("changelog")||e.includes("spec")?"documentation":e.includes("learn")||e.includes("ml-")||e.includes("pattern")||e.includes("optim")?"learning":e.includes("coord")||e.includes("swarm")||e.includes("orchestrat")||e.includes("consensus")||e.includes("manager")?"coordination":"general"}var F={},ie={};function oe(l,e){F={...l??{}},ie={...e??{}}}function ne(l){let e=re(l),t=te[e],r=F[l];if(!r)return t;let i=r.provider!==void 0&&r.provider!==t.provider,o=r.model??(i?ie[r.provider]:void 0);return{...t,...r.provider!==void 0?{provider:r.provider}:{},...o!==void 0?{model:o}:{},...r.temperature!==void 0?{temperature:r.temperature}:{},...r.maxTokens!==void 0?{maxTokens:r.maxTokens}:{},priority:r.priority??t.priority+100}}function se(){return Object.keys(F).map(l=>{let e=ne(l);return{id:`agent-override-${l}`,name:`User override: ${l} -> ${e.provider}/${e.model}`,description:`Per-agent routing override from .agentic-qe/llm-config.json (agentOverrides["${l}"])`,condition:{agentType:[l]},action:{provider:e.provider,model:e.model,temperature:e.temperature,maxTokens:e.maxTokens,priority:e.priority},enabled:!0,priority:e.priority}}).sort((l,e)=>e.priority-l.priority)}P();var x=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},w=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:R,temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:y,temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:R,temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:y,temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:y,temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:y,temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:y,temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"qwen3-coder:30b",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as ge}from"crypto";var E=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${ge().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),a=o.outputTokens??i-n,s={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:a,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(s),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),a=this.calculateAgentMetrics(r,i),s=r.map(m=>m.decisionTimeMs),c=r.length,d=this.countByMode(r),u=r.filter(m=>m.wasFallback).length,p=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:a,totalDecisions:c,decisionsByMode:d,avgDecisionTimeMs:this.average(s),p95DecisionTimeMs:this.percentile(s,95),p99DecisionTimeMs:this.percentile(s,99),fallbackRate:c>0?u/c:0,ruleMatchRate:c>0?p/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,h)=>m+1,0),matched:p,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(s=>s.provider===e),r=this.providerCalls.filter(s=>s.provider===e),i=r.map(s=>s.latencyMs),o=t.map(s=>s.decisionTimeMs),n=r.filter(s=>s.success),a=r.filter(s=>!s.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(s=>s.ruleId).length,fallbackCount:t.filter(s=>s.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((s,c)=>s+(c.cost??0),0),totalTokens:r.reduce((s,c)=>s+c.totalTokens,0),totalInputTokens:r.reduce((s,c)=>s+c.inputTokens,0),totalOutputTokens:r.reduce((s,c)=>s+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:a.length,lastError:a.length>0?a[a.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),a=t.filter(c=>c.wasFallback).length,s=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,d)=>c+(d.cost??0),0),totalTokens:r.reduce((c,d)=>c+d.totalTokens,0),fallbackRate:t.length>0?a/t.length:0,successRate:t.length>0?s/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of C){let o=e.filter(d=>d.provider===i),n=t.filter(d=>d.provider===i);if(o.length===0&&n.length===0)continue;let a=n.map(d=>d.latencyMs),s=o.map(d=>d.decisionTimeMs),c=n.filter(d=>d.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(d=>d.ruleId).length,fallbackCount:o.filter(d=>d.wasFallback).length,avgDecisionTimeMs:this.average(s),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(a),p95LatencyMs:this.percentile(a,95),p99LatencyMs:this.percentile(a,99),totalCost:n.reduce((d,u)=>d+(u.cost??0),0),totalTokens:n.reduce((d,u)=>d+u.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function U(l){return new E(l)}pe();P();var A=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),a={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(a),this.trimRecords(),this.checkAlerts(),a}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of C){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let a=n.reduce((c,d)=>c+d.totalCost,0),s=n.reduce((c,d)=>c+d.inputTokens+d.outputTokens,0);i.set(o,{totalCost:a,totalTokens:s,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:s>0?a/s:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(a=>a.agentType&&i.add(a.agentType));let o=new Map;for(let a of i){let s=r.filter(u=>u.agentType===a),c=s.reduce((u,p)=>u+p.totalCost,0),d=s.reduce((u,p)=>u+p.inputTokens+p.outputTokens,0);o.set(a,{totalCost:c,totalTokens:d,totalRequests:s.length,avgCostPerRequest:s.length>0?c/s.length:0,avgCostPerToken:d>0?c/d:0})}let n=r.filter(a=>!a.agentType);if(n.length>0){let a=n.reduce((c,d)=>c+d.totalCost,0),s=n.reduce((c,d)=>c+d.inputTokens+d.outputTokens,0);o.set("unknown",{totalCost:a,totalTokens:s,totalRequests:n.length,avgCostPerRequest:a/n.length,avgCostPerToken:s>0?a/s:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let a=r.filter(d=>d.model===n),s=a.reduce((d,u)=>d+u.totalCost,0),c=a.reduce((d,u)=>d+u.inputTokens+u.outputTokens,0);o.set(n,{totalCost:s,totalTokens:c,totalRequests:a.length,avgCostPerRequest:a.length>0?s/a.length:0,avgCostPerToken:c>0?s/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let a=new Date(t.getTime()-n*i),s=new Date(a.getTime()-i),c=this.records.filter(d=>d.timestamp>=s&&d.timestamp<a);r.push({timestamp:a,cost:c.reduce((d,u)=>d+u.totalCost,0),tokens:c.reduce((d,u)=>d+u.inputTokens+u.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,a]of t)q(n)&&a.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:a.totalCost*.5,currentCost:a.totalCost,suggestedModel:y}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:a.totalCost*.7,currentCost:a.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,a)=>n+a.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,a)=>n+a.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=q(e);if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,a)=>n+a.inputTokens+a.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function $(l){return new A(l)}de();ue();P();var D=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},T=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={...Q,...t};let r=this.config.rules.length>0?this.config.rules:w;this.ruleEngine=new x(r),this.decisionCache=new D(100,this.config.decisionCacheTtlMs),this.metrics=new H,this.routerMetrics=U(),this.costMetrics=$()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new D(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now(),r=this.config.cacheDecisions&&!e.strictModel;if(r){let o=this.generateCacheKey(e),n=this.decisionCache.get(o);if(n)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),n;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let i;if(e.strictModel)i=this.selectStrict(e);else switch(this.config.mode){case"manual":i=await this.selectManual(e);break;case"rule-based":i=await this.selectRuleBased(e);break;case"cost-optimized":i=await this.selectCostOptimized(e);break;case"performance-optimized":i=await this.selectPerformanceOptimized(e);break;default:i=await this.selectRuleBased(e)}if(i.metadata.decisionTimeMs=Date.now()-t,r){let o=this.generateCacheKey(e);this.decisionCache.set(o,i)}return this.metrics.recordDecision(i,this.config.mode),i}async chat(e){await this.ensureInitialized();let t=Y(),r=await this.selectProvider(e),i=e.agentType??"";if(O(i)&&(k(r.model)||k(r.providerModelId))){if(e.strictModel)throw f(`Strict model request for ${r.model} conflicts with the cyber verification pin for ${i}`,"MODEL_NOT_FOUND",{provider:r.providerType,model:r.model,retryable:!1});let n=r.model,a=r.providerModelId;r.model=I(i,r.model,X),r.providerModelId=I(i,r.providerModelId,z(r.providerType)),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${a}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}selectStrict(e){if(!e.model?.trim())throw f("strictModel requires an explicit nonempty model","MODEL_NOT_FOUND",{retryable:!1});let t=e.preferredProvider??this.config.defaultProvider,r=this.providerManager.getProvider(t);if(!r)throw f(`Strict model provider ${t} is unavailable`,"PROVIDER_UNAVAILABLE",{provider:t,model:e.model,retryable:!1});return this.createDecision(r,t,e.model,"manual")}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,a=o.action.provider,s=this.providerManager.getProvider(a);if(s){let c=this.createDecision(s,a,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let a of t){let s=this.providerManager.getProvider(a);if(!s)continue;let{input:c,output:d}=s.getCostPerToken(),u=this.estimateCostValue(e,c,d);n.push({provider:a,model:s.getConfig().model,reason:`Estimated cost: $${u.toFixed(6)}`,estimatedCost:u,excluded:!1}),u<r&&(r=u,i=a,o=s)}if(o){let a=o.getConfig(),s=this.createDecision(o,i,a.model,"cost-optimization");return s.metadata.estimatedCost=this.createCostEstimate(e,o),s.metadata.alternativesConsidered=n,s}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,a=[];for(let s of t){let c=this.providerManager.getProvider(s);if(!c)continue;let u=r[s]?.avgLatencyMs??1/0;a.push({provider:s,model:c.getConfig().model,reason:`Avg latency: ${u}ms`,estimatedLatencyMs:u,excluded:!1}),u<i&&(i=u,o=s,n=c)}if(n){let s=n.getConfig(),c=this.createDecision(n,o,s.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=a,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,a=0,s=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;if(!e.strictModel&&c&&c!==t.providerType&&s.push({provider:c,model:this.config.defaultModel}),!e.strictModel){for(let p of i.entries)if(p.enabled&&p.provider!==t.providerType)for(let m of p.models)s.push({provider:p.provider,model:m})}let d=e.agentType??"";if(O(d))for(let p of s)k(p.model)&&(p.model=z(p.provider));let u=s;if(e.requiresTools){let p=s.filter(m=>S(m.model));if(p.length>0&&p.length<s.length){let m=s.filter(h=>!S(h.model)).map(h=>`${h.provider}:${h.model}`);console.warn(`[llm-router] requiresTools: skipping tool-less model(s) ${m.join(", ")}`),u=p}}this.providerManager.assertWithinBudget(e.messages,{model:u[0]?.model,maxTokens:e.maxTokens});for(let{provider:p,model:m}of u){if(a>=o.maxAttempts)break;let h=this.providerManager.getProvider(p);if(!h)continue;a++;let N=Date.now();try{let g=await h.generate(e.messages,{model:m,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata});if(this.providerManager.recordResponseSpend(g,e.agentType),e.strictModel){if(g.provider!==p)throw f(`Strict model provider mismatch: expected ${p}, received ${g.provider}`,"PROVIDER_UNAVAILABLE",{provider:p,model:m,retryable:!1});if(!this.isSameModel(t.model,g.model))throw f(`Strict model mismatch: expected ${t.model}, received ${g.model}`,"MODEL_NOT_FOUND",{provider:p,model:m,retryable:!1})}let M=Date.now()-N;return this.metrics.recordSuccess(p),this.routerMetrics.recordRoutingDecision(t,M,{agentType:e.agentType,success:!0,tokenUsage:g.usage,cost:g.cost}),this.routerMetrics.recordProviderCall(p,m,M,g.usage.totalTokens,{inputTokens:g.usage.promptTokens,outputTokens:g.usage.completionTokens,success:!0,cost:g.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(p,m,g.usage,g.cost,{agentType:e.agentType,requestId:g.requestId}),{content:g.content,model:g.model,providerModelId:g.model,provider:g.provider,usage:g.usage,cost:g.cost,latencyMs:g.latencyMs,finishReason:g.finishReason,cached:g.cached,requestId:g.requestId,routingDecision:t}}catch(g){n=G(g);let M=Date.now()-N;if(this.metrics.recordFailure(p),this.routerMetrics.recordProviderCall(p,m,M,0,{success:!1,agentType:e.agentType}),a<s.length){let j=s[a];j&&this.routerMetrics.recordFallback(p,j.provider,n.message,e.agentType)}let ce=W(g)&&!g.retryable;!e.strictModel&&!ce&&a<o.maxAttempts&&await this.delay(o.delayMs)}}throw f(`All providers failed after ${a} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}isSameModel(e,t){if(e===t)return!0;try{return b(e)===b(t)}catch{return!1}}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:a}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:a,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic","claude-code":"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=b(e),n=L(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(J(e)){let n=L(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw f(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let s of e.messages)o+=Math.ceil(s.content.length/4);let n=e.maxTokens??1e3,a=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:a,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},H=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};le();var me=V("llm/router-service");function ae(l){let e={};for(let[i,o]of Object.entries(l.providers??{}))o?.defaultModel&&(e[i]=o.defaultModel);oe(l.agentOverrides,e);let t=se();if(t.length===0)return l;let r=l.rules.length>0?l.rules:w;return{...l,rules:[...t,...r]}}var ye=["ollama","onnx","gemini","openrouter","openai","claude","azure-openai","bedrock"];async function St(l={}){if(l.providerManager){let c=ae(B({projectRoot:l.projectRoot,override:l.override,env:l.env})),d=new T(l.providerManager,c);return await d.initialize(),{router:d,resolvedConfig:c,enabledProviders:he(c)}}if(!ee({projectRoot:l.projectRoot,env:l.env}))return null;let e=ae(B({projectRoot:l.projectRoot,override:l.override,env:l.env})),t=ve(e,l.env??process.env);if(t.length===0)return null;let r=new Set(t);for(let[c,d]of Object.entries(e.agentOverrides??{}))d.provider&&!r.has(d.provider)&&me.warn(`[llm-config] agentOverrides["${c}"] routes to provider "${d.provider}", which is not enabled (no API key detected and not enabled in .agentic-qe/llm-config.json). This override will not take effect until that provider is available.`);let{primary:i,fallbacks:o}=fe(e,t),n={primary:i,fallbacks:o,providers:Ce(e,t,l.allowProjectProviderEndpoints??!0),loadBalancing:"round-robin",global:{enableCostTracking:!0,enableMetrics:!0}},a=new K(n),s=new T(a,e);return await s.initialize(),{router:s,resolvedConfig:e,enabledProviders:t}}function ve(l,e=process.env){let t=Z(e),r=[],i=o=>{r.includes(o)||!l.providers?.[o]?.enabled||t.has(o)&&r.push(o)};i(l.defaultProvider);for(let o of l.fallbackChain?.entries??[])i(o.provider);for(let o of ye)i(o);for(let o of C)i(o);return r}function he(l){let e=new Set([l.defaultProvider]);for(let t of l.fallbackChain?.entries??[])e.add(t.provider);return Array.from(e)}function fe(l,e){if(e.length===0)throw new Error("pickPrimaryAndFallbacks: no enabled providers");let t=e.includes(l.defaultProvider)?l.defaultProvider:e[0],r=e.filter(i=>i!==t);return{primary:t,fallbacks:r}}function Ce(l,e,t=!0){let r={};for(let i of e){let o=l.providers?.[i];if(o){let n={...o};(i==="codex"||i==="claude-code")&&delete n.binaryPath,t||delete n.baseUrl,r[i]=n}}return r}export{St as a,ve as b,fe as c,Ce as d};