agentic-qe 3.10.9 → 3.11.0
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/agents/v3/qe-learning-coordinator.md +1 -1
- package/.claude/skills/README.md +2 -2
- package/.claude/skills/agentic-quality-engineering/SKILL.md +6 -5
- package/.claude/skills/agentic-quality-engineering/schemas/output.json +7 -3
- package/.claude/skills/holistic-testing-pact/SKILL.md +50 -17
- package/.claude/skills/skills-manifest.json +6 -6
- package/.opencode/skills/qe-agentic-quality-engineering.yaml +5 -5
- package/.opencode/skills/qe-holistic-testing-pact.yaml +11 -11
- package/CHANGELOG.md +51 -0
- package/README.md +17 -0
- package/assets/agents/v3/qe-learning-coordinator.md +1 -1
- package/assets/skills/README.md +2 -2
- package/assets/skills/agentic-quality-engineering/SKILL.md +6 -5
- package/assets/skills/agentic-quality-engineering/schemas/output.json +7 -3
- package/assets/skills/holistic-testing-pact/SKILL.md +50 -17
- package/assets/skills/skills-manifest.json +6 -6
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-WLFT5VMV.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-RPAOJXZ3.js → agent-booster-wasm-5CSKQB4O.js} +2 -2
- package/dist/cli/chunks/{agent-handler-SMD5CAS6.js → agent-handler-EBV3OKTE.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-3IOQIQ7Y.js → agent-memory-branch-RZ53YM2U.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-JBH4GZUM.js +2 -0
- package/dist/cli/chunks/{arena-GT3D6EAO.js → arena-QWYTIQ6I.js} +2 -2
- package/dist/cli/chunks/{arena-AP2J62WO.js → arena-UCP74DRO.js} +4 -4
- package/dist/cli/chunks/{audit-Q3GJ5354.js → audit-M4FNIX47.js} +2 -2
- package/dist/cli/chunks/base-A7JGM473.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-YTK7S7GL.js → better-sqlite3-RIBLRHJL.js} +2 -2
- package/dist/cli/chunks/{brain-handler-2Z4ILQF3.js → brain-handler-OY6Q2GY5.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-EZWGL4UM.js → branch-enumerator-TQWN4NIX.js} +2 -2
- package/dist/cli/chunks/{browser-YZELFPLJ.js → browser-2EH3RXJ2.js} +2 -2
- package/dist/cli/chunks/browser-workflow-TIDJWULK.js +2 -0
- package/dist/cli/chunks/{chunk-NOWGQ6YZ.js → chunk-2BBKA5J4.js} +1 -1
- package/dist/cli/chunks/{chunk-7PYEJ4NV.js → chunk-2QU6C3OS.js} +2 -2
- package/dist/cli/chunks/{chunk-MDED3HJI.js → chunk-2TUVBEWK.js} +2 -2
- package/dist/cli/chunks/{chunk-YB3PQ3UV.js → chunk-2WVLFT2I.js} +1 -1
- package/dist/cli/chunks/{chunk-OF3EMOWN.js → chunk-2ZC7S4UG.js} +2 -2
- package/dist/cli/chunks/{chunk-7S6D5K4X.js → chunk-3GWSHRDA.js} +2 -2
- package/dist/cli/chunks/{chunk-HQZX4XYH.js → chunk-3J6LYF6I.js} +2 -2
- package/dist/cli/chunks/{chunk-5HLOQEKL.js → chunk-3LP5GPGU.js} +1 -1
- package/dist/cli/chunks/{chunk-UUA2NVUN.js → chunk-453UDYD2.js} +229 -225
- package/dist/cli/chunks/{chunk-2I5QLMQF.js → chunk-4OTA6KYJ.js} +2 -2
- package/dist/cli/chunks/{chunk-CREORFJV.js → chunk-5ASPEVVF.js} +1 -1
- package/dist/cli/chunks/{chunk-DNE6MVNA.js → chunk-5DG6H553.js} +1 -1
- package/dist/cli/chunks/{chunk-UPGKS6Z3.js → chunk-5OJXVVTI.js} +2 -2
- package/dist/cli/chunks/{chunk-6TR3OM7C.js → chunk-6VQKNPGY.js} +2 -2
- package/dist/cli/chunks/{chunk-QFIKEZB5.js → chunk-72QNONO6.js} +2 -2
- package/dist/cli/chunks/{chunk-3HT4CT6F.js → chunk-73EWPVBJ.js} +2 -2
- package/dist/cli/chunks/{chunk-4MUZGQPE.js → chunk-7BD7DZCB.js} +2 -2
- package/dist/cli/chunks/{chunk-PYQZ4OA3.js → chunk-7E5NYLJT.js} +2 -2
- package/dist/cli/chunks/{chunk-YQBL5XTM.js → chunk-7MBF3S25.js} +1 -1
- package/dist/cli/chunks/{chunk-LHKQW72O.js → chunk-7PTA7AVW.js} +1 -1
- package/dist/cli/chunks/{chunk-G7V2HDTH.js → chunk-7Q6CMSMD.js} +3 -3
- package/dist/cli/chunks/{chunk-ABJPFKHE.js → chunk-ACV2WVMX.js} +1 -1
- package/dist/cli/chunks/{chunk-QL6ZJ7RV.js → chunk-AURDGQNB.js} +2 -2
- package/dist/cli/chunks/{chunk-O36VC7B7.js → chunk-AVKGDS6F.js} +2 -2
- package/dist/cli/chunks/{chunk-ZVF7QY4R.js → chunk-AYOTODUV.js} +1 -1
- package/dist/cli/chunks/{chunk-ILPIH4Z6.js → chunk-B4QA3YN6.js} +1 -1
- package/dist/cli/chunks/{chunk-5U5SEO7C.js → chunk-BA4WZIAQ.js} +2 -2
- package/dist/cli/chunks/{chunk-EL6F72JN.js → chunk-BEOGI5FC.js} +2 -2
- package/dist/cli/chunks/{chunk-OQUH7657.js → chunk-C33BMWYZ.js} +2 -2
- package/dist/cli/chunks/chunk-C4OYHUJV.js +2 -0
- package/dist/cli/chunks/{chunk-DK6WWNCL.js → chunk-CERSTEAJ.js} +2 -2
- package/dist/cli/chunks/{chunk-XYRJL7YN.js → chunk-D3S4SRSA.js} +2 -2
- package/dist/cli/chunks/{chunk-57XCLC55.js → chunk-DCJIXDO6.js} +2 -2
- package/dist/cli/chunks/{chunk-Z6FRNWQA.js → chunk-DDQWW22L.js} +2 -2
- package/dist/cli/chunks/{chunk-5X73HV2P.js → chunk-DV7662EZ.js} +1 -1
- package/dist/cli/chunks/{chunk-QHPLU5BU.js → chunk-ETGEGMYS.js} +3 -3
- package/dist/cli/chunks/{chunk-TIR3Z6TE.js → chunk-ETZ62NFD.js} +1 -1
- package/dist/cli/chunks/{chunk-VHYNRISI.js → chunk-F62ZQZQQ.js} +2 -2
- package/dist/cli/chunks/{chunk-H4SHHYRD.js → chunk-F6Y7DTHR.js} +2 -2
- package/dist/cli/chunks/{chunk-L5IO7QNO.js → chunk-FGOVDO3R.js} +2 -2
- package/dist/cli/chunks/{chunk-62MH7QAQ.js → chunk-FMKALHT3.js} +2 -2
- package/dist/cli/chunks/{chunk-DZWZASDV.js → chunk-FMULOSBL.js} +1 -1
- package/dist/cli/chunks/{chunk-QL7OOCPO.js → chunk-FTOICJQG.js} +2 -2
- package/dist/cli/chunks/{chunk-I5C7O5IQ.js → chunk-G25YZ7Z6.js} +2 -2
- package/dist/cli/chunks/{chunk-WOGWIMQK.js → chunk-G5VE3HQW.js} +2 -2
- package/dist/cli/chunks/{chunk-EYGRNXQT.js → chunk-GBFAQ4DW.js} +1 -1
- package/dist/cli/chunks/{chunk-757YHKIJ.js → chunk-GGSXHGWD.js} +2 -2
- package/dist/cli/chunks/{chunk-VIHFC67B.js → chunk-HHSEIPSQ.js} +1 -1
- package/dist/cli/chunks/{chunk-42FBJF73.js → chunk-HJFQVKPI.js} +1 -1
- package/dist/cli/chunks/{chunk-6HPI6YX3.js → chunk-HMSPPGUF.js} +2 -2
- package/dist/cli/chunks/{chunk-RHOBDQXA.js → chunk-HNSZDIQU.js} +2 -2
- package/dist/cli/chunks/{chunk-4D3LVXUD.js → chunk-I2HQLBWG.js} +2 -2
- package/dist/cli/chunks/{chunk-X7677BX3.js → chunk-IFTEM672.js} +2 -2
- package/dist/cli/chunks/{chunk-NMQEU4BG.js → chunk-IHNBZ5XG.js} +2 -2
- package/dist/cli/chunks/{chunk-QHICG2NI.js → chunk-IKNDGXZZ.js} +2 -2
- package/dist/cli/chunks/{chunk-AHUX7QSE.js → chunk-IOQYSR5S.js} +2 -2
- package/dist/cli/chunks/{chunk-I7RTTJH5.js → chunk-IQSPL2H4.js} +2 -2
- package/dist/cli/chunks/{chunk-R2M3RMCN.js → chunk-ISVBO4XO.js} +2 -2
- package/dist/cli/chunks/{chunk-RSWQY4NZ.js → chunk-ITRUZ3WE.js} +2 -2
- package/dist/cli/chunks/{chunk-CWRSQQHV.js → chunk-J425SQFE.js} +2 -2
- package/dist/cli/chunks/{chunk-QWXJRZEH.js → chunk-JN3IQB4L.js} +1 -1
- package/dist/cli/chunks/{chunk-LT6QHDPK.js → chunk-JNX7IRSI.js} +2 -2
- package/dist/cli/chunks/{chunk-FD37QFXW.js → chunk-JQM64WJ2.js} +1 -1
- package/dist/cli/chunks/{chunk-HZSYCVLC.js → chunk-JQSA6EMI.js} +2 -2
- package/dist/cli/chunks/{chunk-BVEQPMOF.js → chunk-JZFA2PWY.js} +2 -2
- package/dist/cli/chunks/{chunk-AU4DQMLJ.js → chunk-KBVXKFDI.js} +4 -4
- package/dist/cli/chunks/{chunk-VDL277DX.js → chunk-KOOY72E3.js} +2 -2
- package/dist/cli/chunks/{chunk-NYBAH76S.js → chunk-KZE5UR4T.js} +3 -3
- package/dist/cli/chunks/{chunk-TOGD2JH2.js → chunk-L7GQKJLV.js} +2 -2
- package/dist/cli/chunks/{chunk-XEMP2PNW.js → chunk-LCDRRAES.js} +2 -2
- package/dist/cli/chunks/{chunk-VHCHBMZC.js → chunk-LFT7WYHW.js} +2 -2
- package/dist/cli/chunks/{chunk-C6JULAWA.js → chunk-LTH6XARD.js} +5 -5
- package/dist/cli/chunks/{chunk-UJBIHPU5.js → chunk-LYV7WJWA.js} +1 -1
- package/dist/cli/chunks/{chunk-RRSJ7BMF.js → chunk-MDYI4IIW.js} +1 -1
- package/dist/cli/chunks/{chunk-3YKJGKOY.js → chunk-MKLLB4PM.js} +4 -4
- package/dist/cli/chunks/{chunk-JZNMU63B.js → chunk-MTSMFEWK.js} +2 -2
- package/dist/cli/chunks/{chunk-WWGGL3TR.js → chunk-N3R3JGUY.js} +1 -1
- package/dist/cli/chunks/{chunk-BG2FN5K2.js → chunk-N52ZBTPM.js} +2 -2
- package/dist/cli/chunks/{chunk-CLSHSVMY.js → chunk-N7MKF4F4.js} +1 -1
- package/dist/cli/chunks/{chunk-UU7OCRZM.js → chunk-NBTKI2TX.js} +2 -2
- package/dist/cli/chunks/{chunk-NLUWPS2H.js → chunk-NI7O3GKZ.js} +3 -3
- package/dist/cli/chunks/{chunk-CLJNAQXB.js → chunk-NQD4CMXC.js} +2 -2
- package/dist/cli/chunks/{chunk-FALB6Z2Y.js → chunk-O6FN53HB.js} +1 -1
- package/dist/cli/chunks/{chunk-PFGH7TWL.js → chunk-OZQIDDXB.js} +2 -2
- package/dist/cli/chunks/{chunk-TKZABUHO.js → chunk-P3NV6KN3.js} +1 -1
- package/dist/cli/chunks/{chunk-S73EBPI5.js → chunk-PC3VIR2A.js} +3 -3
- package/dist/cli/chunks/{chunk-GPALZJD3.js → chunk-PJ4HSXH3.js} +1 -1
- package/dist/cli/chunks/{chunk-XLK4GP3I.js → chunk-PUTRXS5I.js} +2 -2
- package/dist/cli/chunks/{chunk-HAC7NB6R.js → chunk-PVBJUANU.js} +2 -2
- package/dist/cli/chunks/{chunk-BYVARYGB.js → chunk-QCJ7YOVN.js} +2 -2
- package/dist/cli/chunks/{chunk-CVRTXIYP.js → chunk-QGBXENIP.js} +1 -1
- package/dist/cli/chunks/{chunk-L5NEEGKO.js → chunk-QYXTESM3.js} +2 -2
- package/dist/cli/chunks/{chunk-KJA5A3TV.js → chunk-QZQGYSDG.js} +2 -2
- package/dist/cli/chunks/{chunk-7C5HI4ZA.js → chunk-R3YO3Z7I.js} +4 -4
- package/dist/cli/chunks/{chunk-352W5G4G.js → chunk-R7FHQQAV.js} +2 -2
- package/dist/cli/chunks/{chunk-4BB75U6N.js → chunk-RKDNLPZM.js} +2 -2
- package/dist/cli/chunks/{chunk-J6GKKXCP.js → chunk-RPYYS6BX.js} +2 -2
- package/dist/cli/chunks/{chunk-OSP5AJAB.js → chunk-RVQW6CBF.js} +2 -2
- package/dist/cli/chunks/{chunk-U6TZVACK.js → chunk-SHW43QQV.js} +2 -2
- package/dist/cli/chunks/{chunk-D2JCSWYM.js → chunk-SKL225P5.js} +2 -2
- package/dist/cli/chunks/{chunk-2WRVNEIR.js → chunk-SLWJNHCR.js} +2 -2
- package/dist/cli/chunks/{chunk-CDJIYJIA.js → chunk-SQPDGRYR.js} +1 -1
- package/dist/cli/chunks/{chunk-ZT2DGSIO.js → chunk-T6KT63NC.js} +2 -2
- package/dist/cli/chunks/{chunk-K23XK33X.js → chunk-TGLEREP5.js} +2 -2
- package/dist/cli/chunks/{chunk-7D5JE46U.js → chunk-TYS77XHV.js} +2 -2
- package/dist/cli/chunks/{chunk-H7AQ7M3J.js → chunk-UEH6C5JA.js} +1 -1
- package/dist/cli/chunks/{chunk-IR7PJUO7.js → chunk-UFMW25MS.js} +2 -2
- package/dist/cli/chunks/{chunk-TXWUV3S5.js → chunk-V6WJVFRN.js} +2 -2
- package/dist/cli/chunks/{chunk-KAMFT25W.js → chunk-VGYUVMSN.js} +2 -2
- package/dist/cli/chunks/{chunk-TVU6NMO3.js → chunk-VHON5NDM.js} +3 -3
- package/dist/cli/chunks/{chunk-2K2X75UF.js → chunk-VVJXQ4FR.js} +2 -2
- package/dist/cli/chunks/{chunk-G4KVGUQN.js → chunk-WBQEOACC.js} +2 -2
- package/dist/cli/chunks/{chunk-UX4UHYLE.js → chunk-WP6XUSVW.js} +1 -1
- package/dist/cli/chunks/{chunk-2WSEJHFQ.js → chunk-X2L4POJE.js} +1 -1
- package/dist/cli/chunks/{chunk-WPBVLIWQ.js → chunk-X2TUDGFL.js} +18 -18
- package/dist/cli/chunks/{chunk-OD4OIPXO.js → chunk-XKRG2U3V.js} +1 -1
- package/dist/cli/chunks/{chunk-X6YUGKMM.js → chunk-XMZ2DHUL.js} +1 -1
- package/dist/cli/chunks/{chunk-BSMUT672.js → chunk-XSG4XKGO.js} +2 -2
- package/dist/cli/chunks/{chunk-C6GQIUKW.js → chunk-XVQUVCFR.js} +2 -2
- package/dist/cli/chunks/{chunk-BM52ZEAD.js → chunk-XW5OXBVV.js} +2 -2
- package/dist/cli/chunks/{chunk-246Z3PH6.js → chunk-Y7TBCHW4.js} +2 -2
- package/dist/cli/chunks/{chunk-QE3CZGAC.js → chunk-Y7UJC5OL.js} +3 -3
- package/dist/cli/chunks/{chunk-KRAWWBX5.js → chunk-YQIMO7VJ.js} +2 -2
- package/dist/cli/chunks/{chunk-4EJTE5TL.js → chunk-YR44KQUK.js} +1 -1
- package/dist/cli/chunks/{chunk-YHFCLJMY.js → chunk-YRP73HO4.js} +1 -1
- package/dist/cli/chunks/{chunk-QAP5S7YC.js → chunk-YSTWLDVD.js} +3 -3
- package/dist/cli/chunks/{chunk-HGKZOSAI.js → chunk-Z45QDDZQ.js} +1 -1
- package/dist/cli/chunks/{chunk-OIN3Y4BY.js → chunk-ZEUUVLS2.js} +1 -1
- package/dist/cli/chunks/{chunk-7NT34MLU.js → chunk-ZFP3O5FM.js} +1 -1
- package/dist/cli/chunks/{chunk-ABVBHH7P.js → chunk-ZK56THZT.js} +3 -3
- package/dist/cli/chunks/{chunk-D7NWDUY3.js → chunk-ZT4NPTML.js} +2 -2
- package/dist/cli/chunks/{ci-KDEFR2X3.js → ci-4JK2NFCD.js} +2 -2
- package/dist/cli/chunks/{ci-output-Z3WXRRFI.js → ci-output-LCGTJQWC.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-GS44DEW2.js → circuit-breaker-EJF7D3L4.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-OHVMHAAH.js → claude-flow-setup-3RUC6OB4.js} +2 -2
- package/dist/cli/chunks/client-ZLJ3JMBC.js +2 -0
- package/dist/cli/chunks/{cline-installer-5TCF4MZD.js → cline-installer-6LY5C5QH.js} +2 -2
- package/dist/cli/chunks/{code-3KCGTG7Z.js → code-MPDG4UHS.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-LJBI54MZ.js → code-index-extractor-OY5GQJBM.js} +2 -2
- package/dist/cli/chunks/{codex-installer-IB62Z6LA.js → codex-installer-BO7E2ZVA.js} +2 -2
- package/dist/cli/chunks/{completions-JDXX7KKB.js → completions-VGL3KJ2R.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-6JVDXXXP.js → complexity-analyzer-5DPUK7IL.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-PUB45QVR.js → continuedev-installer-LFDG2D42.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-QWJ36P22.js → copilot-installer-SEMMMIZH.js} +2 -2
- package/dist/cli/chunks/core-handlers-EM7FUYTI.js +2 -0
- package/dist/cli/chunks/{cost-tracker-J3KEJDL5.js → cost-tracker-OPBC6FQM.js} +2 -2
- package/dist/cli/chunks/{coverage-FWKRI2EY.js → coverage-CFDUSRKU.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-DYGHQ6P5.js +2 -0
- package/dist/cli/chunks/{cursor-installer-2HYCUCTH.js → cursor-installer-6TXUUVY4.js} +2 -2
- package/dist/cli/chunks/{daemon-BVP66DIZ.js → daemon-5KO46YQR.js} +4 -4
- package/dist/cli/chunks/{daemon-G3DBRWDQ.js → daemon-7BDBPPAF.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-2AQLNB4B.js → dag-attention-scheduler-6DQKZOUW.js} +2 -2
- package/dist/cli/chunks/{detect-RUM5SHNE.js → detect-R2QAYDPI.js} +2 -2
- package/dist/cli/chunks/{dist-node-GX7MJHFT.js → dist-node-3POCIJ4N.js} +2 -2
- package/dist/cli/chunks/{domain-handler-OFBGZ2U5.js → domain-handler-KW63CHUH.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-6CGRPRGR.js → domain-transfer-2QPOJCUD.js} +2 -2
- package/dist/cli/chunks/dream-DBE5D5BD.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-MUOEVQX2.js → embed-and-insert-pattern-OIDJZQEP.js} +2 -2
- package/dist/cli/chunks/{eval-SJMG67DE.js → eval-UGEKTTAQ.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-ICKN6IXX.js → experience-capture-middleware-3BIM2TT7.js} +3 -3
- package/dist/cli/chunks/{fast-paths-HXLBG3J4.js → fast-paths-HCJQXB7W.js} +2 -2
- package/dist/cli/chunks/{feature-flags-CRUB2ASU.js → feature-flags-GDGJKLN4.js} +2 -2
- package/dist/cli/chunks/{feature-flags-JYZSSQJC.js → feature-flags-W4JSFBMV.js} +2 -2
- package/dist/cli/chunks/{file-discovery-YHHC7NTJ.js → file-discovery-JMUZ4MUH.js} +2 -2
- package/dist/cli/chunks/{fleet-2VGDL4YL.js → fleet-YNNK2CKW.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-7ZAGD4S4.js → gnn-wrapper-R2ZY6CDD.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-HAW3JRHN.js → heartbeat-handler-OZX2EJHQ.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-NFHAANNL.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-HMPCZFBY.js +2 -0
- package/dist/cli/chunks/hnsw-index-KRIWSXX4.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-BO325POX.js → hnsw-legacy-bridge-3S6TYCG3.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-6A6EAXAT.js → hnswlib-node-HMZC5TXM.js} +2 -2
- package/dist/cli/chunks/{hooks-HKM3JTFQ.js → hooks-KM7WR35T.js} +10 -10
- package/dist/cli/chunks/hybrid-router-BAB32B2W.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-LGLGHK6B.js → hypergraph-engine-RX53A73M.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-6QDVREZA.js → hypergraph-handler-3QQB3H3Z.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-3D6XHWQE.js +2 -0
- package/dist/cli/chunks/{init-handler-XUQ7XHIE.js → init-handler-Y62RH4ZI.js} +6 -6
- package/dist/cli/chunks/init-wizard-LLU3WVGC.js +2 -0
- package/dist/cli/chunks/kernel-ZFHAYHHJ.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-6CEZLVIX.js → kilocode-installer-26R253L2.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-6CJGATOS.js → kiro-installer-PFA5QPZZ.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-ETZ65KOY.js +2 -0
- package/dist/cli/chunks/{learning-EIYTYZJY.js → learning-CQLM5ANX.js} +3 -3
- package/dist/cli/chunks/{llm-router-J4CI7VHU.js → llm-router-QZ5PG4PF.js} +4 -4
- package/dist/cli/chunks/llm-router-service-R6CTGF5I.js +2 -0
- package/dist/cli/chunks/{load-CQPWGLQQ.js → load-UPA6LPHM.js} +2 -2
- package/dist/cli/chunks/load-test-UOWIJUCH.js +2 -0
- package/dist/cli/chunks/{mcp-THOATWCO.js → mcp-LSWTLAJ4.js} +2 -2
- package/dist/cli/chunks/{memory-NZHMHMRK.js → memory-VGEYYGCG.js} +5 -5
- package/dist/cli/chunks/memory-backend-E3ZQKW7A.js +2 -0
- package/dist/cli/chunks/{memory-handlers-L2J54AQE.js → memory-handlers-QBURG7NA.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-3P5E773H.js → multi-model-executor-VZVFBIKC.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-IRZMKSNG.js → opencode-installer-PBQAXNLV.js} +2 -2
- package/dist/cli/chunks/{orchestrator-UADLXTKP.js → orchestrator-YND7JB5O.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-OUOJO2RH.js +2 -0
- package/dist/cli/chunks/{pipeline-QEH3XHXJ.js → pipeline-GM5RRUES.js} +2 -2
- package/dist/cli/chunks/{platform-NEZ3NXLT.js → platform-L7OGGRSL.js} +2 -2
- package/dist/cli/chunks/{plugin-O33HR2VO.js → plugin-N4YAE6H5.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-MBUMFEX7.js → prime-radiant-advanced-wasm-7D67XV6Z.js} +2 -2
- package/dist/cli/chunks/protocol-executor-KHAPG5CP.js +2 -0
- package/dist/cli/chunks/{protocol-handler-L455UOUT.js → protocol-handler-V2WTFU7N.js} +2 -2
- package/dist/cli/chunks/{prove-3XA3SMAA.js → prove-33DS5Z3N.js} +2 -2
- package/dist/cli/chunks/provider-manager-FGPPW7T4.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-TS7XOJDA.js +2 -0
- package/dist/cli/chunks/{quality-H6Z5JH5B.js → quality-WCSEA5GH.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-J35FNFQ3.js +2 -0
- package/dist/cli/chunks/{real-embeddings-5DNJ4KEM.js → real-embeddings-OQ5F37DG.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-KHXKR2FK.js → roocode-installer-II7LIR2X.js} +2 -2
- package/dist/cli/chunks/router-AFTKPDI5.js +2 -0
- package/dist/cli/chunks/routing-feedback-SABZUJTF.js +2 -0
- package/dist/cli/chunks/{routing-handler-WAMGESEM.js → routing-handler-6OFHARIY.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-4J7XC6XY.js → ruvector-commands-GD5JTR4M.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-3PZEN6XN.js → rvf-dual-writer-HSK6BYZV.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-OIUNRQSU.js → rvf-migration-adapter-554SMF5S.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-QZXDI4I5.js → rvf-migration-coordinator-OFDBCAYE.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-57MDDSFQ.js +2 -0
- package/dist/cli/chunks/safe-db-2HR6MVYM.js +2 -0
- package/dist/cli/chunks/schedule-KLVAN6XI.js +2 -0
- package/dist/cli/chunks/scheduler-WYZ6BC5Y.js +2 -0
- package/dist/cli/chunks/{security-5NY77AMD.js → security-GN4J6DSS.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-MHPUZIMW.js → shared-rvf-adapter-Q4PM3QCN.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-ITLDYHCX.js → shared-rvf-dual-writer-R5WK5BXQ.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-2CGU5INO.js +2 -0
- package/dist/cli/chunks/{status-handler-7RBRIXZD.js → status-handler-AHS5WVMG.js} +2 -2
- package/dist/cli/chunks/{structural-health-MQPY6GA6.js → structural-health-5KUKNLHZ.js} +2 -2
- package/dist/cli/chunks/{sync-66KCEANE.js → sync-PUMM3SR6.js} +2 -2
- package/dist/cli/chunks/{sync-USVQTHKN.js → sync-TQLGD5HX.js} +2 -2
- package/dist/cli/chunks/{task-handler-4UI4FPPW.js → task-handler-D7VXV4AF.js} +2 -2
- package/dist/cli/chunks/{task-handlers-KRII3GVV.js → task-handlers-QMN4SWUG.js} +3 -3
- package/dist/cli/chunks/{test-JHN2MVEG.js → test-HEWZR6YQ.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-ZWTEGS3S.js → test-scheduling-VTMLBEPA.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-YWXL6AS5.js → token-bootstrap-IYBG7PQ6.js} +2 -2
- package/dist/cli/chunks/{token-usage-INII2XM3.js → token-usage-C7H27BFZ.js} +2 -2
- package/dist/cli/chunks/{transformers-DVFGDNZC.js → transformers-5ZJVC6NB.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-W2XJT3XF.js → tree-sitter-wasm-parser-EARBJG2H.js} +2 -2
- package/dist/cli/chunks/{types-GBZ5Q2GP.js → types-3IHE42PZ.js} +2 -2
- package/dist/cli/chunks/unified-memory-PMYRQC5K.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-7TRL2K5Q.js +2 -0
- package/dist/cli/chunks/unified-persistence-S4BNJK4S.js +2 -0
- package/dist/cli/chunks/{upgrade-2JEXEGQX.js → upgrade-YP3VFSXO.js} +2 -2
- package/dist/cli/chunks/{validate-GDCM5YTS.js → validate-VSBNKPN6.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-QZ5RSJEU.js → validate-swarm-GOCJVWXE.js} +2 -2
- package/dist/cli/chunks/{vibium-I5BMT734.js → vibium-U6YKCLDF.js} +2 -2
- package/dist/cli/chunks/visual-security-RPMZ3J7L.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-3QY2LMLP.js → web-tree-sitter-TSNVGWSN.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-V7OBPLOB.js → windsurf-installer-2VKMEFSD.js} +2 -2
- package/dist/cli/chunks/witness-chain-BTDZSQ6P.js +2 -0
- package/dist/cli/chunks/{witness-chain-BNJ4VSZX.js → witness-chain-BWZCW52H.js} +2 -2
- package/dist/cli/chunks/{workflow-3FJSNLPI.js → workflow-J6SCYLU3.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-42B62D3V.js +2 -0
- package/dist/cli/chunks/{wrappers-ERTQNIPK.js → wrappers-M5C7DONW.js} +2 -2
- package/dist/domains/test-generation/coordinator.d.ts +24 -1
- package/dist/domains/test-generation/coordinator.js +137 -2
- package/dist/domains/test-generation/plugin.js +23 -1
- package/dist/integrations/darwin/index.d.ts +10 -0
- package/dist/integrations/darwin/index.js +2 -0
- package/dist/integrations/darwin/qe-fitness.d.ts +83 -0
- package/dist/integrations/darwin/qe-fitness.js +147 -0
- package/dist/integrations/darwin/types.d.ts +62 -0
- package/dist/integrations/darwin/types.js +14 -0
- package/dist/mcp/bundle.js +375 -371
- package/dist/routing/escalation/auto-escalation-tracker.d.ts +34 -15
- package/dist/routing/escalation/auto-escalation-tracker.js +24 -15
- package/dist/routing/free-tier/executor.d.ts +119 -0
- package/dist/routing/free-tier/executor.js +139 -0
- package/dist/routing/free-tier/feedback-sink.d.ts +49 -0
- package/dist/routing/free-tier/feedback-sink.js +52 -0
- package/dist/routing/free-tier/index.d.ts +14 -0
- package/dist/routing/free-tier/index.js +5 -0
- package/dist/routing/free-tier/ladder.d.ts +41 -0
- package/dist/routing/free-tier/ladder.js +78 -0
- package/dist/routing/free-tier/provider.d.ts +57 -0
- package/dist/routing/free-tier/provider.js +111 -0
- package/dist/routing/free-tier/types.d.ts +80 -0
- package/dist/routing/free-tier/types.js +16 -0
- package/package.json +5 -1
- package/dist/cli/chunks/adapter-TRSV37EA.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-CVJRJOSO.js +0 -2
- package/dist/cli/chunks/base-BX4A2D4V.js +0 -2
- package/dist/cli/chunks/browser-workflow-O3RL7EYT.js +0 -2
- package/dist/cli/chunks/chunk-OPKEQYAC.js +0 -2
- package/dist/cli/chunks/client-T263ZXVV.js +0 -2
- package/dist/cli/chunks/core-handlers-ODKKGCFK.js +0 -2
- package/dist/cli/chunks/cross-domain-router-APU725GC.js +0 -2
- package/dist/cli/chunks/dream-PJ5GKY3J.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-4ZHUIW3Q.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-UVJJ6TTP.js +0 -2
- package/dist/cli/chunks/hnsw-index-K6HS34JZ.js +0 -2
- package/dist/cli/chunks/hybrid-router-25S7OH2Y.js +0 -2
- package/dist/cli/chunks/impact-analyzer-UP4RDMJH.js +0 -2
- package/dist/cli/chunks/init-wizard-2PAJ3GEC.js +0 -2
- package/dist/cli/chunks/kernel-7WOQGMMT.js +0 -2
- package/dist/cli/chunks/knowledge-graph-FN2AWHGR.js +0 -2
- package/dist/cli/chunks/llm-router-service-C3UPBAS3.js +0 -2
- package/dist/cli/chunks/load-test-PQSGLDXJ.js +0 -2
- package/dist/cli/chunks/memory-backend-6FR4RT5O.js +0 -2
- package/dist/cli/chunks/pattern-null-store-B2UX4NZY.js +0 -2
- package/dist/cli/chunks/protocol-executor-OQ6SL7SR.js +0 -2
- package/dist/cli/chunks/provider-manager-DQWHW2RG.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-3JS2CZAE.js +0 -2
- package/dist/cli/chunks/queen-coordinator-KXCWEM3Y.js +0 -2
- package/dist/cli/chunks/router-OVLIKT55.js +0 -2
- package/dist/cli/chunks/routing-feedback-2BYCXNXX.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-YNUYOQ5C.js +0 -2
- package/dist/cli/chunks/safe-db-6TYYEU7C.js +0 -2
- package/dist/cli/chunks/schedule-XVH7RTVY.js +0 -2
- package/dist/cli/chunks/scheduler-DHZBN5HA.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-NR5WXTPN.js +0 -2
- package/dist/cli/chunks/unified-memory-WJEZ5YAK.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-6ZA2PMYO.js +0 -2
- package/dist/cli/chunks/unified-persistence-SWH6R7MA.js +0 -2
- package/dist/cli/chunks/visual-security-PH5JQZCZ.js +0 -2
- package/dist/cli/chunks/witness-chain-WYMBNGSL.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-56JIXCI4.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.
|
|
2
|
-
import{b as C}from"./chunk-CLJNAQXB.js";import{a,d as ne}from"./chunk-7NT34MLU.js";import{b as M,c as oe}from"./chunk-YHFCLJMY.js";import{b as D,d as re}from"./chunk-246Z3PH6.js";import{b as v,c as O}from"./chunk-5U5SEO7C.js";import{b as se,d as de}from"./chunk-WOGWIMQK.js";de();O();var ie={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},Z=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...ie,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(v(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},N=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ie,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new Z(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var ae={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},R=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...ae,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),o=0;for(let i=0;i<n.length;i++){let u=n.charCodeAt(i);o=(o<<5)-o+u,o=o&o}return`${t}:${Math.abs(o).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let s={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,s),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let s of this.cache.values())r+=this.estimateSize(s.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,s]of this.cache.entries())s.ttlMs>0&&t-s.createdAt.getTime()>s.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},U=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...ae,...t},this.generationCache=new R(t),this.embeddingCache=new R(t),this.completionCache=new R(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=R.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,s){if(!this.config.cacheGenerations)return;let n=R.generateKey("generation",t,r);this.generationCache.set(n,e,s)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=R.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,s){if(!this.config.cacheEmbeddings)return;let n=R.generateKey("embedding",t,r);this.embeddingCache.set(n,e,s)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=R.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,s){if(!this.config.cacheCompletions)return;let n=R.generateKey("completion",t,r);this.completionCache.set(n,e,s)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),s=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,o=s+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:s,misses:n,hitRate:o>0?s/o:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};O();function Q(g,t,e,r){let s=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*s;return s+n}var me=1e3,he=3e4;function T(g,t=me,e=he){return Q(g,t,e,0)}import{readFileSync as ge}from"fs";import*as ce from"path";var ee=["low","medium","high","xhigh","max"],fe="xhigh";function q(g){return typeof g=="string"&&ee.includes(g)}var K;function ye(g){try{let e=ge(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&q(e[1])?e[1]:null}catch{return null}}function ue(g={}){if(g.override&&q(g.override))return g.override;if(g.agentEffort&&q(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&q(e))return e;let r=g.fleetDefaultsPath??ce.join(process.cwd(),"config","fleet-defaults.yaml");return K===void 0&&(K=ye(r)),K||fe}function le(g,t){let e=ee.indexOf(g),r=ee.indexOf(t);return e>r?t:g}var be={"claude-sonnet-4-5":{name:"Claude Sonnet 4.5",family:"claude",tier:"standard",description:"Most intelligent model, best for complex reasoning and coding tasks",releaseDate:"2025-09-29",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-opus-4":{name:"Claude Opus 4",family:"claude",tier:"flagship",description:"Flagship model with exceptional reasoning and reliability",releaseDate:"2025-05-14",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:75}},"claude-opus-4-5":{name:"Claude Opus 4.5",family:"claude",tier:"flagship",description:"Latest flagship model with enhanced reasoning capabilities",releaseDate:"2025-11-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:32768,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:75}},"claude-haiku-3-5":{name:"Claude Haiku 3.5",family:"claude",tier:"economy",description:"Fast and cost-effective for routine tasks",releaseDate:"2024-10-22",deprecationDate:"2026-02-19",recommended:!1,capabilities:{contextLength:2e5,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:1,outputCostPerMillion:5}},"claude-sonnet-4":{name:"Claude Sonnet 4",family:"claude",tier:"standard",description:"Balanced model for general-purpose tasks",releaseDate:"2025-05-14",deprecationDate:"2026-06-15",recommended:!1,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-opus-4-7":{name:"Claude Opus 4.7",family:"claude",tier:"flagship",description:"Flagship agentic-coding model (2026-04-16). 1M context at standard pricing, xhigh effort level, adaptive thinking only. New tokenizer emits 1.0\u20131.35\xD7 more tokens.",releaseDate:"2026-04-16",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!0,supportsEffortXHigh:!0,tokenizerVersion:"opus-4-7"},cost:{inputCostPerMillion:5,outputCostPerMillion:25}},"claude-sonnet-4-6":{name:"Claude Sonnet 4.6",family:"claude",tier:"standard",description:"Steady-state agentic-coding workhorse (2026). Standard 200k context, same pricing as Sonnet 4. ADR-093 Tier 3 default for the AQE fleet.",releaseDate:"2026-02-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!1,supportsEffortXHigh:!1,tokenizerVersion:"legacy"},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-haiku-4-5":{name:"Claude Haiku 4.5",family:"claude",tier:"economy",description:"Fast economy model replacing Haiku 3.5 (retired 2026-02-19). Extended thinking support.",releaseDate:"2025-10-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!1,supportsEffortXHigh:!1,tokenizerVersion:"legacy"},cost:{inputCostPerMillion:1,outputCostPerMillion:5}},"gpt-4o":{name:"GPT-4o",family:"gpt",tier:"standard",description:"OpenAI flagship multimodal model, fast and capable",releaseDate:"2024-05-13",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:5,outputCostPerMillion:15,imageCostPerUnit:.00765}},"gpt-4o-mini":{name:"GPT-4o Mini",family:"gpt",tier:"economy",description:"Small, fast, and affordable for lightweight tasks",releaseDate:"2024-07-18",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:.15,outputCostPerMillion:.6,imageCostPerUnit:.001275}},"gpt-4-turbo":{name:"GPT-4 Turbo",family:"gpt",tier:"premium",description:"Previous flagship with vision and function calling",releaseDate:"2024-04-09",recommended:!1,capabilities:{contextLength:128e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:10,outputCostPerMillion:30}},"gpt-4":{name:"GPT-4",family:"gpt",tier:"premium",description:"Original GPT-4 model, now superseded by GPT-4o",releaseDate:"2023-03-14",deprecationDate:"2025-06-01",recommended:!1,capabilities:{contextLength:8192,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:30,outputCostPerMillion:60}},o1:{name:"OpenAI o1",family:"gpt",tier:"flagship",description:"Reasoning-focused model with extended thinking",releaseDate:"2024-12-05",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:1e5,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:60}},"o1-mini":{name:"OpenAI o1 Mini",family:"gpt",tier:"standard",description:"Faster reasoning model optimized for STEM tasks",releaseDate:"2024-09-12",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:65536,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:12}},"gemini-pro":{name:"Gemini Pro",family:"gemini",tier:"standard",description:"Google balanced model for diverse tasks",releaseDate:"2023-12-06",recommended:!1,capabilities:{contextLength:32e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:.5,outputCostPerMillion:1.5}},"gemini-pro-1.5":{name:"Gemini Pro 1.5",family:"gemini",tier:"standard",description:"Google mid-size model with 1M context window",releaseDate:"2024-02-15",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!0},cost:{inputCostPerMillion:3.5,outputCostPerMillion:10.5}},"gemini-flash-1.5":{name:"Gemini Flash 1.5",family:"gemini",tier:"economy",description:"Fast and efficient with 1M context window",releaseDate:"2024-05-14",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!0},cost:{inputCostPerMillion:.075,outputCostPerMillion:.3}},"gemini-ultra":{name:"Gemini Ultra",family:"gemini",tier:"flagship",description:"Google most capable model",releaseDate:"2024-02-08",recommended:!1,capabilities:{contextLength:32e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:12,outputCostPerMillion:36}},llama3:{name:"Llama 3",family:"llama",tier:"economy",description:"Meta open-source 8B model, runs locally",releaseDate:"2024-04-18",recommended:!0,capabilities:{contextLength:8192,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},"llama3.1":{name:"Llama 3.1",family:"llama",tier:"economy",description:"Meta latest open-source model with tool support",releaseDate:"2024-07-23",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},codellama:{name:"CodeLlama",family:"llama",tier:"economy",description:"Meta code-specialized model",releaseDate:"2023-08-24",recommended:!0,capabilities:{contextLength:1e5,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},mistral:{name:"Mistral",family:"mistral",tier:"economy",description:"Mistral AI 7B instruction-tuned model",releaseDate:"2023-09-27",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},mixtral:{name:"Mixtral",family:"mistral",tier:"standard",description:"Mistral AI mixture of experts model",releaseDate:"2023-12-11",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},phi3:{name:"Phi-3",family:"phi",tier:"economy",description:"Microsoft small language model, efficient",releaseDate:"2024-04-23",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},qwen2:{name:"Qwen 2",family:"qwen",tier:"economy",description:"Alibaba multilingual model",releaseDate:"2024-06-07",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}}};function pe(g){let t=ne(g),e=be[t];if(!e)throw new Error(`Model not found in registry: ${g}`);return{...e.capabilities}}var ke={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},B=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...ke,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),s=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:s,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let s=this.formatMessages(t),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,u=`claude-${++this.requestId}-${Date.now()}`,m=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.systemPrompt&&(h.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(h.stop_sequences=e.stopSequences);try{if(pe(n).supportsEffortXHigh){let p=ue({override:e?.effort}),l=le(p,"xhigh");h.thinking={type:"adaptive",effort:l}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-m;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let l=await c.json(),d=l.usage.cache_creation_input_tokens??0,y=l.usage.cache_read_input_tokens??0,b={promptTokens:l.usage.input_tokens,completionTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+d+y+l.usage.output_tokens,cacheCreationTokens:d,cacheReadTokens:y},f=M.calculateCost(n,b);return C.recordTokenUsage(u,"claude-provider","llm","generate",{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,estimatedCostUsd:f.totalCost}),{content:l.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:l.model,provider:"claude",usage:b,cost:f,latencyMs:p,finishReason:this.mapFinishReason(l.stop_reason),cached:!1,requestId:u}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
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.11.0");process.exit(0)}
|
|
2
|
+
import{b as C}from"./chunk-NQD4CMXC.js";import{a,d as ne}from"./chunk-ZFP3O5FM.js";import{b as M,c as oe}from"./chunk-YRP73HO4.js";import{b as D,d as re}from"./chunk-Y7TBCHW4.js";import{b as v,c as O}from"./chunk-BA4WZIAQ.js";import{b as se,d as de}from"./chunk-G5VE3HQW.js";de();O();var ie={failureThreshold:5,resetTimeoutMs:3e4,halfOpenSuccessThreshold:2,failureWindowMs:6e4,includeTimeouts:!0},Z=class{state="closed";failures=[];successCount=0;totalRequests=0;totalSuccesses=0;totalFailures=0;rejectedCount=0;lastFailureTime;lastSuccessTime;openedAt;halfOpenSuccesses=0;config;providerType;constructor(t,e={}){this.providerType=t,this.config={...ie,...e}}getState(){return this.state==="open"&&this.openedAt&&Date.now()-this.openedAt.getTime()>=this.config.resetTimeoutMs&&this.transitionTo("half-open"),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t!=="open"}async execute(t){if(this.totalRequests++,this.getState()==="open")throw this.rejectedCount++,a(`Circuit breaker is open for provider ${this.providerType}`,"CIRCUIT_OPEN",{provider:this.providerType,retryable:!0,retryAfterMs:this.getTimeUntilTransition()});try{let r=await t();return this.recordSuccess(),r}catch(r){throw this.recordFailure(v(r)),r}}recordSuccess(){this.successCount++,this.totalSuccesses++,this.lastSuccessTime=new Date,this.getState()==="half-open"&&(this.halfOpenSuccesses++,this.halfOpenSuccesses>=this.config.halfOpenSuccessThreshold&&this.transitionTo("closed"))}recordFailure(t){if(this.totalFailures++,this.lastFailureTime=new Date,(t.message.toLowerCase().includes("timeout")||t.name==="TimeoutError"||t.name==="AbortError")&&!this.config.includeTimeouts)return;this.failures.push({timestamp:new Date,error:t}),this.cleanOldFailures();let r=this.getState();if(r==="half-open"){this.transitionTo("open");return}r==="closed"&&this.failures.length>=this.config.failureThreshold&&this.transitionTo("open")}getStats(){return{state:this.getState(),totalRequests:this.totalRequests,successCount:this.totalSuccesses,failureCount:this.totalFailures,rejectedCount:this.rejectedCount,lastFailureTime:this.lastFailureTime,lastSuccessTime:this.lastSuccessTime,timeUntilTransitionMs:this.getTimeUntilTransition()}}reset(){this.state="closed",this.failures=[],this.successCount=0,this.halfOpenSuccesses=0,this.openedAt=void 0}forceOpen(){this.transitionTo("open")}forceHalfOpen(){this.transitionTo("half-open")}getRecentFailures(t=5){return this.failures.slice(-t).map(e=>`[${e.timestamp.toISOString()}] ${e.error.message}`)}transitionTo(t){if(this.state!==t)switch(this.state=t,t){case"open":this.openedAt=new Date,this.halfOpenSuccesses=0;break;case"half-open":this.halfOpenSuccesses=0;break;case"closed":this.failures=[],this.openedAt=void 0,this.halfOpenSuccesses=0;break}}cleanOldFailures(){let t=Date.now()-this.config.failureWindowMs;this.failures=this.failures.filter(e=>e.timestamp.getTime()>t)}getTimeUntilTransition(){if(this.state==="open"&&this.openedAt){let t=Date.now()-this.openedAt.getTime(),e=this.config.resetTimeoutMs-t;return Math.max(0,e)}}},N=class{breakers=new Map;defaultConfig;constructor(t={}){this.defaultConfig={...ie,...t}}getBreaker(t,e){let r=this.breakers.get(t);return r||(r=new Z(t,{...this.defaultConfig,...e}),this.breakers.set(t,r)),r}getAllStats(){let t={};for(let[e,r]of this.breakers)t[e]=r.getStats();return t}getAvailableProviders(){let t=[];for(let[e,r]of this.breakers)r.canExecute()&&t.push(e);return t}resetAll(){for(let t of this.breakers.values())t.reset()}reset(t){let e=this.breakers.get(t);e&&e.reset()}};var ae={maxSize:1e3,defaultTtlMs:36e5,enableLRU:!0,cacheGenerations:!0,cacheEmbeddings:!0,cacheCompletions:!0},R=class{cache=new Map;accessOrder=[];config;hits=0;misses=0;evictions=0;constructor(t={}){this.config={...ae,...t}}static generateKey(t,e,r){let n=[t,r?.model??"default",String(r?.temperature??.7),String(r?.maxTokens??0),r?.systemPrompt??"",e].join("|"),o=0;for(let i=0;i<n.length;i++){let u=n.charCodeAt(i);o=(o<<5)-o+u,o=o&o}return`${t}:${Math.abs(o).toString(36)}`}get(t){let e=this.cache.get(t);if(!e){this.misses++;return}if(e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs){this.delete(t),this.misses++;return}return this.hits++,e.lastAccessedAt=new Date,e.accessCount++,this.config.enableLRU&&this.updateAccessOrder(t),e.value}set(t,e,r){this.cache.size>=this.config.maxSize&&!this.cache.has(t)&&this.evictLRU();let s={value:e,createdAt:new Date,lastAccessedAt:new Date,accessCount:1,ttlMs:r??this.config.defaultTtlMs,keyHash:t};this.cache.set(t,s),this.config.enableLRU&&this.updateAccessOrder(t)}has(t){let e=this.cache.get(t);return e?e.ttlMs>0&&Date.now()-e.createdAt.getTime()>e.ttlMs?(this.delete(t),!1):!0:!1}delete(t){let e=this.cache.delete(t);if(e){let r=this.accessOrder.indexOf(t);r!==-1&&this.accessOrder.splice(r,1)}return e}clear(){this.cache.clear(),this.accessOrder=[],this.hits=0,this.misses=0,this.evictions=0}getStats(){let t=this.hits+this.misses,e=t>0?this.hits/t:0,r=0;for(let s of this.cache.values())r+=this.estimateSize(s.value);return{size:this.cache.size,maxSize:this.config.maxSize,hits:this.hits,misses:this.misses,hitRate:e,evictions:this.evictions,memoryUsageBytes:r}}keys(){return Array.from(this.cache.keys())}entries(){return Array.from(this.cache.entries())}import(t){for(let[e,r]of t)r.createdAt=new Date(r.createdAt),r.lastAccessedAt=new Date(r.lastAccessedAt),this.cache.set(e,r),this.accessOrder.push(e);for(;this.cache.size>this.config.maxSize;)this.evictLRU()}pruneExpired(){let t=Date.now(),e=0;for(let[r,s]of this.cache.entries())s.ttlMs>0&&t-s.createdAt.getTime()>s.ttlMs&&(this.delete(r),e++);return e}updateAccessOrder(t){let e=this.accessOrder.indexOf(t);e!==-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length===0){let e=this.cache.keys().next().value;e&&(this.cache.delete(e),this.evictions++);return}let t=this.accessOrder.shift();t&&(this.cache.delete(t),this.evictions++)}estimateSize(t){return t==null?0:JSON.stringify(t).length*2}},U=class{generationCache;embeddingCache;completionCache;config;constructor(t={}){this.config={...ae,...t},this.generationCache=new R(t),this.embeddingCache=new R(t),this.completionCache=new R(t)}getGeneration(t,e){if(!this.config.cacheGenerations)return;let r=R.generateKey("generation",t,e);return this.generationCache.get(r)}setGeneration(t,e,r,s){if(!this.config.cacheGenerations)return;let n=R.generateKey("generation",t,r);this.generationCache.set(n,e,s)}getEmbedding(t,e){if(!this.config.cacheEmbeddings)return;let r=R.generateKey("embedding",t,e);return this.embeddingCache.get(r)}setEmbedding(t,e,r,s){if(!this.config.cacheEmbeddings)return;let n=R.generateKey("embedding",t,r);this.embeddingCache.set(n,e,s)}getCompletion(t,e){if(!this.config.cacheCompletions)return;let r=R.generateKey("completion",t,e);return this.completionCache.get(r)}setCompletion(t,e,r,s){if(!this.config.cacheCompletions)return;let n=R.generateKey("completion",t,r);this.completionCache.set(n,e,s)}getStats(){let t=this.generationCache.getStats(),e=this.embeddingCache.getStats(),r=this.completionCache.getStats(),s=t.hits+e.hits+r.hits,n=t.misses+e.misses+r.misses,o=s+n;return{generation:t,embedding:e,completion:r,total:{size:t.size+e.size+r.size,maxSize:this.config.maxSize*3,hits:s,misses:n,hitRate:o>0?s/o:0,evictions:t.evictions+e.evictions+r.evictions,memoryUsageBytes:t.memoryUsageBytes+e.memoryUsageBytes+r.memoryUsageBytes}}}clear(){this.generationCache.clear(),this.embeddingCache.clear(),this.completionCache.clear()}pruneExpired(){return this.generationCache.pruneExpired()+this.embeddingCache.pruneExpired()+this.completionCache.pruneExpired()}};O();function Q(g,t,e,r){let s=Math.min(t*Math.pow(2,g),e),n=Math.random()*r*s;return s+n}var me=1e3,he=3e4;function T(g,t=me,e=he){return Q(g,t,e,0)}import{readFileSync as ge}from"fs";import*as ce from"path";var ee=["low","medium","high","xhigh","max"],fe="xhigh";function q(g){return typeof g=="string"&&ee.includes(g)}var K;function ye(g){try{let e=ge(g,"utf8").match(/^\s*effort_level\s*:\s*['"]?([a-z]+)['"]?\s*$/m);return e&&q(e[1])?e[1]:null}catch{return null}}function ue(g={}){if(g.override&&q(g.override))return g.override;if(g.agentEffort&&q(g.agentEffort))return g.agentEffort;let e=(g.env??process.env).QE_EFFORT_LEVEL;if(e&&q(e))return e;let r=g.fleetDefaultsPath??ce.join(process.cwd(),"config","fleet-defaults.yaml");return K===void 0&&(K=ye(r)),K||fe}function le(g,t){let e=ee.indexOf(g),r=ee.indexOf(t);return e>r?t:g}var be={"claude-sonnet-4-5":{name:"Claude Sonnet 4.5",family:"claude",tier:"standard",description:"Most intelligent model, best for complex reasoning and coding tasks",releaseDate:"2025-09-29",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-opus-4":{name:"Claude Opus 4",family:"claude",tier:"flagship",description:"Flagship model with exceptional reasoning and reliability",releaseDate:"2025-05-14",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:75}},"claude-opus-4-5":{name:"Claude Opus 4.5",family:"claude",tier:"flagship",description:"Latest flagship model with enhanced reasoning capabilities",releaseDate:"2025-11-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:32768,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:75}},"claude-haiku-3-5":{name:"Claude Haiku 3.5",family:"claude",tier:"economy",description:"Fast and cost-effective for routine tasks",releaseDate:"2024-10-22",deprecationDate:"2026-02-19",recommended:!1,capabilities:{contextLength:2e5,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:1,outputCostPerMillion:5}},"claude-sonnet-4":{name:"Claude Sonnet 4",family:"claude",tier:"standard",description:"Balanced model for general-purpose tasks",releaseDate:"2025-05-14",deprecationDate:"2026-06-15",recommended:!1,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-opus-4-7":{name:"Claude Opus 4.7",family:"claude",tier:"flagship",description:"Flagship agentic-coding model (2026-04-16). 1M context at standard pricing, xhigh effort level, adaptive thinking only. New tokenizer emits 1.0\u20131.35\xD7 more tokens.",releaseDate:"2026-04-16",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!0,supportsEffortXHigh:!0,tokenizerVersion:"opus-4-7"},cost:{inputCostPerMillion:5,outputCostPerMillion:25}},"claude-sonnet-4-6":{name:"Claude Sonnet 4.6",family:"claude",tier:"standard",description:"Steady-state agentic-coding workhorse (2026). Standard 200k context, same pricing as Sonnet 4. ADR-093 Tier 3 default for the AQE fleet.",releaseDate:"2026-02-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!1,supportsEffortXHigh:!1,tokenizerVersion:"legacy"},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-haiku-4-5":{name:"Claude Haiku 4.5",family:"claude",tier:"economy",description:"Fast economy model replacing Haiku 3.5 (retired 2026-02-19). Extended thinking support.",releaseDate:"2025-10-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!1,supportsEffortXHigh:!1,tokenizerVersion:"legacy"},cost:{inputCostPerMillion:1,outputCostPerMillion:5}},"gpt-4o":{name:"GPT-4o",family:"gpt",tier:"standard",description:"OpenAI flagship multimodal model, fast and capable",releaseDate:"2024-05-13",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:5,outputCostPerMillion:15,imageCostPerUnit:.00765}},"gpt-4o-mini":{name:"GPT-4o Mini",family:"gpt",tier:"economy",description:"Small, fast, and affordable for lightweight tasks",releaseDate:"2024-07-18",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:.15,outputCostPerMillion:.6,imageCostPerUnit:.001275}},"gpt-4-turbo":{name:"GPT-4 Turbo",family:"gpt",tier:"premium",description:"Previous flagship with vision and function calling",releaseDate:"2024-04-09",recommended:!1,capabilities:{contextLength:128e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:10,outputCostPerMillion:30}},"gpt-4":{name:"GPT-4",family:"gpt",tier:"premium",description:"Original GPT-4 model, now superseded by GPT-4o",releaseDate:"2023-03-14",deprecationDate:"2025-06-01",recommended:!1,capabilities:{contextLength:8192,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:30,outputCostPerMillion:60}},o1:{name:"OpenAI o1",family:"gpt",tier:"flagship",description:"Reasoning-focused model with extended thinking",releaseDate:"2024-12-05",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:1e5,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:60}},"o1-mini":{name:"OpenAI o1 Mini",family:"gpt",tier:"standard",description:"Faster reasoning model optimized for STEM tasks",releaseDate:"2024-09-12",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:65536,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:12}},"gemini-pro":{name:"Gemini Pro",family:"gemini",tier:"standard",description:"Google balanced model for diverse tasks",releaseDate:"2023-12-06",recommended:!1,capabilities:{contextLength:32e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:.5,outputCostPerMillion:1.5}},"gemini-pro-1.5":{name:"Gemini Pro 1.5",family:"gemini",tier:"standard",description:"Google mid-size model with 1M context window",releaseDate:"2024-02-15",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!0},cost:{inputCostPerMillion:3.5,outputCostPerMillion:10.5}},"gemini-flash-1.5":{name:"Gemini Flash 1.5",family:"gemini",tier:"economy",description:"Fast and efficient with 1M context window",releaseDate:"2024-05-14",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!0},cost:{inputCostPerMillion:.075,outputCostPerMillion:.3}},"gemini-ultra":{name:"Gemini Ultra",family:"gemini",tier:"flagship",description:"Google most capable model",releaseDate:"2024-02-08",recommended:!1,capabilities:{contextLength:32e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:12,outputCostPerMillion:36}},llama3:{name:"Llama 3",family:"llama",tier:"economy",description:"Meta open-source 8B model, runs locally",releaseDate:"2024-04-18",recommended:!0,capabilities:{contextLength:8192,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},"llama3.1":{name:"Llama 3.1",family:"llama",tier:"economy",description:"Meta latest open-source model with tool support",releaseDate:"2024-07-23",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},codellama:{name:"CodeLlama",family:"llama",tier:"economy",description:"Meta code-specialized model",releaseDate:"2023-08-24",recommended:!0,capabilities:{contextLength:1e5,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},mistral:{name:"Mistral",family:"mistral",tier:"economy",description:"Mistral AI 7B instruction-tuned model",releaseDate:"2023-09-27",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},mixtral:{name:"Mixtral",family:"mistral",tier:"standard",description:"Mistral AI mixture of experts model",releaseDate:"2023-12-11",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},phi3:{name:"Phi-3",family:"phi",tier:"economy",description:"Microsoft small language model, efficient",releaseDate:"2024-04-23",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},qwen2:{name:"Qwen 2",family:"qwen",tier:"economy",description:"Alibaba multilingual model",releaseDate:"2024-06-07",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}}};function pe(g){let t=ne(g),e=be[t];if(!e)throw new Error(`Model not found in registry: ${g}`);return{...e.capabilities}}var ke={model:"claude-sonnet-4-6",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,anthropicVersion:"2023-06-01",enableCache:!0,enableCircuitBreaker:!0},B=class{type="claude";name="Anthropic Claude";config;requestId=0;constructor(t={}){this.config={...ke,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set ANTHROPIC_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),s=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:s,models:this.getSupportedModels(),details:{apiVersion:this.config.anthropicVersion,defaultModel:this.config.model}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("Anthropic API key not configured","API_KEY_MISSING",{provider:"claude",retryable:!1});let s=this.formatMessages(t),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,u=`claude-${++this.requestId}-${Date.now()}`,m=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.systemPrompt&&(h.system=this.config.enableCache!==!1?[{type:"text",text:e.systemPrompt,cache_control:{type:"ephemeral"}}]:e.systemPrompt),e?.stopSequences&&e.stopSequences.length>0&&(h.stop_sequences=e.stopSequences);try{if(pe(n).supportsEffortXHigh){let p=ue({override:e?.effort}),l=le(p,"xhigh");h.thinking={type:"adaptive",effort:l}}}catch{}try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/messages`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-m;if(!c.ok){let k=await c.json().catch(()=>({error:{message:"Unknown error"}}));throw this.handleApiError(c.status,k,n)}let l=await c.json(),d=l.usage.cache_creation_input_tokens??0,y=l.usage.cache_read_input_tokens??0,b={promptTokens:l.usage.input_tokens,completionTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+d+y+l.usage.output_tokens,cacheCreationTokens:d,cacheReadTokens:y},f=M.calculateCost(n,b);return C.recordTokenUsage(u,"claude-provider","llm","generate",{inputTokens:l.usage.input_tokens,outputTokens:l.usage.output_tokens,totalTokens:l.usage.input_tokens+l.usage.output_tokens,estimatedCostUsd:f.totalCost}),{content:l.content.filter(k=>k.type==="text").map(k=>k.text).join(""),model:l.model,provider:"claude",usage:b,cost:f,latencyMs:p,finishReason:this.mapFinishReason(l.stop_reason),cached:!1,requestId:u}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"claude",model:n,retryable:!0,cause:c})}}async embed(t,e){throw a("Claude does not support native embeddings. Use OpenAI or Ollama for embeddings.","MODEL_NOT_FOUND",{provider:"claude",retryable:!1})}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
3
3
|
|
|
4
4
|
`,"```"]});return{completion:r.content,model:r.model,provider:"claude",usage:r.usage,latencyMs:r.latencyMs,cached:r.cached}}getConfig(){return{...this.config}}getSupportedModels(){return["claude-opus-4-7","claude-sonnet-4-6","claude-haiku-4-5-20251001","claude-3-opus-20240229","claude-3-sonnet-20240229","claude-3-haiku-20240307"]}getCostPerToken(){return M.getCostPerToken(this.config.model)}async dispose(){}getApiKey(){return this.config.apiKey??process.env.ANTHROPIC_API_KEY}getBaseUrl(){return(this.config.baseUrl??process.env.ANTHROPIC_BASE_URL??"https://api.anthropic.com").replace(/\/$/,"")}getHeaders(){return{"Content-Type":"application/json","x-api-key":this.getApiKey(),"anthropic-version":this.config.anthropicVersion??"2023-06-01"}}formatMessages(t){return typeof t=="string"?[{role:"user",content:t}]:t.filter(e=>e.role!=="system").map(e=>({role:e.role,content:e.content}))}mapFinishReason(t){switch(t){case"end_turn":return"stop";case"max_tokens":return"length";case"stop_sequence":return"stop";default:return"stop"}}handleApiError(t,e,r){let s="error"in e?e.error?.message??"Unknown API error":"Unknown API error",n="error"in e&&"type"in e.error?e.error.type:"";switch(t){case 401:throw a(s,"API_KEY_INVALID",{provider:"claude",model:r,retryable:!1});case 429:throw a(s,"RATE_LIMITED",{provider:"claude",model:r,retryable:!0,retryAfterMs:6e4});case 400:throw n==="invalid_request_error"&&s.includes("context")?a(s,"CONTEXT_LENGTH_EXCEEDED",{provider:"claude",model:r,retryable:!1}):a(s,"UNKNOWN",{provider:"claude",model:r,retryable:!1});case 500:case 502:case 503:throw a(s,"PROVIDER_UNAVAILABLE",{provider:"claude",model:r,retryable:!0,retryAfterMs:5e3});default:throw a(s,"UNKNOWN",{provider:"claude",model:r,retryable:!1})}}async fetchWithTimeout(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{return await fetch(t,{...e,signal:s.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?a("Request timed out","TIMEOUT",{provider:"claude",retryable:!0}):o}finally{clearTimeout(n)}}async fetchWithRetry(t,e,r,s){let n;for(let o=0;o<s;o++)try{let i=await this.fetchWithTimeout(t,e,r);if(i.status>=400&&i.status<500&&i.status!==429)return i;if((i.status>=500||i.status===429)&&o<s-1){let u=T(o);await this.sleep(u);continue}return i}catch(i){if(n=v(i),o<s-1){let u=T(o);await this.sleep(u)}}throw n??new Error("Request failed after retries")}sleep(t){return new Promise(e=>setTimeout(e,t))}};O();var Te={model:"gpt-4o",maxTokens:4096,temperature:.7,timeoutMs:6e4,maxRetries:3,enableCache:!0,enableCircuitBreaker:!0},G=class{type="openai";name="OpenAI";config;requestId=0;constructor(t={}){this.config={...Te,...t}}async isAvailable(){if(!this.getApiKey())return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(!this.getApiKey())return{healthy:!1,error:"API key not configured. Set OPENAI_API_KEY environment variable."};let e=Date.now();try{let r=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:this.config.model,max_tokens:1,messages:[{role:"user",content:"Hi"}]})},5e3),s=Date.now()-e;if(!r.ok){let n=await r.text();return{healthy:!1,latencyMs:s,error:`API error: ${r.status} - ${n}`}}return{healthy:!0,latencyMs:s,models:this.getSupportedModels(),details:{defaultModel:this.config.model,organization:this.config.organization}}}catch(r){return{healthy:!1,error:r instanceof Error?r.message:"Unknown error"}}}async generate(t,e){if(!this.getApiKey())throw a("OpenAI API key not configured","API_KEY_MISSING",{provider:"openai",retryable:!1});let s=this.formatMessages(t,e?.systemPrompt),n=e?.model??this.config.model,o=e?.maxTokens??this.config.maxTokens??4096,i=e?.temperature??this.config.temperature??.7,u=`openai-${++this.requestId}-${Date.now()}`,m=Date.now(),h={model:n,max_tokens:o,temperature:i,messages:s};e?.stopSequences&&e.stopSequences.length>0&&(h.stop=e.stopSequences),this.config.presencePenalty!==void 0&&(h.presence_penalty=this.config.presencePenalty),this.config.frequencyPenalty!==void 0&&(h.frequency_penalty=this.config.frequencyPenalty);try{let c=await this.fetchWithRetry(`${this.getBaseUrl()}/v1/chat/completions`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify(h)},e?.timeoutMs??this.config.timeoutMs??6e4,this.config.maxRetries??3),p=Date.now()-m;if(!c.ok){let f=await c.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(c.status,f,n)}let l=await c.json(),d={promptTokens:l.usage.prompt_tokens,completionTokens:l.usage.completion_tokens,totalTokens:l.usage.total_tokens},y=M.calculateCost(n,d);return C.recordTokenUsage(u,"openai-provider","llm","generate",{inputTokens:l.usage.prompt_tokens,outputTokens:l.usage.completion_tokens,totalTokens:l.usage.total_tokens,estimatedCostUsd:y.totalCost}),{content:l.choices[0]?.message?.content??"",model:l.model,provider:"openai",usage:d,cost:y,latencyMs:p,finishReason:this.mapFinishReason(l.choices[0]?.finish_reason),cached:!1,requestId:u}}catch(c){throw c instanceof Error&&"code"in c?c:a(c instanceof Error?c.message:"Request failed","NETWORK_ERROR",{provider:"openai",model:n,retryable:!0,cause:c})}}async embed(t,e){if(!this.getApiKey())throw a("OpenAI API key not configured","API_KEY_MISSING",{provider:"openai",retryable:!1});let s=e?.model??"text-embedding-3-small",n=Date.now();try{let o=await this.fetchWithTimeout(`${this.getBaseUrl()}/v1/embeddings`,{method:"POST",headers:this.getHeaders(),body:JSON.stringify({model:s,input:t})},e?.timeoutMs??this.config.timeoutMs??3e4),i=Date.now()-n;if(!o.ok){let m=await o.json().catch(()=>({error:{message:"Unknown error",type:"unknown",code:null}}));throw this.handleApiError(o.status,m,s)}let u=await o.json();return{embedding:u.data[0].embedding,model:u.model,provider:"openai",tokenCount:u.usage.total_tokens,latencyMs:i,cached:!1}}catch(o){throw o instanceof Error&&"code"in o?o:a(o instanceof Error?o.message:"Embedding request failed","NETWORK_ERROR",{provider:"openai",model:s,retryable:!0,cause:o})}}async complete(t,e){let r=await this.generate(t,{model:e?.model,temperature:e?.temperature??.2,maxTokens:e?.maxTokens??256,stopSequences:e?.stopSequences??[`
|
|
5
5
|
|
|
@@ -1,14 +1,14 @@
|
|
|
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.
|
|
2
|
-
import{a as
|
|
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.11.0");process.exit(0)}
|
|
2
|
+
import{a as _}from"./chunk-WP6XUSVW.js";import{a as w}from"./chunk-AURDGQNB.js";import{c as k}from"./chunk-YRP73HO4.js";import{i as M,m as U}from"./chunk-QYXTESM3.js";import{b as f,d as P}from"./chunk-Y7TBCHW4.js";import{a as g,c as F}from"./chunk-BA4WZIAQ.js";import{a as R}from"./chunk-ACV2WVMX.js";import{randomUUID as N}from"crypto";U();P();F();var x={alpha:.1,minOutcomes:10,weightFloor:.2,weightCeiling:2},p=class{records=new Map;config;constructor(e){this.config={...x,...e}}recordOutcome(e,t,o){let{alpha:i,minOutcomes:r,weightFloor:s,weightCeiling:n}=this.config,c=this.records.get(e),d=t?1:0,a=Math.max(0,Math.min(1,o)),l,u;c?(l=i*d+(1-i)*c.emaAccuracy,u=i*a+(1-i)*c.emaQuality):(l=d,u=a);let h=(c?.totalOutcomes??0)+1,C;h>=r?C=Math.max(s,Math.min(n,l*2)):C=1;let S={agentId:e,emaAccuracy:l,emaQuality:u,calibratedWeight:C,totalOutcomes:h,lastUpdated:new Date};return this.records.set(e,S),S}getCalibration(e){return this.records.get(e)??null}getCalibratedWeight(e){let t=this.records.get(e);return!t||t.totalOutcomes<this.config.minOutcomes?1:t.calibratedWeight}getAllCalibrations(){return Array.from(this.records.values())}reset(e){e!==void 0?this.records.delete(e):this.records.clear()}serialize(){let e={};for(let[t,o]of this.records)e[t]={...o};return e}deserialize(e){this.records.clear();for(let[t,o]of Object.entries(e))this.records.set(t,{...o,lastUpdated:new Date(o.lastUpdated)})}};var D={escalateAfterFailures:2,deEscalateAfterSuccesses:5,maxTier:"opus",minTier:"haiku"},q=["booster","haiku","sonnet","opus"],b=class{config;tierOrder;states=new Map;constructor(e){this.config={...D,...e},this.tierOrder=this.config.tierOrder??q}tierIndex(e){return this.tierOrder.indexOf(e)}recordOutcome(e,t,o){let i=this.states.get(e);i||(i={agentId:e,currentTier:o,baseTier:o,consecutiveFailures:0,consecutiveSuccesses:0,escalationCount:0,deEscalationCount:0,lastAction:"none",lastActionTimestamp:new Date},this.states.set(e,i));let r=i.currentTier;if(t){if(i.consecutiveSuccesses++,i.consecutiveFailures=0,i.consecutiveSuccesses>=this.config.deEscalateAfterSuccesses){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.minTier);if(s>n)return i.currentTier=this.tierOrder[s-1],i.deEscalationCount++,i.consecutiveSuccesses=0,i.lastAction="de-escalate",i.lastActionTimestamp=new Date,{action:"de-escalate",previousTier:r,newTier:i.currentTier}}}else if(i.consecutiveFailures++,i.consecutiveSuccesses=0,i.consecutiveFailures>=this.config.escalateAfterFailures){let s=this.tierIndex(i.currentTier),n=this.tierIndex(this.config.maxTier);if(s>=0&&s<n)return i.currentTier=this.tierOrder[s+1],i.escalationCount++,i.consecutiveFailures=0,i.lastAction="escalate",i.lastActionTimestamp=new Date,{action:"escalate",previousTier:r,newTier:i.currentTier}}return{action:"none",previousTier:r,newTier:i.currentTier}}getCurrentTier(e){return this.states.get(e)?.currentTier??null}getState(e){return this.states.get(e)??null}getAllStates(){return Array.from(this.states.values())}reset(e){e?this.states.delete(e):this.states.clear()}};var T={booster:{avgInputTokens:0,avgOutputTokens:0,costPerTask:0},haiku:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.0035},sonnet:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.021},opus:{avgInputTokens:2e3,avgOutputTokens:1e3,costPerTask:.105}},v=["booster","haiku","sonnet","opus"],y=T.opus.costPerTask,I={qualityWeight:.6,costWeight:.4,budgetPerHourUsd:0,budgetPerDayUsd:0,minQualityThreshold:.5,enabled:!0},L=.15,E=class{config;costTracker;tierQualityEstimates=new Map;tierOutcomeCounts=new Map;constructor(e,t){let o={...I,...t};o.qualityWeight=Math.max(0,Math.min(1,o.qualityWeight)),o.costWeight=Math.max(0,Math.min(1,o.costWeight)),o.minQualityThreshold=Math.max(0,Math.min(1,o.minQualityThreshold)),o.budgetPerHourUsd=Math.max(0,o.budgetPerHourUsd),o.budgetPerDayUsd=Math.max(0,o.budgetPerDayUsd);let i=o.qualityWeight+o.costWeight;i>0&&i!==1&&(o.qualityWeight/=i,o.costWeight/=i),this.config=o,this.costTracker=e,this.tierQualityEstimates.set("booster",.3),this.tierQualityEstimates.set("haiku",.55),this.tierQualityEstimates.set("sonnet",.75),this.tierQualityEstimates.set("opus",.9)}scoreTiers(e){let t=v.map(o=>{let i=this.getQualityEstimate(o,e),r=T[o].costPerTask,s=r>0?i/r:i>0?1/0:0,n=y>0?1-r/y:1,c=this.config.qualityWeight*i+this.config.costWeight*n;return{tier:o,qualityScore:i,estimatedCostUsd:r,qualityPerDollar:s,economicScore:c}});return t.sort((o,i)=>i.economicScore-o.economicScore),t}selectTier(e){let t=this.scoreTiers(e);for(let r of t)if(!(r.qualityScore<this.config.minQualityThreshold)&&!this.wouldExceedBudget(r.tier))return{tier:r.tier,reason:`Best economic score (${r.economicScore.toFixed(3)}): quality=${r.qualityScore.toFixed(2)}, cost=$${r.estimatedCostUsd.toFixed(4)}`,scores:t};let o=t.filter(r=>r.qualityScore>=this.config.minQualityThreshold);if(o.length>0){let r=[...o].sort((s,n)=>s.estimatedCostUsd-n.estimatedCostUsd)[0];return{tier:r.tier,reason:`Budget constrained fallback to ${r.tier}`,scores:t}}let i=[...t].sort((r,s)=>s.qualityScore-r.qualityScore)[0];return{tier:i.tier,reason:`No tier meets quality threshold ${this.config.minQualityThreshold}; using best quality: ${i.tier}`,scores:t}}wouldExceedBudget(e){let t=T[e].costPerTask;if(t===0)return!1;let o=this.costTracker.getCurrentCost("hour"),i=this.costTracker.getCurrentCost("day");return this.config.budgetPerHourUsd>0&&o+t>this.config.budgetPerHourUsd||this.config.budgetPerDayUsd>0&&i+t>this.config.budgetPerDayUsd}updateFromOutcome(e,t){let o=e.outcome.qualityScore,i=this.tierQualityEstimates.get(t)??.5,r=this.tierOutcomeCounts.get(t)??0,s=r<5?.4:L,n=i*(1-s)+o*s;this.tierQualityEstimates.set(t,n),this.tierOutcomeCounts.set(t,r+1)}getEconomicReport(){let e=this.scoreTiers(.5),t=this.costTracker.getCurrentCost("hour"),o=this.costTracker.getCurrentCost("day"),i={hourly:this.config.budgetPerHourUsd>0?Math.max(0,this.config.budgetPerHourUsd-t):null,daily:this.config.budgetPerDayUsd>0?Math.max(0,this.config.budgetPerDayUsd-o):null},r=null,s=[...e].sort((a,l)=>l.qualityPerDollar-a.qualityPerDollar),n=s.find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar)),c=[...s].reverse().find(a=>a.estimatedCostUsd>0&&isFinite(a.qualityPerDollar));if(n&&c&&n.tier!==c.tier){let a=c.estimatedCostUsd-n.estimatedCostUsd;a>0&&(r={usd:a,description:`Switch from ${c.tier} ($${c.estimatedCostUsd.toFixed(4)}/task) to ${n.tier} ($${n.estimatedCostUsd.toFixed(4)}/task) for comparable tasks to save ~$${a.toFixed(4)}/task`})}let d=this.generateRecommendation(e,i);return{tierEfficiency:e,currentHourlyCostUsd:t,currentDailyCostUsd:o,budgetRemaining:i,recommendation:d,savingsOpportunity:r}}computeCostAdjustedReward(e,t,o){let i=T[t].costPerTask;if(y===0)return e;let r=i/y,s=Math.max(0,o-this.config.minQualityThreshold),n=r*(1-s),c=e-n*this.config.costWeight;return Math.max(-1,Math.min(1,c))}serializeEstimates(){let e={};for(let t of v)e[t]={quality:this.tierQualityEstimates.get(t)??.5,count:this.tierOutcomeCounts.get(t)??0};return e}deserializeEstimates(e){for(let t of v)e[t]&&(this.tierQualityEstimates.set(t,e[t].quality),this.tierOutcomeCounts.set(t,e[t].count))}getConfig(){return{...this.config}}getQualityEstimate(e,t){let o=this.tierQualityEstimates.get(e)??.5,i=e==="booster"?t*.4:e==="haiku"?t*.2:0;return Math.max(0,Math.min(1,o-i))}generateRecommendation(e,t){if(t.hourly!==null&&t.hourly<.01)return"Hourly budget nearly exhausted. Consider increasing budget or routing to cheaper tiers.";if(t.daily!==null&&t.daily<.1)return"Daily budget nearly exhausted. Only critical tasks should use expensive tiers.";let o=e[0];return o?`Most cost-efficient tier: ${o.tier} (score=${o.economicScore.toFixed(3)}, quality=${o.qualityScore.toFixed(2)})`:"No economic data available yet."}};var A=class{outcomes=[];maxOutcomes;constructor(e=1e4){this.maxOutcomes=e}add(e){this.outcomes.push(e),this.outcomes.length>this.maxOutcomes&&(this.outcomes=this.outcomes.slice(-this.maxOutcomes))}getByAgent(e,t=100){return this.outcomes.filter(o=>o.usedAgent===e).slice(-t)}getAll(e=1e3){return this.outcomes.slice(-e)}getRecentOverrides(e=50){return this.outcomes.filter(t=>!t.followedRecommendation).slice(-e)}clear(){this.outcomes=[]}get size(){return this.outcomes.length}},O=class m{static schemaMigrated=!1;outcomeStore;router=null;db=null;calibrator=null;escalationTracker=null;economicModel=null;economicPersistCounter=0;static ECONOMIC_PERSIST_INTERVAL=10;persistCount=0;maxOutcomes;static RETENTION_CLEANUP_INTERVAL=100;constructor(e=1e4,t){this.maxOutcomes=e,this.outcomeStore=new A(e),t?.enableEMACalibration&&this.enableCalibration(),t?.enableAutoEscalation&&this.enableAutoEscalation()}async initialize(){try{this.db=M(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromDb(),this.loadCalibratorState()}catch(e){console.warn("[RoutingFeedbackCollector] DB init failed, using memory-only:",g(e)),this.db=null}}async loadFromDb(){if(!this.db)return;let t=this.db.getDatabase().prepare(`
|
|
3
3
|
SELECT * FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
|
|
4
|
-
`).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}
|
|
4
|
+
`).all(this.maxOutcomes);for(let o of t.reverse()){let i={id:o.id,task:f(o.task_json),decision:f(o.decision_json),usedAgent:o.used_agent,followedRecommendation:!!o.followed_recommendation,outcome:{success:!!o.success,qualityScore:o.quality_score,durationMs:o.duration_ms,error:o.error||void 0},timestamp:new Date(o.created_at),advisorConsultation:o.advisor_consultation_json?f(o.advisor_consultation_json):void 0};this.outcomeStore.add(i)}t.length>0&&console.log(`[RoutingFeedbackCollector] Loaded ${t.length} outcomes from DB`)}persistOutcome(e){if(this.db)try{let t=this.db.getDatabase();if(!m.schemaMigrated){for(let r of["ALTER TABLE routing_outcomes ADD COLUMN model_tier TEXT","ALTER TABLE routing_outcomes ADD COLUMN advisor_consultation_json TEXT"])try{t.prepare(r).run()}catch{}_(t),m.schemaMigrated=!0}let o=this.inferTier(e.usedAgent),i=e.advisorConsultation?JSON.stringify(e.advisorConsultation):null;t.prepare(`
|
|
5
5
|
INSERT OR REPLACE INTO routing_outcomes (
|
|
6
6
|
id, task_json, decision_json, used_agent,
|
|
7
7
|
followed_recommendation, success, quality_score,
|
|
8
8
|
duration_ms, error, model_tier, advisor_consultation_json
|
|
9
9
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
10
|
-
`).run(e.id,JSON.stringify(e.task),JSON.stringify(e.decision),e.usedAgent,e.followedRecommendation?1:0,e.outcome.success?1:0,e.outcome.qualityScore,e.outcome.durationMs,e.outcome.error||null,o,i),this.persistCount++,this.persistCount%m.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[RoutingFeedbackCollector] Failed to persist outcome:",g(t))}}loadAdvisorConsultationSidecar(e){try{let{readdirSync:t,readFileSync:o}=
|
|
10
|
+
`).run(e.id,JSON.stringify(e.task),JSON.stringify(e.decision),e.usedAgent,e.followedRecommendation?1:0,e.outcome.success?1:0,e.outcome.qualityScore,e.outcome.durationMs,e.outcome.error||null,o,i),this.persistCount++,this.persistCount%m.RETENTION_CLEANUP_INTERVAL===0&&this.enforceRetention(t)}catch(t){console.warn("[RoutingFeedbackCollector] Failed to persist outcome:",g(t))}}loadAdvisorConsultationSidecar(e){try{let{readdirSync:t,readFileSync:o}=R("fs"),{join:i}=R("path"),{homedir:r}=R("os"),s=i(r(),".agentic-qe","advisor","consultations"),n=t(s).filter(l=>l.endsWith(".json")).sort().reverse();if(n.length===0)return;let c=n[0],d=JSON.parse(o(i(s,c),"utf-8"));return Date.now()-new Date(d.timestamp).getTime()>300*1e3?void 0:d}catch{return}}inferTier(e){let t=e.toLowerCase();return t.includes("booster")||t==="tier-0"?"booster":t==="tier-1"||t.includes("haiku")?"haiku":t==="tier-2"||t.includes("sonnet")?"sonnet":t.includes("opus")?"opus":"sonnet"}enforceRetention(e){try{let t=this.maxOutcomes*2;e.prepare(`
|
|
11
11
|
DELETE FROM routing_outcomes WHERE id NOT IN (
|
|
12
12
|
SELECT id FROM routing_outcomes ORDER BY created_at DESC LIMIT ?
|
|
13
13
|
)
|
|
14
|
-
`).run(t)}catch(t){console.warn("[RoutingFeedbackCollector] Retention cleanup failed:",g(t))}}loadCalibratorState(){if(!(!this.db||!this.calibrator))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:ema_calibrator_state'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.calibrator.deserialize(o),console.log("[RoutingFeedbackCollector] Loaded EMA calibrator state from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load calibrator state:",g(e))}}persistCalibratorState(){if(!(!this.db||!this.calibrator))try{let e=this.db.getDatabase(),t=JSON.stringify(this.calibrator.serialize());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:ema_calibrator_state",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist calibrator state:",g(e))}}loadEconomicState(){if(!(!this.db||!this.economicModel))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:economic_quality_estimates'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.economicModel.deserializeEstimates(o),console.log("[RoutingFeedbackCollector] Loaded economic quality estimates from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load economic state:",g(e))}}persistEconomicState(){if(!(!this.db||!this.economicModel))try{let e=this.db.getDatabase(),t=JSON.stringify(this.economicModel.serializeEstimates());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:economic_quality_estimates",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist economic state:",g(e))}}connectRouter(e){this.router=e}enableCalibration(e){this.calibrator=new p(e)}getCalibratedWeight(e){return this.calibrator?.getCalibratedWeight(e)??1}enableAutoEscalation(e){this.escalationTracker=new b(e)}getEscalationState(e){return this.escalationTracker?.getState(e)??null}enableEconomicRouting(e,t){let o=t??
|
|
14
|
+
`).run(t)}catch(t){console.warn("[RoutingFeedbackCollector] Retention cleanup failed:",g(t))}}loadCalibratorState(){if(!(!this.db||!this.calibrator))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:ema_calibrator_state'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.calibrator.deserialize(o),console.log("[RoutingFeedbackCollector] Loaded EMA calibrator state from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load calibrator state:",g(e))}}persistCalibratorState(){if(!(!this.db||!this.calibrator))try{let e=this.db.getDatabase(),t=JSON.stringify(this.calibrator.serialize());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:ema_calibrator_state",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist calibrator state:",g(e))}}loadEconomicState(){if(!(!this.db||!this.economicModel))try{let t=this.db.getDatabase().prepare("SELECT value FROM kv_store WHERE key = 'routing:economic_quality_estimates'").get();if(t){let o=f(t.value);o&&typeof o=="object"&&(this.economicModel.deserializeEstimates(o),console.log("[RoutingFeedbackCollector] Loaded economic quality estimates from DB"))}}catch(e){console.warn("[RoutingFeedbackCollector] Failed to load economic state:",g(e))}}persistEconomicState(){if(!(!this.db||!this.economicModel))try{let e=this.db.getDatabase(),t=JSON.stringify(this.economicModel.serializeEstimates());e.prepare("INSERT OR REPLACE INTO kv_store (key, value, updated_at) VALUES (?, ?, datetime('now'))").run("routing:economic_quality_estimates",t)}catch(e){console.warn("[RoutingFeedbackCollector] Failed to persist economic state:",g(e))}}connectRouter(e){this.router=e}enableCalibration(e){this.calibrator=new p(e)}getCalibratedWeight(e){return this.calibrator?.getCalibratedWeight(e)??1}enableAutoEscalation(e){this.escalationTracker=new b(e)}getEscalationState(e){return this.escalationTracker?.getState(e)??null}enableEconomicRouting(e,t){let o=t??k();this.economicModel=new E(o,e),this.loadEconomicState()}getEconomicReport(){return this.economicModel?.getEconomicReport()??null}getEconomicScore(e){return this.economicModel?.scoreTiers(e)??null}recordOutcome(e,t,o,i,r){let s=r;s||(s=this.loadAdvisorConsultationSidecar(e));let n={id:`outcome-${Date.now()}-${N().slice(0,8)}`,task:e,decision:t,usedAgent:o,followedRecommendation:o===t.recommended,outcome:i,timestamp:new Date,advisorConsultation:s};if(this.outcomeStore.add(n),this.persistOutcome(n),this.router&&this.router.updateAgentPerformance(o,i.success,i.qualityScore,i.durationMs),this.calibrator&&(this.calibrator.recordOutcome(o,i.success,i.qualityScore),this.persistCount%10===0&&this.persistCalibratorState()),this.escalationTracker){let c=t.recommended===o?"sonnet":"haiku",d=this.escalationTracker.recordOutcome(o,i.success,c);d.action!=="none"&&console.log(`[RoutingFeedbackCollector] Agent "${o}" ${d.action}d: ${d.previousTier} \u2192 ${d.newTier}`)}if(this.economicModel){let c=this.inferTier(o);this.economicModel.updateFromOutcome(n,c),this.economicPersistCounter++,this.economicPersistCounter%m.ECONOMIC_PERSIST_INTERVAL===0&&this.persistEconomicState()}return n}getAgentMetrics(e){let t=this.outcomeStore.getByAgent(e);if(t.length===0)return null;let o=t.filter(u=>u.outcome.success).length,i=t.reduce((u,h)=>u+h.outcome.durationMs,0),r=t.reduce((u,h)=>u+h.outcome.qualityScore,0),s=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.decision.recommended===e).length,n=t.filter(u=>u.decision.recommended!==u.usedAgent&&u.usedAgent===e).length,c=t.slice(-10),d=c.filter(u=>u.outcome.success).length/c.length,a=o/t.length,l;return d>a+.1?l="improving":d<a-.1?l="declining":l="stable",{agentId:e,totalTasks:t.length,successfulTasks:o,successRate:o/t.length,avgQualityScore:r/t.length,avgDurationMs:i/t.length,overriddenCount:s,selectedOverOthersCount:n,trend:l,updatedAt:new Date}}getAllAgentMetrics(){let e=[];for(let t of w){let o=this.getAgentMetrics(t.id);o&&e.push(o)}return e.sort((t,o)=>o.successRate-t.successRate)}analyzeRoutingAccuracy(){let e=this.outcomeStore.getAll();if(e.length===0)return{totalOutcomes:0,followedRecommendations:0,overrideRate:0,recommendationSuccessRate:0,overrideSuccessRate:0,confidenceCorrelation:0};let t=e.filter(n=>n.followedRecommendation),o=e.filter(n=>!n.followedRecommendation),i=t.filter(n=>n.outcome.success).length,r=o.filter(n=>n.outcome.success).length,s=this.calculateConfidenceCorrelation(e);return{totalOutcomes:e.length,followedRecommendations:t.length,overrideRate:o.length/e.length,recommendationSuccessRate:t.length>0?i/t.length:0,overrideSuccessRate:o.length>0?r/o.length:0,confidenceCorrelation:s}}calculateConfidenceCorrelation(e){if(e.length<2)return 0;let t=e.map(a=>a.decision.confidence),o=e.map(a=>a.outcome.success?1:0),i=t.reduce((a,l)=>a+l,0)/t.length,r=o.reduce((a,l)=>a+l,0)/o.length,s=0,n=0,c=0;for(let a=0;a<e.length;a++){let l=t[a]-i,u=o[a]-r;s+=l*u,n+=l*l,c+=u*u}let d=Math.sqrt(n*c);return d===0?0:s/d}getImprovementRecommendations(){let e=[],t=this.analyzeRoutingAccuracy();if(t.totalOutcomes<50)return e.push("Collect more routing outcomes for reliable analysis (at least 50)"),e;t.overrideRate>.3&&t.overrideSuccessRate>t.recommendationSuccessRate&&e.push("Users are frequently overriding recommendations with better results. Consider adjusting routing weights or updating agent capabilities."),t.confidenceCorrelation<.3&&e.push("Low correlation between confidence and success. Consider improving semantic matching or adjusting weight distribution.");let o=this.getAllAgentMetrics(),i=o.filter(s=>s.successRate<.5&&s.totalTasks>=10);i.length>0&&e.push(`Agents with low success rates: ${i.map(s=>s.agentId).join(", ")}. Consider reviewing their capability mappings.`);let r=o.filter(s=>s.trend==="declining"&&s.totalTasks>=10);return r.length>0&&e.push(`Agents with declining performance: ${r.map(s=>s.agentId).join(", ")}. Monitor for potential issues.`),e.length===0&&e.push("Routing performance is healthy. Continue collecting feedback."),e}exportOutcomes(){return this.outcomeStore.getAll()}importOutcomes(e){for(let t of e)this.outcomeStore.add(t)}getStats(){let e=this.outcomeStore.getAll(),t=new Set(e.map(o=>o.usedAgent));return{totalOutcomes:this.outcomeStore.size,uniqueAgentsUsed:t.size,recentOverrides:this.outcomeStore.getRecentOverrides().length}}clear(){this.outcomeStore.clear()}};function re(m=1e4,e){return new O(m,e)}export{b as a,O as b,re 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.
|
|
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.11.0");process.exit(0)}
|
|
2
2
|
import{existsSync as c,readFileSync as f}from"fs";import{join as p,dirname as i}from"path";import{fileURLToPath as s}from"url";function u(o,a=10){let t=i(s(o));for(let r=0;r<a;r++){let n=p(t,"package.json");if(c(n))try{if(JSON.parse(f(n,"utf-8")).name==="agentic-qe")return t}catch{}let e=i(t);if(e===t)break;t=e}return null}export{u as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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.11.0");process.exit(0)}
|
|
2
2
|
var s={"test-generation":/test|spec|describe|it\(|expect|assert|mock|stub|fixture|tdd|bdd/i,"test-execution":/run|execute|parallel|retry|flaky|timeout|worker|orchestrat/i,"coverage-analysis":/coverage|branch|line|uncovered|gap|untested|percentage|sublinear/i,"quality-assessment":/quality|gate|deploy|readiness|metric|threshold|sla|score/i,"defect-intelligence":/defect|bug|predict|root.?cause|regression|failure|incident/i,"requirements-validation":/requirement|bdd|gherkin|testabil|accept|criteri|scenario/i,"code-intelligence":/semantic|knowledge|graph|ast|symbol|reference|impact|depend/i,"security-compliance":/vuln|cve|owasp|xss|sqli|injection|csrf|auth|secret|compliance|sast|dast/i,"contract-testing":/contract|pact|openapi|swagger|graphql|schema|endpoint|api/i,"visual-accessibility":/screenshot|visual|snapshot|pixel|percy|a11y|aria|wcag|screen.?reader|accessible|contrast/i,"chaos-resilience":/chaos|resilience|fault|inject|blast|recover|latency|failure|stress|load/i,"learning-optimization":/learn|pattern|optim|neural|embedding|vector|memory|adapt|train/i};function l(e){for(let[t,a]of Object.entries(s))if(a.test(e))return t;return null}function m(e){let t=[];for(let[a,n]of Object.entries(s))n.test(e)&&t.push(a);return t}function u(e){return e}function d(e){let t=Math.min(e.usageCount/100,1);return e.confidence*.3+t*.2+e.successRate*.5}var c=3;function p(e,t,a=.4){let n=e.tier==="short-term"&&e.successfulUses>=c,r=e.successRate>=.7&&e.confidence>=.6,i=t===void 0||t<a,o;return n?r?i||(o="coherence_violation"):o="low_quality":o="insufficient_usage",{meetsUsageCriteria:n,meetsQualityCriteria:r,meetsCoherenceCriteria:i,blockReason:o}}function y(e){let t=[];if(e.id||t.push("Pattern ID is required"),e.patternType||t.push("Pattern type is required"),e.qeDomain||t.push("QE domain is required"),e.name||t.push("Pattern name is required"),e.template?.content||t.push("Template content is required"),e.confidence!==void 0&&(e.confidence<0||e.confidence>1)&&t.push("Confidence must be between 0 and 1"),e.successRate!==void 0&&(e.successRate<0||e.successRate>1)&&t.push("Success rate must be between 0 and 1"),e.template?.variables){let a=new Set;for(let n of e.template.variables)a.has(n.name)&&t.push(`Duplicate variable name: ${n.name}`),a.add(n.name),e.template.content.includes(`{{${n.name}}}`)||t.push(`Variable ${n.name} not referenced in template`)}return{valid:t.length===0,errors:t}}function f(e,t){let a=e.content;for(let n of e.variables){let r=t[n.name]??n.defaultValue;if(n.required&&r===void 0)throw new Error(`Required variable ${n.name} not provided`);if(r!==void 0){let i=`{{${n.name}}}`,o=typeof r=="object"?JSON.stringify(r):String(r);a=a.split(i).join(o)}}return a}var g=Object.keys(s);export{l as a,m as b,u as c,d,c as e,p as f,y as g,f as h,g as i};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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.11.0");process.exit(0)}
|
|
2
|
+
import{a as W}from"./chunk-JQSA6EMI.js";import{c as V,d as q}from"./chunk-ETGEGMYS.js";import{c as M}from"./chunk-N52ZBTPM.js";import{a as G}from"./chunk-C4OYHUJV.js";import{c as N}from"./chunk-F62ZQZQQ.js";import{b as D,d as $}from"./chunk-Y7TBCHW4.js";import{a as E,c as H}from"./chunk-BA4WZIAQ.js";import{i as y}from"./chunk-JN3IQB4L.js";import{a as R,b as U,d as ee}from"./chunk-G5VE3HQW.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-HZSYCVLC.js";import{c as V,d as q}from"./chunk-QHPLU5
|
|
|
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-JYZSSQJC.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-W4JSFBMV.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-HZSYCVLC.js";import{c as V,d as q}from"./chunk-QHPLU5
|
|
|
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-JYZSSQJC.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-MHPUZIMW.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-MHPUZIMW.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-ITLDYHCX.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-W4JSFBMV.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-Q4PM3QCN.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-Q4PM3QCN.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-R5WK5BXQ.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};
|