agentic-qe 3.14.3 → 3.14.4

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 (724) 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 +111 -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/cli/bundle.js +7 -7
  219. package/dist/cli/chunks/adapter-TNNNJRDG.js +2 -0
  220. package/dist/cli/chunks/{agent-booster-wasm-TQOMLWWX.js → agent-booster-wasm-5PC7D2FW.js} +2 -2
  221. package/dist/cli/chunks/{agent-handler-Q3SEMMI2.js → agent-handler-RDNTK4CA.js} +2 -2
  222. package/dist/cli/chunks/{agent-memory-branch-SJXAQSZI.js → agent-memory-branch-NAAMBWIR.js} +2 -2
  223. package/dist/cli/chunks/aqe-learning-engine-5ZRMYJLB.js +2 -0
  224. package/dist/cli/chunks/{arena-7RC7TBGW.js → arena-HXTWJ5YY.js} +4 -4
  225. package/dist/cli/chunks/{arena-UPB7TKUY.js → arena-KXFHRWX4.js} +2 -2
  226. package/dist/cli/chunks/{audit-IXN5R4WB.js → audit-YSGA7UWT.js} +3 -3
  227. package/dist/cli/chunks/base-KWZHOPSH.js +2 -0
  228. package/dist/cli/chunks/{better-sqlite3-RP4DEGK3.js → better-sqlite3-UICJZIDG.js} +2 -2
  229. package/dist/cli/chunks/brain-handler-ET6YAP4B.js +90 -0
  230. package/dist/cli/chunks/{branch-enumerator-VPRWDGFJ.js → branch-enumerator-SS7UNVIA.js} +2 -2
  231. package/dist/cli/chunks/{browser-B6E7JPPJ.js → browser-77GI6KBE.js} +2 -2
  232. package/dist/cli/chunks/browser-workflow-2FZTKDUL.js +2 -0
  233. package/dist/cli/chunks/{chunk-ZHXWGNYM.js → chunk-2JW3BCGG.js} +1 -1
  234. package/dist/cli/chunks/{chunk-TGLAWI62.js → chunk-33YYYWBQ.js} +1 -1
  235. package/dist/cli/chunks/{chunk-BN7DKW5D.js → chunk-34WO57CW.js} +1 -1
  236. package/dist/cli/chunks/{chunk-TTMHIOQ3.js → chunk-3QHGWY7T.js} +2 -2
  237. package/dist/cli/chunks/chunk-3TW5W5LX.js +2 -0
  238. package/dist/cli/chunks/{chunk-E3FBW6G2.js → chunk-3UPAMMCB.js} +1 -1
  239. package/dist/cli/chunks/{chunk-MDZ6RRLX.js → chunk-3VOQRIQM.js} +2 -2
  240. package/dist/cli/chunks/{chunk-G5C2XVZC.js → chunk-3X3DJZJJ.js} +1 -1
  241. package/dist/cli/chunks/{chunk-4C6UJIHB.js → chunk-4MHXCAG2.js} +1 -1
  242. package/dist/cli/chunks/{chunk-7BUERZYL.js → chunk-4OYFXLBK.js} +2 -2
  243. package/dist/cli/chunks/{chunk-TFHQE6NK.js → chunk-55RWDRJD.js} +3 -3
  244. package/dist/cli/chunks/chunk-5R3QL7WN.js +14 -0
  245. package/dist/cli/chunks/{chunk-ZUG5MOUB.js → chunk-5SJHQ2CO.js} +2 -2
  246. package/dist/cli/chunks/{chunk-VIDBBB6F.js → chunk-5YPYDPBJ.js} +2 -2
  247. package/dist/cli/chunks/chunk-5Z6XZV7K.js +65 -0
  248. package/dist/cli/chunks/{chunk-JV4FZUE7.js → chunk-64PFWE2F.js} +2 -2
  249. package/dist/cli/chunks/{chunk-TISSZFHO.js → chunk-6CQN24ZK.js} +1 -1
  250. package/dist/cli/chunks/{chunk-G6DCESPU.js → chunk-6J62K3SW.js} +2 -2
  251. package/dist/cli/chunks/{chunk-7SLAZAVU.js → chunk-6KJABXAR.js} +2 -2
  252. package/dist/cli/chunks/{chunk-KF63AYXD.js → chunk-6QYNWR7U.js} +2 -2
  253. package/dist/cli/chunks/{chunk-74PK3NEW.js → chunk-6TPKK7LD.js} +2 -2
  254. package/dist/cli/chunks/{chunk-JRYZKBY2.js → chunk-6UWGMOND.js} +2 -2
  255. package/dist/cli/chunks/{chunk-ZN3J6TZD.js → chunk-6VRA2QGL.js} +1 -1
  256. package/dist/cli/chunks/{chunk-YCBDE2N7.js → chunk-7D777LTF.js} +2 -2
  257. package/dist/cli/chunks/chunk-7ZIOFPL3.js +2 -0
  258. package/dist/cli/chunks/chunk-A4FYONNU.js +2 -0
  259. package/dist/cli/chunks/{chunk-5Y5TC6BY.js → chunk-AIHDEEJO.js} +2 -2
  260. package/dist/cli/chunks/{chunk-N4H2QOT5.js → chunk-AUXFKCQL.js} +2 -2
  261. package/dist/cli/chunks/{chunk-7G6UX2QN.js → chunk-AWWNB2T7.js} +2 -2
  262. package/dist/cli/chunks/{chunk-33VPWGCM.js → chunk-BDESSCVR.js} +3 -3
  263. package/dist/cli/chunks/{chunk-OVDKWCD7.js → chunk-BFP7KO7P.js} +2 -2
  264. package/dist/cli/chunks/{chunk-MXMFGSWR.js → chunk-BGE6FOLM.js} +2 -2
  265. package/dist/cli/chunks/{chunk-2GNRW3OD.js → chunk-BOARZKU3.js} +2 -2
  266. package/dist/cli/chunks/{chunk-4JBFJTHJ.js → chunk-BOZZYWCR.js} +1 -1
  267. package/dist/cli/chunks/{chunk-D4Z2N74A.js → chunk-C2WU3533.js} +1 -1
  268. package/dist/cli/chunks/{chunk-B7SWW5A6.js → chunk-CDHQFHRP.js} +2 -2
  269. package/dist/cli/chunks/chunk-CDKG6EI7.js +16 -0
  270. package/dist/cli/chunks/{chunk-IU4EBTA2.js → chunk-CIKSHTEQ.js} +3 -3
  271. package/dist/cli/chunks/{chunk-RTJ2M6V6.js → chunk-CIZ5JPDC.js} +2 -2
  272. package/dist/cli/chunks/{chunk-CR3QGHVN.js → chunk-CLTMDCSE.js} +2 -2
  273. package/dist/cli/chunks/{chunk-T35GZXTU.js → chunk-CNG6GQEZ.js} +2 -2
  274. package/dist/cli/chunks/{chunk-IQEJGZV6.js → chunk-CSU5NYOX.js} +3 -3
  275. package/dist/cli/chunks/chunk-CU46J64M.js +4 -0
  276. package/dist/cli/chunks/{chunk-LLVGTEHU.js → chunk-CXQPR5MY.js} +1 -1
  277. package/dist/cli/chunks/{chunk-5BLFXQEB.js → chunk-DA5K5754.js} +1 -1
  278. package/dist/cli/chunks/{chunk-5FOZO7KM.js → chunk-DAEFDCJ4.js} +45 -45
  279. package/dist/cli/chunks/{chunk-SJPZSCZP.js → chunk-DEYLEDJN.js} +2 -2
  280. package/dist/cli/chunks/{chunk-LHGNNZ76.js → chunk-DFZCKIGY.js} +3 -3
  281. package/dist/cli/chunks/{chunk-YAKS3CAB.js → chunk-DHJPWQBR.js} +2 -2
  282. package/dist/cli/chunks/{chunk-37BASGWC.js → chunk-DOTK76IJ.js} +2 -2
  283. package/dist/cli/chunks/{chunk-STRDSVH3.js → chunk-DPFRKBOG.js} +2 -2
  284. package/dist/cli/chunks/{chunk-H5ZRV5K5.js → chunk-EDJ3O7RH.js} +2 -2
  285. package/dist/cli/chunks/{chunk-DBA3N742.js → chunk-EKQ673SA.js} +1 -1
  286. package/dist/cli/chunks/chunk-F3SBRQC6.js +2 -0
  287. package/dist/cli/chunks/{chunk-HOQQCY2K.js → chunk-FGYMFUE2.js} +2 -2
  288. package/dist/cli/chunks/{chunk-FKG5OQFT.js → chunk-FLYOJOKN.js} +1 -1
  289. package/dist/cli/chunks/{chunk-MWWAMDHI.js → chunk-FRH6VAUS.js} +1 -1
  290. package/dist/cli/chunks/{chunk-UYJHYMEQ.js → chunk-FWGOHAAB.js} +2 -2
  291. package/dist/cli/chunks/{chunk-HRUU7E3D.js → chunk-G6T45OIC.js} +2 -2
  292. package/dist/cli/chunks/{chunk-4Q35TI6Z.js → chunk-GPLQ6DOK.js} +2 -2
  293. package/dist/cli/chunks/{chunk-PI74GOE4.js → chunk-HDSAM2RE.js} +2 -2
  294. package/dist/cli/chunks/chunk-HIVA55CJ.js +2 -0
  295. package/dist/cli/chunks/{chunk-B5XFDFBT.js → chunk-HIYXCDEP.js} +1 -1
  296. package/dist/cli/chunks/{chunk-ZK5JKHP4.js → chunk-HUWNIPZ5.js} +1 -1
  297. package/dist/cli/chunks/{chunk-H6XBM2LY.js → chunk-HV2J7KKQ.js} +2 -2
  298. package/dist/cli/chunks/{chunk-IFFZR6GY.js → chunk-IFCLB7FJ.js} +1 -1
  299. package/dist/cli/chunks/{chunk-3ABRGG3C.js → chunk-IPR4QP3H.js} +2 -2
  300. package/dist/cli/chunks/{chunk-7FYMDKQH.js → chunk-ISDMD6EU.js} +165 -167
  301. package/dist/cli/chunks/{chunk-B2ZONZPZ.js → chunk-J6GNQS62.js} +2 -2
  302. package/dist/cli/chunks/{chunk-G6ZHTF42.js → chunk-JBNEE5UH.js} +2 -2
  303. package/dist/cli/chunks/chunk-JZ3ORVZ3.js +54 -0
  304. package/dist/cli/chunks/{chunk-5IAB5NRZ.js → chunk-KCZR45PA.js} +2 -2
  305. package/dist/cli/chunks/chunk-KGT36Z42.js +14 -0
  306. package/dist/cli/chunks/{chunk-IP7NSFQQ.js → chunk-KHFNNVJA.js} +2 -2
  307. package/dist/cli/chunks/{chunk-2WT7AKKK.js → chunk-KPA7MZ6C.js} +2 -2
  308. package/dist/cli/chunks/{chunk-7JQHPANT.js → chunk-KSKEF7LZ.js} +3 -3
  309. package/dist/cli/chunks/{chunk-F67AV5P2.js → chunk-M2JBBZQB.js} +2 -2
  310. package/dist/cli/chunks/{chunk-SGXSB7YO.js → chunk-M4WJKGVK.js} +1 -1
  311. package/dist/cli/chunks/{chunk-4UDZLD42.js → chunk-M5QUBZY6.js} +2 -2
  312. package/dist/cli/chunks/{chunk-PZTVH2AS.js → chunk-MCUJEZT6.js} +2 -2
  313. package/dist/cli/chunks/{chunk-KPMGTVB4.js → chunk-MDWCE7YW.js} +1 -1
  314. package/dist/cli/chunks/{chunk-LS3EUMBP.js → chunk-MEGDYJPV.js} +5 -5
  315. package/dist/cli/chunks/chunk-MIQTXNBG.js +4 -0
  316. package/dist/cli/chunks/{chunk-VWNHKYK7.js → chunk-MNW6QGNJ.js} +2 -2
  317. package/dist/cli/chunks/{chunk-NN76NTOX.js → chunk-MOBNBMFW.js} +1 -1
  318. package/dist/cli/chunks/{chunk-SG47AXJG.js → chunk-MTZH7AHC.js} +1 -1
  319. package/dist/cli/chunks/chunk-MVNP7GIR.js +2 -0
  320. package/dist/cli/chunks/chunk-MVPCNSPY.js +2 -0
  321. package/dist/cli/chunks/chunk-NA7B2QYB.js +2 -0
  322. package/dist/cli/chunks/{chunk-26GM5CWD.js → chunk-NDPFGIMJ.js} +3 -3
  323. package/dist/cli/chunks/{chunk-ELU4IC3I.js → chunk-NJBGXDQ7.js} +1 -1
  324. package/dist/cli/chunks/chunk-OBAP2TXZ.js +2 -0
  325. package/dist/cli/chunks/{chunk-NTSXHZTC.js → chunk-OCWWP5PL.js} +4 -4
  326. package/dist/cli/chunks/{chunk-XA7CG3LH.js → chunk-ODKLFVYC.js} +2 -2
  327. package/dist/cli/chunks/{chunk-IKIITGU5.js → chunk-ONII3572.js} +4 -4
  328. package/dist/cli/chunks/{chunk-JBB7E26R.js → chunk-OSLYSG3B.js} +2 -2
  329. package/dist/cli/chunks/{chunk-CB5JPRIZ.js → chunk-OULHKEVH.js} +2 -2
  330. package/dist/cli/chunks/{chunk-YGB6R5DW.js → chunk-PAWXJ73E.js} +1 -1
  331. package/dist/cli/chunks/chunk-PEPFCPES.js +2 -0
  332. package/dist/cli/chunks/{chunk-FUE6LL72.js → chunk-PFR4G3DJ.js} +2 -2
  333. package/dist/cli/chunks/chunk-PO3IXGMQ.js +2 -0
  334. package/dist/cli/chunks/{chunk-OY7MLMEX.js → chunk-PZJOPURC.js} +5 -5
  335. package/dist/cli/chunks/{chunk-UHQY3GK7.js → chunk-Q5DO24IJ.js} +2 -2
  336. package/dist/cli/chunks/chunk-QGIU2WRL.js +2 -0
  337. package/dist/cli/chunks/{chunk-4RP5VUBI.js → chunk-R4VL6E65.js} +2 -2
  338. package/dist/cli/chunks/{chunk-RKJZWWB7.js → chunk-R5NE6B2M.js} +2 -2
  339. package/dist/cli/chunks/{chunk-5F6DWHQG.js → chunk-RJCYCLZV.js} +2 -2
  340. package/dist/cli/chunks/{chunk-GNTVFN7D.js → chunk-SGYJ4NFZ.js} +1 -1
  341. package/dist/cli/chunks/{chunk-OYMLHX2B.js → chunk-SRKETSFF.js} +1 -1
  342. package/dist/cli/chunks/{chunk-XX7HUSX2.js → chunk-STJCATGN.js} +2 -2
  343. package/dist/cli/chunks/{chunk-C46DMCWF.js → chunk-STM3UDNO.js} +1 -1
  344. package/dist/cli/chunks/{chunk-EY4OQHU3.js → chunk-T6BVLVI5.js} +1 -1
  345. package/dist/cli/chunks/{chunk-LKN7JQTW.js → chunk-TDZ53WO2.js} +2 -2
  346. package/dist/cli/chunks/{chunk-OV5EZO3U.js → chunk-TPGED2IF.js} +2 -2
  347. package/dist/cli/chunks/{chunk-DX3C5HPN.js → chunk-TSRSV3LD.js} +1 -1
  348. package/dist/cli/chunks/{chunk-Y2DVFVGI.js → chunk-TT23RRB7.js} +1 -1
  349. package/dist/cli/chunks/{chunk-XXCYQXK3.js → chunk-TWAWHOP7.js} +2 -2
  350. package/dist/cli/chunks/{chunk-2IGT5WNQ.js → chunk-U5K45TFH.js} +1 -1
  351. package/dist/cli/chunks/{chunk-SQ3PPISY.js → chunk-UDHKLT4C.js} +1 -1
  352. package/dist/cli/chunks/{chunk-YDNSLLBS.js → chunk-UEM7ZF5K.js} +2 -2
  353. package/dist/cli/chunks/{chunk-4XPPMADQ.js → chunk-UGVHCMUN.js} +6 -6
  354. package/dist/cli/chunks/{chunk-YL7T3VV7.js → chunk-V3QLFNA2.js} +2 -2
  355. package/dist/cli/chunks/{chunk-YEXPFHV6.js → chunk-VD6QRULW.js} +2 -2
  356. package/dist/cli/chunks/{chunk-OVPJQWHW.js → chunk-VIHTL3U2.js} +2 -2
  357. package/dist/cli/chunks/chunk-W7BWUTVV.js +2 -0
  358. package/dist/cli/chunks/{chunk-3P6NCFI2.js → chunk-WLG5AJ4N.js} +2 -2
  359. package/dist/cli/chunks/{chunk-V4AOVDCJ.js → chunk-XC7DYDSY.js} +8 -8
  360. package/dist/cli/chunks/{chunk-LTBCAFTZ.js → chunk-XJ7QNVI5.js} +3 -3
  361. package/dist/cli/chunks/chunk-XRT2WRMS.js +2 -0
  362. package/dist/cli/chunks/{chunk-UMENRGHK.js → chunk-XRYF6JV7.js} +2 -2
  363. package/dist/cli/chunks/{chunk-SHGKY3QB.js → chunk-XWMZ6D6N.js} +2 -2
  364. package/dist/cli/chunks/{chunk-72UJXEKQ.js → chunk-Y3MW3YBC.js} +2 -2
  365. package/dist/cli/chunks/chunk-YNXS6CGV.js +2 -0
  366. package/dist/cli/chunks/{chunk-LVLBIKJD.js → chunk-Z3RHREWF.js} +1 -1
  367. package/dist/cli/chunks/{chunk-HXE5NBJG.js → chunk-ZBAKA4YB.js} +1 -1
  368. package/dist/cli/chunks/chunk-ZBJ4XOOV.js +180 -0
  369. package/dist/cli/chunks/chunk-ZBQY5GLF.js +11 -0
  370. package/dist/cli/chunks/{chunk-NBWQBQO5.js → chunk-ZJ26AQA5.js} +1 -1
  371. package/dist/cli/chunks/{chunk-TJEIOE7F.js → chunk-ZNEMGX5O.js} +1 -1
  372. package/dist/cli/chunks/{chunk-AB4U6ZNI.js → chunk-ZNPKDCZR.js} +2 -2
  373. package/dist/cli/chunks/{chunk-WYMGK5DX.js → chunk-ZZDIMOOV.js} +2 -2
  374. package/dist/cli/chunks/ci-464KPQNP.js +81 -0
  375. package/dist/cli/chunks/{ci-output-LK3MBXLZ.js → ci-output-I7FX2RSO.js} +2 -2
  376. package/dist/cli/chunks/{circuit-breaker-7AIXACR7.js → circuit-breaker-3FW237WW.js} +2 -2
  377. package/dist/cli/chunks/{claude-flow-setup-UA7EO6VN.js → claude-flow-setup-6JKMBPGU.js} +2 -2
  378. package/dist/cli/chunks/client-7E4LM2WW.js +2 -0
  379. package/dist/cli/chunks/{cline-installer-YDDCKKEV.js → cline-installer-UWFHT6VY.js} +2 -2
  380. package/dist/cli/chunks/{code-URB7UAKW.js → code-KQSUT3FS.js} +29 -29
  381. package/dist/cli/chunks/{code-index-extractor-BL6HWH4Q.js → code-index-extractor-PABBNUSC.js} +2 -2
  382. package/dist/cli/chunks/{codex-installer-2AVEO4EA.js → codex-installer-CQ24DTP5.js} +2 -2
  383. package/dist/cli/chunks/{completions-RCKBSSSS.js → completions-7RWHAUAR.js} +2 -2
  384. package/dist/cli/chunks/complexity-analyzer-XPOAF33E.js +2 -0
  385. package/dist/cli/chunks/{continuedev-installer-VOTCEBFH.js → continuedev-installer-V4F2FIZP.js} +2 -2
  386. package/dist/cli/chunks/{copilot-installer-NVTGLZX3.js → copilot-installer-JMICURQB.js} +2 -2
  387. package/dist/cli/chunks/core-handlers-IFG3757P.js +2 -0
  388. package/dist/cli/chunks/cost-tracker-5OFHEYFJ.js +2 -0
  389. package/dist/cli/chunks/{coverage-ZTPJWXWE.js → coverage-QKN57JDS.js} +3 -3
  390. package/dist/cli/chunks/cross-domain-router-EK7W4PGP.js +2 -0
  391. package/dist/cli/chunks/{cursor-installer-CMGJQMHX.js → cursor-installer-GBJ7YXSM.js} +2 -2
  392. package/dist/cli/chunks/{daemon-V456IWR3.js → daemon-GKP7CMEK.js} +3 -3
  393. package/dist/cli/chunks/{daemon-Y2I3YVIU.js → daemon-IAVSO6HK.js} +4 -4
  394. package/dist/cli/chunks/{dag-attention-scheduler-ZCBBOD3D.js → dag-attention-scheduler-S225TCI7.js} +2 -2
  395. package/dist/cli/chunks/{detect-2GHEA4A3.js → detect-IUYH422U.js} +2 -2
  396. package/dist/cli/chunks/{dist-node-44AGYJCH.js → dist-node-2YRE6A7C.js} +2 -2
  397. package/dist/cli/chunks/{domain-handler-IDLIEP6X.js → domain-handler-PL2TZC6H.js} +2 -2
  398. package/dist/cli/chunks/domain-plugins-HCGLXKIT.js +2 -0
  399. package/dist/cli/chunks/{domain-transfer-KLEXGIRF.js → domain-transfer-KQJRUPXA.js} +2 -2
  400. package/dist/cli/chunks/dream-NFSCSLY7.js +2 -0
  401. package/dist/cli/chunks/{embed-and-insert-pattern-DUW6K35A.js → embed-and-insert-pattern-ZPAG7235.js} +2 -2
  402. package/dist/cli/chunks/eval-WCK7KNFN.js +17 -0
  403. package/dist/cli/chunks/{experience-capture-middleware-CJJJN7CF.js → experience-capture-middleware-2MSQWSAR.js} +3 -3
  404. package/dist/cli/chunks/{fast-paths-LGLLKX6P.js → fast-paths-VYOSIBKF.js} +2 -2
  405. package/dist/cli/chunks/{feature-flags-33D3I4DD.js → feature-flags-UJRHFBRX.js} +2 -2
  406. package/dist/cli/chunks/{feature-flags-QL4NCEGW.js → feature-flags-WCFUKHNQ.js} +2 -2
  407. package/dist/cli/chunks/{file-discovery-GKCYJPFZ.js → file-discovery-JDGL4ZWS.js} +2 -2
  408. package/dist/cli/chunks/fleet-ROXVMZ2F.js +43 -0
  409. package/dist/cli/chunks/{gnn-wrapper-ELSGT67Z.js → gnn-wrapper-NIO4ZCO3.js} +2 -2
  410. package/dist/cli/chunks/{heartbeat-handler-ZUI3DOOP.js → heartbeat-handler-PI42WD3C.js} +4 -4
  411. package/dist/cli/chunks/heartbeat-scheduler-ZATCDJDK.js +2 -0
  412. package/dist/cli/chunks/hnsw-adapter-WXQABRCA.js +2 -0
  413. package/dist/cli/chunks/hnsw-index-TPSWLEA5.js +2 -0
  414. package/dist/cli/chunks/{hnsw-legacy-bridge-EZMM5JWL.js → hnsw-legacy-bridge-YLC7SPK2.js} +2 -2
  415. package/dist/cli/chunks/{hnswlib-node-G4CE3EOS.js → hnswlib-node-LG6OS3B7.js} +2 -2
  416. package/dist/cli/chunks/{hooks-LCVXXA55.js → hooks-WVALP5GX.js} +10 -10
  417. package/dist/cli/chunks/{hypergraph-engine-6Z7RQ3HI.js → hypergraph-engine-GJEMW3EG.js} +2 -2
  418. package/dist/cli/chunks/{hypergraph-handler-PLI2GYPK.js → hypergraph-handler-BLF6LXEV.js} +3 -3
  419. package/dist/cli/chunks/impact-analyzer-HNIU45P5.js +2 -0
  420. package/dist/cli/chunks/{init-handler-7VH3QJ5Y.js → init-handler-K25RWRYY.js} +6 -6
  421. package/dist/cli/chunks/init-wizard-JUIPBMHG.js +2 -0
  422. package/dist/cli/chunks/kernel-5BOZQ754.js +2 -0
  423. package/dist/cli/chunks/{kilocode-installer-U3MW62DE.js → kilocode-installer-BXN6WZ7G.js} +2 -2
  424. package/dist/cli/chunks/{kiro-installer-PPEAC44T.js → kiro-installer-PM362DLN.js} +12 -12
  425. package/dist/cli/chunks/knowledge-graph-EWDAENWM.js +2 -0
  426. package/dist/cli/chunks/learning-CPERDDRG.js +122 -0
  427. package/dist/cli/chunks/llm-router-GOAV5FPI.js +37 -0
  428. package/dist/cli/chunks/llm-router-service-3YT7JGBS.js +2 -0
  429. package/dist/cli/chunks/{load-VO7ABNHV.js → load-2BG6SHAK.js} +2 -2
  430. package/dist/cli/chunks/load-test-BP2CPLIV.js +2 -0
  431. package/dist/cli/chunks/{mcp-THXEINCL.js → mcp-5TTB37DC.js} +2 -2
  432. package/dist/cli/chunks/{memory-FZTT7ADM.js → memory-4NHBYT6S.js} +5 -5
  433. package/dist/cli/chunks/memory-backend-4PYQBPRM.js +2 -0
  434. package/dist/cli/chunks/memory-handlers-2B27NITS.js +2 -0
  435. package/dist/cli/chunks/multi-model-executor-KCWSGCDT.js +14 -0
  436. package/dist/cli/chunks/{opencode-installer-GQ7J5SBG.js → opencode-installer-ATZLLK74.js} +2 -2
  437. package/dist/cli/chunks/{orchestrator-66JK2OS5.js → orchestrator-RKB7XJRG.js} +19 -19
  438. package/dist/cli/chunks/pattern-null-store-OYOQOV2O.js +2 -0
  439. package/dist/cli/chunks/{pattern-usage-recorder-O6XHM2G5.js → pattern-usage-recorder-7VE4XDAI.js} +2 -2
  440. package/dist/cli/chunks/pipeline-LQZSNDD2.js +19 -0
  441. package/dist/cli/chunks/{platform-Q7UH7FZQ.js → platform-OD5H5U6G.js} +2 -2
  442. package/dist/cli/chunks/{plugin-7OFLNGOS.js → plugin-EJ6K2MGU.js} +2 -2
  443. package/dist/cli/chunks/{prime-radiant-advanced-wasm-OSRDK2FW.js → prime-radiant-advanced-wasm-OIHTKJMN.js} +2 -2
  444. package/dist/cli/chunks/protocol-executor-3ATJTXWG.js +2 -0
  445. package/dist/cli/chunks/{protocol-handler-WLYTX6FS.js → protocol-handler-NRBROAU7.js} +2 -2
  446. package/dist/cli/chunks/{prove-QVNE4V3J.js → prove-EJOGEGD3.js} +2 -2
  447. package/dist/cli/chunks/qe-reasoning-bank-LLMYZT4X.js +2 -0
  448. package/dist/cli/chunks/{quality-DNE2RKE5.js → quality-E55UC73D.js} +2 -2
  449. package/dist/cli/chunks/{quality-gate-2K35GCSI.js → quality-gate-OIQATNT3.js} +3 -3
  450. package/dist/cli/chunks/queen-coordinator-RN7L6KG5.js +2 -0
  451. package/dist/cli/chunks/{real-embeddings-SF42ML7G.js → real-embeddings-FPFFNOSZ.js} +2 -2
  452. package/dist/cli/chunks/ref-validation-OPO6J7OL.js +2 -0
  453. package/dist/cli/chunks/{roocode-installer-NCEZPF5L.js → roocode-installer-ODY5KRWU.js} +2 -2
  454. package/dist/cli/chunks/router-MDHITQ2V.js +2 -0
  455. package/dist/cli/chunks/routing-feedback-5XLNJ3Y3.js +2 -0
  456. package/dist/cli/chunks/{routing-handler-4MXXZRYP.js → routing-handler-KQM6VWLC.js} +4 -4
  457. package/dist/cli/chunks/{ruvector-commands-WDFMMCMK.js → ruvector-commands-U2GVV6PF.js} +2 -2
  458. package/dist/cli/chunks/rvf-dual-writer-JBW4O3II.js +2 -0
  459. package/dist/cli/chunks/rvf-migration-adapter-BPPQL4XJ.js +2 -0
  460. package/dist/cli/chunks/{rvf-migration-coordinator-JT7ZCJY7.js → rvf-migration-coordinator-V2GHCJKN.js} +2 -2
  461. package/dist/cli/chunks/rvf-native-adapter-S4562CG5.js +2 -0
  462. package/dist/cli/chunks/rvf-store-integrity-KMIHD3LP.js +2 -0
  463. package/dist/cli/chunks/safe-db-FIRHSXVF.js +2 -0
  464. package/dist/cli/chunks/schedule-RVXFB4HK.js +2 -0
  465. package/dist/cli/chunks/scheduler-IKKAMAOO.js +2 -0
  466. package/dist/cli/chunks/{security-CJJ3WJSB.js → security-P5NM353C.js} +3 -3
  467. package/dist/cli/chunks/{shared-rvf-adapter-6RGCTLHD.js → shared-rvf-adapter-LVIUOO4S.js} +2 -2
  468. package/dist/cli/chunks/{shared-rvf-dual-writer-KIA6Q6MT.js → shared-rvf-dual-writer-2CSG7C4W.js} +2 -2
  469. package/dist/cli/chunks/sqlite-persistence-SQ3HCUQ7.js +2 -0
  470. package/dist/cli/chunks/{status-handler-BADQV2KA.js → status-handler-6TU6O37R.js} +2 -2
  471. package/dist/cli/chunks/{structural-health-VMYEYRZG.js → structural-health-KBIJSTXJ.js} +2 -2
  472. package/dist/cli/chunks/{sync-PXLROLHB.js → sync-LNHI5SB7.js} +2 -2
  473. package/dist/cli/chunks/{sync-ULY7T5II.js → sync-UHOX6RJW.js} +2 -2
  474. package/dist/cli/chunks/task-handler-AVDHMLGI.js +49 -0
  475. package/dist/cli/chunks/task-handlers-KYK4VTRA.js +9 -0
  476. package/dist/cli/chunks/{test-WCLURQUT.js → test-DHAAI3DU.js} +4 -4
  477. package/dist/cli/chunks/test-scheduling-XDBZ3QC2.js +15 -0
  478. package/dist/cli/chunks/{token-bootstrap-GTI24JAL.js → token-bootstrap-GUTTLPZX.js} +2 -2
  479. package/dist/cli/chunks/{token-usage-DRVG6PKO.js → token-usage-Q2YG5YQN.js} +2 -2
  480. package/dist/cli/chunks/{transformers-IMDDAMYQ.js → transformers-F5UQTQCY.js} +2 -2
  481. package/dist/cli/chunks/{tree-sitter-wasm-parser-WBZIHVFA.js → tree-sitter-wasm-parser-DEGOHS6F.js} +2 -2
  482. package/dist/cli/chunks/types-JQ7EQO5Q.js +2 -0
  483. package/dist/cli/chunks/unified-memory-CXHLHB5I.js +2 -0
  484. package/dist/cli/chunks/unified-memory-hnsw-I7WAE54M.js +2 -0
  485. package/dist/cli/chunks/unified-persistence-6CPF65WI.js +2 -0
  486. package/dist/cli/chunks/{upgrade-6ALSDWDD.js → upgrade-TJRVGHGD.js} +2 -2
  487. package/dist/cli/chunks/{validate-XF4ZG3LC.js → validate-BWPCVHBN.js} +2 -2
  488. package/dist/cli/chunks/{validate-swarm-P5TAFRDA.js → validate-swarm-QVVKCQLP.js} +2 -2
  489. package/dist/cli/chunks/{vibium-2XDXKNKZ.js → vibium-ZFATIWHO.js} +2 -2
  490. package/dist/cli/chunks/visual-security-GNPHME5H.js +2 -0
  491. package/dist/cli/chunks/{web-tree-sitter-4JVRQPX5.js → web-tree-sitter-KPLY7ONR.js} +2 -2
  492. package/dist/cli/chunks/{windsurf-installer-WYJXVDO5.js → windsurf-installer-H7XM7ISA.js} +2 -2
  493. package/dist/cli/chunks/{witness-chain-RPZ2SE2V.js → witness-chain-RRN6NDCH.js} +2 -2
  494. package/dist/cli/chunks/witness-chain-VT4UHHBR.js +2 -0
  495. package/dist/cli/chunks/{witness-key-manager-LXG2VBQQ.js → witness-key-manager-DFRL42GE.js} +2 -2
  496. package/dist/cli/chunks/workflow-2ZQO6WYI.js +51 -0
  497. package/dist/cli/chunks/workflow-orchestrator-DB3HIECD.js +2 -0
  498. package/dist/cli/chunks/{wrappers-DIJNNFU6.js → wrappers-SUS6XEJD.js} +2 -2
  499. package/dist/cli/commands/ci.js +54 -28
  500. package/dist/cli/commands/code.js +6 -0
  501. package/dist/cli/commands/eval.js +3 -2
  502. package/dist/cli/commands/fleet.js +35 -16
  503. package/dist/cli/commands/learning-snapshot.d.ts +38 -0
  504. package/dist/cli/commands/learning-snapshot.js +171 -0
  505. package/dist/cli/commands/learning.js +16 -64
  506. package/dist/cli/commands/llm-router.js +13 -12
  507. package/dist/cli/commands/pipeline.js +9 -0
  508. package/dist/cli/commands/workflow.js +9 -1
  509. package/dist/cli/handlers/task-handler.js +19 -9
  510. package/dist/cli/helpers/domain-plugins.d.ts +5 -0
  511. package/dist/cli/helpers/domain-plugins.js +11 -0
  512. package/dist/cli/index.js +17 -8
  513. package/dist/cli/utils/ci-config.d.ts +3 -0
  514. package/dist/context/sources/git-source.d.ts +2 -0
  515. package/dist/context/sources/git-source.js +9 -2
  516. package/dist/coordination/cancelled-task-settlement.d.ts +11 -0
  517. package/dist/coordination/cancelled-task-settlement.js +15 -0
  518. package/dist/coordination/consensus/providers/claude-provider.d.ts +2 -2
  519. package/dist/coordination/consensus/providers/claude-provider.js +18 -25
  520. package/dist/coordination/consensus/providers/gemini-provider.d.ts +14 -4
  521. package/dist/coordination/consensus/providers/gemini-provider.js +39 -36
  522. package/dist/coordination/consensus/providers/ollama-provider.d.ts +8 -7
  523. package/dist/coordination/consensus/providers/ollama-provider.js +16 -18
  524. package/dist/coordination/consensus/providers/openai-provider.d.ts +14 -4
  525. package/dist/coordination/consensus/providers/openai-provider.js +36 -34
  526. package/dist/coordination/consensus/providers/openrouter-provider.d.ts +5 -5
  527. package/dist/coordination/consensus/providers/openrouter-provider.js +64 -37
  528. package/dist/coordination/handlers/test-execution-handlers.js +5 -3
  529. package/dist/coordination/interfaces.d.ts +2 -2
  530. package/dist/coordination/protocol-executor.js +68 -9
  531. package/dist/coordination/queen-coordinator.js +10 -4
  532. package/dist/coordination/queen-event-handlers.js +17 -0
  533. package/dist/coordination/queen-task-management.js +25 -0
  534. package/dist/coordination/queen-types.d.ts +2 -0
  535. package/dist/coordination/task-executor.js +4 -8
  536. package/dist/coordination/workflow-composition.d.ts +19 -0
  537. package/dist/coordination/workflow-composition.js +114 -0
  538. package/dist/coordination/workflow-orchestrator.d.ts +3 -2
  539. package/dist/coordination/workflow-orchestrator.js +219 -85
  540. package/dist/coordination/workflow-types.d.ts +30 -1
  541. package/dist/coordination/yaml-pipeline-loader.js +9 -5
  542. package/dist/domains/chaos-resilience/services/chaos-engineer.js +2 -7
  543. package/dist/domains/code-intelligence/services/knowledge-graph.js +2 -7
  544. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +9 -40
  545. package/dist/domains/constants.d.ts +1 -6
  546. package/dist/domains/constants.js +2 -6
  547. package/dist/domains/contract-testing/services/contract-validator.js +2 -7
  548. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +2 -12
  549. package/dist/domains/coverage-analysis/services/gap-detector.js +2 -7
  550. package/dist/domains/defect-intelligence/services/defect-predictor.js +2 -12
  551. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +2 -7
  552. package/dist/domains/learning-optimization/services/learning-coordinator.js +2 -7
  553. package/dist/domains/quality-assessment/services/deployment-advisor.js +2 -7
  554. package/dist/domains/quality-assessment/services/quality-analyzer.js +2 -7
  555. package/dist/domains/requirements-validation/services/requirements-validator.js +2 -7
  556. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +3 -7
  557. package/dist/domains/test-execution/services/flaky-detector.js +33 -3
  558. package/dist/domains/test-execution/services/retry-handler.js +22 -14
  559. package/dist/domains/test-execution/services/test-executor.js +42 -21
  560. package/dist/domains/test-generation/services/test-generator.js +2 -7
  561. package/dist/domains/visual-accessibility/services/visual-tester.js +2 -7
  562. package/dist/init/init-wizard-steps.js +1 -1
  563. package/dist/init/kiro-installer.js +9 -8
  564. package/dist/init/opencode-installer.js +1 -1
  565. package/dist/init/phases/07-hooks.js +4 -2
  566. package/dist/init/phases/12-verification.js +1 -1
  567. package/dist/init/settings-merge.d.ts +10 -3
  568. package/dist/init/settings-merge.js +40 -9
  569. package/dist/integrations/agentic-flow/model-router/types.js +6 -8
  570. package/dist/integrations/ruvector/brain-exporter.js +9 -15
  571. package/dist/integrations/ruvector/brain-rvf-exporter.js +17 -30
  572. package/dist/integrations/ruvector/brain-shared.d.ts +5 -1
  573. package/dist/integrations/ruvector/brain-shared.js +70 -4
  574. package/dist/integrations/ruvector/rvf-dual-writer.js +36 -15
  575. package/dist/integrations/ruvector/rvf-store-integrity.d.ts +14 -9
  576. package/dist/integrations/ruvector/rvf-store-integrity.js +39 -9
  577. package/dist/integrations/ruvector/shared-rvf-adapter.js +20 -23
  578. package/dist/kernel/memory-factory.js +14 -4
  579. package/dist/kernel/project-root.js +10 -8
  580. package/dist/kernel/unified-memory.js +1 -1
  581. package/dist/learning/local-judge-client.d.ts +6 -5
  582. package/dist/learning/local-judge-client.js +7 -6
  583. package/dist/learning/pattern-store.js +29 -11
  584. package/dist/mcp/bundle.js +488 -488
  585. package/dist/mcp/handlers/index.d.ts +1 -1
  586. package/dist/mcp/handlers/index.js +1 -1
  587. package/dist/mcp/handlers/pipeline-handlers.d.ts +31 -1
  588. package/dist/mcp/handlers/pipeline-handlers.js +63 -0
  589. package/dist/mcp/handlers/task-handlers.d.ts +1 -0
  590. package/dist/mcp/handlers/task-handlers.js +12 -4
  591. package/dist/mcp/protocol-server.d.ts +2 -0
  592. package/dist/mcp/protocol-server.js +104 -49
  593. package/dist/mcp/security/sampling-server.js +2 -1
  594. package/dist/mcp/tool-annotations.js +1 -1
  595. package/dist/mcp/tools/test-execution/schedule.js +7 -0
  596. package/dist/mcp/types.d.ts +5 -1
  597. package/dist/optimization/session-cache.d.ts +5 -0
  598. package/dist/optimization/session-cache.js +23 -0
  599. package/dist/routing/advisor/multi-model-executor.d.ts +4 -1
  600. package/dist/routing/advisor/multi-model-executor.js +8 -1
  601. package/dist/routing/free-tier/ladder.d.ts +2 -1
  602. package/dist/routing/free-tier/ladder.js +3 -2
  603. package/dist/routing/security/cyber-pin.d.ts +35 -11
  604. package/dist/routing/security/cyber-pin.js +76 -14
  605. package/dist/routing/value-score.js +1 -1
  606. package/dist/shared/git/index.d.ts +1 -0
  607. package/dist/shared/git/index.js +1 -0
  608. package/dist/shared/git/ref-validation.d.ts +20 -0
  609. package/dist/shared/git/ref-validation.js +43 -0
  610. package/dist/shared/llm/anthropic-params.d.ts +40 -0
  611. package/dist/shared/llm/anthropic-params.js +51 -0
  612. package/dist/shared/llm/cost-tracker.d.ts +15 -2
  613. package/dist/shared/llm/cost-tracker.js +62 -10
  614. package/dist/shared/llm/index.d.ts +2 -2
  615. package/dist/shared/llm/index.js +2 -2
  616. package/dist/shared/llm/interfaces.d.ts +1 -1
  617. package/dist/shared/llm/metrics/cost-metrics.js +5 -4
  618. package/dist/shared/llm/model-mapping.js +131 -0
  619. package/dist/shared/llm/model-registry.d.ts +37 -11
  620. package/dist/shared/llm/model-registry.js +393 -18
  621. package/dist/shared/llm/openai-params.d.ts +35 -0
  622. package/dist/shared/llm/openai-params.js +54 -0
  623. package/dist/shared/llm/provider-manager.js +4 -3
  624. package/dist/shared/llm/providers/azure-openai.d.ts +11 -0
  625. package/dist/shared/llm/providers/azure-openai.js +26 -15
  626. package/dist/shared/llm/providers/bedrock.js +11 -19
  627. package/dist/shared/llm/providers/claude.js +6 -29
  628. package/dist/shared/llm/providers/codex.js +4 -3
  629. package/dist/shared/llm/providers/gemini.d.ts +3 -2
  630. package/dist/shared/llm/providers/gemini.js +19 -10
  631. package/dist/shared/llm/providers/ollama.d.ts +2 -0
  632. package/dist/shared/llm/providers/ollama.js +30 -20
  633. package/dist/shared/llm/providers/openai.js +10 -17
  634. package/dist/shared/llm/providers/openrouter.d.ts +1 -1
  635. package/dist/shared/llm/providers/openrouter.js +57 -21
  636. package/dist/shared/llm/router/agent-router-config.js +33 -32
  637. package/dist/shared/llm/router/hybrid-router.js +21 -9
  638. package/dist/shared/llm/router/routing-rules.js +9 -8
  639. package/dist/shared/llm/router/types.js +81 -13
  640. package/dist/shared/llm/translation/message-formatter.js +4 -23
  641. package/dist/shared/vitest-json-report.d.ts +7 -7
  642. package/dist/shared/vitest-json-report.js +23 -14
  643. package/dist/test-scheduling/executors/vitest-executor.d.ts +7 -2
  644. package/dist/test-scheduling/executors/vitest-executor.js +157 -47
  645. package/dist/test-scheduling/git-aware/test-selector.js +3 -0
  646. package/dist/test-scheduling/phase-scheduler.d.ts +1 -0
  647. package/dist/test-scheduling/phase-scheduler.js +23 -1
  648. package/package.json +1 -1
  649. package/dist/cli/chunks/adapter-AKQYU6UH.js +0 -2
  650. package/dist/cli/chunks/aqe-learning-engine-MICRPL3N.js +0 -2
  651. package/dist/cli/chunks/base-DZK36ITB.js +0 -2
  652. package/dist/cli/chunks/brain-handler-H5OVZ22L.js +0 -90
  653. package/dist/cli/chunks/browser-workflow-ADK54DOE.js +0 -2
  654. package/dist/cli/chunks/chunk-42VSQ2MX.js +0 -4
  655. package/dist/cli/chunks/chunk-44WISFTU.js +0 -2
  656. package/dist/cli/chunks/chunk-4OUPCTBS.js +0 -16
  657. package/dist/cli/chunks/chunk-4TXAP3YH.js +0 -2
  658. package/dist/cli/chunks/chunk-4W7QVUNO.js +0 -2
  659. package/dist/cli/chunks/chunk-527HQAY7.js +0 -14
  660. package/dist/cli/chunks/chunk-5DFHE4H5.js +0 -180
  661. package/dist/cli/chunks/chunk-5P3G6ZW4.js +0 -2
  662. package/dist/cli/chunks/chunk-6F2RM6X2.js +0 -2
  663. package/dist/cli/chunks/chunk-7Y2CEXRS.js +0 -65
  664. package/dist/cli/chunks/chunk-AWNYEAGB.js +0 -2
  665. package/dist/cli/chunks/chunk-CBOPBYPU.js +0 -2
  666. package/dist/cli/chunks/chunk-FD2JFEQC.js +0 -2
  667. package/dist/cli/chunks/chunk-I4NDQGKP.js +0 -2
  668. package/dist/cli/chunks/chunk-L2GKMBDP.js +0 -2
  669. package/dist/cli/chunks/chunk-QLWNXBRU.js +0 -2
  670. package/dist/cli/chunks/chunk-R2AFVFRF.js +0 -2
  671. package/dist/cli/chunks/chunk-ROX7NLS4.js +0 -14
  672. package/dist/cli/chunks/chunk-T62DH4GG.js +0 -11
  673. package/dist/cli/chunks/chunk-UMNYF5EZ.js +0 -2
  674. package/dist/cli/chunks/chunk-UTVRQEZM.js +0 -54
  675. package/dist/cli/chunks/chunk-Y5SQBI2F.js +0 -2
  676. package/dist/cli/chunks/ci-YVKDQWIX.js +0 -81
  677. package/dist/cli/chunks/client-M72GXFVQ.js +0 -2
  678. package/dist/cli/chunks/complexity-analyzer-LEDG62YK.js +0 -2
  679. package/dist/cli/chunks/core-handlers-C32RAMVI.js +0 -2
  680. package/dist/cli/chunks/cost-tracker-GJIFB2BM.js +0 -2
  681. package/dist/cli/chunks/cross-domain-router-UGFUCPKC.js +0 -2
  682. package/dist/cli/chunks/dream-UFBBXY5W.js +0 -2
  683. package/dist/cli/chunks/eval-PR6YWDFM.js +0 -17
  684. package/dist/cli/chunks/fleet-QNT6X2YI.js +0 -43
  685. package/dist/cli/chunks/heartbeat-scheduler-VQWHSGTY.js +0 -2
  686. package/dist/cli/chunks/hnsw-adapter-BS3NXWGU.js +0 -2
  687. package/dist/cli/chunks/hnsw-index-JP26B4HW.js +0 -2
  688. package/dist/cli/chunks/impact-analyzer-WRE4CWPJ.js +0 -2
  689. package/dist/cli/chunks/init-wizard-OFOEYB75.js +0 -2
  690. package/dist/cli/chunks/kernel-MXNFWNUD.js +0 -2
  691. package/dist/cli/chunks/knowledge-graph-7JE2TVKJ.js +0 -2
  692. package/dist/cli/chunks/learning-7B5NITDV.js +0 -122
  693. package/dist/cli/chunks/llm-router-BNEPT5OB.js +0 -37
  694. package/dist/cli/chunks/llm-router-service-GTDVDKSU.js +0 -2
  695. package/dist/cli/chunks/load-test-JZ4CLSBF.js +0 -2
  696. package/dist/cli/chunks/memory-backend-Q54CC5A5.js +0 -2
  697. package/dist/cli/chunks/memory-handlers-IIBJXKHZ.js +0 -2
  698. package/dist/cli/chunks/multi-model-executor-HEDVOZ6X.js +0 -14
  699. package/dist/cli/chunks/pattern-null-store-W33O7FYO.js +0 -2
  700. package/dist/cli/chunks/pipeline-UOG6UO6D.js +0 -19
  701. package/dist/cli/chunks/protocol-executor-VGN4M7XY.js +0 -2
  702. package/dist/cli/chunks/qe-reasoning-bank-7VB5LJGS.js +0 -2
  703. package/dist/cli/chunks/queen-coordinator-HIDMJMMG.js +0 -2
  704. package/dist/cli/chunks/router-CTIJS4D7.js +0 -2
  705. package/dist/cli/chunks/routing-feedback-LFYYZS5J.js +0 -2
  706. package/dist/cli/chunks/rvf-dual-writer-MNPMIWVM.js +0 -2
  707. package/dist/cli/chunks/rvf-migration-adapter-DXOKSSNW.js +0 -2
  708. package/dist/cli/chunks/rvf-native-adapter-PZKUKA7R.js +0 -2
  709. package/dist/cli/chunks/rvf-store-integrity-Q3FGYKFT.js +0 -2
  710. package/dist/cli/chunks/safe-db-73BLFV2C.js +0 -2
  711. package/dist/cli/chunks/schedule-YVTGTTI4.js +0 -2
  712. package/dist/cli/chunks/scheduler-5DSAFIRQ.js +0 -2
  713. package/dist/cli/chunks/sqlite-persistence-LRG4IPCU.js +0 -2
  714. package/dist/cli/chunks/task-handler-L7E2I267.js +0 -49
  715. package/dist/cli/chunks/task-handlers-6DPKE4AK.js +0 -9
  716. package/dist/cli/chunks/test-scheduling-4CNJA6TW.js +0 -15
  717. package/dist/cli/chunks/types-TXMY5M2K.js +0 -2
  718. package/dist/cli/chunks/unified-memory-VBQ572X4.js +0 -2
  719. package/dist/cli/chunks/unified-memory-hnsw-J3L74ZRY.js +0 -2
  720. package/dist/cli/chunks/unified-persistence-EM2VYRTQ.js +0 -2
  721. package/dist/cli/chunks/visual-security-GX4S7K6O.js +0 -2
  722. package/dist/cli/chunks/witness-chain-QGKMHCNW.js +0 -2
  723. package/dist/cli/chunks/workflow-2OYNO7UU.js +0 -51
  724. package/dist/cli/chunks/workflow-orchestrator-KWHIJMFV.js +0 -2
