agentic-qe 3.9.31 → 3.9.32
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/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +88 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-CDQOF5TF.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-AQXZYWZY.js → agent-booster-wasm-WKS3E6KT.js} +2 -2
- package/dist/cli/chunks/{agent-handler-7N4ZPXCY.js → agent-handler-LYCAWE7S.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-FLKF2JVX.js → agent-memory-branch-XF7IOMRK.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +2 -0
- package/dist/cli/chunks/{audit-B4V4IKTA.js → audit-D2AY3HFP.js} +2 -2
- package/dist/cli/chunks/base-UGH6TVO4.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-WENGW3YX.js → better-sqlite3-K2VWFDKT.js} +2 -2
- package/dist/cli/chunks/{brain-handler-OOXJ2KYY.js → brain-handler-NNW4TAO2.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-LFKFW3A4.js → branch-enumerator-OM5HNZKV.js} +2 -2
- package/dist/cli/chunks/{browser-F72IES2I.js → browser-Y2FU2NV4.js} +2 -2
- package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +2 -0
- package/dist/cli/chunks/{chunk-35SFAIXE.js → chunk-2L5GAOST.js} +2 -2
- package/dist/cli/chunks/{chunk-MAJ5QFVY.js → chunk-2XC4XVCI.js} +1 -1
- package/dist/cli/chunks/{chunk-QEJBJST4.js → chunk-2Z2IQBIJ.js} +1 -1
- package/dist/cli/chunks/{chunk-AKFRM4IO.js → chunk-33PGBYTC.js} +2 -2
- package/dist/cli/chunks/{chunk-W7XVEWKQ.js → chunk-3MHWBCSC.js} +1 -1
- package/dist/cli/chunks/{chunk-NBKM7NKX.js → chunk-3R4CMTWF.js} +2 -2
- package/dist/cli/chunks/{chunk-4N736EES.js → chunk-45N22VAB.js} +2 -2
- package/dist/cli/chunks/{chunk-3VKB4HVT.js → chunk-4H4PEZUX.js} +2 -2
- package/dist/cli/chunks/{chunk-CFLA2GBS.js → chunk-4VAZSCTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-JF3U456G.js → chunk-5A6LBGRU.js} +2 -2
- package/dist/cli/chunks/{chunk-TYUIQSSF.js → chunk-5DSANX6S.js} +2 -2
- package/dist/cli/chunks/chunk-5R5WOLZM.js +5 -0
- package/dist/cli/chunks/{chunk-K6MFAVXK.js → chunk-5WR42V5O.js} +2 -2
- package/dist/cli/chunks/{chunk-PUSZ4NBY.js → chunk-5XY6SULI.js} +2 -2
- package/dist/cli/chunks/{chunk-VOOJDHLI.js → chunk-62UXGD5J.js} +3 -3
- package/dist/cli/chunks/{chunk-REJEFTWX.js → chunk-667I4RTC.js} +1 -1
- package/dist/cli/chunks/{chunk-KXRDQQGN.js → chunk-6EKXBWJD.js} +2 -2
- package/dist/cli/chunks/{chunk-CNKOIHF6.js → chunk-6R6QCGNU.js} +2 -2
- package/dist/cli/chunks/{chunk-YEZJE2ZW.js → chunk-6SYP7QX6.js} +4 -4
- package/dist/cli/chunks/{chunk-TLCCM2AF.js → chunk-6YGFAJ3X.js} +1 -1
- package/dist/cli/chunks/{chunk-KJAIE7SL.js → chunk-6ZG6TBWF.js} +4 -4
- package/dist/cli/chunks/{chunk-NLUBN642.js → chunk-7AISRWBS.js} +2 -2
- package/dist/cli/chunks/{chunk-LF5RO6WO.js → chunk-7IDPVSTF.js} +1 -1
- package/dist/cli/chunks/{chunk-VUL5HIKR.js → chunk-7PTW3M67.js} +2 -2
- package/dist/cli/chunks/{chunk-QGLWFZVQ.js → chunk-A4UNK5SY.js} +2 -2
- package/dist/cli/chunks/{chunk-JRIDPOEZ.js → chunk-A6VI5BZU.js} +4 -4
- package/dist/cli/chunks/{chunk-7OVVBBOZ.js → chunk-BBPOTFIY.js} +2 -2
- package/dist/cli/chunks/{chunk-AKJWBJDK.js → chunk-BDXEL3GM.js} +2 -2
- package/dist/cli/chunks/{chunk-GJSH4UZ3.js → chunk-BGRC4676.js} +3 -3
- package/dist/cli/chunks/{chunk-PSF6YQQM.js → chunk-BQML7B4W.js} +3 -3
- package/dist/cli/chunks/{chunk-VAIOZDG5.js → chunk-BV3SGEV7.js} +1 -1
- package/dist/cli/chunks/{chunk-XNJ6DIEW.js → chunk-DBE2LIYG.js} +2 -2
- package/dist/cli/chunks/{chunk-AQN6PDHI.js → chunk-DFY7F4TE.js} +1 -1
- package/dist/cli/chunks/{chunk-IRRGUXAU.js → chunk-EFEJLZDN.js} +1 -1
- package/dist/cli/chunks/{chunk-5G2L4XRU.js → chunk-ESNBKAT6.js} +2 -2
- package/dist/cli/chunks/{chunk-7UHRT5AX.js → chunk-EVSUZKD5.js} +2 -2
- package/dist/cli/chunks/{chunk-FUHPLXJX.js → chunk-FFBF5BLQ.js} +1 -1
- package/dist/cli/chunks/{chunk-N6P7ENG7.js → chunk-FIONYUVH.js} +2 -2
- package/dist/cli/chunks/{chunk-TJGIIGKL.js → chunk-FNQCWEVJ.js} +2 -2
- package/dist/cli/chunks/{chunk-NTVJKQ5S.js → chunk-FV2MU6CY.js} +2 -2
- package/dist/cli/chunks/{chunk-M6RVKGIP.js → chunk-FWEYOD3S.js} +2 -2
- package/dist/cli/chunks/{chunk-EAIPJSKH.js → chunk-G6AJMFWL.js} +3 -3
- package/dist/cli/chunks/{chunk-L7DNPOAQ.js → chunk-G6VVOUUF.js} +2 -2
- package/dist/cli/chunks/{chunk-BYHUGO73.js → chunk-G77CYF7H.js} +3 -3
- package/dist/cli/chunks/{chunk-EJXRBAQF.js → chunk-H7YKTJMY.js} +2 -2
- package/dist/cli/chunks/{chunk-CUSLB7MB.js → chunk-HGWQC7PR.js} +2 -2
- package/dist/cli/chunks/{chunk-XE4YKDIM.js → chunk-HHBFI3YA.js} +2 -2
- package/dist/cli/chunks/{chunk-PTOTOBOU.js → chunk-HPQZSXED.js} +1 -1
- package/dist/cli/chunks/{chunk-YN7HCVUP.js → chunk-HR6NX6DW.js} +2 -2
- package/dist/cli/chunks/{chunk-QITO7E7Y.js → chunk-I6Q6BPVH.js} +1 -1
- package/dist/cli/chunks/{chunk-L63KB63A.js → chunk-IGEZVFOM.js} +2 -2
- package/dist/cli/chunks/{chunk-ENCFLC44.js → chunk-IGQPGXP7.js} +2 -2
- package/dist/cli/chunks/{chunk-YMN4C32S.js → chunk-IJQJV7BC.js} +3 -3
- package/dist/cli/chunks/chunk-JDW6GN3A.js +2 -0
- package/dist/cli/chunks/{chunk-LRWRFKQH.js → chunk-JRYNHFZA.js} +1 -1
- package/dist/cli/chunks/{chunk-7V7TP242.js → chunk-KHZRNJ3A.js} +1 -1
- package/dist/cli/chunks/{chunk-PYYNY7RJ.js → chunk-LHDTXTS7.js} +1 -1
- package/dist/cli/chunks/{chunk-ONMJJ2C3.js → chunk-LI2IOJMM.js} +1 -1
- package/dist/cli/chunks/{heartbeat-scheduler-OH3SS7MH.js → chunk-LR5VW3OS.js} +2 -2
- package/dist/cli/chunks/{chunk-XY3WUGD3.js → chunk-LTSNDM5N.js} +2 -2
- package/dist/cli/chunks/{chunk-CQWZNVIM.js → chunk-M5PYPGBC.js} +2 -2
- package/dist/cli/chunks/{chunk-RTGNWRQI.js → chunk-MEHNT37H.js} +2 -2
- package/dist/cli/chunks/{chunk-ZG4EKPGV.js → chunk-MERMCKPG.js} +1 -1
- package/dist/cli/chunks/{chunk-JKKV5KKS.js → chunk-MIHQIAVK.js} +2 -2
- package/dist/cli/chunks/{chunk-RDJWUKIR.js → chunk-MMVSERJQ.js} +2 -2
- package/dist/cli/chunks/{chunk-5WWQLPB4.js → chunk-MQQANXFS.js} +2 -2
- package/dist/cli/chunks/{chunk-I3TFGMOQ.js → chunk-MTOHV22P.js} +1 -1
- package/dist/cli/chunks/{chunk-7RPEBKQZ.js → chunk-NVZHCAEB.js} +2 -2
- package/dist/cli/chunks/{chunk-52D3CYE5.js → chunk-NW5FYGDE.js} +2 -2
- package/dist/cli/chunks/{chunk-UIRTXM7C.js → chunk-NZRJWK5H.js} +61 -121
- package/dist/cli/chunks/chunk-O5NEZCTB.js +2 -0
- package/dist/cli/chunks/{chunk-YQJBE6NX.js → chunk-O5UGJ3OI.js} +2 -2
- package/dist/cli/chunks/{chunk-WB6TI6Q3.js → chunk-OK2TFTXP.js} +2 -2
- package/dist/cli/chunks/{chunk-NNF3GCGF.js → chunk-OKEHGXIS.js} +2 -2
- package/dist/cli/chunks/{chunk-5AMAJCZS.js → chunk-OKRY4LNE.js} +3 -3
- package/dist/cli/chunks/{chunk-NZQYNUGM.js → chunk-OMOGD2NN.js} +2 -2
- package/dist/cli/chunks/{chunk-X2FLWV5C.js → chunk-ONNTJXU7.js} +2 -2
- package/dist/cli/chunks/{chunk-MYCVU3D3.js → chunk-OPOGZAN5.js} +2 -2
- package/dist/cli/chunks/{chunk-ZBJRNCWX.js → chunk-PG5F2VHA.js} +2 -2
- package/dist/cli/chunks/{chunk-JMLOEW7Y.js → chunk-PHRMWRXA.js} +2 -2
- package/dist/cli/chunks/{chunk-N6SIKSCO.js → chunk-PIXUX2NR.js} +2 -2
- package/dist/cli/chunks/{chunk-IY4P35N3.js → chunk-PLGMPG7S.js} +2 -2
- package/dist/cli/chunks/{chunk-K37CNLQZ.js → chunk-PPS6VN24.js} +1 -1
- package/dist/cli/chunks/{chunk-XMMWYQJK.js → chunk-PQAYCK2U.js} +2 -2
- package/dist/cli/chunks/{chunk-SL4TAJOE.js → chunk-PS6ISBED.js} +2 -2
- package/dist/cli/chunks/{chunk-OXOXNAEZ.js → chunk-QPYNQSWD.js} +2 -2
- package/dist/cli/chunks/{chunk-62KYX5NH.js → chunk-QRTZ67BC.js} +2 -2
- package/dist/cli/chunks/{chunk-DUF733Z7.js → chunk-REW3W3ZW.js} +1 -1
- package/dist/cli/chunks/{chunk-T4DDCMKG.js → chunk-RHXYZ6AZ.js} +127 -127
- package/dist/cli/chunks/{chunk-VLAGWLHF.js → chunk-RZXAXWBD.js} +2 -2
- package/dist/cli/chunks/{chunk-XTWYCMAM.js → chunk-S4M7U6CZ.js} +2 -2
- package/dist/cli/chunks/{chunk-ROEIR3OD.js → chunk-SJETAUZA.js} +1 -1
- package/dist/cli/chunks/{chunk-47QIAHUJ.js → chunk-SLH7LFVY.js} +2 -2
- package/dist/cli/chunks/{chunk-XGBIXRKD.js → chunk-SRJ5N7LD.js} +2 -2
- package/dist/cli/chunks/{chunk-EKYPQ5DX.js → chunk-T5ADVYPH.js} +1 -1
- package/dist/cli/chunks/{chunk-7MXQV7RB.js → chunk-THYGFSTA.js} +2 -2
- package/dist/cli/chunks/{chunk-462MZLJB.js → chunk-TX2DBLTL.js} +1 -1
- package/dist/cli/chunks/{chunk-TVHWI77X.js → chunk-UJMGNO6L.js} +1 -1
- package/dist/cli/chunks/{chunk-YLEMSN46.js → chunk-UUQ3SOKM.js} +1 -1
- package/dist/cli/chunks/{chunk-ZWSRIJ2T.js → chunk-V5RLGPEW.js} +2 -2
- package/dist/cli/chunks/{chunk-CYUGE5ZQ.js → chunk-V6HM2BKJ.js} +1 -1
- package/dist/cli/chunks/{chunk-UIIEZMSM.js → chunk-V7I6FTLG.js} +1 -1
- package/dist/cli/chunks/{chunk-5M4F3PAL.js → chunk-V7ZBPSVG.js} +1 -1
- package/dist/cli/chunks/{chunk-VSKABN3B.js → chunk-VJL7DNUU.js} +2 -2
- package/dist/cli/chunks/{chunk-2NLZXG6V.js → chunk-VKCWWR6C.js} +1 -1
- package/dist/cli/chunks/chunk-VKNCMGOJ.js +29 -0
- package/dist/cli/chunks/{chunk-L4JTTPU7.js → chunk-W2VTHUDK.js} +2 -2
- package/dist/cli/chunks/{chunk-FOAWHNOP.js → chunk-W3JB3G7C.js} +2 -2
- package/dist/cli/chunks/{chunk-A424Z7LA.js → chunk-WQ4MT74X.js} +1 -1
- package/dist/cli/chunks/{chunk-GQFAVT2I.js → chunk-WTNM7NA4.js} +1 -1
- package/dist/cli/chunks/chunk-XB3SIYGU.js +62 -0
- package/dist/cli/chunks/{chunk-HHEIQHLQ.js → chunk-XCUNQ3FK.js} +2 -2
- package/dist/cli/chunks/{chunk-BMS7WFDB.js → chunk-XHQFVTFD.js} +1 -1
- package/dist/cli/chunks/{chunk-QMSDKKYG.js → chunk-YBUUAFKR.js} +1 -1
- package/dist/cli/chunks/{chunk-G2U7Q6V6.js → chunk-YJV6TTCW.js} +2 -2
- package/dist/cli/chunks/{chunk-GN7FUCJH.js → chunk-YUSGT2CU.js} +1 -1
- package/dist/cli/chunks/{chunk-JJRZOLDY.js → chunk-YUTSN5BK.js} +2 -2
- package/dist/cli/chunks/{chunk-G3YKCZWQ.js → chunk-YVMJTBXB.js} +3 -3
- package/dist/cli/chunks/chunk-YVQ4PR4H.js +2 -0
- package/dist/cli/chunks/{chunk-UNXUSYRL.js → chunk-Z2EDNMCQ.js} +2 -2
- package/dist/cli/chunks/{chunk-DMF4Z2M6.js → chunk-ZESMMAKZ.js} +2 -2
- package/dist/cli/chunks/{chunk-VA45HLBF.js → chunk-ZIVOT3B7.js} +2 -2
- package/dist/cli/chunks/{ci-LRTJSZHT.js → ci-NSF6OHB4.js} +2 -2
- package/dist/cli/chunks/{ci-output-LISCHUKD.js → ci-output-ZPDJ42U3.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-7PMP25KZ.js → circuit-breaker-Y2RUJDYG.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-DOW4QVMC.js → claude-flow-setup-OH6G6KM2.js} +2 -2
- package/dist/cli/chunks/client-QQGRKAY7.js +2 -0
- package/dist/cli/chunks/{cline-installer-2NXQGW73.js → cline-installer-IHH4F27G.js} +2 -2
- package/dist/cli/chunks/{code-3X6RWAS7.js → code-SFAHWFTX.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-4ABP5WCP.js → code-index-extractor-GXECMOM2.js} +2 -2
- package/dist/cli/chunks/{codex-installer-V7PII6GL.js → codex-installer-UPMSAFCQ.js} +2 -2
- package/dist/cli/chunks/{completions-Y7LNQ63I.js → completions-5TX6LDHY.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-XLYMAM6I.js → complexity-analyzer-J2ZR3XZB.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-GOT4TKNT.js → continuedev-installer-GWYZKB5A.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-D6BAQVIO.js → copilot-installer-DQZMQWI7.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-VT7C5Q52.js → cost-tracker-V7KIGCLZ.js} +2 -2
- package/dist/cli/chunks/{coverage-C62MRP4M.js → coverage-3X6LA2GZ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +2 -0
- package/dist/cli/chunks/{cursor-installer-WAWSS2K2.js → cursor-installer-ENDG4JIU.js} +2 -2
- package/dist/cli/chunks/daemon-4XVAO7GT.js +16 -0
- package/dist/cli/chunks/daemon-TC65CQFK.js +10 -0
- package/dist/cli/chunks/{dag-attention-scheduler-SZIZWPV7.js → dag-attention-scheduler-JOSCDRZC.js} +2 -2
- package/dist/cli/chunks/{detect-AJX6NJEP.js → detect-KWZX3OMK.js} +2 -2
- package/dist/cli/chunks/{dist-node-E5X47QTY.js → dist-node-R4U2PJ47.js} +2 -2
- package/dist/cli/chunks/{domain-handler-FN3PIP45.js → domain-handler-BMYYZO2L.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-N3TOJEMT.js → domain-transfer-MSDBBDLC.js} +2 -2
- package/dist/cli/chunks/dream-OCZK42FM.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-PJI5TZKR.js → embed-and-insert-pattern-MFINPOLS.js} +2 -2
- package/dist/cli/chunks/{eval-OS54TDQU.js → eval-OER6UNUY.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-FBM4ANZW.js → experience-capture-middleware-F5I77ECG.js} +3 -3
- package/dist/cli/chunks/{fast-paths-2CVAAPQO.js → fast-paths-P3KT5DUQ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-A5KFWVFC.js → feature-flags-5EBWQ5WU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-GEXTW6OT.js → feature-flags-DYFZSQLV.js} +2 -2
- package/dist/cli/chunks/{file-discovery-KWLVC7KN.js → file-discovery-MOBVABSM.js} +2 -2
- package/dist/cli/chunks/{fleet-MNKH356S.js → fleet-J3R3NQNC.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-ALTWYFVZ.js → gnn-wrapper-QD76SULF.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-MBMEPEGW.js → heartbeat-handler-AJEWTPZ4.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-EAVZR6TJ.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-BY4XB7FB.js +2 -0
- package/dist/cli/chunks/hnsw-index-657CZRG7.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-WTD5PR5V.js → hnsw-legacy-bridge-5VRM5N7K.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-NYOVLWBG.js → hnswlib-node-BWUH4OQT.js} +2 -2
- package/dist/cli/chunks/{hooks-ELHGEBFK.js → hooks-7PMVKQOE.js} +10 -10
- package/dist/cli/chunks/{hybrid-router-D6ZMIZCE.js → hybrid-router-2K2LW45J.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-JOQ6TERZ.js → hypergraph-engine-2CQ735JO.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-HX45YWWN.js → hypergraph-handler-AQ53GVIW.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +2 -0
- package/dist/cli/chunks/{init-handler-TNVU6NQ6.js → init-handler-ZOVJPAWO.js} +6 -6
- package/dist/cli/chunks/init-wizard-HOH577MH.js +2 -0
- package/dist/cli/chunks/kernel-JDYBG5GE.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-YC5RJIY4.js → kilocode-installer-GWQCNLKI.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-EAB26M55.js → kiro-installer-6KVES4MO.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +2 -0
- package/dist/cli/chunks/{learning-A2OB7D2B.js → learning-6XMNWXRT.js} +3 -3
- package/dist/cli/chunks/{llm-router-KEG6PA7C.js → llm-router-GS4AZJJC.js} +4 -4
- package/dist/cli/chunks/{load-D6ZDLVA3.js → load-FEMEQNE6.js} +2 -2
- package/dist/cli/chunks/load-test-3MEJ43U2.js +2 -0
- package/dist/cli/chunks/{mcp-ERJHZ6FN.js → mcp-6V2H7EXU.js} +2 -2
- package/dist/cli/chunks/{memory-GSRIJIVR.js → memory-YLGPOB2H.js} +5 -5
- package/dist/cli/chunks/memory-backend-2A47ZRGO.js +2 -0
- package/dist/cli/chunks/memory-handlers-UBTBC7D2.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-GK3V7ERC.js → multi-model-executor-SL2EKAH2.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-6TTN26RG.js → opencode-installer-ADOJVGNA.js} +2 -2
- package/dist/cli/chunks/{orchestrator-YVTSM6QW.js → orchestrator-O4IWW2VU.js} +5 -5
- package/dist/cli/chunks/{pipeline-EWLJCY5G.js → pipeline-5BD5YQNQ.js} +2 -2
- package/dist/cli/chunks/{platform-2ULHQQME.js → platform-HXSUOOJH.js} +2 -2
- package/dist/cli/chunks/{plugin-PYN2KOXA.js → plugin-HOLH5CUH.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-IULCTOGZ.js → prime-radiant-advanced-wasm-PJTL7OLS.js} +2 -2
- package/dist/cli/chunks/protocol-executor-3FR7FBVM.js +2 -0
- package/dist/cli/chunks/{protocol-handler-FZYI2SBP.js → protocol-handler-K27YGLC7.js} +2 -2
- package/dist/cli/chunks/{prove-DN7S74SP.js → prove-MHCLHQQ6.js} +2 -2
- package/dist/cli/chunks/{provider-manager-FT3MCROB.js → provider-manager-3645PPXX.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +2 -0
- package/dist/cli/chunks/{quality-ITBU6LGC.js → quality-NDE6EDOY.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +2 -0
- package/dist/cli/chunks/{real-embeddings-PZUZ5RXJ.js → real-embeddings-VD3EVV3U.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-2LMVZOUZ.js → roocode-installer-63Y45UUG.js} +2 -2
- package/dist/cli/chunks/router-23HRN2Z6.js +2 -0
- package/dist/cli/chunks/routing-feedback-R6A4B6ZG.js +2 -0
- package/dist/cli/chunks/{routing-handler-5RB73UCF.js → routing-handler-76XISU2E.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-VBN4APMG.js → ruvector-commands-AEKOZZHZ.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-BNY4AUWT.js → rvf-dual-writer-4DMUIZQF.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-73MKPBGV.js → rvf-migration-adapter-YUTXFOZ3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-SGVB7ZAZ.js → rvf-migration-coordinator-XJ5N2W37.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-QINEJZM7.js +2 -0
- package/dist/cli/chunks/safe-db-YXMCSKFH.js +2 -0
- package/dist/cli/chunks/schedule-XVFD27P5.js +2 -0
- package/dist/cli/chunks/scheduler-NWH2IDEU.js +2 -0
- package/dist/cli/chunks/{security-XUH4H7R3.js → security-6YS6GQGO.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-FTZY35WI.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-GML4EDYF.js → shared-rvf-dual-writer-MH2Y65HA.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-BR6YJF5P.js +2 -0
- package/dist/cli/chunks/{status-handler-XI7GJF6Z.js → status-handler-57JQMPY5.js} +2 -2
- package/dist/cli/chunks/{structural-health-WPCYKOXV.js → structural-health-34D5VWRD.js} +2 -2
- package/dist/cli/chunks/sync-HJD2US5P.js +2 -0
- package/dist/cli/chunks/sync-TTQ6ZB5D.js +17 -0
- package/dist/cli/chunks/{task-handler-FZB55IEG.js → task-handler-4RF57637.js} +2 -2
- package/dist/cli/chunks/{task-handlers-EXZGFH7F.js → task-handlers-BRSK7HDE.js} +3 -3
- package/dist/cli/chunks/{test-XYRN4OVU.js → test-GMUW2VR3.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-FLVOPGOT.js → test-scheduling-7LF24IFV.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-FDCFVRHM.js → token-bootstrap-VYT4RTHU.js} +2 -2
- package/dist/cli/chunks/{token-usage-MHNZF3DM.js → token-usage-NFNCPQGW.js} +2 -2
- package/dist/cli/chunks/{transformers-4CRVTMWY.js → transformers-GGD5GIEY.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-CI3V4AND.js → tree-sitter-wasm-parser-GKYG6NKT.js} +2 -2
- package/dist/cli/chunks/{types-RKCD4BNL.js → types-WJ3ZTRD5.js} +2 -2
- package/dist/cli/chunks/unified-memory-AT3Z4CY7.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-6FOIGINN.js +2 -0
- package/dist/cli/chunks/unified-persistence-TCJB7MQS.js +2 -0
- package/dist/cli/chunks/{upgrade-463W7VKH.js → upgrade-IMBT4F6K.js} +2 -2
- package/dist/cli/chunks/{validate-LENSMEAY.js → validate-76OVF45Z.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-4FEBNAWA.js → validate-swarm-HH2ZYWXA.js} +2 -2
- package/dist/cli/chunks/{vibium-TXNVIVWJ.js → vibium-74WQNDBX.js} +2 -2
- package/dist/cli/chunks/visual-security-IBAUX2K5.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-BZEGWID4.js → web-tree-sitter-W6RGE4SL.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-7AFXJTPU.js → windsurf-installer-7DMSFCA2.js} +2 -2
- package/dist/cli/chunks/{witness-chain-G6SUZOZG.js → witness-chain-BLZ4ZKAD.js} +2 -2
- package/dist/cli/chunks/witness-chain-GNNF23XU.js +2 -0
- package/dist/cli/chunks/{workflow-EVQPO6FH.js → workflow-RNSDKRZ4.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +2 -0
- package/dist/cli/chunks/{wrappers-HR6RUDI2.js → wrappers-J7RXMIOY.js} +2 -2
- package/dist/domains/learning-optimization/services/learning-coordinator.js +37 -17
- package/dist/kernel/hybrid-backend.d.ts +17 -7
- package/dist/kernel/hybrid-backend.js +24 -10
- package/dist/kernel/interfaces.d.ts +21 -6
- package/dist/kernel/memory-backend.d.ts +5 -5
- package/dist/kernel/memory-backend.js +14 -7
- package/dist/mcp/bundle.js +447 -447
- package/dist/mcp/handlers/core-handlers.js +21 -0
- package/dist/workers/interfaces.d.ts +26 -0
- package/dist/workers/worker-manager.d.ts +15 -12
- package/dist/workers/worker-manager.js +11 -0
- package/dist/workers/workers/learning-consolidation.js +116 -89
- package/package.json +3 -1
- package/dist/cli/chunks/adapter-CI2GZYME.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-KNQKALLI.js +0 -2
- package/dist/cli/chunks/base-P7PRMQWY.js +0 -2
- package/dist/cli/chunks/browser-workflow-QUP4A763.js +0 -2
- package/dist/cli/chunks/chunk-5Z6PYYWK.js +0 -2
- package/dist/cli/chunks/chunk-RBDAHW2M.js +0 -2
- package/dist/cli/chunks/client-XF6SJO2C.js +0 -2
- package/dist/cli/chunks/cross-domain-router-J2OFPM6R.js +0 -2
- package/dist/cli/chunks/daemon-CP2ETHRF.js +0 -19
- package/dist/cli/chunks/dream-D5LD5SOZ.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-M2MMM3N6.js +0 -2
- package/dist/cli/chunks/hnsw-index-JO7KNF7M.js +0 -2
- package/dist/cli/chunks/impact-analyzer-ROQL4J7P.js +0 -2
- package/dist/cli/chunks/init-wizard-4BDFZX4M.js +0 -2
- package/dist/cli/chunks/kernel-37Y63WKR.js +0 -2
- package/dist/cli/chunks/knowledge-graph-V3DX6ZCX.js +0 -2
- package/dist/cli/chunks/load-test-HPBA2CMT.js +0 -2
- package/dist/cli/chunks/memory-backend-DODDBB46.js +0 -2
- package/dist/cli/chunks/memory-handlers-MFLCRS7V.js +0 -2
- package/dist/cli/chunks/protocol-executor-D56OYMCJ.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-KXROIEK7.js +0 -2
- package/dist/cli/chunks/queen-coordinator-XOGATERL.js +0 -2
- package/dist/cli/chunks/router-3EHNUCOM.js +0 -2
- package/dist/cli/chunks/routing-feedback-ZHKGET22.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-4YC5IQUW.js +0 -2
- package/dist/cli/chunks/safe-db-PLJRHQIC.js +0 -2
- package/dist/cli/chunks/schedule-7DGELVJE.js +0 -2
- package/dist/cli/chunks/scheduler-VWASEC2J.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-DCVDY2XW.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-CTEBGVOW.js +0 -2
- package/dist/cli/chunks/sync-SFKTCRZC.js +0 -23
- package/dist/cli/chunks/unified-memory-YDKXKW3D.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-6N7YZCLR.js +0 -2
- package/dist/cli/chunks/unified-persistence-UTWLPUQI.js +0 -2
- package/dist/cli/chunks/visual-security-DGXSOFKD.js +0 -2
- package/dist/cli/chunks/witness-chain-VP4MF6EU.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-VXSYAKQY.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{d as s}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.9.32");process.exit(0)}
|
|
2
|
+
import{d as s}from"./chunk-OK2TFTXP.js";s();
|
|
@@ -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.9.
|
|
2
|
-
import{b as d,d as L}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.9.32");process.exit(0)}
|
|
2
|
+
import{b as d,d as L}from"./chunk-THYGFSTA.js";import{createHash as m}from"crypto";import{existsSync as g,readFileSync as R,writeFileSync as A,openSync as X,writeSync as U,closeSync as f}from"fs";var p=[`CREATE TABLE IF NOT EXISTS qe_patterns (
|
|
3
3
|
id TEXT PRIMARY KEY, pattern_type TEXT NOT NULL, qe_domain TEXT NOT NULL,
|
|
4
4
|
domain TEXT NOT NULL, name TEXT NOT NULL, description TEXT,
|
|
5
5
|
confidence REAL DEFAULT 0.5, usage_count INTEGER DEFAULT 0,
|
|
@@ -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.9.
|
|
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.9.32");process.exit(0)}
|
|
2
|
+
import{a as W}from"./chunk-6EKXBWJD.js";import{c as V,d as q}from"./chunk-YVMJTBXB.js";import{c as M}from"./chunk-XCUNQ3FK.js";import{b as D,d as $}from"./chunk-OK2TFTXP.js";import{a as H}from"./chunk-YVQ4PR4H.js";import{c as N}from"./chunk-OMOGD2NN.js";import{a as E,c as G}from"./chunk-5WR42V5O.js";import{i as y}from"./chunk-WTNM7NA4.js";import{a as R,b as U,d as Z}from"./chunk-MQQANXFS.js";var B={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();G();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-KXRDQQGN.js";import{c as V,d as q}from"./chunk-G3YKCZ
|
|
|
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 ee(d){return new A(d)}Z();function te(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=te(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 ne}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=ne().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}}};$();G();H();import{existsSync as ie,unlinkSync as re}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-A5KFWVFC.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&&ie(n)&&re(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}},z=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 z(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 ee(d){return new A(d)}Z();function te(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=te(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 ne}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=ne().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}}};$();G();H();import{existsSync as ie,unlinkSync as re}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-5EBWQ5WU.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&&ie(n)&&re(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}},z=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 z(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-KXRDQQGN.js";import{c as V,d as q}from"./chunk-G3YKCZ
|
|
|
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 ae(d){let e=new _(d);return import("./feature-flags-A5KFWVFC.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-DCVDY2XW.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var se=_;H();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"),K={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},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={...K,...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(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),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 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 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 oe(d,e){return new L(d,e)}var ce=[{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}}],k=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,K as b,L as c,oe as d,B as e,A as f,ee 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,ae as s,se as t,ce as u,k 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 ae(d){let e=new _(d);return import("./feature-flags-5EBWQ5WU.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-FTZY35WI.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var se=_;H();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"),K={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},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={...K,...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(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),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 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 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 oe(d,e){return new L(d,e)}var ce=[{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}}],k=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,K as b,L as c,oe as d,B as e,A as f,ee 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,ae as s,se as t,ce as u,k as v};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as T}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
|
|
2
|
+
import{c as T}from"./chunk-XHQFVTFD.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as M}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.32");process.exit(0)}
|
|
2
|
+
import{a as M}from"./chunk-G6AJMFWL.js";import{f as y,o as T}from"./chunk-THYGFSTA.js";import{a as p,c as S}from"./chunk-5WR42V5O.js";import{i as b}from"./chunk-WTNM7NA4.js";T();S();import*as c from"path";import*as d from"fs";var m=null,u=null,l=null;function R(o){l=o}async function P(){return m||u||(u=(async()=>{let o=y(),e=c.join(o,".agentic-qe");d.existsSync(e)||d.mkdirSync(e,{recursive:!0});let r=new M({sqlite:{path:c.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"mcp-tools"});return await r.initialize(),m=r,r})(),u)}function $(){if(l)try{l()}catch{}m&&(m.dispose().catch(()=>{}),m=null),u=null}async function D(o){return o?.memory?o.memory:P()}var C={info:(o,e)=>console.log(`[MCP-TOOL] ${o}`,e||""),warn:(o,e)=>console.warn(`[MCP-TOOL] \u26A0\uFE0F ${o}`,e||""),error:(o,e)=>console.error(`[MCP-TOOL] \u274C ${o}`,e||"")},h=class{logger=C;currentDataSource="real";setLogger(e){this.logger=e}markAsDemoData(e,r){this.currentDataSource=e.demoMode?"demo":"fallback",this.logger.warn(`${this.config.name} returning ${this.currentDataSource} data`,{reason:r,requestId:e.requestId,demoMode:e.demoMode})}markAsRealData(){this.currentDataSource="real"}isDemoMode(e){return e.demoMode===!0}validate(e){let r=[];if(typeof e!="object"||e===null)return{valid:!1,errors:["Parameters must be an object"]};let t=e,{properties:a,required:n}=this.config.schema;if(n)for(let i of n)i in t||r.push(`Missing required field: ${i}`);for(let[i,s]of Object.entries(t)){let g=a[i];if(!g)continue;let f=this.validateType(i,s,g);f&&r.push(f)}return{valid:r.length===0,errors:r}}validateType(e,r,t){if(r==null)return null;let a=Array.isArray(r)?"array":typeof r;if(t.type==="array"&&!Array.isArray(r))return`${e} must be an array`;if(t.type!=="array"&&a!==t.type)return`${e} must be of type ${t.type}, got ${a}`;if(t.enum&&!t.enum.includes(r))return`${e} must be one of: ${t.enum.join(", ")}`;if(t.type==="number"){let n=r;if(t.minimum!==void 0&&n<t.minimum)return`${e} must be >= ${t.minimum}`;if(t.maximum!==void 0&&n>t.maximum)return`${e} must be <= ${t.maximum}`}if(t.type==="string"){let n=r;if(t.minLength!==void 0&&n.length<t.minLength)return`${e} must be at least ${t.minLength} characters`;if(t.maxLength!==void 0&&n.length>t.maxLength)return`${e} must be at most ${t.maxLength} characters`}return null}async invoke(e,r={}){let t=Date.now(),a=b();this.currentDataSource="real";let n=this.validate(e);if(!n.valid)return{success:!1,error:`Validation failed: ${n.errors.join("; ")}`,metadata:this.createMetadata(t,a)};let i={requestId:a,startTime:t,streaming:r.streaming,onStream:r.onStream,abortSignal:r.abortSignal,demoMode:r.demoMode};try{let s=await this.execute(e,i);return{...s,metadata:{...s.metadata,...this.createMetadata(t,a)}}}catch(s){return{success:!1,error:p(s),metadata:this.createMetadata(t,a)}}}createMetadata(e,r){return{executionTime:Date.now()-e,timestamp:new Date().toISOString(),requestId:r,domain:this.config.domain,toolName:this.config.name,dataSource:this.currentDataSource}}emitStream(e,r){e.streaming&&e.onStream&&e.onStream(r)}isAborted(e){return e.abortSignal?.aborted??!1}get name(){return this.config.name}get description(){return this.config.description}get domain(){return this.config.domain}getSchema(){return this.config.schema}get timeout(){return this.config.timeout??6e4}get supportsStreaming(){return this.config.streaming??!1}resetInstanceCache(){}};export{R as a,P as b,$ as c,D as d,C as e,h as f};
|
|
@@ -1,6 +1,6 @@
|
|
|
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.9.
|
|
2
|
-
import{e as x,f as C,j as y,k as R,q as F}from"./chunk-
|
|
3
|
-
Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-
|
|
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.9.32");process.exit(0)}
|
|
2
|
+
import{e as x,f as C,j as y,k as R,q as F}from"./chunk-3R4CMTWF.js";import{b as I,c as k}from"./chunk-5WR42V5O.js";import{c as w}from"./chunk-XHQFVTFD.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
|
|
3
|
+
Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-74WQNDBX.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
|
|
4
4
|
Array.from(document.querySelectorAll('${t}'))
|
|
5
5
|
.map(el => ({
|
|
6
6
|
tag: el.tagName.toLowerCase(),
|