agentic-qe 3.10.6 → 3.10.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/hooks/aqe-hook.cjs +38 -2
- package/.claude/skills/.validation/examples/chaos-engineering-output.example.json +1 -1
- package/.claude/skills/.validation/examples/performance-testing-output.example.json +1 -1
- package/.claude/skills/.validation/examples/security-testing-output.example.json +1 -1
- package/.claude/skills/.validation/examples/testability-scoring-output.example.json +1 -1
- package/.claude/skills/.validation/schemas/skill-eval.schema.json +2 -4
- package/.claude/skills/.validation/schemas/skill-frontmatter.schema.json +1 -1
- package/.claude/skills/.validation/schemas/skill-output.template.json +1 -1
- package/.claude/skills/.validation/templates/eval.template.yaml +3 -3
- package/.claude/skills/.validation/templates/security-testing-eval.template.yaml +3 -2
- package/.claude/skills/.validation/templates/skill-frontmatter.example.yaml +2 -2
- package/.claude/skills/a11y-ally/evals/a11y-ally.yaml +2 -2
- package/.claude/skills/accessibility-testing/evals/accessibility-testing.yaml +2 -3
- package/.claude/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -3
- package/.claude/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +3 -3
- package/.claude/skills/cicd-pipeline-qe-orchestrator/evals/cicd-pipeline-qe-orchestrator.yaml +2 -2
- package/.claude/skills/compatibility-testing/evals/compatibility-testing.yaml +2 -2
- package/.claude/skills/compliance-testing/evals/compliance-testing.yaml +2 -3
- package/.claude/skills/contract-testing/evals/contract-testing.yaml +2 -3
- package/.claude/skills/database-testing/evals/database-testing.yaml +2 -3
- package/.claude/skills/enterprise-integration-testing/evals/enterprise-integration-testing.yaml +2 -2
- package/.claude/skills/localization-testing/evals/localization-testing.yaml +2 -2
- package/.claude/skills/middleware-testing-patterns/evals/middleware-testing-patterns.yaml +2 -2
- package/.claude/skills/mobile-testing/evals/mobile-testing.yaml +2 -2
- package/.claude/skills/mutation-testing/evals/mutation-testing.yaml +2 -3
- package/.claude/skills/mutation-testing/test-data/sample-output.json +1 -1
- package/.claude/skills/n8n-expression-testing/evals/n8n-expression-testing.yaml +2 -2
- package/.claude/skills/n8n-integration-testing-patterns/evals/n8n-integration-testing-patterns.yaml +2 -2
- package/.claude/skills/n8n-security-testing/evals/n8n-security-testing.yaml +3 -2
- package/.claude/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +2 -2
- package/.claude/skills/n8n-workflow-testing-fundamentals/evals/n8n-workflow-testing-fundamentals.yaml +2 -2
- package/.claude/skills/observability-testing-patterns/evals/observability-testing-patterns.yaml +2 -2
- package/.claude/skills/pentest-validation/evals/pentest-validation.yaml +3 -3
- package/.claude/skills/performance-testing/evals/performance-testing.yaml +2 -3
- package/.claude/skills/qcsd-cicd-swarm/evals/qcsd-cicd-swarm.yaml +2 -2
- package/.claude/skills/qcsd-development-swarm/evals/qcsd-development-swarm.yaml +2 -2
- package/.claude/skills/qcsd-ideation-swarm/evals/qcsd-ideation-swarm.yaml +2 -2
- package/.claude/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +2 -2
- package/.claude/skills/qcsd-refinement-swarm/evals/qcsd-refinement-swarm.yaml +2 -2
- package/.claude/skills/qe-browser/evals/qe-browser.yaml +2 -2
- package/.claude/skills/qe-chaos-resilience/evals/qe-chaos-resilience.yaml +3 -2
- package/.claude/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +2 -2
- package/.claude/skills/qe-coverage-analysis/evals/qe-coverage-analysis.yaml +2 -2
- package/.claude/skills/qe-defect-intelligence/evals/qe-defect-intelligence.yaml +3 -2
- package/.claude/skills/qe-learning-optimization/evals/qe-learning-optimization.yaml +4 -4
- package/.claude/skills/qe-quality-assessment/evals/qe-quality-assessment.yaml +2 -2
- package/.claude/skills/qe-requirements-validation/evals/qe-requirements-validation.yaml +2 -2
- package/.claude/skills/qe-test-execution/evals/qe-test-execution.yaml +2 -2
- package/.claude/skills/qe-test-generation/evals/qe-test-generation.yaml +2 -2
- package/.claude/skills/qe-visual-accessibility/evals/qe-visual-accessibility.yaml +2 -2
- package/.claude/skills/quality-metrics/evals/quality-metrics.yaml +2 -2
- package/.claude/skills/regression-testing/evals/regression-testing.yaml +2 -2
- package/.claude/skills/risk-based-testing/evals/risk-based-testing.yaml +2 -2
- package/.claude/skills/security-testing/evals/security-testing.yaml +3 -3
- package/.claude/skills/security-visual-testing/evals/security-visual-testing.yaml +3 -2
- package/.claude/skills/shift-left-testing/evals/shift-left-testing.yaml +2 -2
- package/.claude/skills/shift-right-testing/evals/shift-right-testing.yaml +2 -2
- package/.claude/skills/skills-manifest.json +1 -1
- package/.claude/skills/test-automation-strategy/evals/test-automation-strategy.yaml +2 -2
- package/.claude/skills/test-data-management/evals/test-data-management.yaml +2 -2
- package/.claude/skills/test-design-techniques/evals/test-design-techniques.yaml +2 -2
- package/.claude/skills/test-reporting-analytics/evals/test-reporting-analytics.yaml +2 -2
- package/.claude/skills/testability-scoring/evals/testability-scoring.yaml +2 -3
- package/.claude/skills/validation-pipeline/evals/validation-pipeline.yaml +2 -2
- package/.claude/skills/verification-quality/evals/verification-quality.yaml +2 -2
- package/.claude/skills/visual-testing-advanced/evals/visual-testing-advanced.yaml +2 -2
- package/.claude/skills/wms-testing-patterns/evals/wms-testing-patterns.yaml +2 -1
- package/CHANGELOG.md +41 -0
- package/assets/skills/.validation/examples/chaos-engineering-output.example.json +1 -1
- package/assets/skills/.validation/examples/performance-testing-output.example.json +1 -1
- package/assets/skills/.validation/examples/security-testing-output.example.json +1 -1
- package/assets/skills/.validation/examples/testability-scoring-output.example.json +1 -1
- package/assets/skills/.validation/schemas/skill-eval.schema.json +2 -4
- package/assets/skills/.validation/schemas/skill-frontmatter.schema.json +1 -1
- package/assets/skills/.validation/schemas/skill-output.template.json +1 -1
- package/assets/skills/.validation/templates/eval.template.yaml +3 -3
- package/assets/skills/.validation/templates/security-testing-eval.template.yaml +3 -2
- package/assets/skills/.validation/templates/skill-frontmatter.example.yaml +2 -2
- package/assets/skills/a11y-ally/evals/a11y-ally.yaml +2 -2
- package/assets/skills/accessibility-testing/evals/accessibility-testing.yaml +2 -3
- package/assets/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -3
- package/assets/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +3 -3
- package/assets/skills/cicd-pipeline-qe-orchestrator/evals/cicd-pipeline-qe-orchestrator.yaml +2 -2
- package/assets/skills/compatibility-testing/evals/compatibility-testing.yaml +2 -2
- package/assets/skills/compliance-testing/evals/compliance-testing.yaml +2 -3
- package/assets/skills/contract-testing/evals/contract-testing.yaml +2 -3
- package/assets/skills/database-testing/evals/database-testing.yaml +2 -3
- package/assets/skills/enterprise-integration-testing/evals/enterprise-integration-testing.yaml +2 -2
- package/assets/skills/localization-testing/evals/localization-testing.yaml +2 -2
- package/assets/skills/middleware-testing-patterns/evals/middleware-testing-patterns.yaml +2 -2
- package/assets/skills/mobile-testing/evals/mobile-testing.yaml +2 -2
- package/assets/skills/mutation-testing/evals/mutation-testing.yaml +2 -3
- package/assets/skills/mutation-testing/test-data/sample-output.json +1 -1
- package/assets/skills/n8n-expression-testing/evals/n8n-expression-testing.yaml +2 -2
- package/assets/skills/n8n-integration-testing-patterns/evals/n8n-integration-testing-patterns.yaml +2 -2
- package/assets/skills/n8n-security-testing/evals/n8n-security-testing.yaml +3 -2
- package/assets/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +2 -2
- package/assets/skills/n8n-workflow-testing-fundamentals/evals/n8n-workflow-testing-fundamentals.yaml +2 -2
- package/assets/skills/observability-testing-patterns/evals/observability-testing-patterns.yaml +2 -2
- package/assets/skills/pentest-validation/evals/pentest-validation.yaml +3 -3
- package/assets/skills/performance-testing/evals/performance-testing.yaml +2 -3
- package/assets/skills/qcsd-cicd-swarm/evals/qcsd-cicd-swarm.yaml +2 -2
- package/assets/skills/qcsd-development-swarm/evals/qcsd-development-swarm.yaml +2 -2
- package/assets/skills/qcsd-ideation-swarm/evals/qcsd-ideation-swarm.yaml +2 -2
- package/assets/skills/qcsd-production-swarm/evals/qcsd-production-swarm.yaml +2 -2
- package/assets/skills/qcsd-refinement-swarm/evals/qcsd-refinement-swarm.yaml +2 -2
- package/assets/skills/qe-browser/evals/qe-browser.yaml +2 -2
- package/assets/skills/qe-chaos-resilience/evals/qe-chaos-resilience.yaml +3 -2
- package/assets/skills/qe-code-intelligence/evals/qe-code-intelligence.yaml +2 -2
- package/assets/skills/qe-coverage-analysis/evals/qe-coverage-analysis.yaml +2 -2
- package/assets/skills/qe-defect-intelligence/evals/qe-defect-intelligence.yaml +3 -2
- package/assets/skills/qe-learning-optimization/evals/qe-learning-optimization.yaml +4 -4
- package/assets/skills/qe-quality-assessment/evals/qe-quality-assessment.yaml +2 -2
- package/assets/skills/qe-requirements-validation/evals/qe-requirements-validation.yaml +2 -2
- package/assets/skills/qe-test-execution/evals/qe-test-execution.yaml +2 -2
- package/assets/skills/qe-test-generation/evals/qe-test-generation.yaml +2 -2
- package/assets/skills/qe-visual-accessibility/evals/qe-visual-accessibility.yaml +2 -2
- package/assets/skills/quality-metrics/evals/quality-metrics.yaml +2 -2
- package/assets/skills/regression-testing/evals/regression-testing.yaml +2 -2
- package/assets/skills/risk-based-testing/evals/risk-based-testing.yaml +2 -2
- package/assets/skills/security-testing/evals/security-testing.yaml +3 -3
- package/assets/skills/security-visual-testing/evals/security-visual-testing.yaml +3 -2
- package/assets/skills/shift-left-testing/evals/shift-left-testing.yaml +2 -2
- package/assets/skills/shift-right-testing/evals/shift-right-testing.yaml +2 -2
- package/assets/skills/test-automation-strategy/evals/test-automation-strategy.yaml +2 -2
- package/assets/skills/test-data-management/evals/test-data-management.yaml +2 -2
- package/assets/skills/test-design-techniques/evals/test-design-techniques.yaml +2 -2
- package/assets/skills/test-reporting-analytics/evals/test-reporting-analytics.yaml +2 -2
- package/assets/skills/testability-scoring/evals/testability-scoring.yaml +2 -3
- package/assets/skills/validation-pipeline/evals/validation-pipeline.yaml +2 -2
- package/assets/skills/verification-quality/evals/verification-quality.yaml +2 -2
- package/assets/skills/visual-testing-advanced/evals/visual-testing-advanced.yaml +2 -2
- package/assets/skills/wms-testing-patterns/evals/wms-testing-patterns.yaml +2 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-TTIBYXH2.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-J5CITTTV.js → agent-booster-wasm-6I3JMU2M.js} +2 -2
- package/dist/cli/chunks/{agent-handler-HMN4ZBZ6.js → agent-handler-XWI7YM6R.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-SCAKN4DU.js → agent-memory-branch-QFZKQN2L.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-CTV5OLSN.js +2 -0
- package/dist/cli/chunks/{arena-CJOLCHZW.js → arena-5HNPVTBZ.js} +4 -4
- package/dist/cli/chunks/{arena-FVBTSGKS.js → arena-P4IUBKZP.js} +2 -2
- package/dist/cli/chunks/{audit-SOF6L5RY.js → audit-PBSH25VZ.js} +2 -2
- package/dist/cli/chunks/base-ISNCJZ7A.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-LFVNGGCL.js → better-sqlite3-F262IAGH.js} +2 -2
- package/dist/cli/chunks/{brain-handler-D2ZQQI2J.js → brain-handler-EVYRCKXI.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-QQXOCGOR.js → branch-enumerator-SUDGYJQJ.js} +2 -2
- package/dist/cli/chunks/{browser-XASHKIEN.js → browser-4UKMW2RE.js} +2 -2
- package/dist/cli/chunks/browser-workflow-OD32QTTI.js +2 -0
- package/dist/cli/chunks/{chunk-F72A356B.js → chunk-222ZQTL5.js} +2 -2
- package/dist/cli/chunks/{chunk-NKEGEQ3J.js → chunk-262F3EMN.js} +2 -2
- package/dist/cli/chunks/{chunk-5QTUGFFP.js → chunk-2J4ZUUU5.js} +2 -2
- package/dist/cli/chunks/{chunk-2I5RXDNO.js → chunk-2JWFS2K2.js} +2 -2
- package/dist/cli/chunks/{chunk-K32AUACO.js → chunk-2MLISLRR.js} +1 -1
- package/dist/cli/chunks/{chunk-J2SMTP2L.js → chunk-32E2OPIE.js} +3 -3
- package/dist/cli/chunks/{chunk-Q5432RIH.js → chunk-34NT5NBZ.js} +2 -2
- package/dist/cli/chunks/{chunk-TWH3ZL6B.js → chunk-3IJS52OS.js} +2 -2
- package/dist/cli/chunks/{chunk-T6CUKJHS.js → chunk-3O4Q4GAX.js} +1 -1
- package/dist/cli/chunks/{chunk-Z3RPA3RD.js → chunk-3W6QASVB.js} +2 -2
- package/dist/cli/chunks/{chunk-GXNNKM7F.js → chunk-3XEL7XCA.js} +1 -1
- package/dist/cli/chunks/{chunk-TNVOINYC.js → chunk-4I6FK67T.js} +3 -3
- package/dist/cli/chunks/{chunk-UQYDFT6I.js → chunk-4MJQJQLY.js} +2 -2
- package/dist/cli/chunks/{chunk-H6UPZFI6.js → chunk-4RGV6Z2H.js} +2 -2
- package/dist/cli/chunks/{chunk-4N4TU7ST.js → chunk-4W5QWFU4.js} +1 -1
- package/dist/cli/chunks/{chunk-ELC6JIXL.js → chunk-5QMIVHFT.js} +2 -2
- package/dist/cli/chunks/{chunk-X5R6SUWM.js → chunk-64BSODHA.js} +2 -2
- package/dist/cli/chunks/{chunk-J3WUBGLQ.js → chunk-6A2HRMTD.js} +2 -2
- package/dist/cli/chunks/{chunk-LEDF3LGZ.js → chunk-6F5KPT6U.js} +1 -1
- package/dist/cli/chunks/{chunk-BHD6THT5.js → chunk-6OLPKIYU.js} +1 -1
- package/dist/cli/chunks/{chunk-6DHJPKAH.js → chunk-6QBD64W3.js} +2 -2
- package/dist/cli/chunks/{chunk-7RTI5WT4.js → chunk-6RG7ZJ2H.js} +2 -2
- package/dist/cli/chunks/{chunk-Q4LYWIEX.js → chunk-76JYG426.js} +2 -2
- package/dist/cli/chunks/{chunk-TFA5UETW.js → chunk-76SUEI7S.js} +1 -1
- package/dist/cli/chunks/{chunk-B3H2TTYT.js → chunk-7NK2H7H5.js} +2 -2
- package/dist/cli/chunks/{chunk-7SFCZ3AE.js → chunk-AKL5A3IZ.js} +1 -1
- package/dist/cli/chunks/{chunk-HMHQOEU7.js → chunk-AKSCYNFH.js} +2 -2
- package/dist/cli/chunks/{chunk-QZSNYXYC.js → chunk-AW3LGLC3.js} +2 -2
- package/dist/cli/chunks/{chunk-ZMCMSDXR.js → chunk-AY4IEMRI.js} +2 -2
- package/dist/cli/chunks/{chunk-XOYTW6LI.js → chunk-B5ZJV7GZ.js} +2 -2
- package/dist/cli/chunks/{chunk-KVMY2ABO.js → chunk-BLFZFKT6.js} +2 -2
- package/dist/cli/chunks/{chunk-ESZDW6G7.js → chunk-BPC6X6VR.js} +2 -2
- package/dist/cli/chunks/{chunk-HDEFCRHI.js → chunk-BRYYQQUV.js} +1 -1
- package/dist/cli/chunks/{chunk-CH7KUYGO.js → chunk-BU2I77YW.js} +3 -3
- package/dist/cli/chunks/{chunk-NEIJP6TG.js → chunk-C5CY5NSW.js} +2 -2
- package/dist/cli/chunks/{chunk-H4Q36ILL.js → chunk-CGBEI7UH.js} +2 -2
- package/dist/cli/chunks/{chunk-VFFIMJWT.js → chunk-CJTDQJ7E.js} +1 -1
- package/dist/cli/chunks/{chunk-XKRJQIGP.js → chunk-CW7JQVXV.js} +2 -2
- package/dist/cli/chunks/chunk-DF7V6X3N.js +2 -0
- package/dist/cli/chunks/{chunk-6ZLVQTQ5.js → chunk-DPT37UHR.js} +4 -4
- package/dist/cli/chunks/{chunk-IB3QQDC4.js → chunk-DU7Y54JI.js} +1 -1
- package/dist/cli/chunks/{chunk-TUFU3BAK.js → chunk-DYNO72WD.js} +2 -2
- package/dist/cli/chunks/{chunk-LOQMQEKN.js → chunk-DYSRMAZP.js} +1 -1
- package/dist/cli/chunks/{chunk-RTFFD263.js → chunk-EWNJK2BU.js} +1 -1
- package/dist/cli/chunks/{chunk-JPL53G4V.js → chunk-F5RZSNHI.js} +2 -2
- package/dist/cli/chunks/{chunk-RH3I4Q23.js → chunk-FK4JHBG4.js} +2 -2
- package/dist/cli/chunks/{chunk-DAUQIXHW.js → chunk-FQBNPSV2.js} +2 -2
- package/dist/cli/chunks/{chunk-LHA4OQ7G.js → chunk-FWLXK6AH.js} +2 -2
- package/dist/cli/chunks/{chunk-UVWOIF6P.js → chunk-G7ISGLKP.js} +1 -1
- package/dist/cli/chunks/{chunk-EYKID5HA.js → chunk-GUDOOOO6.js} +1 -1
- package/dist/cli/chunks/{chunk-SA5FTDRS.js → chunk-HARYQMWN.js} +2 -2
- package/dist/cli/chunks/{chunk-RA7HEY5G.js → chunk-HBWAMCVB.js} +2 -2
- package/dist/cli/chunks/{chunk-NUCJS3Z7.js → chunk-HDLF6LGO.js} +3 -3
- package/dist/cli/chunks/{chunk-XLFYVBOD.js → chunk-HELQ7CXL.js} +1 -1
- package/dist/cli/chunks/{chunk-USPBUR6P.js → chunk-HI4DA7Z3.js} +2 -2
- package/dist/cli/chunks/{chunk-PIIBVLFC.js → chunk-I64BLAFS.js} +2 -2
- package/dist/cli/chunks/{chunk-AQPFTDGS.js → chunk-I7M574IO.js} +2 -2
- package/dist/cli/chunks/{chunk-JP2YXWJD.js → chunk-INI3AGF5.js} +2 -2
- package/dist/cli/chunks/{chunk-ZY4G7O7Y.js → chunk-ISLI6D4K.js} +2 -2
- package/dist/cli/chunks/{chunk-T6SCQVWH.js → chunk-IXAABYGS.js} +2 -2
- package/dist/cli/chunks/{chunk-2IC2I525.js → chunk-IYZWEYWJ.js} +1 -1
- package/dist/cli/chunks/{chunk-M4OYZMXE.js → chunk-J5ETX2DG.js} +2 -2
- package/dist/cli/chunks/{chunk-XOGBTPJI.js → chunk-JJELOEIY.js} +4 -4
- package/dist/cli/chunks/{chunk-EDPVATNH.js → chunk-JNQVPTOM.js} +2 -2
- package/dist/cli/chunks/{chunk-5VTRPOYL.js → chunk-JNXPRDNV.js} +3 -3
- package/dist/cli/chunks/{chunk-7OK5H6ML.js → chunk-K6A3AWUI.js} +1 -1
- package/dist/cli/chunks/{chunk-ULEVKOWQ.js → chunk-K6IU2MV4.js} +1 -1
- package/dist/cli/chunks/{chunk-SHVTMMJB.js → chunk-KXENXRZE.js} +1 -1
- package/dist/cli/chunks/{chunk-HWKFBRMX.js → chunk-L2ZSYIDA.js} +1 -1
- package/dist/cli/chunks/{chunk-RTAGNKCV.js → chunk-L3EQQMFI.js} +2 -2
- package/dist/cli/chunks/{chunk-S574AFAT.js → chunk-L5UUUSSB.js} +1 -1
- package/dist/cli/chunks/{chunk-5V4IFRG5.js → chunk-L6NB4UHR.js} +2 -2
- package/dist/cli/chunks/{chunk-2UI5LQ7C.js → chunk-LEZ2MGHM.js} +3 -3
- package/dist/cli/chunks/{chunk-NN35QH6X.js → chunk-LFSQSLNP.js} +2 -2
- package/dist/cli/chunks/{chunk-L2IMTNZF.js → chunk-LHZYTNOQ.js} +2 -2
- package/dist/cli/chunks/{chunk-JADBRSQN.js → chunk-LJHCPN4E.js} +2 -2
- package/dist/cli/chunks/{chunk-UNDPB5SS.js → chunk-LRRQEAP5.js} +1 -1
- package/dist/cli/chunks/{chunk-ZBSEXVEI.js → chunk-LSHUPEQQ.js} +2 -2
- package/dist/cli/chunks/{chunk-HZGOVRZ6.js → chunk-LUZH2IZY.js} +2 -2
- package/dist/cli/chunks/{chunk-UWDC3TZP.js → chunk-M7SO5KNJ.js} +2 -2
- package/dist/cli/chunks/{chunk-KQOJYO5Z.js → chunk-MDVJVY4C.js} +4 -4
- package/dist/cli/chunks/{chunk-TFJDJVPC.js → chunk-MK73CCKO.js} +2 -2
- package/dist/cli/chunks/{chunk-JXCIRWLQ.js → chunk-MMR23KAO.js} +2 -2
- package/dist/cli/chunks/{chunk-ROXH622K.js → chunk-MOI74MMX.js} +2 -2
- package/dist/cli/chunks/{chunk-MSJGDIRP.js → chunk-MRLGQX7Y.js} +2 -2
- package/dist/cli/chunks/{chunk-2RQSFRON.js → chunk-MWRKNBSY.js} +2 -2
- package/dist/cli/chunks/{chunk-BXOGLZGU.js → chunk-NKYMHEHY.js} +2 -2
- package/dist/cli/chunks/{chunk-MJLDZSFB.js → chunk-O4B6FFC5.js} +1 -1
- package/dist/cli/chunks/{chunk-JX7HZMW5.js → chunk-OAXDI4XM.js} +1 -1
- package/dist/cli/chunks/{chunk-PFSBUTDA.js → chunk-OMDV6GFP.js} +1 -1
- package/dist/cli/chunks/{chunk-OBLAWVXM.js → chunk-OPLLH67G.js} +1 -1
- package/dist/cli/chunks/{chunk-LAGNWKAD.js → chunk-OSETFZVE.js} +2 -2
- package/dist/cli/chunks/{chunk-OU4HRUVV.js → chunk-OW4LJ5HE.js} +2 -2
- package/dist/cli/chunks/{chunk-NHC635LL.js → chunk-PY3HWJRJ.js} +2 -2
- package/dist/cli/chunks/{chunk-DFBVWMX3.js → chunk-QBVFONWU.js} +2 -2
- package/dist/cli/chunks/{chunk-7BPYFDWY.js → chunk-QBVS4CXM.js} +1 -1
- package/dist/cli/chunks/{chunk-O2H5WYFK.js → chunk-QDBFB4XD.js} +2 -2
- package/dist/cli/chunks/{chunk-X3YWLJGT.js → chunk-QLVZEEPR.js} +2 -2
- package/dist/cli/chunks/{chunk-4B22URZJ.js → chunk-QMGNYRR5.js} +3 -3
- package/dist/cli/chunks/{chunk-MCMVRPNG.js → chunk-R2B6EQQF.js} +2 -2
- package/dist/cli/chunks/{chunk-VQM2TC2V.js → chunk-R7KIC6TL.js} +1 -1
- package/dist/cli/chunks/{chunk-HFU3LTQX.js → chunk-RJBCIN2G.js} +2 -2
- package/dist/cli/chunks/{chunk-PIJ5XOMM.js → chunk-RLXCFURS.js} +2 -2
- package/dist/cli/chunks/{chunk-WNAFMYND.js → chunk-S423UHYM.js} +2 -2
- package/dist/cli/chunks/{chunk-GWHDPEBT.js → chunk-S4NNQE4L.js} +1 -1
- package/dist/cli/chunks/{chunk-AJ2VDNPB.js → chunk-S7FNTWFM.js} +2 -2
- package/dist/cli/chunks/{chunk-H73FLSBV.js → chunk-SFW6IDMR.js} +10 -10
- package/dist/cli/chunks/{chunk-QUQA4NNZ.js → chunk-SG6O3PXZ.js} +2 -2
- package/dist/cli/chunks/{chunk-P7EOYGR2.js → chunk-SLASYVNX.js} +2 -2
- package/dist/cli/chunks/{chunk-A2DCROAN.js → chunk-TIUC5LRA.js} +2 -2
- package/dist/cli/chunks/{chunk-LHZOIXJ6.js → chunk-TTLAWPEN.js} +2 -2
- package/dist/cli/chunks/{chunk-QNIL3D6E.js → chunk-TXXRBNOB.js} +1 -1
- package/dist/cli/chunks/{chunk-6RFPELCD.js → chunk-TY7XPI6R.js} +2 -2
- package/dist/cli/chunks/{chunk-QJXZ4SU7.js → chunk-U7EGKKN3.js} +2 -2
- package/dist/cli/chunks/{chunk-I7ADT6AZ.js → chunk-UPDPD43T.js} +2 -2
- package/dist/cli/chunks/{chunk-RBZWUWUG.js → chunk-UURGDFGU.js} +1 -1
- package/dist/cli/chunks/{chunk-MQN3HYFX.js → chunk-UVUVWA4B.js} +1 -1
- package/dist/cli/chunks/{chunk-2CZQA3NN.js → chunk-V3KNHI5B.js} +2 -2
- package/dist/cli/chunks/{chunk-ELTN4F4R.js → chunk-V7WBNB2S.js} +2 -2
- package/dist/cli/chunks/{chunk-4XEUJH2M.js → chunk-VPBXVZWE.js} +1 -1
- package/dist/cli/chunks/{chunk-3XUPDWMA.js → chunk-WCXQA24H.js} +8 -8
- package/dist/cli/chunks/{chunk-CSM4LXTH.js → chunk-X3HRJV65.js} +1 -1
- package/dist/cli/chunks/{chunk-DF4Z7TKZ.js → chunk-X6OJFP7G.js} +2 -2
- package/dist/cli/chunks/{chunk-M3APJ7VS.js → chunk-XCYPVJ34.js} +2 -2
- package/dist/cli/chunks/{chunk-LWUIK5DH.js → chunk-XK7P7OXO.js} +2 -2
- package/dist/cli/chunks/{chunk-O4MNYX4X.js → chunk-XWPUCPYW.js} +2 -2
- package/dist/cli/chunks/{chunk-EJWAKPZD.js → chunk-YB4GXJJG.js} +1 -1
- package/dist/cli/chunks/{chunk-SUGQZCNI.js → chunk-YBM4LUSF.js} +2 -2
- package/dist/cli/chunks/{chunk-C75ODWRP.js → chunk-YLXUF5KW.js} +3 -3
- package/dist/cli/chunks/{chunk-ULV5K4V5.js → chunk-YMBPKBKG.js} +1 -1
- package/dist/cli/chunks/{chunk-7NXVVIJZ.js → chunk-Z44VJC5U.js} +2 -2
- package/dist/cli/chunks/{ci-COQUVZH6.js → ci-OO42YBET.js} +2 -2
- package/dist/cli/chunks/{ci-output-KVUHUEOT.js → ci-output-YXMTEX7Q.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-O4JNXAYH.js → circuit-breaker-EHA4N643.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-J65U34NA.js → claude-flow-setup-E6G6SLYI.js} +2 -2
- package/dist/cli/chunks/client-N4FQ6SMD.js +2 -0
- package/dist/cli/chunks/{cline-installer-ZTG234Z2.js → cline-installer-6JPWD64G.js} +2 -2
- package/dist/cli/chunks/{code-5GWPY4IX.js → code-Q3U6XDOO.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-TWNKG4VS.js → code-index-extractor-BK2DC4MO.js} +2 -2
- package/dist/cli/chunks/{codex-installer-4TM4BLAE.js → codex-installer-DA3GBMLN.js} +2 -2
- package/dist/cli/chunks/{completions-BBNHQXMV.js → completions-TZ5F33TA.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-2SCI2VGH.js → complexity-analyzer-N7U4V7ID.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-CTIORASU.js → continuedev-installer-DDDJGW26.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-4R2V4IYB.js → copilot-installer-JVFCE6GT.js} +2 -2
- package/dist/cli/chunks/core-handlers-SFD5HCA3.js +2 -0
- package/dist/cli/chunks/{cost-tracker-KDBYQBKG.js → cost-tracker-ZTIDLUFW.js} +2 -2
- package/dist/cli/chunks/{coverage-QQJQVDPZ.js → coverage-6G7T7TRQ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-7HGRUNLT.js +2 -0
- package/dist/cli/chunks/{cursor-installer-5WEZCESZ.js → cursor-installer-JFNYGSDD.js} +2 -2
- package/dist/cli/chunks/{daemon-M4DKHEEA.js → daemon-5A4GD6XA.js} +3 -3
- package/dist/cli/chunks/{daemon-Y7H3ZUXQ.js → daemon-KTXGJJRI.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-SD2UIADT.js → dag-attention-scheduler-4CUEQZD6.js} +2 -2
- package/dist/cli/chunks/{detect-WONWUXFH.js → detect-I32JUSUE.js} +2 -2
- package/dist/cli/chunks/{dist-node-Q5GQN2R6.js → dist-node-7ITNV6QS.js} +2 -2
- package/dist/cli/chunks/{domain-handler-EMXE2XQW.js → domain-handler-LIFCXSZ4.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-QATUJJRP.js → domain-transfer-67UWLHSK.js} +2 -2
- package/dist/cli/chunks/dream-HPGD5TLD.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-AAFHLBEJ.js → embed-and-insert-pattern-4WC5RUD6.js} +2 -2
- package/dist/cli/chunks/{eval-73BDNLSK.js → eval-DLS2UAQ2.js} +3 -3
- package/dist/cli/chunks/{experience-capture-middleware-YPAPVSYY.js → experience-capture-middleware-VG5E6OJA.js} +3 -3
- package/dist/cli/chunks/{fast-paths-33ZKMNYY.js → fast-paths-262IVHDN.js} +2 -2
- package/dist/cli/chunks/{feature-flags-QKO5YYDU.js → feature-flags-JJ3FHZGD.js} +2 -2
- package/dist/cli/chunks/{feature-flags-F3DVW4ST.js → feature-flags-L3K7DBN3.js} +2 -2
- package/dist/cli/chunks/{file-discovery-YYVZLRYD.js → file-discovery-Q3PBKVUW.js} +2 -2
- package/dist/cli/chunks/{fleet-EJX6BXLR.js → fleet-LQ5S2YHG.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-TBNLYPTM.js → gnn-wrapper-I33Z537H.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-HPRTS6SI.js → heartbeat-handler-RYIRAGZ7.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-O6TI5E4P.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-TOVTN23J.js +2 -0
- package/dist/cli/chunks/hnsw-index-KCZ75V7K.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-Z6V6TOF5.js → hnsw-legacy-bridge-SSENBBPR.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-5G7LRX7Q.js → hnswlib-node-ILDTCGLZ.js} +2 -2
- package/dist/cli/chunks/{hooks-GG2Z3BDB.js → hooks-LR5KQMN5.js} +10 -10
- package/dist/cli/chunks/hybrid-router-4JEPC4JZ.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-X4Q2TTET.js → hypergraph-engine-NDZA2DKP.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-6BZWV5PL.js → hypergraph-handler-ADMWVHBT.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-3MHIU3SE.js +2 -0
- package/dist/cli/chunks/{init-handler-EKUS7U6L.js → init-handler-MGCYDX62.js} +6 -6
- package/dist/cli/chunks/init-wizard-ERBO5JNA.js +2 -0
- package/dist/cli/chunks/kernel-XJPIIWET.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-BWAVVSQG.js → kilocode-installer-DQVWZUKP.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-UADO53E5.js → kiro-installer-TINLYZ22.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-NTJEG6ZE.js +2 -0
- package/dist/cli/chunks/{learning-HMUTCYQM.js → learning-KBT3S5WW.js} +3 -3
- package/dist/cli/chunks/{llm-router-453TBDUY.js → llm-router-2MX5LUAB.js} +4 -4
- package/dist/cli/chunks/llm-router-service-4T66BGB5.js +2 -0
- package/dist/cli/chunks/{load-DBBSNP6T.js → load-IQWTGMLZ.js} +2 -2
- package/dist/cli/chunks/load-test-PM674TSK.js +2 -0
- package/dist/cli/chunks/{mcp-PK3SAKRF.js → mcp-GCTTJUBZ.js} +2 -2
- package/dist/cli/chunks/{memory-63NHVBXS.js → memory-XQVPI4UT.js} +5 -5
- package/dist/cli/chunks/memory-backend-53NQ5CG7.js +2 -0
- package/dist/cli/chunks/{memory-handlers-YIKKORRY.js → memory-handlers-XD7MSFUN.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-HUGRXJ6D.js → multi-model-executor-JC63UCWG.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-A6IXNF26.js → opencode-installer-6VJGEBIU.js} +2 -2
- package/dist/cli/chunks/{orchestrator-KDFYDNE3.js → orchestrator-B75QWJUF.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-IF2RG2ON.js +2 -0
- package/dist/cli/chunks/{pipeline-HSPRKEYE.js → pipeline-TCBQ2UTZ.js} +2 -2
- package/dist/cli/chunks/{platform-X74IBN2H.js → platform-T43AYI3Z.js} +2 -2
- package/dist/cli/chunks/{plugin-KDJZ7VFD.js → plugin-MSI3ZU3Z.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-2YZGKQE7.js → prime-radiant-advanced-wasm-V62CWI6M.js} +2 -2
- package/dist/cli/chunks/protocol-executor-7AS75ZWT.js +2 -0
- package/dist/cli/chunks/{protocol-handler-I2SDHC7B.js → protocol-handler-OH2INET2.js} +2 -2
- package/dist/cli/chunks/{prove-JQJDNIZH.js → prove-6PTMXMUL.js} +2 -2
- package/dist/cli/chunks/provider-manager-AU2C4AET.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-WATQRCFO.js +2 -0
- package/dist/cli/chunks/{quality-2P7KHVY3.js → quality-PLNQN5GU.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-IOCC4VQH.js +2 -0
- package/dist/cli/chunks/{real-embeddings-L7NMMNDO.js → real-embeddings-OW4OKR77.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-LA4QN5AG.js → roocode-installer-C32LCYAJ.js} +2 -2
- package/dist/cli/chunks/router-SCJMX6WA.js +2 -0
- package/dist/cli/chunks/routing-feedback-RWC7F553.js +2 -0
- package/dist/cli/chunks/{routing-handler-B5CDEZF3.js → routing-handler-CKFXXPMI.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-SOVCRLJ6.js → ruvector-commands-GERRPTJL.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-M6WI2KFB.js → rvf-dual-writer-5FAB2QPA.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-YDMZGPMA.js → rvf-migration-adapter-46COKWYB.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-TFGQ5EO4.js → rvf-migration-coordinator-AJVRWSNC.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-W2RT6PTO.js +2 -0
- package/dist/cli/chunks/safe-db-HO2LCAO3.js +2 -0
- package/dist/cli/chunks/schedule-XENCR4MR.js +2 -0
- package/dist/cli/chunks/scheduler-WKZ3O2SS.js +2 -0
- package/dist/cli/chunks/{security-R3IXQXDA.js → security-Q622IVRB.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-GZX7LSQZ.js → shared-rvf-adapter-EST24R3R.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-YT7SJX7K.js → shared-rvf-dual-writer-CP6EXKBT.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-IN6BOSCX.js +2 -0
- package/dist/cli/chunks/{status-handler-7PZSPBHJ.js → status-handler-LLRQB4E2.js} +2 -2
- package/dist/cli/chunks/{structural-health-UMJS6IVR.js → structural-health-BUFWTNN2.js} +2 -2
- package/dist/cli/chunks/{sync-UIREA3UG.js → sync-JDG4SNT5.js} +2 -2
- package/dist/cli/chunks/{sync-HA5SLSBA.js → sync-RDL2RUOV.js} +2 -2
- package/dist/cli/chunks/{task-handler-NV4HGMEG.js → task-handler-KPP6ZXA6.js} +2 -2
- package/dist/cli/chunks/{task-handlers-RXYWWOSU.js → task-handlers-MRK2BQWI.js} +3 -3
- package/dist/cli/chunks/{test-2Y6OXGEU.js → test-7NYFTHRY.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-N55VFOYT.js → test-scheduling-LGPKDMWD.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-FW3ZVMRP.js → token-bootstrap-H5JHB7TD.js} +2 -2
- package/dist/cli/chunks/{token-usage-YXKOB3U6.js → token-usage-TWPDS5U3.js} +2 -2
- package/dist/cli/chunks/{transformers-GBRSFAVA.js → transformers-GRNPPUHM.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-FJHMEHJS.js → tree-sitter-wasm-parser-DOH5F6TO.js} +2 -2
- package/dist/cli/chunks/{types-NVMRVSBH.js → types-NYV3YKE3.js} +2 -2
- package/dist/cli/chunks/unified-memory-6MXOYRXZ.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-HY3JJD5Z.js +2 -0
- package/dist/cli/chunks/unified-persistence-LKQNQYRY.js +2 -0
- package/dist/cli/chunks/{upgrade-L2OTYHD3.js → upgrade-GDJMRYAT.js} +2 -2
- package/dist/cli/chunks/{validate-3NWRQYTP.js → validate-SIRFOPPM.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-MDURRWXK.js → validate-swarm-XGMJYR6X.js} +2 -2
- package/dist/cli/chunks/{vibium-SZX7RB4H.js → vibium-NP6ENRKV.js} +2 -2
- package/dist/cli/chunks/visual-security-7TBWICHP.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-LGQT7JRD.js → web-tree-sitter-YDBWPYZD.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-EYYGHPPX.js → windsurf-installer-MFI6EAPH.js} +2 -2
- package/dist/cli/chunks/witness-chain-24SVOWQL.js +2 -0
- package/dist/cli/chunks/{witness-chain-YYYA2CU3.js → witness-chain-YHLBWQQ3.js} +2 -2
- package/dist/cli/chunks/{workflow-UD45FQAH.js → workflow-TA6RY7R5.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-XBDXCTLY.js +2 -0
- package/dist/cli/chunks/{wrappers-JXD3KNSR.js → wrappers-DS77IK4H.js} +2 -2
- package/dist/cli/commands/eval.js +2 -2
- package/dist/mcp/bundle.js +1 -1
- package/package.json +2 -2
- package/dist/cli/chunks/adapter-AMIHQ243.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-LRG2UG6P.js +0 -2
- package/dist/cli/chunks/base-WDL3FANJ.js +0 -2
- package/dist/cli/chunks/browser-workflow-W7S4IKWD.js +0 -2
- package/dist/cli/chunks/chunk-434VUSZP.js +0 -2
- package/dist/cli/chunks/client-VJNNIAMG.js +0 -2
- package/dist/cli/chunks/core-handlers-MV5CAR7O.js +0 -2
- package/dist/cli/chunks/cross-domain-router-ULY4NIML.js +0 -2
- package/dist/cli/chunks/dream-PIGWXWE4.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-5BBLZP6R.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-FMEBL5T4.js +0 -2
- package/dist/cli/chunks/hnsw-index-K2R24V4Z.js +0 -2
- package/dist/cli/chunks/hybrid-router-LVF6N345.js +0 -2
- package/dist/cli/chunks/impact-analyzer-CCVVMGWE.js +0 -2
- package/dist/cli/chunks/init-wizard-KDPMO4G3.js +0 -2
- package/dist/cli/chunks/kernel-PBYNK5VA.js +0 -2
- package/dist/cli/chunks/knowledge-graph-C7LVHHLN.js +0 -2
- package/dist/cli/chunks/llm-router-service-LMTRJCPP.js +0 -2
- package/dist/cli/chunks/load-test-FHMZXTXD.js +0 -2
- package/dist/cli/chunks/memory-backend-UZHPCQTB.js +0 -2
- package/dist/cli/chunks/pattern-null-store-5PS4JN6V.js +0 -2
- package/dist/cli/chunks/protocol-executor-2GTGIOFD.js +0 -2
- package/dist/cli/chunks/provider-manager-VH6YTBB3.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-47JSO76G.js +0 -2
- package/dist/cli/chunks/queen-coordinator-C7EDY7IS.js +0 -2
- package/dist/cli/chunks/router-7DVH66WB.js +0 -2
- package/dist/cli/chunks/routing-feedback-4I2MF235.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-UN3ESMMW.js +0 -2
- package/dist/cli/chunks/safe-db-Y2ZXKWBK.js +0 -2
- package/dist/cli/chunks/schedule-PG2NVRGA.js +0 -2
- package/dist/cli/chunks/scheduler-CNH6WWU2.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-WWT4DRRP.js +0 -2
- package/dist/cli/chunks/unified-memory-PXEJKKMN.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-M7OI5WUU.js +0 -2
- package/dist/cli/chunks/unified-persistence-WR4VDTAF.js +0 -2
- package/dist/cli/chunks/visual-security-CKSZZHKG.js +0 -2
- package/dist/cli/chunks/witness-chain-IOQX3XFG.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-Z2ZJRWIN.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{a as W}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
|
|
2
|
+
import{a as W}from"./chunk-LFSQSLNP.js";import{c as V,d as q}from"./chunk-4I6FK67T.js";import{c as M}from"./chunk-MOI74MMX.js";import{a as G}from"./chunk-DF7V6X3N.js";import{c as N}from"./chunk-222ZQTL5.js";import{b as D,d as $}from"./chunk-QBVFONWU.js";import{a as E,c as H}from"./chunk-XWPUCPYW.js";import{i as y}from"./chunk-6OLPKIYU.js";import{a as R,b as U,d as ee}from"./chunk-DYNO72WD.js";var B={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...B,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${E(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
|
|
3
3
|
INSERT INTO concept_nodes
|
|
4
4
|
(id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -59,7 +59,7 @@ import{a as W}from"./chunk-NN35QH6X.js";import{c as V,d as q}from"./chunk-TNVOIN
|
|
|
59
59
|
ORDER BY weight DESC
|
|
60
60
|
LIMIT -1 OFFSET ?
|
|
61
61
|
)
|
|
62
|
-
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(d){return new A(d)}ee();function ne(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let s=d[t];d[t]=d[i],d[i]=s}if(d[n]<d[t]){let s=d[t];d[t]=d[n],d[n]=s}if(d[i]<d[n]){let s=d[i];d[i]=d[n],d[n]=s}let r=d[n],a=t;for(let s=t;s<n;s++)if(d[s]<=r){let c=d[a];d[a]=d[s],d[s]=c,a++}let o=d[a];if(d[a]=d[n],d[n]=o,a===e)return d[a];a<e?t=a+1:n=a-1}return d[t]}var P=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(p=>this.graph.getConcept(p)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let p of i)this.graph.setActivation(p,t),this.recordActivation(p,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let p=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>a&&(a=u.activationLevel);if(l.length===o&&p===0){if(s++,s>=3)break}else s=0;o=l.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(p=>({nodeId:p.id,activation:p.activationLevel})).sort((p,l)=>l.activation-p.activation),h=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:h.map(p=>({source:p.source.id,target:p.target.id,strength:p.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let p=U(0,o.length),l=o[p];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let b of f.activatedNodes)a.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),h=Array.from(a).map(p=>{let l=this.graph.getConcept(p);return{nodeId:p,activation:l?.activationLevel??0}}).filter(p=>p.activation>0).sort((p,l)=>l.activation-p.activation);return this.trimHistory(),{iterations:i,nodesActivated:h.length,peakActivation:r,activatedNodes:h,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],h=Math.sqrt(s.activationLevel*c.activationLevel),p=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=p!==void 0||l!==void 0,m=p?.weight??l?.weight??0,v=!u||m<.3;h>.3&&(r.push({source:s,target:c,coActivation:h,isNovel:v}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=P)return;let e=Math.floor(P*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,h=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:h})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,h)=>h.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),h=Math.max(s?.weight??0,c?.weight??0),p=this.calculateContentSimilarity(a.content,o.content),l=Math.sqrt(a.activationLevel*o.activationLevel),u=h*.4+p*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:h,contentSimilarity:p,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,h=o!==void 0&&o<.6;if(s||c&&h){let p=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:p,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-QKO5YYDU.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let p=-r/n.patternCount;p>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(p*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let p=o/n.highConfidenceCount;p>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(p*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let p=this.rvfAdapter.dimension?.()??384,l=new Float32Array(p);for(let m=0;m<p;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let h=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:h,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let h=await new I(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=h.length;for(let l of h)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let p={cycle:{...this.currentCycle},insights:h,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,p}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
62
|
+
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?D(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(d){return new A(d)}ee();function ne(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let s=d[t];d[t]=d[i],d[i]=s}if(d[n]<d[t]){let s=d[t];d[t]=d[n],d[n]=s}if(d[i]<d[n]){let s=d[i];d[i]=d[n],d[n]=s}let r=d[n],a=t;for(let s=t;s<n;s++)if(d[s]<=r){let c=d[a];d[a]=d[s],d[s]=c,a++}let o=d[a];if(d[a]=d[n],d[n]=o,a===e)return d[a];a<e?t=a+1:n=a-1}return d[t]}var P=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(p=>this.graph.getConcept(p)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let p of i)this.graph.setActivation(p,t),this.recordActivation(p,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let p=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>a&&(a=u.activationLevel);if(l.length===o&&p===0){if(s++,s>=3)break}else s=0;o=l.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(p=>({nodeId:p.id,activation:p.activationLevel})).sort((p,l)=>l.activation-p.activation),h=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:h.map(p=>({source:p.source.id,target:p.target.id,strength:p.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let p=U(0,o.length),l=o[p];if(l){let u=this.config.noiseLevel+R()*this.config.noiseLevel*2,m=l.activationLevel,v=Math.min(1,m+u+.3);this.graph.setActivation(l.id,v);let f=await this.spread([l.id],v,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let b of f.activatedNodes)a.add(b.nodeId);for(let b of f.novelAssociations)n.push(b)}if(Date.now()>=s)break;await this.sleep(50+R()*50)}let c=this.deduplicateAssociations(n),h=Array.from(a).map(p=>{let l=this.graph.getConcept(p);return{nodeId:p,activation:l?.activationLevel??0}}).filter(p=>p.activation>0).sort((p,l)=>l.activation-p.activation);return this.trimHistory(),{iterations:i,nodesActivated:h.length,peakActivation:r,activatedNodes:h,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],h=Math.sqrt(s.activationLevel*c.activationLevel),p=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=p!==void 0||l!==void 0,m=p?.weight??l?.weight??0,v=!u||m<.3;h>.3&&(r.push({source:s,target:c,coActivation:h,isNovel:v}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=P)return;let e=Math.floor(P*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,h=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:h})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(R()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,h)=>h.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),h=Math.max(s?.weight??0,c?.weight??0),p=this.calculateContentSimilarity(a.content,o.content),l=Math.sqrt(a.activationLevel*o.activationLevel),u=h*.4+p*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:h,contentSimilarity:p,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,h=o!==void 0&&o<.6;if(s||c&&h){let p=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),l=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:p,confidenceScore:l,actionable:l>=this.config.minConfidence,applied:!1,suggestedAction:l>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var T={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},C=class{constructor(e,t=T){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-JJ3FHZGD.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let p=-r/n.patternCount;p>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(p*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let p=o/n.highConfidenceCount;p>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(p*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let p=this.rvfAdapter.dimension?.()??384,l=new Float32Array(p);for(let m=0;m<p;m++)l[m]=Math.sin(m*.1);let u=this.rvfAdapter.search?.(l,10)??[];u.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${u.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let h=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:h,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var x=N.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...T}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},_=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=M(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new C(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${E(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),x.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),x.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){x.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:y(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let h=await new I(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=h.length;for(let l of h)await this.saveInsight(l);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let l=this.branchManager.validateBranch(i);if(l.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,l);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,l);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:l.reason},"dream-engine")}catch{}x.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:l.reason})}i=null}let p={cycle:{...this.currentCycle},insights:h,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,p}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=E(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async ensureConceptsLoaded(){if(this.ensureInitialized(),(await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
63
63
|
confidence, success_rate as successRate
|
|
64
64
|
FROM qe_patterns
|
|
65
65
|
WHERE confidence >= 0.3
|
|
@@ -92,4 +92,4 @@ import{a as W}from"./chunk-NN35QH6X.js";import{c as V,d as q}from"./chunk-TNVOIN
|
|
|
92
92
|
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
93
93
|
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
94
94
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
95
|
-
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(d){let e=new _(d);return import("./feature-flags-QKO5YYDU.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-GZX7LSQZ.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var oe=_;G();var Y="learning:loop-health";async function J(d,e,t){try{let n=new Date().toISOString(),i=await d.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await d.set(Y,i)}catch{}}var g=N.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&g.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){g.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-GZX7LSQZ.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&g.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){g.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-YT7SJX7K.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&g.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){g.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>d.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){g.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ce(d,e){return new L(d,e)}var de=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,h)=>{let p=this.scoreValidation(c.validation);return this.scoreValidation(h.validation)>p?h:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,Z as b,L as c,ce as d,B as e,A as f,te as g,P as h,O as i,F as j,j as k,w as l,Q as m,I as n,T as o,C as p,X as q,_ as r,se as s,oe as t,de as u,z as v};
|
|
95
|
+
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:D(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(d){let e=new _(d);return import("./feature-flags-JJ3FHZGD.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-EST24R3R.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var oe=_;G();var Y="learning:loop-health";async function J(d,e,t){try{let n=new Date().toISOString(),i=await d.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await d.set(Y,i)}catch{}}var g=N.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new q}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,g.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),g.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),g.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,g.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(g.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{g.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,g.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&g.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){g.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&g.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){g.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-EST24R3R.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&g.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){g.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-CP6EXKBT.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&g.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){g.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new W,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){g.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)g.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>d.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:y(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{g.debug("Failed to publish meta-learning insight event")}}}else g.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),g.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){g.info("Quality gate failed but cannot start dream yet");return}g.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){g.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){g.info("Milestone reached but cannot start dream yet");return}g.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){g.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:y(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){g.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){g.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){g.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],g.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){g.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function ce(d,e){return new L(d,e)}var de=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new C(e,t??T)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,h)=>{let p=this.scoreValidation(c.validation);return this.scoreValidation(h.validation)>p?h:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,Z as b,L as c,ce as d,B as e,A as f,te as g,P as h,O as i,F as j,j as k,w as l,Q as m,I as n,T as o,C as p,X as q,_ as r,se as s,oe as t,de as u,z as v};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{b as x,c as w,d as U,e as A}from"./chunk-7BPYFDWY.js";import{a as v,b as _}from"./chunk-CSM4LXTH.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-HWKFBRMX.js";import{a as P}from"./chunk-EYKID5HA.js";import{b as I,c as H}from"./chunk-O4MNYX4X.js";import{i as z}from"./chunk-BHD6THT5.js";var h={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},D=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as $}from"crypto";var C=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${$().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function E(p){return new C(p)}var R=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),s={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(s),this.trimRecords(),this.checkAlerts(),s}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,s)=>n+s.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=P[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,s)=>n+s.inputTokens+s.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function q(p){return new R(p)}H();var T=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new T(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function je(p,e){return new M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
|
|
2
|
+
import{b as x,c as w,d as U,e as A}from"./chunk-QBVS4CXM.js";import{a as v,b as _}from"./chunk-X3HRJV65.js";import{a as b,b as B,c as k,d as O,e as F}from"./chunk-L2ZSYIDA.js";import{a as P}from"./chunk-GUDOOOO6.js";import{b as I,c as H}from"./chunk-XWPUCPYW.js";import{i as z}from"./chunk-6OLPKIYU.js";var h={heavyweight:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!0,requiresJsonMode:!0,minContextSize:1e5,costSensitivity:"low",latencySensitivity:"low"},standard:{requiresReasoning:!0,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:5e4,costSensitivity:"medium",latencySensitivity:"medium"},lightweight:{requiresReasoning:!1,requiresTools:!0,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!0,minContextSize:16e3,costSensitivity:"medium",latencySensitivity:"high"},minimal:{requiresReasoning:!1,requiresTools:!1,requiresVision:!1,requiresExtendedThinking:!1,requiresJsonMode:!1,minContextSize:4e3,costSensitivity:"high",latencySensitivity:"medium"}},V={security:h.heavyweight,"test-generation":h.standard,"code-analysis":h.standard,learning:h.standard,performance:{...h.lightweight,costSensitivity:"high"},coordination:h.lightweight,general:{...h.lightweight,requiresJsonMode:!1,latencySensitivity:"medium"},documentation:{...h.minimal,minContextSize:16e3},simple:h.minimal};var f=class{rules=[];constructor(e=[]){this.setRules(e)}setRules(e){this.rules=[...e].filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}getRules(){return[...this.rules]}addRule(e){this.rules.push(e),this.rules=this.rules.filter(t=>t.enabled).sort((t,r)=>r.priority-t.priority)}removeRule(e){let t=this.rules.findIndex(r=>r.id===e);return t>=0?(this.rules.splice(t,1),!0):!1}setRuleEnabled(e,t){let r=this.rules.find(i=>i.id===e);return r?(r.enabled=t,this.rules=this.rules.filter(i=>i.enabled).sort((i,o)=>o.priority-i.priority),!0):!1}evaluate(e){let t=0;for(let r of this.rules)if(t++,this.matchesCondition(e,r.condition))return{rule:r,rulesEvaluated:t};return null}evaluateAll(e){return this.rules.filter(t=>this.matchesCondition(e,t.condition))}matchesCondition(e,t){if(t.agentType!==void 0&&(!e.agentType||!t.agentType.includes(e.agentType))||t.requiresTools!==void 0&&!!e.requiresTools!==t.requiresTools)return!1;if(t.complexity!==void 0){let r=Array.isArray(t.complexity)?t.complexity:[t.complexity];if(!e.complexity||!r.includes(e.complexity))return!1}if(t.localOnly!==void 0&&t.localOnly){let r=["ollama","onnx"];if(e.preferredProvider&&!r.includes(e.preferredProvider))return!1}if(t.requiresReasoning!==void 0&&t.requiresReasoning&&e.complexity==="low")return!1;if(t.tokenRange!==void 0){let r=this.estimateTokens(e);if(t.tokenRange.min!==void 0&&r<t.tokenRange.min||t.tokenRange.max!==void 0&&r>t.tokenRange.max)return!1}return!(t.requiredCapabilities!==void 0&&t.requiredCapabilities.length>0&&(!e.requiredCapabilities||e.requiredCapabilities.length===0||!t.requiredCapabilities.every(i=>e.requiredCapabilities.includes(i)))||t.custom!==void 0&&!t.custom(e))}estimateTokens(e){let t=0;e.systemPrompt&&(t+=Math.ceil(e.systemPrompt.length/4));for(let r of e.messages)t+=Math.ceil(r.content.length/4);return t}},D=[{id:"security-agents-opus",name:"Security Agents to Claude Opus",description:"Route security-critical agents to Claude Opus for best security analysis",condition:{agentType:["security-auditor","security-architect","v3-qe-security-scanner"]},action:{provider:"claude",model:"claude-opus-4-7",temperature:.1},enabled:!0,priority:100},{id:"test-gen-with-tools",name:"Test Generation with Tools",description:"Route test generation requests that need tools to Claude Sonnet",condition:{agentType:["v3-qe-test-generator","tester"],requiresTools:!0},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:95},{id:"high-complexity-reasoning",name:"High Complexity Reasoning",description:"Route high complexity tasks requiring reasoning to advanced models",condition:{complexity:"high",requiresReasoning:!0},action:{provider:"claude",model:"claude-opus-4-7",temperature:.2},enabled:!0,priority:90},{id:"code-analysis-agents",name:"Code Analysis Agents",description:"Route code analysis to Claude Sonnet for balanced performance",condition:{agentType:["code-analyzer","v3-qe-code-intelligence","reviewer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.2},enabled:!0,priority:85},{id:"coverage-analysis",name:"Coverage Analysis Agents",description:"Route coverage analysis to efficient models",condition:{agentType:["v3-qe-coverage-analyzer"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.1},enabled:!0,priority:80},{id:"defect-prediction",name:"Defect Prediction Agents",description:"Route defect prediction to capable models",condition:{agentType:["v3-qe-defect-predictor"]},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:75},{id:"medium-complexity",name:"Medium Complexity Tasks",description:"Route medium complexity to balanced Claude Sonnet",condition:{complexity:"medium"},action:{provider:"claude",model:"claude-sonnet-4-6",temperature:.3},enabled:!0,priority:60},{id:"low-complexity-haiku",name:"Low Complexity to Haiku",description:"Route low complexity tasks to Haiku for cost efficiency",condition:{complexity:"low"},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:50},{id:"local-only-ollama",name:"Local Only Requests",description:"Route local-only requests to Ollama",condition:{localOnly:!0},action:{provider:"ollama",model:"llama3.1",temperature:.3},enabled:!0,priority:40},{id:"small-requests-haiku",name:"Small Token Requests",description:"Route small requests to Haiku for efficiency",condition:{tokenRange:{max:500}},action:{provider:"claude",model:"claude-haiku-4-5-20251001",temperature:.3},enabled:!0,priority:30}];import{randomUUID as $}from"crypto";var C=class{decisions=[];providerCalls=[];fallbacks=[];cacheHits=0;cacheMisses=0;startTime=new Date;maxRecords;maxCallRecords;constructor(e={}){this.maxRecords=e.maxRecords??1e4,this.maxCallRecords=e.maxCallRecords??5e3}recordRoutingDecision(e,t,r={}){let i={id:`rd-${Date.now()}-${$().slice(0,8)}`,timestamp:new Date,provider:e.providerType,model:e.model,mode:this.inferMode(e.reason),reason:e.reason,latencyMs:t,decisionTimeMs:e.metadata.decisionTimeMs,agentType:r.agentType,success:r.success??!0,tokenUsage:r.tokenUsage,cost:r.cost,wasFallback:e.reason==="fallback",ruleId:e.matchedRule?.id};this.decisions.push(i),this.trimRecords()}recordProviderCall(e,t,r,i,o={}){let n=o.inputTokens??Math.floor(i*.7),s=o.outputTokens??i-n,a={timestamp:new Date,provider:e,model:t,latencyMs:r,inputTokens:n,outputTokens:s,totalTokens:i,success:o.success??!0,cost:o.cost,agentType:o.agentType};this.providerCalls.push(a),this.trimCallRecords()}recordFallback(e,t,r,i){let o={timestamp:new Date,fromProvider:e,toProvider:t,reason:r,agentType:i};this.fallbacks.push(o),this.fallbacks.length>1e3&&(this.fallbacks=this.fallbacks.slice(-1e3))}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(e="all"){let t=this.getWindowStart(e),r=this.filterByTime(this.decisions,t),i=this.filterByTime(this.providerCalls,t),o=this.filterByTime(this.fallbacks,t),n=this.calculateProviderMetrics(r,i),s=this.calculateAgentMetrics(r,i),a=r.map(m=>m.decisionTimeMs),c=r.length,l=this.countByMode(r),d=r.filter(m=>m.wasFallback).length,g=r.filter(m=>m.ruleId).length;return{byProvider:Object.fromEntries(n),byAgentType:s,totalDecisions:c,decisionsByMode:l,avgDecisionTimeMs:this.average(a),p95DecisionTimeMs:this.percentile(a,95),p99DecisionTimeMs:this.percentile(a,99),fallbackRate:c>0?d/c:0,ruleMatchRate:c>0?g/c:0,estimatedCostSavings:this.calculateCostSavings(r),ruleStats:{totalEvaluated:r.reduce((m,u)=>m+1,0),matched:g,avgRulesPerDecision:1},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:t,end:new Date},recentDecisions:r.slice(-50),fallbackStats:this.calculateFallbackStats(o)}}getMetricsByProvider(e){let t=this.decisions.filter(a=>a.provider===e),r=this.providerCalls.filter(a=>a.provider===e),i=r.map(a=>a.latencyMs),o=t.map(a=>a.decisionTimeMs),n=r.filter(a=>a.success),s=r.filter(a=>!a.success);return{provider:e,selectionCount:t.length,ruleMatchCount:t.filter(a=>a.ruleId).length,fallbackCount:t.filter(a=>a.wasFallback).length,avgDecisionTimeMs:this.average(o),successRate:r.length>0?n.length/r.length:1,avgLatencyMs:this.average(i),p95LatencyMs:this.percentile(i,95),p99LatencyMs:this.percentile(i,99),totalCost:r.reduce((a,c)=>a+(c.cost??0),0),totalTokens:r.reduce((a,c)=>a+c.totalTokens,0),totalInputTokens:r.reduce((a,c)=>a+c.inputTokens,0),totalOutputTokens:r.reduce((a,c)=>a+c.outputTokens,0),circuitState:"closed",latencyHistogram:i.slice(-100),decisionTimeHistogram:o.slice(-100),errorCount:s.length,lastError:s.length>0?s[s.length-1].timestamp:void 0,recentCalls:r.slice(-20)}}getMetricsByAgentType(e){let t=this.decisions.filter(c=>c.agentType===e),r=this.providerCalls.filter(c=>c.agentType===e),i=new Map,o=new Map;for(let c of t)i.set(c.provider,(i.get(c.provider)??0)+1),o.set(c.model,(o.get(c.model)??0)+1);let n=r.map(c=>c.latencyMs),s=t.filter(c=>c.wasFallback).length,a=t.filter(c=>c.success).length;return{agentType:e,totalDecisions:t.length,providerDistribution:i,modelDistribution:o,avgLatencyMs:this.average(n),totalCost:r.reduce((c,l)=>c+(l.cost??0),0),totalTokens:r.reduce((c,l)=>c+l.totalTokens,0),fallbackRate:t.length>0?s/t.length:0,successRate:t.length>0?a/t.length:1}}getAuditLog(e={}){let t=this.decisions;e.since&&(t=t.filter(i=>i.timestamp>=e.since)),e.provider&&(t=t.filter(i=>i.provider===e.provider)),e.agentType&&(t=t.filter(i=>i.agentType===e.agentType));let r=e.limit??100;return t.slice(-r).map(i=>({id:i.id,timestamp:i.timestamp,context:{agentType:i.agentType},decision:{providerType:i.provider,model:i.model,providerModelId:i.model,reason:i.reason,confidence:1,metadata:{decisionTimeMs:i.decisionTimeMs,timestamp:i.timestamp}},outcome:{success:i.success,latencyMs:i.latencyMs,tokenUsage:i.tokenUsage,cost:i.cost}}))}resetMetrics(){this.decisions=[],this.providerCalls=[],this.fallbacks=[],this.cacheHits=0,this.cacheMisses=0,this.startTime=new Date}inferMode(e){switch(e){case"manual":return"manual";case"rule-match":return"rule-based";case"cost-optimization":return"cost-optimized";case"performance-optimization":return"performance-optimized";default:return"rule-based"}}trimRecords(){this.decisions.length>this.maxRecords&&(this.decisions=this.decisions.slice(-this.maxRecords))}trimCallRecords(){this.providerCalls.length>this.maxCallRecords&&(this.providerCalls=this.providerCalls.slice(-this.maxCallRecords))}getWindowStart(e){let t=new Date;switch(e){case"1m":return new Date(t.getTime()-60*1e3);case"5m":return new Date(t.getTime()-300*1e3);case"15m":return new Date(t.getTime()-900*1e3);case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);default:return this.startTime}}filterByTime(e,t){return e.filter(r=>r.timestamp>=t)}calculateProviderMetrics(e,t){let r=new Map;for(let i of v){let o=e.filter(l=>l.provider===i),n=t.filter(l=>l.provider===i);if(o.length===0&&n.length===0)continue;let s=n.map(l=>l.latencyMs),a=o.map(l=>l.decisionTimeMs),c=n.filter(l=>l.success);r.set(i,{provider:i,selectionCount:o.length,ruleMatchCount:o.filter(l=>l.ruleId).length,fallbackCount:o.filter(l=>l.wasFallback).length,avgDecisionTimeMs:this.average(a),successRate:n.length>0?c.length/n.length:1,avgLatencyMs:this.average(s),p95LatencyMs:this.percentile(s,95),p99LatencyMs:this.percentile(s,99),totalCost:n.reduce((l,d)=>l+(d.cost??0),0),totalTokens:n.reduce((l,d)=>l+d.totalTokens,0),circuitState:"closed"})}return r}calculateAgentMetrics(e,t){let r=new Set;e.forEach(o=>o.agentType&&r.add(o.agentType)),t.forEach(o=>o.agentType&&r.add(o.agentType));let i=new Map;for(let o of r)i.set(o,this.getMetricsByAgentType(o));return i}countByMode(e){let t={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};for(let r of e)t[r.mode]++;return t}calculateFallbackStats(e){let t=new Map,r=new Map;for(let i of e)t.set(i.fromProvider,(t.get(i.fromProvider)??0)+1),r.set(i.reason,(r.get(i.reason)??0)+1);return{total:e.length,byProvider:t,byReason:r}}calculateCostSavings(e){return e.reduce((t,r)=>r.cost&&r.mode==="cost-optimized"?t+r.cost.totalCost*.2:t,0)}average(e){return e.length===0?0:e.reduce((t,r)=>t+r,0)/e.length}percentile(e,t){if(e.length===0)return 0;let r=[...e].sort((o,n)=>o-n),i=Math.ceil(t/100*r.length)-1;return r[Math.max(0,i)]}};function E(p){return new C(p)}var R=class{records=[];alerts=[];maxRecords;alertCheckInterval;constructor(e={}){this.maxRecords=e.maxRecords??1e4}recordCost(e,t,r,i,o={}){let n=this.calculateCost(t,r,i),s={timestamp:new Date,provider:e,model:t,inputTokens:r,outputTokens:i,inputCost:n.inputCost,outputCost:n.outputCost,totalCost:n.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(s),this.trimRecords(),this.checkAlerts(),s}recordCostFromInfo(e,t,r,i,o={}){let n={timestamp:new Date,provider:e,model:t,inputTokens:r.promptTokens,outputTokens:r.completionTokens,inputCost:i.inputCost,outputCost:i.outputCost,totalCost:i.totalCost,agentType:o.agentType,requestId:o.requestId};return this.records.push(n),this.trimRecords(),this.checkAlerts(),n}getCostByProvider(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Map;for(let o of v){let n=r.filter(c=>c.provider===o);if(n.length===0)continue;let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);i.set(o,{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return i}getCostByAgentType(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(s=>s.agentType&&i.add(s.agentType));let o=new Map;for(let s of i){let a=r.filter(d=>d.agentType===s),c=a.reduce((d,g)=>d+g.totalCost,0),l=a.reduce((d,g)=>d+g.inputTokens+g.outputTokens,0);o.set(s,{totalCost:c,totalTokens:l,totalRequests:a.length,avgCostPerRequest:a.length>0?c/a.length:0,avgCostPerToken:l>0?c/l:0})}let n=r.filter(s=>!s.agentType);if(n.length>0){let s=n.reduce((c,l)=>c+l.totalCost,0),a=n.reduce((c,l)=>c+l.inputTokens+l.outputTokens,0);o.set("unknown",{totalCost:s,totalTokens:a,totalRequests:n.length,avgCostPerRequest:s/n.length,avgCostPerToken:a>0?s/a:0})}return o}getCostByModel(e="all"){let t=this.getPeriodStart(e),r=this.filterByTime(t),i=new Set;r.forEach(n=>i.add(n.model));let o=new Map;for(let n of i){let s=r.filter(l=>l.model===n),a=s.reduce((l,d)=>l+d.totalCost,0),c=s.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0);o.set(n,{totalCost:a,totalTokens:c,totalRequests:s.length,avgCostPerRequest:s.length>0?a/s.length:0,avgCostPerToken:c>0?a/c:0})}return o}getTotalCost(e="all"){let t=this.getPeriodStart(e);return this.filterByTime(t).reduce((i,o)=>i+o.totalCost,0)}getCostTrend(e){let t=new Date,r=[],i,o;switch(e){case"1h":i=300*1e3,o=12;break;case"24h":i=3600*1e3,o=24;break;case"7d":i=1440*60*1e3,o=7;break}for(let n=o-1;n>=0;n--){let s=new Date(t.getTime()-n*i),a=new Date(s.getTime()-i),c=this.records.filter(l=>l.timestamp>=a&&l.timestamp<s);r.push({timestamp:s,cost:c.reduce((l,d)=>l+d.totalCost,0),tokens:c.reduce((l,d)=>l+d.inputTokens+d.outputTokens,0),requests:c.length})}return r}addBudgetAlert(e,t,r){let i={threshold:e,period:t,callback:r,active:!0};return this.alerts.push(i),this.alertCheckInterval||(this.alertCheckInterval=setInterval(()=>this.checkAlerts(),6e4)),`alert-${this.alerts.length-1}`}removeBudgetAlert(e){return e>=0&&e<this.alerts.length?(this.alerts.splice(e,1),this.alerts.length===0&&this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0),!0):!1}getOptimizationSuggestions(){let e=[],t=this.getCostByModel("24h");for(let[n,s]of t)P[n]&&s.totalCost>1&&(n.includes("opus")&&e.push({type:"model-switch",description:"Consider using Sonnet instead of Opus for non-critical tasks",estimatedSavings:s.totalCost*.5,currentCost:s.totalCost,suggestedModel:"claude-sonnet-4-6"}),n==="gpt-4o"&&e.push({type:"model-switch",description:"Consider using GPT-4o-mini for simpler tasks",estimatedSavings:s.totalCost*.7,currentCost:s.totalCost,suggestedModel:"gpt-4o-mini"}));let r=this.getCostByProvider("24h"),i=[...r.values()].reduce((n,s)=>n+s.totalCost,0);return i>10&&!r.has("ollama")&&e.push({type:"provider-switch",description:"Consider using Ollama for development/testing workloads",estimatedSavings:i*.3,currentCost:i,suggestedProvider:"ollama"}),[...t.values()].reduce((n,s)=>n+s.totalRequests,0)>100&&e.push({type:"caching",description:"Enable response caching to reduce redundant API calls",estimatedSavings:i*.15,currentCost:i}),e}getRecords(){return[...this.records]}clear(){this.records=[]}reset(){this.records=[],this.alerts=[],this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}dispose(){this.alertCheckInterval&&(clearInterval(this.alertCheckInterval),this.alertCheckInterval=void 0)}calculateCost(e,t,r){let i=P[e];if(!i)return{inputCost:0,outputCost:0,totalCost:0,currency:"USD"};let o=t/1e6*i.input,n=r/1e6*i.output;return{inputCost:o,outputCost:n,totalCost:o+n,currency:"USD"}}trimRecords(){this.records.length>this.maxRecords&&(this.records=this.records.slice(-this.maxRecords))}getPeriodStart(e){let t=new Date;switch(e){case"1h":return new Date(t.getTime()-3600*1e3);case"24h":return new Date(t.getTime()-1440*60*1e3);case"7d":return new Date(t.getTime()-10080*60*1e3);case"30d":return new Date(t.getTime()-720*60*60*1e3);default:return new Date(0)}}filterByTime(e){return this.records.filter(t=>t.timestamp>=e)}checkAlerts(){for(let e of this.alerts){if(!e.active)continue;let t=this.getTotalCost(e.period);if(t>=e.threshold){e.active=!1;let r=this.getPeriodStart(e.period),i=this.filterByTime(r),o=i.reduce((n,s)=>n+s.inputTokens+s.outputTokens,0);try{e.callback({totalCost:t,totalTokens:o,totalRequests:i.length,avgCostPerRequest:i.length>0?t/i.length:0,avgCostPerToken:o>0?t/o:0})}catch(n){console.error("Budget alert callback error:",n)}}}}};function q(p){return new R(p)}H();var T=class{cache=new Map;maxSize;ttlMs;constructor(e=100,t=6e4){this.maxSize=e,this.ttlMs=t}get(e){let t=this.cache.get(e);return t?Date.now()>t.expiresAt?(this.cache.delete(e),null):t.decision:null}set(e,t){if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{hits:0,misses:0,size:this.cache.size}}},M=class{config;providerManager;ruleEngine;decisionCache;metrics;routerMetrics;costMetrics;initialized=!1;constructor(e,t){this.providerManager=e,this.config={..._,...t};let r=this.config.rules.length>0?this.config.rules:D;this.ruleEngine=new f(r),this.decisionCache=new T(100,this.config.decisionCacheTtlMs),this.metrics=new S,this.routerMetrics=E(),this.costMetrics=q()}async initialize(){this.initialized||(await this.providerManager.initialize(),this.initialized=!0)}getMode(){return this.config.mode}setMode(e){this.config.mode=e,this.decisionCache.clear()}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},e.rules&&this.ruleEngine.setRules(e.rules),e.decisionCacheTtlMs&&(this.decisionCache=new T(100,e.decisionCacheTtlMs))}async selectProvider(e){await this.ensureInitialized();let t=Date.now();if(this.config.cacheDecisions){let i=this.generateCacheKey(e),o=this.decisionCache.get(i);if(o)return this.metrics.recordCacheHit(),this.routerMetrics.recordCacheHit(),o;this.metrics.recordCacheMiss(),this.routerMetrics.recordCacheMiss()}let r;switch(this.config.mode){case"manual":r=await this.selectManual(e);break;case"rule-based":r=await this.selectRuleBased(e);break;case"cost-optimized":r=await this.selectCostOptimized(e);break;case"performance-optimized":r=await this.selectPerformanceOptimized(e);break;default:r=await this.selectRuleBased(e)}if(r.metadata.decisionTimeMs=Date.now()-t,this.config.cacheDecisions){let i=this.generateCacheKey(e);this.decisionCache.set(i,r)}return this.metrics.recordDecision(r,this.config.mode),r}async chat(e){await this.ensureInitialized();let t=z(),r=await this.selectProvider(e),i=e.agentType??"";if(U(i)&&(w(r.model)||w(r.providerModelId))){let n=r.model,s=r.providerModelId;r.model=A(i,r.model,x),r.providerModelId=A(i,r.providerModelId,x),console.warn(`[aqe] ADR-093: ${i} pinned to ${r.model} (was ${n}/${s}); set AQE_CYBER_VERIFIED=true after Cyber Verification Program approval`)}return await this.executeWithFallback(e,r,t)}async*stream(e){await this.ensureInitialized();let t=await this.selectProvider(e),r=await this.chat(e),i=100;for(let o=0;o<r.content.length;o+=i){let n=o+i>=r.content.length;yield{type:n?"done":"content",delta:r.content.slice(o,o+i),accumulated:r.content.slice(0,o+i),done:n,tokenCount:Math.ceil((o+i)/4),model:r.model,provider:t.providerType,usage:n?r.usage:void 0}}}getMetrics(){return this.metrics.getMetrics()}getEnhancedMetrics(e){return this.routerMetrics.getMetrics(e)}getProviderMetrics(e){return this.routerMetrics.getMetricsByProvider(e)}getAgentMetrics(e){return this.routerMetrics.getMetricsByAgentType(e)}getCostByProvider(e){return this.costMetrics.getCostByProvider(e)}getCostByAgentType(e){return this.costMetrics.getCostByAgentType(e)}getCostByModel(e){return this.costMetrics.getCostByModel(e)}getTotalCost(e){return this.costMetrics.getTotalCost(e)}getCostTrend(e){return this.costMetrics.getCostTrend(e)}getAuditLog(e){return this.routerMetrics.getAuditLog(e)}getOptimizationSuggestions(){return this.costMetrics.getOptimizationSuggestions()}resetMetrics(){this.metrics.reset(),this.routerMetrics.resetMetrics(),this.costMetrics.reset()}clearCache(){this.decisionCache.clear()}async selectManual(e){let t=e.preferredProvider??this.config.defaultProvider,r=e.model??this.config.defaultModel,i=this.providerManager.getProvider(t);return i?this.createDecision(i,t,r,"manual"):this.createFallbackDecision(e,"manual")}async selectRuleBased(e){let t=this.ruleEngine.evaluate(e);if(t){let{rule:o,rulesEvaluated:n}=t,s=o.action.provider,a=this.providerManager.getProvider(s);if(a){let c=this.createDecision(a,s,o.action.model,"rule-match",o);return c.metadata.rulesEvaluated=n,c}}let r=this.config.defaultProvider,i=this.providerManager.getProvider(r);return i?this.createDecision(i,r,this.config.defaultModel,"default"):this.createFallbackDecision(e,"rule-based")}async selectCostOptimized(e){let t=this.providerManager.getAvailableProviders();if(t.length===0)return this.createFallbackDecision(e,"cost-optimized");let r=1/0,i=t[0],o,n=[];for(let s of t){let a=this.providerManager.getProvider(s);if(!a)continue;let{input:c,output:l}=a.getCostPerToken(),d=this.estimateCostValue(e,c,l);n.push({provider:s,model:a.getConfig().model,reason:`Estimated cost: $${d.toFixed(6)}`,estimatedCost:d,excluded:!1}),d<r&&(r=d,i=s,o=a)}if(o){let s=o.getConfig(),a=this.createDecision(o,i,s.model,"cost-optimization");return a.metadata.estimatedCost=this.createCostEstimate(e,o),a.metadata.alternativesConsidered=n,a}return this.createFallbackDecision(e,"cost-optimized")}async selectPerformanceOptimized(e){let t=this.providerManager.getAvailableProviders(),r=this.providerManager.getMetrics();if(t.length===0)return this.createFallbackDecision(e,"performance-optimized");let i=1/0,o=t[0],n,s=[];for(let a of t){let c=this.providerManager.getProvider(a);if(!c)continue;let d=r[a]?.avgLatencyMs??1/0;s.push({provider:a,model:c.getConfig().model,reason:`Avg latency: ${d}ms`,estimatedLatencyMs:d,excluded:!1}),d<i&&(i=d,o=a,n=c)}if(n){let a=n.getConfig(),c=this.createDecision(n,o,a.model,"performance-optimization");return c.metadata.estimatedLatencyMs=i,c.metadata.alternativesConsidered=s,c}return this.createFallbackDecision(e,"performance-optimized")}async executeWithFallback(e,t,r){let{fallbackChain:i,fallbackBehavior:o}=this.config,n,s=0,a=[{provider:t.providerType,model:t.providerModelId}],c=this.config.defaultProvider;c&&c!==t.providerType&&a.push({provider:c,model:this.config.defaultModel});for(let l of i.entries)if(l.enabled&&l.provider!==t.providerType)for(let d of l.models)a.push({provider:l.provider,model:d});for(let{provider:l,model:d}of a){if(s>=o.maxAttempts)break;let g=this.providerManager.getProvider(l);if(!g)continue;s++;let m=Date.now();try{let u=await g.generate(e.messages,{model:d,temperature:e.temperature,maxTokens:e.maxTokens,systemPrompt:e.systemPrompt,timeoutMs:e.timeoutMs,skipCache:e.skipCache,metadata:e.metadata}),y=Date.now()-m;return this.metrics.recordSuccess(l),this.routerMetrics.recordRoutingDecision(t,y,{agentType:e.agentType,success:!0,tokenUsage:u.usage,cost:u.cost}),this.routerMetrics.recordProviderCall(l,d,y,u.usage.totalTokens,{inputTokens:u.usage.promptTokens,outputTokens:u.usage.completionTokens,success:!0,cost:u.cost.totalCost,agentType:e.agentType}),this.costMetrics.recordCostFromInfo(l,d,u.usage,u.cost,{agentType:e.agentType,requestId:u.requestId}),{content:u.content,model:u.model,providerModelId:u.model,provider:u.provider,usage:u.usage,cost:u.cost,latencyMs:u.latencyMs,finishReason:u.finishReason,cached:u.cached,requestId:u.requestId,routingDecision:t}}catch(u){n=I(u);let y=Date.now()-m;if(this.metrics.recordFailure(l),this.routerMetrics.recordProviderCall(l,d,y,0,{success:!1,agentType:e.agentType}),s<a.length){let L=a[s];L&&this.routerMetrics.recordFallback(l,L.provider,n.message,e.agentType)}!(B(u)&&!u.retryable)&&s<o.maxAttempts&&await this.delay(o.delayMs)}}throw b(`All providers failed after ${s} attempts: ${n?.message??"Unknown error"}`,"PROVIDER_UNAVAILABLE",{retryable:!1,cause:n})}createDecision(e,t,r,i,o){let{canonicalModel:n,providerModelId:s}=this.resolveModelIds(r,t);return{provider:e,providerType:t,model:n,providerModelId:s,reason:i,matchedRule:o,confidence:i==="rule-match"?.95:.8,metadata:{decisionTimeMs:0,timestamp:new Date}}}resolveModelIds(e,t){let i={claude:"anthropic",openai:"openai",ollama:"ollama",openrouter:"openrouter",gemini:"gemini","azure-openai":"azure",bedrock:"bedrock"}[t];if(!i)return{canonicalModel:e,providerModelId:e};try{let o=O(e),n=k(o,i);return{canonicalModel:o,providerModelId:n}}catch{try{if(F(e)){let n=k(e,i);return{canonicalModel:e,providerModelId:n}}}catch{}return{canonicalModel:e,providerModelId:e}}}createFallbackDecision(e,t){for(let i of this.config.fallbackChain.entries){if(!i.enabled||!["claude","openai","ollama"].includes(i.provider))continue;let n=this.providerManager.getProvider(i.provider);if(n)return this.createDecision(n,i.provider,i.models[0],"fallback")}let r=this.providerManager.getAvailableProviders();if(r.length>0){let i=r[0],o=this.providerManager.getProvider(i);return this.createDecision(o,i,o.getConfig().model,"fallback")}throw b(`No providers available for ${t} selection`,"PROVIDER_UNAVAILABLE",{retryable:!1})}generateCacheKey(e){return[this.config.mode,e.agentType??"default",e.complexity??"medium",e.requiresTools?"tools":"no-tools",e.preferredProvider??"any"].join(":")}estimateCostValue(e,t,r){let i=0;e.systemPrompt&&(i+=Math.ceil(e.systemPrompt.length/4));for(let n of e.messages)i+=Math.ceil(n.content.length/4);let o=e.maxTokens??1e3;return i*t+o*r}createCostEstimate(e,t){let{input:r,output:i}=t.getCostPerToken(),o=0;e.systemPrompt&&(o+=Math.ceil(e.systemPrompt.length/4));for(let a of e.messages)o+=Math.ceil(a.content.length/4);let n=e.maxTokens??1e3,s=o*r+n*i;return{inputTokens:o,outputTokens:n,totalCostUsd:s,inputCostPer1M:r*1e6,outputCostPer1M:i*1e6}}delay(e){return new Promise(t=>setTimeout(t,e))}async ensureInitialized(){this.initialized||await this.initialize()}},S=class{decisions=new Map;decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0};totalDecisions=0;cacheHits=0;cacheMisses=0;totalRulesEvaluated=0;rulesMatched=0;fallbackCount=0;startTime=new Date;recordDecision(e,t){this.totalDecisions++,this.decisionsByMode[t]++,e.metadata.rulesEvaluated&&(this.totalRulesEvaluated+=e.metadata.rulesEvaluated),e.matchedRule&&this.rulesMatched++,e.reason==="fallback"&&this.fallbackCount++;let r=this.decisions.get(e.providerType);r||(r=this.createEmptyMetrics(e.providerType),this.decisions.set(e.providerType,r)),r.selectionCount++,e.reason==="rule-match"&&r.ruleMatchCount++,e.reason==="fallback"&&r.fallbackCount++}recordSuccess(e){let t=this.decisions.get(e);if(t){let r=t.successRate*t.selectionCount;t.successRate=(r+1)/t.selectionCount}}recordFailure(e){}recordCacheHit(){this.cacheHits++}recordCacheMiss(){this.cacheMisses++}getMetrics(){let e={};for(let[r,i]of this.decisions)e[r]={...i};let t=this.totalDecisions>0?this.rulesMatched/this.totalDecisions:0;return{byProvider:e,totalDecisions:this.totalDecisions,decisionsByMode:{...this.decisionsByMode},avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:this.totalDecisions>0?this.fallbackCount/this.totalDecisions:0,ruleMatchRate:t,estimatedCostSavings:0,ruleStats:{totalEvaluated:this.totalRulesEvaluated,matched:this.rulesMatched,avgRulesPerDecision:this.totalDecisions>0?this.totalRulesEvaluated/this.totalDecisions:0},cacheStats:{hits:this.cacheHits,misses:this.cacheMisses,hitRate:this.cacheHits+this.cacheMisses>0?this.cacheHits/(this.cacheHits+this.cacheMisses):0},period:{start:this.startTime,end:new Date}}}reset(){this.decisions.clear(),this.decisionsByMode={manual:0,"rule-based":0,"cost-optimized":0,"performance-optimized":0},this.totalDecisions=0,this.cacheHits=0,this.cacheMisses=0,this.totalRulesEvaluated=0,this.rulesMatched=0,this.fallbackCount=0,this.startTime=new Date}createEmptyMetrics(e){return{provider:e,selectionCount:0,ruleMatchCount:0,fallbackCount:0,avgDecisionTimeMs:0,successRate:1,avgLatencyMs:0,p95LatencyMs:0,p99LatencyMs:0,totalCost:0,totalTokens:0,circuitState:"closed"}}};function je(p,e){return new M(p,e)}function Je(p){return new M(p,{mode:"rule-based",rules:D,defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",enableMetrics:!0,cacheDecisions:!0})}export{M as a,je as b,Je as c};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{i as e}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
|
|
2
|
+
import{i as e}from"./chunk-6OLPKIYU.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},o={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},s={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...o,...s,...d,...l,...c,...m,...p};export{g as a,i as b,o as c,s as d,d as e,l as f,c as g,m as h,p as i};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{f as s,i as o,k as c,m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
|
|
2
|
+
import{f as s,i as o,k as c,m}from"./chunk-HBWAMCVB.js";import{a,c as d}from"./chunk-XWPUCPYW.js";import{a as r,e as l}from"./chunk-MRLGQX7Y.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,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{c as T}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
|
|
2
|
+
import{c as T}from"./chunk-LRRQEAP5.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.
|
|
2
|
-
import{g}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.7");process.exit(0)}
|
|
2
|
+
import{g}from"./chunk-YLXUF5KW.js";import{b as p,c as d}from"./chunk-2MLISLRR.js";import{b as m,c as f}from"./chunk-XWPUCPYW.js";import{i as h}from"./chunk-6OLPKIYU.js";f();var I={maxDepth:5,riskWeights:{directImpact:.4,transitiveImpact:.2,testCoverage:.2,criticalPath:.15,dependencyCount:.05},testPatterns:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","**/test_*.py","**/*_test.py","**/*_test.go"],criticalPaths:["**/auth/**","**/security/**","**/payment/**","**/api/**","**/core/**"],namespace:"code-intelligence:impact"},u=class{constructor(e,t,i={}){this.memory=e;this.config={...I,...i},this.knowledgeGraph=t||new g(e)}memory;config;knowledgeGraph;async analyzeImpact(e){try{let{changedFiles:t,depth:i=this.config.maxDepth,includeTests:r=!0}=e;if(t.length===0)return p({directImpact:[],transitiveImpact:[],impactedTests:[],riskLevel:"info",recommendations:[]});let n=await this.analyzeDirectImpact(t),l=await this.analyzeTransitiveImpact(t,n,i),s=[];if(r){let a=await this.getImpactedTests(t);a.success&&(s=a.value)}let c={directImpact:n,transitiveImpact:l,impactedTests:s,riskLevel:"info",recommendations:[]};return c.riskLevel=this.calculateRiskLevel(c),c.recommendations=this.getRecommendations(c),await this.storeAnalysis(t,c),p(c)}catch(t){return d(m(t))}}async getImpactedTests(e){try{let t=new Set;for(let i of e){if(this.isTestFile(i)){t.add(i);continue}let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:3});if(r.success)for(let s of r.value.nodes)this.isTestFile(s.path)&&t.add(s.path);let n=this.getBaseName(i),l=[`${n}.test`,`${n}.spec`,`test_${n}`,`${n}_test`];for(let s of l){let c=await this.memory.search(`code-intelligence:kg:node:*${s}*`,10,{namespace:"code-intelligence:kg"});for(let a of c){let o=await this.memory.get(a,{namespace:"code-intelligence:kg"});o?.properties?.path&&this.isTestFile(o.properties.path)&&t.add(o.properties.path)}}}return p(Array.from(t))}catch(t){return d(m(t))}}calculateRiskLevel(e){let t=this.config.riskWeights,i=0,r=Math.min(1,e.directImpact.length/10);i+=r*t.directImpact;let n=Math.min(1,e.transitiveImpact.length/20);i+=n*t.transitiveImpact;let l=e.impactedTests.length>0?Math.max(0,1-e.impactedTests.length/(e.directImpact.length||1)):1;i+=l*t.testCoverage;let s=this.countCriticalFiles([...e.directImpact.map(o=>o.file),...e.transitiveImpact.map(o=>o.file)]),c=Math.min(1,s/5);i+=c*t.criticalPath;let a=this.calculateAverageRiskScore([...e.directImpact,...e.transitiveImpact]);return i+=a*t.dependencyCount,i>=.8?"critical":i>=.6?"high":i>=.4?"medium":i>=.2?"low":"info"}getRecommendations(e){let t=[];(e.riskLevel==="critical"||e.riskLevel==="high")&&t.push("This change has significant impact - consider peer review before merging"),e.impactedTests.length===0&&e.directImpact.length>0?t.push("No tests found for impacted files - add test coverage"):e.impactedTests.length<e.directImpact.length/2&&t.push("Test coverage appears low for impacted files"),e.impactedTests.length>0&&(e.impactedTests.length<=10?t.push(`Run these ${e.impactedTests.length} tests: ${e.impactedTests.slice(0,3).join(", ")}${e.impactedTests.length>3?"...":""}`):t.push(`Run all ${e.impactedTests.length} impacted tests before deployment`));let i=[...e.directImpact,...e.transitiveImpact].filter(n=>this.isCriticalPath(n.file));i.length>0&&t.push(`${i.length} critical path files affected - extra scrutiny recommended`),e.transitiveImpact.length>10&&t.push("Large transitive impact - consider breaking down into smaller changes");let r=[...e.directImpact,...e.transitiveImpact].filter(n=>n.riskScore>=.7);return r.length>0&&t.push(`${r.length} high-risk files impacted: ${r.slice(0,2).map(n=>this.getFileName(n.file)).join(", ")}`),t}async analyzeDirectImpact(e){let t=[];for(let i of e){let r=await this.knowledgeGraph.mapDependencies({files:[i],direction:"incoming",depth:1});if(r.success){let{nodes:n,edges:l}=r.value;for(let s of n){if(s.path===i)continue;let c=l.find(o=>o.target===s.id||o.source===s.id),a=this.calculateFileRiskScore(s.path,s.inDegree,s.outDegree);t.push({file:s.path,reason:`Directly ${c?.type||"depends on"} ${this.getFileName(i)}`,distance:1,riskScore:a})}}}return this.deduplicateImpact(t)}async analyzeTransitiveImpact(e,t,i){let r=[],n=new Set([...e,...t.map(s=>s.file)]),l=t.map(s=>({file:s.file,distance:1}));for(;l.length>0;){let s=l.shift();if(s.distance>=i)continue;let c=await this.knowledgeGraph.mapDependencies({files:[s.file],direction:"incoming",depth:1});if(c.success)for(let a of c.value.nodes){if(n.has(a.path)||a.path===s.file)continue;n.add(a.path);let o=this.calculateFileRiskScore(a.path,a.inDegree,a.outDegree,s.distance+1);r.push({file:a.path,reason:`Transitively depends via ${this.getFileName(s.file)}`,distance:s.distance+1,riskScore:o}),l.push({file:a.path,distance:s.distance+1})}}return this.deduplicateImpact(r)}calculateFileRiskScore(e,t,i,r=1){let n=0;return n+=Math.min(.3,t/20),n+=Math.min(.2,i/30),this.isCriticalPath(e)&&(n+=.3),this.isEntryPoint(e)&&(n+=.2),n=n*Math.pow(.8,r-1),Math.min(1,Math.max(0,n))}calculateAverageRiskScore(e){return e.length===0?0:e.reduce((i,r)=>i+r.riskScore,0)/e.length}countCriticalFiles(e){return e.filter(t=>this.isCriticalPath(t)).length}isTestFile(e){return[/\.test\.[tj]sx?$/,/\.spec\.[tj]sx?$/,/_test\.[tj]sx?$/,/test_.*\.py$/,/.*_test\.py$/,/.*_test\.go$/].some(i=>i.test(e))}isCriticalPath(e){return this.config.criticalPaths.map(i=>i.replace(/\*\*/g,".*").replace(/\*/g,"[^/]*")).some(i=>new RegExp(i).test(e))}isEntryPoint(e){return[/\/index\.[tj]sx?$/,/\/main\.[tj]sx?$/,/\/app\.[tj]sx?$/,/^src\/[^/]+\.[tj]sx?$/,/\/server\.[tj]sx?$/,/\/__init__\.py$/,/\/main\.go$/].some(i=>i.test(e))}getBaseName(e){return this.getFileName(e).replace(/\.[^.]+$/,"")}getFileName(e){return e.split(/[/\\]/).pop()||e}deduplicateImpact(e){let t=new Map;for(let i of e){let r=t.get(i.file);(!r||i.distance<r.distance)&&t.set(i.file,i)}return Array.from(t.values()).sort((i,r)=>r.riskScore!==i.riskScore?r.riskScore-i.riskScore:i.distance-r.distance)}async storeAnalysis(e,t){let i=h();await this.memory.set(`${this.config.namespace}:analysis:${i}`,{id:i,changedFiles:e,analysis:t,timestamp:new Date().toISOString()},{namespace:this.config.namespace,persist:!0})}};export{u as a};
|