@@ -0,0 +1,65 @@
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.4");process.exit(0)}
2
+ import{d as j,e as W,f as ie,g as V}from"./chunk-T6BVLVI5.js";import{a as ae}from"./chunk-ZJ26AQA5.js";import{b as Le}from"./chunk-OBAP2TXZ.js";import{a as oe}from"./chunk-IPR4QP3H.js";import{c as Oe,n as T}from"./chunk-NDPFGIMJ.js";import{b as Fe,c as ct}from"./chunk-PEPFCPES.js";import{a as se,b as _e,d as Ne,f as lt}from"./chunk-TDZ53WO2.js";import{c as X,e as Me,f as He}from"./chunk-QGIU2WRL.js";import{b as P,c as v}from"./chunk-STM3UDNO.js";import{a as S,b as Ie,c as De}from"./chunk-G6T45OIC.js";import{i as D}from"./chunk-SRKETSFF.js";import{B as $,D as L,G as ne,P as k,S as O,b as F}from"./chunk-CNG6GQEZ.js";import{d as B,f as ot}from"./chunk-TT23RRB7.js";var K=B(E=>{var vt=E&&E.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(E,"__esModule",{value:!0});var St=Object.prototype.hasOwnProperty;function fe(n,e){return St.call(n,e)}E.hasOwnProperty=fe;function je(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)fe(n,i)&&r.push(i);return r}E._objectKeys=je;function wt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}E._deepClone=wt;function Pt(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}E.isInteger=Pt;function ue(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}E.escapePathComponent=ue;function bt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}E.unescapePathComponent=bt;function me(n,e){var t;for(var r in n)if(fe(n,r)){if(n[r]===e)return ue(r)+"/";if(typeof n[r]=="object"&&(t=me(n[r],e),t!=""))return ue(r)+"/"+t}return""}E._getPathRecursive=me;function Et(n,e){if(n===e)return"/";var t=me(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}E.getPath=Et;function he(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(he(n[e]))return!0}else if(typeof n=="object"){for(var r=je(n),i=r.length,s=0;s<i;s++)if(he(n[r[s]]))return!0}}return!1}E.hasUndefined=he;function Be(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
3
+ `)}var At=(function(n){vt(e,n);function e(t,r,i,s,o){var c=this.constructor,d=n.call(this,Be(t,{name:r,index:i,operation:s,tree:o}))||this;return d.name=r,d.index=i,d.operation=s,d.tree=o,Object.setPrototypeOf(d,c.prototype),d.message=Be(t,{name:r,index:i,operation:s,tree:o}),d}return e})(Error);E.PatchError=At});var pe=B(g=>{Object.defineProperty(g,"__esModule",{value:!0});var R=K();g.JsonPatchError=R.PatchError;g.deepClone=R._deepClone;var U={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Z(t,this.path);r&&(r=R._deepClone(r));var i=_(t,{op:"remove",path:this.from}).removed;return _(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Z(t,this.from);return _(t,{op:"add",path:this.path,value:R._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:J(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},Rt={add:function(n,e,t){return R.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:U.move,copy:U.copy,test:U.test,_get:U._get};function Z(n,e){if(e=="")return n;var t={op:"_get",path:e};return _(n,t),t.value}g.getValueByPointer=Z;function _(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):ee(e,0)),e.path===""){var o={newDocument:n};if(e.op==="add")return o.newDocument=e.value,o;if(e.op==="replace")return o.newDocument=e.value,o.removed=n,o;if(e.op==="move"||e.op==="copy")return o.newDocument=Z(n,e.from),e.op==="move"&&(o.removed=n),o;if(e.op==="test"){if(o.test=J(n,e.value),o.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o.newDocument=n,o}else{if(e.op==="remove")return o.removed=n,o.newDocument=null,o;if(e.op==="_get")return e.value=n,o;if(t)throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return o}}else{r||(n=R._deepClone(n));var c=e.path||"",d=c.split("/"),a=n,l=1,h=d.length,f=void 0,u=void 0,m=void 0;for(typeof t=="function"?m=t:m=ee;;){if(u=d[l],u&&u.indexOf("~")!=-1&&(u=R.unescapePathComponent(u)),i&&(u=="__proto__"||u=="prototype"&&l>0&&d[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(a[u]===void 0?f=d.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&m(e,0,n,f)),l++,Array.isArray(a)){if(u==="-")u=a.length;else{if(t&&!R.isInteger(u))throw new g.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);R.isInteger(u)&&(u=~~u)}if(l>=h){if(t&&e.op==="add"&&u>a.length)throw new g.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var o=Rt[e.op].call(e,a,u,n);if(o.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}}else if(l>=h){var o=U[e.op].call(e,a,u,n);if(o.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return o}if(a=a[u],t&&l<h&&(!a||typeof a!="object"))throw new g.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}g.applyOperation=_;function We(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=R._deepClone(n));for(var s=new Array(e.length),o=0,c=e.length;o<c;o++)s[o]=_(n,e[o],t,!0,i,o),n=s[o].newDocument;return s.newDocument=n,s}g.applyPatch=We;function Tt(n,e,t){var r=_(n,e);if(r.test===!1)throw new g.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}g.applyReducer=Tt;function ee(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new g.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(U[n.op]){if(typeof n.path!="string")throw new g.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new g.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new g.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&R.hasUndefined(n.value))throw new g.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new g.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new g.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var o={op:"_get",path:n.from,value:void 0},c=Ve([o],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new g.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new g.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}g.validator=ee;function Ve(n,e,t){try{if(!Array.isArray(n))throw new g.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)We(R._deepClone(e),R._deepClone(n),t||!0);else{t=t||ee;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof g.JsonPatchError)return i;throw i}}g.validate=Ve;function J(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,o;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!J(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(o=c[i],!J(n[o],e[o]))return!1;return!0}return n!==n&&e!==e}g._areEquals=J});var Xe=B(q=>{Object.defineProperty(q,"__esModule",{value:!0});var b=K(),Ct=pe(),ye=new WeakMap,xt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),It=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function Dt(n){return ye.get(n)}function Ft(n,e){return n.observers.get(e)}function Ot(n,e){n.observers.delete(e.callback)}function _t(n,e){e.unobserve()}q.unobserve=_t;function Nt(n,e){var t=[],r,i=Dt(n);if(!i)i=new xt(n),ye.set(n,i);else{var s=Ft(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=b._deepClone(n),e){r.callback=e,r.next=null;var o=function(){ge(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){ge(r),clearTimeout(r.next),Ot(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new It(e,r)),r}q.observe=Nt;function ge(n,e){e===void 0&&(e=!1);var t=ye.get(n.object);ve(t.value,n.object,n.patches,"",e),n.patches.length&&Ct.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}q.generate=ge;function ve(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=b._objectKeys(e),o=b._objectKeys(n),c=!1,d=!1,a=o.length-1;a>=0;a--){var l=o[a],h=n[l];if(b.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?ve(h,f,t,r+"/"+b.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(h)}),t.push({op:"replace",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(h)}),t.push({op:"remove",path:r+"/"+b.escapePathComponent(l)}),d=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!d&&s.length==o.length))for(var a=0;a<s.length;a++){var l=s[a];!b.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+b.escapePathComponent(l),value:b._deepClone(e[l])})}}}function Mt(n,e,t){t===void 0&&(t=!1);var r=[];return ve(n,e,r,"",t),r}q.compare=Mt});var Ge=B(N=>{var Ht=pe();Object.assign(N,Ht);var Lt=Xe();Object.assign(N,Lt);var te=K();N.JsonPatchError=te.PatchError;N.deepClone=te._deepClone;N.escapePathComponent=te.escapePathComponent;N.unescapePathComponent=te.unescapePathComponent});var A=class extends Error{patternId;disposition;cause;constructor(e,t,r){super(`${t}: pattern ${e}: ${r instanceof Error?r.message:String(r)}`),this.name="PatternMutationError",this.patternId=e,this.disposition=t,this.cause=r}};ct();import{existsSync as Vt}from"node:fs";import{join as it}from"node:path";De();var z=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??G,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1,this.embeddingSpaceId=t?.embeddingSpaceId}createAdapter;config;rvfPath;skipCloseOnDispose;embeddingSpaceId;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){if(this.rvfInitError=null,process.env.AQE_MEMORY_BACKEND==="memory"){this.adapter=null,this.initialized=!0;return}try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension);let e=T()?.spaceId??this.embeddingSpaceId??null;Oe(this.rvfPath,e,this.adapter.status()?.totalVectors??0),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=S(e);try{this.adapter?.close()}catch{}console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-SQ3HCUQ7.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let o=JSON.parse(r(s,"utf-8")),c=new Set((o.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),d=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),a=[...c].filter(l=>!d.has(l));if(a.length===0)return;this.adapter.delete(a),console.log(`[RvfPatternStore] Removed ${a.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${S(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let r=T()?.spaceId??this.embeddingSpaceId;if(e.embedding&&!r)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));let i=!1;if(this.sqliteStore)try{let s=this.sqliteStore.storePattern(e,e.embedding,r);s&&s!==e.id&&(e.id=s),i=!0}catch(s){return v(new A(e.id,"FAILED",s))}if(e.embedding&&!this.adapter&&this.rvfInitError)return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",new Error(`RVF unavailable ${i?"after":"before"} authoritative pattern commit: ${this.rvfInitError}`)));if(e.embedding&&this.adapter)try{let s=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding),o=this.adapter.ingest([{id:e.id,vector:s}]);if(o.accepted!==1||o.rejected!==0)throw new Error(`RVF rejected pattern vector (accepted=${o.accepted}, rejected=${o.rejected})`)}catch(s){return v(new A(e.id,i?"COMMITTED_PENDING_INDEX":"FAILED",s))}return P(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:j({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)){let c=T()?.spaceId??this.embeddingSpaceId;if(!c||t.embeddingSpaceId!==c)return v(new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId"))}if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),d=this.adapter.search(c,i*2);for(let a of d){let l=await this.get(a.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,a.score);s.push({pattern:l,score:a.score,matchType:"vector",similarity:a.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",S(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),d=e,a=Math.sqrt(d.reduce((l,h)=>l+h*h,0));if(a>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==d.length)continue;let u=0,m=0;for(let w=0;w<d.length;w++)u+=d[w]*f[w],m+=f[w]*f[w];if(m=Math.sqrt(m),m===0)continue;let p=u/(a*m),y=this.calculateReuseInfo(h,p);s.push({pattern:h,score:p,matchType:"vector",similarity:p,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),d=new Set(s.map(a=>a.pattern.id));for(let a of c){if(d.has(a.id)||!this.matchesFilters(a,t))continue;let l=this.calculateReuseInfo(a,a.confidence);s.push({pattern:a,score:a.confidence,matchType:"exact",similarity:a.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),d=new Set(s.map(a=>a.pattern.id));for(let a of c){if(d.has(a.id))continue;let l=await this.get(a.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,a.ftsScore);s.push({pattern:l,score:.5*a.ftsScore,matchType:"exact",similarity:a.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,d)=>d.score-c.score);let o=performance.now()-r;return this.searchOps++,this.totalSearchMs+=o,P(s.slice(0,i))}async recordUsage(e,t,r,i){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t,r,i),P(void 0)}catch(s){return v(new Error(`recordUsage failed: ${S(s)}`))}}async promote(e){if(!this.sqliteStore)return v(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),P(void 0)}catch(t){return v(new Error(`promote failed: ${S(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,S(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return v(new Error(`SQLite delete failed: ${S(t)}`))}return P(void 0)}async getStats(){let e=this.adapter?.status(),t=0,r={},i={shortTerm:0,longTerm:0};if(this.sqliteStore)try{let s=this.sqliteStore.getStats();t=s.totalPatterns,r=s.byDomain,i={shortTerm:s.byTier["short-term"]??0,longTerm:s.byTier["long-term"]??0}}catch{}return{totalPatterns:t,byTier:i,byDomain:r,byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",S(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};lt();De();O();function ut(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),o=i;for(let c of s){if(o==null)break;if(typeof o=="object")o=o[c];else{o=void 0;break}}if(o!==void 0)return o}}function ht(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),o=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=o&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function Y(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>Y(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>Y(n,r))}case"NOT":return e.child?!Y(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=ut(n,e.field);return ht(t,e.operator,e.value)}default:return!0}}function ke(n,e){return e?n.filter(t=>Y(t,e)):n}O();O();var qe=1e4,Qe=2166136261;function $e(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var de=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;de[n]=e}var Ue="0123456789abcdef";function ft(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ue[i>>4]+Ue[i&15]}return t}function mt(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function pt(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let o=0;o<8;o++){let c=0,d=1<<o;for(let a=0;a<n.length;a++)n[a][i]&d&&c++;c>=r&&(s|=d)}t[i]=s}return t}function gt(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=de[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function yt(n,e,t){return 1-gt(n,e,t)}var ce=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??qe,this.baseSeed=e?.seed??Qe,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=$e(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=mt(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return pt([r,i])}similarity(e,t){return yt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ae(e),i=0;for(;i<this.byteLen;){let o=r.next(),c=Math.min(4,this.byteLen-i);for(let d=0;d<c;d++)t[i++]=o>>>d*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},le=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??qe,this.baseSeed=e?.seed??Qe,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=$e(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:ft(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=de[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ae(e),s=0;for(;s<t;){let c=i.next(),d=t-s,a=d<4?d:4;for(let l=0;l<a;l++)r[s++]=c>>>l*8&255}let o=this.dimensions%8;return o>0&&(r[t-1]&=(1<<o)-1),r}};function ze(n){return new le(n)}function Je(n){return $()?new ce(n):null}var we=ot(Ge(),1),Se=we.default??we,kt=`
4
+ CREATE TABLE IF NOT EXISTS pattern_deltas (
5
+ id TEXT PRIMARY KEY,
6
+ pattern_id TEXT NOT NULL,
7
+ version INTEGER NOT NULL,
8
+ timestamp INTEGER NOT NULL,
9
+ type TEXT NOT NULL CHECK (type IN ('genesis', 'update', 'rollback')),
10
+ patch TEXT NOT NULL DEFAULT '[]',
11
+ reverse_patch TEXT NOT NULL DEFAULT '[]',
12
+ metadata TEXT
13
+ );
14
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_pid_version
15
+ ON pattern_deltas (pattern_id, version);
16
+ CREATE INDEX IF NOT EXISTS idx_pattern_deltas_timestamp
17
+ ON pattern_deltas (timestamp);
18
+ `;function Ye(n,e){let t=Se.compare(n,e),r=Se.compare(e,n);return{forward:t,reverse:r}}function Ut(n,e){let t=JSON.parse(JSON.stringify(n));return Se.applyPatch(t,e).newDocument}function Ke(n){return{id:n.id,patternId:n.pattern_id,version:n.version,timestamp:n.timestamp,type:n.type,patch:JSON.parse(n.patch),reversePatch:JSON.parse(n.reverse_patch),metadata:n.metadata?JSON.parse(n.metadata):void 0}}var re=class{db;config;prepared=new Map;initialized=!1;constructor(e,t){this.db=e,this.config={maxVersionsPerPattern:t?.maxVersionsPerPattern??100,compressDeltas:t?.compressDeltas??!1}}initialize(){this.initialized||(this.db.exec(kt),this.prepareStatements(),this.initialized=!0)}prepareStatements(){this.prepared.set("insert",this.db.prepare(`
19
+ INSERT INTO pattern_deltas (id, pattern_id, version, timestamp, type, patch, reverse_patch, metadata)
20
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
21
+ `)),this.prepared.set("getHistory",this.db.prepare(`
22
+ SELECT * FROM pattern_deltas
23
+ WHERE pattern_id = ?
24
+ ORDER BY version ASC
25
+ `)),this.prepared.set("currentVersion",this.db.prepare(`
26
+ SELECT MAX(version) as max_version FROM pattern_deltas
27
+ WHERE pattern_id = ?
28
+ `)),this.prepared.set("incrementalSync",this.db.prepare(`
29
+ SELECT * FROM pattern_deltas
30
+ WHERE timestamp > ?
31
+ ORDER BY timestamp ASC
32
+ `)),this.prepared.set("countForPattern",this.db.prepare(`
33
+ SELECT COUNT(*) as cnt FROM pattern_deltas
34
+ WHERE pattern_id = ?
35
+ `)),this.prepared.set("deleteOldest",this.db.prepare(`
36
+ DELETE FROM pattern_deltas
37
+ WHERE pattern_id = ? AND version IN (
38
+ SELECT version FROM pattern_deltas
39
+ WHERE pattern_id = ?
40
+ ORDER BY version ASC
41
+ LIMIT ?
42
+ )
43
+ `))}ensureInitialized(){if(!this.initialized)throw new Error("DeltaTracker not initialized. Call initialize() first.")}createGenesis(e,t,r){this.ensureInitialized();let i=this.getCurrentVersion(e);if(i>=0)throw new Error(`Genesis already exists for pattern ${e} (current version: ${i})`);let s={id:D(),patternId:e,version:0,timestamp:Date.now(),type:"genesis",patch:[],reversePatch:[],metadata:{...r,snapshot:t}};return this.insertEvent(s),s}recordDelta(e,t,r,i){this.ensureInitialized();let s=this.getCurrentVersion(e);if(s<0)throw new Error(`No genesis found for pattern ${e}. Call createGenesis() first.`);let{forward:o,reverse:c}=Ye(t,r),d={id:D(),patternId:e,version:s+1,timestamp:Date.now(),type:"update",patch:o,reversePatch:c,metadata:i};return this.insertEvent(d),this.enforceRetention(e),d}rollback(e,t){this.ensureInitialized();let r=this.getHistory(e);if(r.length===0)throw new Error(`No history found for pattern ${e}`);let i=r[r.length-1].version;if(t<0||t>i)throw new Error(`Invalid rollback version ${t}. Valid range: 0-${i}`);if(t===i)return this.reconstructState(r,i);let s=this.reconstructState(r,t),o=this.reconstructState(r,i),{forward:c,reverse:d}=Ye(o,s),a={id:D(),patternId:e,version:i+1,timestamp:Date.now(),type:"rollback",patch:c,reversePatch:d,metadata:{rolledBackTo:t}};return this.insertEvent(a),this.enforceRetention(e),s}getHistory(e){return this.ensureInitialized(),this.prepared.get("getHistory").all(e).map(Ke)}incrementalSync(e){return this.ensureInitialized(),this.prepared.get("incrementalSync").all(e).map(Ke)}getCurrentVersion(e){return this.ensureInitialized(),this.prepared.get("currentVersion").get(e).max_version??-1}insertEvent(e){this.prepared.get("insert").run(e.id,e.patternId,e.version,e.timestamp,e.type,JSON.stringify(e.patch),JSON.stringify(e.reversePatch),e.metadata?JSON.stringify(e.metadata):null)}reconstructState(e,t){let r=e.find(s=>s.type==="genesis");if(!r||!r.metadata?.snapshot)throw new Error("Cannot reconstruct state: no genesis snapshot found");let i=JSON.parse(JSON.stringify(r.metadata.snapshot));for(let s of e)if(s.version!==0){if(s.version>t)break;i=Ut(i,s.patch)}return i}enforceRetention(e){let{maxVersionsPerPattern:t}=this.config,i=this.prepared.get("countForPattern").get(e).cnt;if(i>t){let s=i-t;this.db.prepare(`DELETE FROM pattern_deltas
44
+ WHERE pattern_id = ? AND version != 0 AND id IN (
45
+ SELECT id FROM pattern_deltas
46
+ WHERE pattern_id = ? AND version != 0
47
+ ORDER BY version ASC
48
+ LIMIT ?
49
+ )`).run(e,e,s)}}};O();var qt={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},Pe=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...qt,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},o={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(o),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let o=s+1,c=this.computeSparseChanges(t,r),d={patternId:e,version:o,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,o),this.getOrCreate(this.history,e).push(d),this.buffer.push(d),o%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:o,fullVector:[...r],timestamp:d.timestamp}),this.enforceRetention(e),d}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],o=null;for(let a=s.length-1;a>=0;a--)if(s[a].version<=t){o=s[a];break}if(!o)return null;let c=[...o.fullVector],d=o.version+1;for(let a of r)if(!(a.version<d)){if(a.version>t)break;this.applySparseForward(c,a.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,o=i.slice(0,s),c=i.slice(s),d=o.findIndex(h=>h.deltaType==="genesis");d>=0&&(c.unshift(o[d]),o.splice(d,1)),this.history.set(e,c);let a=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=a)),o.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let o=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(o-c)>this.config.epsilon&&r.push({index:s,oldValue:o,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Ze(n){return L()?new Pe(n):null}O();var Qt=128,$t=8,zt=1e4,be=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??Qt,this.beta=e?.beta??$t,this.maxPatterns=e?.maxPatterns??zt,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,o=i[0];for(let l=1;l<i.length;l++)i[l]>o&&(o=i[l],s=l);let c=this.patterns[s],d=this.getEnergy(t),a=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:d,similarity:a}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let a=0;a<this.patterns.length;a++)r[a]=this.dotProduct(this.patterns[a].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let a=0;a<this.patterns.length;a++)i[a]=this.beta*r[a],i[a]>s&&(s=i[a]);let o=0;for(let a=0;a<this.patterns.length;a++)o+=Math.exp(i[a]-s);let c=1/this.beta*(s+Math.log(o)),d=this.dotProduct(t,t);return-c+.5*d}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!F().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function et(n){return new be(n)}O();var Jt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},M=1e-5,tt=1-M;function Bt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function C(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function jt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var x=class n{static poincareDistance(e,t){let r=C(jt(e,t)),i=Math.max(M,1-C(e)),s=Math.max(M,1-C(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Bt(e,t),i=C(e),s=C(t),o=Math.max(M,1+2*r+i*s),c=1+2*r+s,d=1-i,a=new Float32Array(e.length);for(let l=0;l<e.length;l++)a[l]=(c*e[l]+d*t[l])/o;return n.project(a)}static expMap(e,t){let r=2/Math.max(M,1-C(e)),i=Math.sqrt(C(t));if(i<M)return new Float32Array(e);let s=Math.tanh(r*i/2),o=new Float32Array(t.length);for(let c=0;c<t.length;c++)o[c]=s/i*t[c];return n.mobiusAdd(e,o)}static project(e){let t=Math.sqrt(C(e));if(t<=tt)return new Float32Array(e);let r=tt/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(C(e));if(t<M)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},Ee=class{config;points=new Map;constructor(e){if(this.config={...Jt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:x.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=x.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:x.poincareDistance(r,s.coordinates),point:s});return i.sort((s,o)=>s.distance-o.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,o=[];for(let d of e)if(s.set(d.id,d),!d.parentId)o.push(d.id);else{let a=i.get(d.parentId);a||(a=[],i.set(d.parentId,a)),a.push(d.id)}let c=o.map((d,a)=>({id:d,depth:0,angOff:2*Math.PI*a/Math.max(1,o.length),angSpan:2*Math.PI/Math.max(1,o.length)}));for(;c.length>0;){let{id:d,depth:a,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(a+.1)),u=l+h/2,m=new Float32Array(r);m[0]=f*Math.cos(u),m[1]=f*Math.sin(u);let p=s.get(d);if(p&&p.features.length>0){let H=f*.1;for(let I=2;I<r&&I-2<p.features.length;I++)m[I]=p.features[I-2]*H}let y=x.project(m);t.set(d,y),this.points.set(d,{id:d,coordinates:y,metadata:{depth:a,parentId:p?.parentId}});let w=i.get(d)??[];for(let H=0;H<w.length;H++){let I=h/Math.max(1,w.length);c.push({id:w[H],depth:a+1,angOff:l+H*I,angSpan:I})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function rt(n){return Wt()?new Ee(n):null}function Wt(){return F().useHyperbolicHnsw}O();var Ae=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!k())return!1;try{return this.index=rt(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=x.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=x.euclideanToHyperbolic(r);return this.index.search(i,t).map(o=>({patternId:o.id,distance:o.distance,metadata:o.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function nt(n){return new Ae(n)}var Re=null;function st(){return Re||(Re=ze({dimensions:1e4})),Re}var Te;function Xt(){return Te===void 0&&(Te=Je()),Te}var Q=null,Ce=0;function at(n){return(!Q||Ce!==n)&&(Q=et({dimension:n,maxPatterns:1e4}),Ce=n),Q}var G={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},xe=class{constructor(e,t={}){this.memory=e;this.config={...G,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;nullStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswSpaceId=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,L()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new re(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){if(this.hnswIndex!==null){let e=T()?.spaceId??this.config.embeddingSpaceId??null;return this.hnswSpaceId!==e?(console.warn("[PatternStore] VECTOR_SPACE_MISMATCH: active embedder changed; semantic index disabled"),null):this.hnswIndex}return this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(this.hnswSpaceId=T()?.spaceId??this.config.embeddingSpaceId??null,!this.hnswSpaceId)throw new Error("VECTOR_SPACE_UNVERIFIED: cannot initialize HNSW without runtime provenance");if(F().useUnifiedHnsw)try{let{HnswLegacyBridge:o}=await import("./hnsw-legacy-bridge-YLC7SPK2.js"),{HnswAdapter:c}=await import("./hnsw-adapter-WXQABRCA.js"),d=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new o(d),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(o){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",o)}let{HNSWIndex:t}=await import("./hnsw-index-TPSWLEA5.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((o,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",S(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0,s=T()?.spaceId??this.config.embeddingSpaceId;for(let{patternId:o,embedding:c,spaceId:d}of e){if(r>=t)break;if(!s||d!==s||!c||c.length!==this.config.embeddingDimension){i++;continue}let a=this.patternCache.get(o);if(!a){i++;continue}try{await this.hnswIndex.insert(o,c,{filePath:a.patternType,lineCoverage:a.confidence*100,branchCoverage:a.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-a.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",S(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Ze()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",S(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=V(e);if(!t.valid)return v(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return v(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));let r=(process.env.AQE_MEMORY_BACKEND??"memory")!=="memory";if(r&&!this.sqliteStore)return v(new A(e.id,"FAILED",new Error("authoritative SQLite pattern store is unavailable")));let i=T()?.spaceId??this.config.embeddingSpaceId;if(e.embedding&&!i)return v(new Error("VECTOR_SPACE_UNVERIFIED: refusing to persist or index an embedding without runtime provenance"));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let o=this.patternCache.get(e.id)??null,c=!1,d=()=>{this.unindexPattern(e),o&&this.indexPattern(o)};if(this.indexPattern(e),this.sqliteStore)try{let a=this.sqliteStore.storePattern(e,e.embedding,i);a&&a!==e.id&&(this.unindexPattern(e),e.id=a,this.indexPattern(e)),c=!0}catch(a){return d(),v(new A(e.id,"FAILED",a))}if(e.embedding){let a=await this.ensureHNSW();if(!a&&c)return v(new A(e.id,"COMMITTED_PENDING_INDEX",new Error("HNSW unavailable after authoritative pattern commit")));if(!a&&r)return d(),v(new A(e.id,"FAILED",new Error("HNSW unavailable before an authoritative pattern commit")));if(a)try{await a.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(l){return c||d(),v(new A(e.id,c?"COMMITTED_PENDING_INDEX":"FAILED",l))}}if($())try{let l=st().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,l.vector)}catch(a){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,S(a))}try{let a=Xt();if(a){let l=[e.patternType,e.qeDomain];e.context?.tags&&l.push(...e.context.tags),e.name&&l.push(e.name);let h=a.fingerprintPattern(l);this.hdcTokenCache.set(e.id,h)}}catch(a){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,S(a))}if(ne()&&e.embedding)try{at(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(a){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,S(a))}if(L()&&this.deltaTracker)try{let a={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,a)}catch(a){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,S(a))}if(e.embedding)try{let a=this.getVectorDeltaTracker();a&&(o?.embedding?a.recordDelta(e.id,o.embedding,e.embedding):a.getVersion(e.id)<0&&a.recordGenesis(e.id,e.embedding))}catch(a){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,S(a))}try{k()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return P(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:D(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?P(i):v(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&ne())try{let f=at(e.length);if(f.getPatternCount()>0){let u=f.recall(new Float32Array(e));if(u&&u.similarity>.98){let m=u.metadata.id,p=await this.get(m);if(p&&this.matchesFilters(p,t)){let y=this.calculateReuseInfo(p,u.similarity);s.push({pattern:p,score:u.similarity,matchType:"vector",similarity:u.similarity,canReuse:y.canReuse,estimatedTokenSavings:y.estimatedTokenSavings,reuseConfidence:y.reuseConfidence})}}}}catch(f){console.debug("[PatternStore] Hopfield recall failed:",S(f))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let f=T()?.spaceId??this.config.embeddingSpaceId;if(!f||t.embeddingSpaceId!==f)throw new Error("VECTOR_SPACE_UNVERIFIED: pre-computed query vectors require the active embeddingSpaceId");let u=await this.ensureHNSW();if(u){let m=await u.search(e,i*2);for(let p of m){let y=await this.get(p.key);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.score);s.push({pattern:y,score:p.score,matchType:"vector",similarity:p.score,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let f=this.sqliteStore.searchFTS(e,i*2);if(f.length>0){let u=new Map(f.map(p=>[p.id,p.ftsScore])),m=new Set(s.map(p=>p.pattern.id));for(let p of s){let y=u.get(p.pattern.id);y!==void 0&&(p.score=.75*p.score+.25*y)}for(let p of f){if(m.has(p.id))continue;let y=await this.get(p.id);if(y&&this.matchesFilters(y,t)){let w=this.calculateReuseInfo(y,p.ftsScore);s.push({pattern:y,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:w.canReuse,estimatedTokenSavings:w.estimatedTokenSavings,reuseConfidence:w.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let f=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),u=new Set(s.map(m=>m.pattern.id));for(let m of f)u.has(m.pattern.id)||s.push(m)}let o=720*60*60*1e3,c=Date.now();for(let f of s){let u=f.pattern.lastUsedAt?.getTime()??f.pattern.createdAt.getTime(),m=c-u,p=Math.pow(.5,m/o),y=f.pattern.usageCount>0?p:.5;f.score=f.score*(.7+.3*y)}let d=this.sqliteStore?.getDatabase();if(d&&s.length>0)try{this.nullStore||(this.nullStore=new oe(d));let f=this.nullStore.getNullSummaries(s.map(u=>u.pattern.id));for(let u of s){let m=f.get(u.pattern.id);m&&(u.nullSummary=m,u.score=oe.applyNullDiscount(u.score,m,t.contextFingerprint))}}catch(f){console.debug("[PatternStore] null discount skipped:",S(f))}s.sort((f,u)=>u.score-f.score);let a=s;t.filter&&(a=ke(s,t.filter));let l=a.slice(0,i),h=performance.now()-r;return this.recordSearchLatency(h),P(l)}catch(o){return v(Ie(o))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),o;t.domain?o=this.domainIndex.get(t.domain)||new Set:t.patternType?o=this.typeIndex.get(t.patternType)||new Set:t.tier?o=this.tierIndex.get(t.tier)||new Set:o=new Set(this.patternCache.keys());let c=[...o];if($()&&s&&this.hdcCache.size>0)try{let d=st(),a=d.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(u=>this.hdcCache.has(u)).map(u=>({id:u,similarity:d.similarity(a.vector,this.hdcCache.get(u))}));l.sort((u,m)=>m.similarity-u.similarity);let h=l.map(u=>u.id),f=c.filter(u=>!this.hdcCache.has(u));c=[...h,...f]}catch{}for(let d of c){if(i.length>=r)break;let a=this.patternCache.get(d);if(!a||!this.matchesFilters(a,t))continue;let l=0;if(s){let h=a.name.toLowerCase(),f=a.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let u of a.context.tags)if(u.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=a.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(a,l);i.push({pattern:a,score:l||a.qualityScore,matchType:s?"exact":"context",similarity:l||a.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,o=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),d=(Date.now()-o)/(1e3*60*60*24)<=r.maxAgeForReuse,a=r.enabled&&e.reusable&&i&&s&&d,l=a?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,u=Math.min(e.reuseCount/10,1),m=a?h*.4+f*.4+u*.2:0;return{canReuse:a,estimatedTokenSavings:l,reuseConfidence:m}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t,r,i){let s=await this.get(e);if(!s)return v(new Error(`Pattern not found: ${e}`));let o=new Date,c=s.usageCount+1,d=s.successfulUses+(t?1:0),a=d/c,l=t?.02:-.01,h=Math.max(.1,Math.min(1,s.confidence+l)),f=j({confidence:h,usageCount:c,successRate:a}),u={...s,usageCount:c,successfulUses:d,successRate:a,confidence:h,qualityScore:f,lastUsedAt:o};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t,r,i)}catch(y){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,S(y))}if(L()&&this.deltaTracker)try{let y={id:s.id,name:s.name,confidence:s.confidence,qualityScore:s.qualityScore,usageCount:s.usageCount,successRate:s.successRate,tier:s.tier},w={id:u.id,name:u.name,confidence:u.confidence,qualityScore:u.qualityScore,usageCount:u.usageCount,successRate:u.successRate,tier:u.tier};this.deltaTracker.recordDelta(e,y,w,{success:t})}catch(y){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,S(y))}let m=ie(u);return m.meetsUsageCriteria&&m.meetsQualityCriteria&&m.meetsCoherenceCriteria&&u.tier==="short-term"?await this.promote(e):this.patternCache.set(e,u),P(void 0)}async promote(e){let t=await this.get(e);if(!t)return v(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return P(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),P(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return v(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return P(void 0)}async getStats(){let e={},t={};for(let[a,l]of this.domainIndex)e[a]=l.size;for(let[a,l]of this.typeIndex)t[a]=l.size;let r=0,i=0,s=0,o=0;for(let a of this.patternCache.values())r+=a.confidence,i+=a.qualityScore,s+=a.successRate,o++;let c=await this.ensureHNSW(),d=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:o>0?r/o:0,avgQualityScore:o>0?i/o:0,avgSuccessRate:o>0?s/o:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:d.nativeHNSW,vectorCount:d.vectorCount,indexSizeBytes:d.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let o=ie(s);if(o.meetsUsageCriteria&&o.meetsQualityCriteria&&o.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let d=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),a=Date.now()-d,l=a>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&a>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let o of t){let c=this.patternCache.get(o);c&&r.push(c)}r.sort((o,c)=>o.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let o of r){if(s>=i)break;o.tier==="short-term"&&(await this.delete(o.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),Q&&(Q.clear(),Q=null,Ce=0),this.initialized=!1}indexHyperbolic(e,t,r){if(k())try{this.hyperbolicIndex||(this.hyperbolicIndex=nt({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!k()||!this.hyperbolicIndex)return P([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let o=await this.get(s.patternId);if(!o)continue;let c=Math.exp(-s.distance),d=this.calculateReuseInfo(o,c);i.push({pattern:o,score:c,matchType:"vector",similarity:c,canReuse:d.canReuse,estimatedTokenSavings:d.estimatedTokenSavings,reuseConfidence:d.reuseConfidence})}return P(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),P([])}}};function sn(n,e){try{if(F().useRVFPatternStore&&Ne()){let r=process.env.AQE_PROJECT_ROOT??Fe(),i=it(r,".agentic-qe"),s=it(i,"patterns.rvf");if(Vt(i)){let o={...G,...e},c=!1;try{let d=Le(i,o.embeddingDimension);if(d){c=!0;let a=new z(()=>d,{rvfPath:s,base:o,skipCloseOnDispose:!0,embeddingSpaceId:o.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),a}}catch{}if(!c){let d=new z((a,l)=>{let h,f=()=>{try{return _e(a)}catch(m){return h=m,null}},u=f();if(!u&&X(h)&&(!Me(a)||(u=f(),!u&&X(h))))throw h;if(u){let m=u.dimension();if(m!==l){try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${m}, requested=${l})`)}return u}try{return se(a,l)}catch(m){if(u=f(),u){if(u.dimension()!==l){let p=u.dimension();try{u.close()}catch{}throw new Error(`RVF dimension mismatch (file=${p}, requested=${l})`)}return u}if(X(h))throw h;if(He(a,m instanceof Error?m.message:String(m),h))return se(a,l);throw m}},{rvfPath:s,base:o,embeddingSpaceId:o.embeddingSpaceId});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),d}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new xe(n,e)}export{A as a,sn as b};
50
+ /*! Bundled license information:
51
+
52
+ fast-json-patch/commonjs/helpers.js:
53
+ (*!
54
+ * https://github.com/Starcounter-Jack/JSON-Patch
55
+ * (c) 2017-2022 Joachim Wester
56
+ * MIT licensed
57
+ *)
58
+
59
+ fast-json-patch/commonjs/duplex.js:
60
+ (*!
61
+ * https://github.com/Starcounter-Jack/JSON-Patch
62
+ * (c) 2017-2021 Joachim Wester
63
+ * MIT license
64
+ *)
65
+ */
@@ -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 v,b as k}from"./chunk-YL7T3VV7.js";import{k as g,o as P}from"./chunk-TFHQE6NK.js";import{a as d,b as y,c as R}from"./chunk-HRUU7E3D.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-V3QLFNA2.js";import{k as g,o as P}from"./chunk-55RWDRJD.js";import{a as d,b as y,c as R}from"./chunk-G6T45OIC.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -1,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.4");process.exit(0)}
2
2
  import{createHash as o}from"node:crypto";import a from"node:fs";function c(r){let n=[...r].sort((e,t)=>e.id.localeCompare(t.id)).map(e=>({id:e.id,inputUnderTest:e.inputUnderTest,moduleName:e.moduleName,referenceImpl:e.referenceImpl,requirements:e.requirements,expectedMutants:e.expectedMutants}));return JSON.stringify(n)}function s(r){return o("sha256").update(c(r)).digest("hex")}function u(r){let n=JSON.parse(a.readFileSync(r,"utf8")),e=s(n.items);if(e!==n.contentHash)throw new Error(`Anchor set hash drift at ${r}: recorded ${n.contentHash}, recomputed ${e}. Refusing to load a mutated frozen anchor (ADR-117). A legitimate change must be a versioned re-freeze (qe-anchor-v2), never an in-place edit.`);if(n.items.length===0)throw new Error(`Anchor set at ${r} has no items \u2014 a frozen anchor must be non-empty.`);return n}function h(r,n,e){return r>=n-e}export{u as a,h as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{a as S}from"./chunk-L2GKMBDP.js";import{c as g}from"./chunk-72UJXEKQ.js";import{S as T,b as l}from"./chunk-T35GZXTU.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},v=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},y=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new v,this.plateauDetector=new y,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{h as a,p as b,V as c,v as d,y as e,D as f,C as g,P as h,J as i};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
+ import{a as S}from"./chunk-NA7B2QYB.js";import{c as g}from"./chunk-Y3MW3YBC.js";import{S as T,b as l}from"./chunk-CNG6GQEZ.js";S();T();import{createRequire as B}from"module";var G=B(import.meta.url),d=class{validateTransfer(e,t){return{approved:!0}}};function R(){if(l().useCoherenceGate)try{let{CoherenceGate:o}=G("./coherence-gate.js");return new o}catch{}return new d}S();var x=g.create("transfer-verification"),A={maxSourceRegression:.05,minTargetImprovement:0,maxSourceConfidenceRegression:.1},b=class{config;constructor(e={}){this.config={...A,...e}}verifyTransfer(e){let t=e.sourcePerformanceAfter.successRate-e.sourcePerformanceBefore.successRate,r=e.targetPerformanceAfter.successRate-e.targetPerformanceBefore.successRate,n=e.sourcePerformanceAfter.avgConfidence-e.sourcePerformanceBefore.avgConfidence,a=e.targetPerformanceAfter.avgConfidence-e.targetPerformanceBefore.avgConfidence,s=t>=-this.config.maxSourceRegression&&n>=-this.config.maxSourceConfidenceRegression,c=r>=this.config.minTargetImprovement,u=s&&c,m;if(!u){let i=[];s||i.push(`source domain regressed: successRate delta=${t.toFixed(4)}, confidence delta=${n.toFixed(4)}`),c||i.push(`target domain did not improve: successRate delta=${r.toFixed(4)}`),m=i.join("; ")}return u?x.debug("Transfer verification passed",{transferId:e.transferId,sourceDelta:t,targetDelta:r}):x.warn("Transfer verification failed",{transferId:e.transferId,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourceDelta:t,targetDelta:r,failureReason:m}),{passed:u,sourceStable:s,targetImproved:c,sourceDelta:t,targetDelta:r,sourceConfidenceDelta:n,targetConfidenceDelta:a,failureReason:m}}getConfig(){return{...this.config}}};function M(o){return new b(o)}T();var p=class{alphas=new Map;betas=new Map;sample(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return this.sampleBeta(t,r)}update(e,t){t?this.alphas.set(e,(this.alphas.get(e)??1)+1):this.betas.set(e,(this.betas.get(e)??1)+1)}getMean(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t/(t+r)}getObservationCount(e){let t=this.alphas.get(e)??1,r=this.betas.get(e)??1;return t-1+(r-1)}getAlpha(e){return this.alphas.get(e)??1}getBeta(e){return this.betas.get(e)??1}sampleBeta(e,t){let r=this.sampleGamma(e),n=this.sampleGamma(t);return r+n===0?.5:r/(r+n)}sampleGamma(e){if(e<1){let n=Math.random();return this.sampleGamma(e+1)*Math.pow(n,1/e)}let t=e-1/3,r=1/Math.sqrt(9*t);for(;;){let n,a;do n=this.standardNormal(),a=1+r*n;while(a<=0);a=a*a*a;let s=Math.random();if(s<1-.0331*n*n*n*n||Math.log(s)<.5*n*n+t*(1-a+Math.log(a)))return t*a}}standardNormal(){let e=Math.random(),t=Math.random();return Math.sqrt(-2*Math.log(e||1e-10))*Math.cos(2*Math.PI*t)}};var I={threshold:5,slack:.5,resetOnAlarm:!0,warmupSamples:20},h=class{config;states=new Map;constructor(e={}){this.config={...I,...e}}update(e,t){let r=this.getOrCreateState(e);if(r.samplesSinceReset++,r.mu===null)return r.warmupSum+=t,r.warmupCount++,r.warmupCount>=this.config.warmupSamples&&(r.mu=r.warmupSum/r.warmupCount),{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:r.samplesSinceReset};r.sPlus=Math.max(0,r.sPlus+(t-r.mu-this.config.slack)),r.sMinus=Math.max(0,r.sMinus+(-t+r.mu-this.config.slack));let n=Math.max(r.sPlus,r.sMinus),a=!1,s="none";r.sPlus>this.config.threshold?(a=!0,s="positive"):r.sMinus>this.config.threshold&&(a=!0,s="negative");let c={driftDetected:a,cumulativeSum:n,direction:s,samplesSinceReset:r.samplesSinceReset};return a&&this.config.resetOnAlarm&&(r.sPlus=0,r.sMinus=0,r.samplesSinceReset=0),c}reset(e){e?this.states.delete(e):this.states.clear()}getState(e){let t=this.states.get(e);if(!t)return{driftDetected:!1,cumulativeSum:0,direction:"none",samplesSinceReset:0};let r=Math.max(t.sPlus,t.sMinus),n="none";return t.sPlus>this.config.threshold?n="positive":t.sMinus>this.config.threshold&&(n="negative"),{driftDetected:t.sPlus>this.config.threshold||t.sMinus>this.config.threshold,cumulativeSum:r,direction:n,samplesSinceReset:t.samplesSinceReset}}getOrCreateState(e){let t=this.states.get(e);return t||(t={sPlus:0,sMinus:0,samplesSinceReset:0,warmupSum:0,warmupCount:0,mu:null},this.states.set(e,t)),t}};var w=g.create("domain-transfer"),V={minTransferProbability:.3,explorationWarmup:5,verification:{},maxHistorySize:1e3,useMetaLearningEnhancements:!0},v=class{constructor(e=100){this.decayThreshold=e}decayThreshold;getDecayMultiplier(e){return e<=0?1:Math.pow(.5,e/this.decayThreshold)}applyDecay(e,t,r){return t+(e-t)*this.getDecayMultiplier(r)}},y=class{cusum;outcomes=[];windowSize;constructor(e=20){this.windowSize=e,this.cusum=new h({threshold:3,slack:.1,resetOnAlarm:!1,warmupSamples:Math.min(10,Math.floor(e/2))})}record(e){this.outcomes.push(e),this.outcomes.length>this.windowSize*2&&this.outcomes.splice(0,this.outcomes.length-this.windowSize*2);let t=this.getCurrentRate();this.cusum.update("learn",t)}isPlateaued(){return this.outcomes.length<this.windowSize?!1:!this.cusum.getState("learn").driftDetected}getCurrentRate(){if(this.outcomes.length===0)return 0;let e=this.outcomes.slice(-this.windowSize);return e.filter(Boolean).length/e.length}getOutcomeCount(){return this.outcomes.length}getCusumState(){return this.cusum.getState("learn")}},D=class{front=[];dominates(e,t){let r=e.successRate>=t.successRate&&e.speed>=t.speed&&e.confidence>=t.confidence,n=e.successRate>t.successRate||e.speed>t.speed||e.confidence>t.confidence;return r&&n}add(e){for(let t=this.front.length-1;t>=0;t--)this.dominates(e,this.front[t])&&this.front.splice(t,1);this.front.some(t=>this.dominates(t,e))||this.front.push(e)}getFront(){return[...this.front]}isNonDominated(e){return!this.front.some(t=>this.dominates(t,e))}},C=class{constructor(e=.2){this.bonusScale=e}bonusScale;triedPairs=new Set;markTried(e){this.triedPairs.add(e)}isTried(e){return this.triedPairs.has(e)}getBonus(e){return this.triedPairs.has(e)?0:this.bonusScale}apply(e,t){return Math.min(1,e+this.getBonus(t))}getTriedCount(){return this.triedPairs.size}},P=class{config;sampler;verifier;coherenceGate;transferHistory=[];affinityScores=new Map;performanceProvider=null;transferExecutor=null;nativeModule=null;decayingBeta;plateauDetector;paretoFront;curiosityBonus;constructor(e={}){this.config={...V,...e},this.sampler=new p,this.verifier=M(this.config.verification),this.coherenceGate=R(),this.decayingBeta=new v,this.plateauDetector=new y,this.paretoFront=new D,this.curiosityBonus=new C,this.tryLoadNativeModule()}evaluateTransfer(e,t){if(!this.isEnabled())return this.createRejectedCandidate(e,t);let r=this.makePairKey(e,t),n=this.sampler.sample(r),s=this.sampler.getObservationCount(r)<this.config.explorationWarmup,c=this.getAffinityScore(e,t);if(this.isMetaLearningEnabled()){let u=this.sampler.getMean(r),m=this.sampler.getAlpha(r)-1;n=this.decayingBeta.applyDecay(n,u,m),n=this.curiosityBonus.apply(n,r)}return{sourceDomain:e,targetDomain:t,sampledProbability:n,affinityScore:c,isExploration:s,pairKey:r}}executeTransfer(e){let t=`transfer-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,r=this.coherenceGate.validateTransfer({domain:e.sourceDomain},e.targetDomain);if(!r.approved)return w.info("Transfer blocked by coherence gate",{transferId:t,source:e.sourceDomain,target:e.targetDomain,reason:r.rejectionReason}),this.createBlockedResult(t,e,r);let n=this.getPerformanceSnapshot(e.sourceDomain),a=this.getPerformanceSnapshot(e.targetDomain),s=this.computeSqrtDampening(e),c=this.doTransfer(e.sourceDomain,e.targetDomain,s),u=this.getPerformanceSnapshot(e.sourceDomain),m=this.getPerformanceSnapshot(e.targetDomain),i=this.verifier.verifyTransfer({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m}),f=c&&i.passed;if(this.sampler.update(e.pairKey,f),this.updateAffinityScore(e.pairKey,f),this.isMetaLearningEnabled()){this.plateauDetector.record(f),this.curiosityBonus.markTried(e.pairKey);let F=this.sampler.getMean(e.pairKey);this.paretoFront.add({pairKey:e.pairKey,successRate:F,speed:1/(1+s),confidence:this.getAffinityScore(e.sourceDomain,e.targetDomain)})}return this.addToHistory({transferId:t,sourceDomain:e.sourceDomain,targetDomain:e.targetDomain,success:f,sampledProbability:e.sampledProbability,dampeningFactor:s,sourceDelta:i.sourceDelta,targetDelta:i.targetDelta,timestamp:Date.now()}),w.info("Transfer completed",{transferId:t,source:e.sourceDomain,target:e.targetDomain,success:f,dampeningFactor:s.toFixed(4),sourceDelta:i.sourceDelta.toFixed(4),targetDelta:i.targetDelta.toFixed(4)}),{transferId:t,candidate:e,success:f,dampeningFactor:s,verification:i,coherenceResult:r,sourcePerformanceBefore:n,sourcePerformanceAfter:u,targetPerformanceBefore:a,targetPerformanceAfter:m,timestamp:Date.now()}}getAffinityScore(e,t){return this.affinityScores.get(this.makePairKey(e,t))??.5}getTransferHistory(){return[...this.transferHistory]}getExpectedSuccessRate(e,t){return this.sampler.getMean(this.makePairKey(e,t))}getObservationCount(e,t){return this.sampler.getObservationCount(this.makePairKey(e,t))}setPerformanceProvider(e){this.performanceProvider=e}setTransferExecutor(e){this.transferExecutor=e}getSampler(){return this.sampler}getCoherenceGate(){return this.coherenceGate}getDecayingBeta(){return this.decayingBeta}getPlateauDetector(){return this.plateauDetector}getParetoFront(){return this.paretoFront}getCuriosityBonus(){return this.curiosityBonus}isLearningPlateaued(){return this.plateauDetector.isPlateaued()}isEnabled(){return l().useCrossDomainTransfer===!0}isMetaLearningEnabled(){return this.config.useMetaLearningEnhancements===!0&&l().useMetaLearningEnhancements!==!1}makePairKey(e,t){return`${e}->${t}`}computeSqrtDampening(e){let t=this.sampler.getObservationCount(e.pairKey);return Math.sqrt(t/(t+this.config.explorationWarmup))}doTransfer(e,t,r){return this.transferExecutor?this.transferExecutor(e,t,r):!0}getPerformanceSnapshot(e){return this.performanceProvider?this.performanceProvider(e):{domain:e,successRate:.5,avgConfidence:.5,patternCount:0,timestamp:Date.now()}}updateAffinityScore(e,t){let r=this.affinityScores.get(e)??.5;this.affinityScores.set(e,.2*(t?1:0)+.8*r)}addToHistory(e){for(this.transferHistory.push(e);this.transferHistory.length>this.config.maxHistorySize;)this.transferHistory.shift()}createBlockedResult(e,t,r){let n={domain:"",successRate:0,avgConfidence:0,patternCount:0,timestamp:Date.now()};return{transferId:e,candidate:t,success:!1,dampeningFactor:0,verification:{passed:!1,sourceStable:!1,targetImproved:!1,sourceDelta:0,targetDelta:0,sourceConfidenceDelta:0,targetConfidenceDelta:0,failureReason:`Coherence gate rejected: ${r.rejectionReason??"unknown"}`},coherenceResult:r,sourcePerformanceBefore:{...n,domain:t.sourceDomain},sourcePerformanceAfter:{...n,domain:t.sourceDomain},targetPerformanceBefore:{...n,domain:t.targetDomain},targetPerformanceAfter:{...n,domain:t.targetDomain},timestamp:Date.now()}}createRejectedCandidate(e,t){return{sourceDomain:e,targetDomain:t,sampledProbability:0,affinityScore:0,isExploration:!1,pairKey:this.makePairKey(e,t)}}tryLoadNativeModule(){this.nativeModule=null}};function J(o){return new P(o)}export{h as a,p as b,V as c,v as d,y as e,D as f,C as g,P as h,J as i};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{k as C,o as M}from"./chunk-TFHQE6NK.js";import{i as b}from"./chunk-OYMLHX2B.js";M();import{createRequire as H}from"node:module";var w=H(import.meta.url),_=null;function T(){if(_)return _;let E=w("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function U(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=U(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=w("../../../kernel/hnsw-adapter.js"),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=T(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=T(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var O={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...O,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=C();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
+ import{k as C,o as M}from"./chunk-55RWDRJD.js";import{i as b}from"./chunk-SRKETSFF.js";M();import{createRequire as H}from"node:module";var w=H(import.meta.url),_=null;function T(){if(_)return _;let E=w("hnswlib-node");if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function U(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=U(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=w("../../../kernel/hnsw-adapter.js"),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=T(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=T(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var O={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...O,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=C();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
3
3
  SELECT id, task, domain, quality, success, application_count,
4
4
  consolidation_count, reuse_success_count, reuse_failure_count,
5
5
  embedding, embedding_dimension, started_at
@@ -1,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 m}from"./chunk-44WISFTU.js";import{a as l,c as d}from"./chunk-HRUU7E3D.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-VO7ABNHV.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};export{c as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.4");process.exit(0)}
2
+ import{l as m}from"./chunk-W7BWUTVV.js";import{a as l,c as d}from"./chunk-G6T45OIC.js";d();var c=class extends m{config={name:"qe/tests/load",description:"Run agent load tests to validate fleet scalability. Supports light, medium, and heavy workload profiles. Uses mock agents by default (safe); set mockMode=false to test with real fleet agents (requires fleet_init). Reports bottlenecks and pass/fail criteria.",domain:"test-execution",schema:this.buildSchema(),timeout:3e5};buildSchema(){return{type:"object",properties:{targetAgents:{type:"number",description:"Target number of concurrent agents to simulate",default:10,minimum:1,maximum:200},profile:{type:"string",description:"Workload profile: light, medium, or heavy",enum:["light","medium","heavy"],default:"medium"},durationMs:{type:"number",description:"Test duration in milliseconds",default:3e4,minimum:5e3,maximum:3e5},mockMode:{type:"boolean",description:"Use mock agents (true, default) or real fleet agents (false, requires fleet_init)",default:!0}}}}async execute(t,u){try{let{createAgentLoadTester:r}=await import("./load-2BG6SHAK.js"),a=t.profile||"medium",o=t.targetAgents||10,i=t.durationMs||3e4,n=t.mockMode!==!1,s=await r({maxAgents:o,workloadProfile:a,mockMode:n}).runTest(o,i),e=s.bottlenecks;return{success:!0,data:{testId:u.requestId,profile:a,targetAgents:o,duration:s.duration,mockMode:n,passed:s.success,bottleneckCount:e?.bottlenecks?.length??0,report:{overallSeverity:e?.overallSeverity??"none",hasCritical:e?.hasCritical??!1,checksPerformed:e?.summary?.totalChecks??0,bottlenecksDetected:e?.summary?.detected??0},summary:`Load test (${a}, ${n?"mock":"real"}): ${o} agents, ${i}ms \u2014 ${s.success?"PASSED":"FAILED"}`+(e?.hasCritical?" [CRITICAL BOTTLENECKS]":"")}}}catch(r){return{success:!1,error:l(r)}}}};export{c as a};
@@ -1,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{h as o,k as l,o as h}from"./chunk-TFHQE6NK.js";import{a as m}from"./chunk-L2GKMBDP.js";import{c as s}from"./chunk-72UJXEKQ.js";import{a as r,e as u}from"./chunk-OVDKWCD7.js";h();u();m();var c=s.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??r.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??r.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??o.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??r.BUSY_TIMEOUT_MS};this.unifiedMemory=l(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),a=await this.unifiedMemory.vectorDelete(e);return n||a}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i,t){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i,void 0,t)).map(a=>({key:a.id,score:a.score,metadata:a.metadata}))}getVectorSearchProvenance(){return this.ensureInitialized(),this.unifiedMemory.getVectorSearchProvenance()}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.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.4");process.exit(0)}
2
+ import{h as o,k as l,o as h}from"./chunk-55RWDRJD.js";import{a as m}from"./chunk-NA7B2QYB.js";import{c as s}from"./chunk-Y3MW3YBC.js";import{a as r,e as u}from"./chunk-BFP7KO7P.js";h();u();m();var c=s.create("hybrid-backend"),d=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??r.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??r.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??o.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??r.BUSY_TIMEOUT_MS};this.unifiedMemory=l(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),a=await this.unifiedMemory.vectorDelete(e);return n||a}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i,t){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i,void 0,t)).map(a=>({key:a.id,score:a.score,metadata:a.metadata}))}getVectorSearchProvenance(){return this.ensureInitialized(),this.unifiedMemory.getVectorSearchProvenance()}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
3
  SELECT COUNT(*) as count FROM kv_store
4
4
  WHERE namespace LIKE ?
5
5
  AND (expires_at IS NULL OR expires_at > ?)
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.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.4");process.exit(0)}
2
+ import{a as T}from"./chunk-NA7B2QYB.js";import{c as S}from"./chunk-Y3MW3YBC.js";import{b as C,d as P}from"./chunk-DHJPWQBR.js";import{a as b,c as $}from"./chunk-G6T45OIC.js";import{a as w,d as M}from"./chunk-KCZR45PA.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)}
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.4");process.exit(0)}
2
2
  var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n as a};
@@ -1,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{h as s,k as o,m as c,o as m}from"./chunk-TFHQE6NK.js";import{a,c as d}from"./chunk-HRUU7E3D.js";import{a as r,e as l}from"./chunk-OVDKWCD7.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
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.4");process.exit(0)}
2
+ import{h as s,k as o,m as c,o as m}from"./chunk-55RWDRJD.js";import{a,c as d}from"./chunk-G6T45OIC.js";import{a as r,e as l}from"./chunk-BFP7KO7P.js";d();m();l();var u={dbPath:s.dbPath,walMode:!0,mmapSize:r.MMAP_SIZE_BYTES,cacheSize:r.CACHE_SIZE_KB,busyTimeout:r.BUSY_TIMEOUT_MS},n=class e{static instance=null;static instancePromise=null;unifiedMemory=null;config;initialized=!1;initPromise=null;constructor(i){this.config={...u,...i}}static getInstance(i){return e.instance||(e.instance=new e(i)),e.instance}static async getInstanceAsync(i){return e.instance?.initialized?e.instance:(e.instancePromise||(e.instancePromise=(async()=>{let t=e.getInstance(i);return await t.initialize(),t})()),e.instancePromise)}static resetInstance(){e.instance&&(e.instance.close(),e.instance=null),e.instancePromise=null,c()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let i={dbPath:this.config.dbPath,walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,mmapSize:this.config.mmapSize,cacheSize:this.config.cacheSize};this.unifiedMemory=o(i),await this.unifiedMemory.initialize(),this.initialized=!0,console.log(`[UnifiedPersistence] Initialized via UnifiedMemoryManager: ${this.config.dbPath}`)}catch(i){throw this.initPromise=null,new Error(`Failed to initialize UnifiedPersistenceManager: ${a(i)}`)}}getDatabase(){if(!this.unifiedMemory||!this.initialized)throw new Error("UnifiedPersistenceManager not initialized");return this.unifiedMemory.getDatabase()}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(i,t){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.prepare(i,t)}transaction(i){if(!this.unifiedMemory)throw new Error("Database not initialized");return this.unifiedMemory.transaction(i)}getStats(){if(!this.unifiedMemory)throw new Error("Database not initialized");let i=this.unifiedMemory.getStats();return{tables:i.tables,fileSize:i.fileSize,walSize:i.walSize}}vacuum(){this.getDatabase().exec("VACUUM")}checkpoint(){this.getDatabase().pragma("wal_checkpoint(TRUNCATE)")}close(){this.initialized=!1,console.log("[UnifiedPersistence] Facade closed")}};function g(e){return n.getInstance(e)}async function U(e){let i=g(e);return await i.initialize(),i}function z(){n.resetInstance()}var f=!1;function h(){if(f)return;f=!0;let e=()=>{try{let i=n.instance;i&&i.close()}catch(i){console.debug("[UnifiedPersistence] Cleanup error:",i instanceof Error?i.message:i)}};process.on("beforeExit",e),process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)})}h();export{u as a,n as b,g as c,U as d,z as e};
@@ -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.4");process.exit(0)}
2
+ import{a as w}from"./chunk-AUXFKCQL.js";import{b as p,c as l}from"./chunk-STM3UDNO.js";import{a as g,b as x,c as y}from"./chunk-G6T45OIC.js";import{i as v}from"./chunk-SRKETSFF.js";y();var h=class extends Error{constructor(e){super(`Action timed out after ${e}ms; outcome is unknown`),this.name="ActionTimeoutError"}},m={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolOutcomeUnknown:"coordination.ProtocolOutcomeUnknown",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed",ActionOutcomeUnknown:"coordination.ActionOutcomeUnknown"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):l(new Error(`Protocol is disabled: ${e}`)):l(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):l(new Error(`Protocol is disabled: ${e}`)):l(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?l(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(m.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):l(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?l(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):l(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?l(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):l(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let n=v(),a=o?.correlationId??n,i={executionId:n,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},d={execution:i,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(n,d),await this.publishEvent(m.ProtocolStarted,{executionId:n,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(d);let r=Array.from(d.actionResults.values()),s=r.filter(c=>c.status==="unknown").map(c=>c.actionId),u=r.filter(c=>c.status==="failed").map(c=>c.actionId);return d.cancelled?i.status="cancelled":s.length>0?(i.status="unknown",await this.publishEvent(m.ProtocolOutcomeUnknown,{executionId:n,protocolId:e.id,unknownActions:s,failedActions:u},a)):u.length>0?(i.status="failed",await this.publishEvent(m.ProtocolFailed,{executionId:n,protocolId:e.id,failedActions:u},a)):(i.status="completed",await this.publishEvent(m.ProtocolCompleted,{executionId:n,protocolId:e.id,duration:Date.now()-i.startedAt.getTime()},a)),i.completedAt=new Date,i.results=d.actionResults,await this.storeExecutionHistory(i),p(this.toImmutableExecution(i))}catch(r){return i.status="failed",i.completedAt=new Date,await this.publishEvent(m.ProtocolFailed,{executionId:n,protocolId:e.id,error:g(r)},a),l(x(r))}}async executeActions(e){let{protocol:t,actionResults:o}=e,n=new Set(t.actions.map(i=>i.id)),a=new Set;for(;n.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let i=t.actions.filter(r=>n.has(r.id)&&this.dependenciesSatisfied(r,a));if(i.length===0&&n.size>0){let r=!1;for(let s of t.actions)n.has(s.id)&&s.dependsOn?.some(u=>{let c=o.get(u)?.status;return c!==void 0&&c!=="completed"})&&(o.set(s.id,{actionId:s.id,status:"skipped"}),n.delete(s.id),r=!0);if(r)continue;throw new Error(`Deadlock detected: actions ${Array.from(n).join(", ")} cannot proceed`)}let d=await Promise.allSettled(i.map(r=>this.executeAction(r,e)));for(let r=0;r<i.length;r++){let s=i[r],u=d[r],c;u.status==="fulfilled"?c=u.value:c={actionId:s.id,status:"failed",error:u.reason instanceof Error?u.reason.message:String(u.reason)},o.set(s.id,c),n.delete(s.id),c.status==="completed"&&a.add(s.id)}}for(let i of n)o.set(i,{actionId:i,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(m.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let n=0,a=e.retry?.maxAttempts??1,i;for(;n<a;){n++;try{let r=this.getDomainAPI(e.targetDomain);if(!r)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=r[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let u={...e.params,...t.params},c=await this.executeWithTimeout(s.bind(r)(u),e.timeout??3e4),P=new Date;return await this.publishEvent(m.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:P.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:P,duration:P.getTime()-o.getTime(),result:c,retryAttempts:n>1?n-1:void 0}}catch(r){if(i=x(r),r instanceof h){let s=new Date;return await this.publishEvent(m.ActionOutcomeUnknown,{executionId:t.execution.executionId,actionId:e.id,error:r.message,attempts:n},t.execution.correlationId),{actionId:e.id,status:"unknown",startedAt:o,completedAt:s,duration:s.getTime()-o.getTime(),error:r.message,retryAttempts:n>1?n-1:void 0}}if(n<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,n-1);await this.sleep(s)}}}let d=new Date;return await this.publishEvent(m.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:i?.message??"Unknown error",attempts:n},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:d,duration:d.getTime()-o.getTime(),error:i?.message??"Unknown error",retryAttempts:n>1?n-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){let o;try{return await Promise.race([e,new Promise((n,a)=>{o=setTimeout(()=>a(new h(t)),t)})])}finally{o&&clearTimeout(o)}}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:86400})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let n=w(e,"learning-optimization",t,o);await this.eventBus.publish(n)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(f,e,t){return new E(f,e,t)}export{E as a,S 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.4");process.exit(0)}
2
+ import{i as t,j as s,l as a,n as m}from"./chunk-3TW5W5LX.js";m();var p={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:[a[1],"gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:[t,"gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:[t],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:[s,"gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},c={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},b={budgetConfig:c,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",...a}},r=class extends Error{constructor(e,i,y){super(e);this.code=i;this.cause=y;this.name="ModelRouterError"}code;cause},l=class extends r{constructor(e,i,y){super(e,"BUDGET_EXCEEDED");this.tier=i;this.usage=y;this.name="BudgetExceededError"}tier;usage},d=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},u=class extends r{constructor(e,i){super(e,"ROUTING_TIMEOUT");this.timeoutMs=i;this.name="RoutingTimeoutError"}timeoutMs};export{p as a,c as b,b as c,r as d,l as e,d as f,u as g};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.3");process.exit(0)}
2
- import{a,e as p}from"./chunk-OVDKWCD7.js";import{a as l,d}from"./chunk-XA7CG3LH.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),a.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*a.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=a.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let c of this.store.keys())if(!(o&&!c.startsWith(o))&&n.test(c)&&(i.push(c),i.length>=r))break;return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}getVectorSearchProvenance(){return{backend:"in-memory",indexType:"flat",approximate:!1,estimatedRecall:1}}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};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.4");process.exit(0)}
2
+ import{a,e as p}from"./chunk-BFP7KO7P.js";import{a as l,d}from"./chunk-ODKLFVYC.js";d();p();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),a.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*a.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=a.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(s.replace(/\*/g,".*")),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let c of this.store.keys())if(!(o&&!c.startsWith(o))&&n.test(c)&&(i.push(c),i.length>=r))break;return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}getVectorSearchProvenance(){return{backend:"in-memory",indexType:"flat",approximate:!1,estimatedRecall:1}}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};