agentic-qe 3.9.30 → 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 +208 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/bridge/captured-experience-bridge.js +31 -2
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-CDQOF5TF.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-TOSXWTUQ.js → agent-booster-wasm-WKS3E6KT.js} +2 -2
- package/dist/cli/chunks/{agent-handler-2BU6TYZZ.js → agent-handler-LYCAWE7S.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-JFG3BXZY.js → agent-memory-branch-XF7IOMRK.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +2 -0
- package/dist/cli/chunks/{audit-4IGZZKUW.js → audit-D2AY3HFP.js} +2 -2
- package/dist/cli/chunks/base-UGH6TVO4.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-STKRZIU3.js → better-sqlite3-K2VWFDKT.js} +2 -2
- package/dist/cli/chunks/{brain-handler-RIDW27HH.js → brain-handler-NNW4TAO2.js} +4 -4
- package/dist/cli/chunks/{branch-enumerator-GMYHLLWD.js → branch-enumerator-OM5HNZKV.js} +2 -2
- package/dist/cli/chunks/{browser-N76A3I2P.js → browser-Y2FU2NV4.js} +2 -2
- package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +2 -0
- package/dist/cli/chunks/{chunk-ETEHVG76.js → chunk-2L5GAOST.js} +2 -2
- package/dist/cli/chunks/{chunk-ECX6VXMW.js → chunk-2XC4XVCI.js} +1 -1
- package/dist/cli/chunks/{chunk-L7X3A36M.js → chunk-2Z2IQBIJ.js} +1 -1
- package/dist/cli/chunks/{chunk-UYLHIGNC.js → chunk-33PGBYTC.js} +2 -2
- package/dist/cli/chunks/{chunk-OOFWYDG6.js → chunk-3MHWBCSC.js} +1 -1
- package/dist/cli/chunks/{chunk-FI4HRS2G.js → chunk-3R4CMTWF.js} +2 -2
- package/dist/cli/chunks/{chunk-IP6ZTXNJ.js → chunk-45N22VAB.js} +2 -2
- package/dist/cli/chunks/{chunk-FG5GL26L.js → chunk-4H4PEZUX.js} +2 -2
- package/dist/cli/chunks/{chunk-CNNVL5W4.js → chunk-4VAZSCTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-AWWD3EI3.js → chunk-5A6LBGRU.js} +2 -2
- package/dist/cli/chunks/{chunk-ER6BT4GS.js → chunk-5DSANX6S.js} +2 -2
- package/dist/cli/chunks/chunk-5R5WOLZM.js +5 -0
- package/dist/cli/chunks/{chunk-RNO6CE7I.js → chunk-5WR42V5O.js} +2 -2
- package/dist/cli/chunks/{chunk-UEXOMDRS.js → chunk-5XY6SULI.js} +2 -2
- package/dist/cli/chunks/{chunk-WVODEWH5.js → chunk-62UXGD5J.js} +14 -8
- package/dist/cli/chunks/{chunk-EWNJ6OAT.js → chunk-667I4RTC.js} +1 -1
- package/dist/cli/chunks/{chunk-ND6VCNN5.js → chunk-6EKXBWJD.js} +2 -2
- package/dist/cli/chunks/{chunk-Y57V4FDT.js → chunk-6R6QCGNU.js} +2 -2
- package/dist/cli/chunks/{chunk-VRP4GB4Y.js → chunk-6SYP7QX6.js} +4 -4
- package/dist/cli/chunks/{chunk-BFJLKG3D.js → chunk-6YGFAJ3X.js} +1 -1
- package/dist/cli/chunks/{chunk-UWWX4RK7.js → chunk-6ZG6TBWF.js} +4 -4
- package/dist/cli/chunks/{chunk-QSV4ROZD.js → chunk-7AISRWBS.js} +2 -2
- package/dist/cli/chunks/{chunk-SJCEPKZO.js → chunk-7IDPVSTF.js} +1 -1
- package/dist/cli/chunks/{chunk-HQIWLMDS.js → chunk-7PTW3M67.js} +2 -2
- package/dist/cli/chunks/{chunk-TA3QYAZ6.js → chunk-A4UNK5SY.js} +2 -2
- package/dist/cli/chunks/chunk-A6VI5BZU.js +95 -0
- package/dist/cli/chunks/{chunk-XVTZXCHI.js → chunk-BBPOTFIY.js} +2 -2
- package/dist/cli/chunks/{chunk-OEGFOMXP.js → chunk-BDXEL3GM.js} +2 -2
- package/dist/cli/chunks/{chunk-YETPSL6H.js → chunk-BGRC4676.js} +3 -3
- package/dist/cli/chunks/chunk-BQML7B4W.js +180 -0
- package/dist/cli/chunks/{chunk-DEDFPHJL.js → chunk-BV3SGEV7.js} +1 -1
- package/dist/cli/chunks/{chunk-FGMHVSLV.js → chunk-DBE2LIYG.js} +2 -2
- package/dist/cli/chunks/{chunk-2GBBZLXT.js → chunk-DFY7F4TE.js} +1 -1
- package/dist/cli/chunks/{chunk-LDGNVPBZ.js → chunk-EFEJLZDN.js} +1 -1
- package/dist/cli/chunks/{chunk-ZKZTSYPU.js → chunk-ESNBKAT6.js} +2 -2
- package/dist/cli/chunks/{chunk-5F26LSG2.js → chunk-EVSUZKD5.js} +2 -2
- package/dist/cli/chunks/{chunk-QOJ7EAF5.js → chunk-FFBF5BLQ.js} +1 -1
- package/dist/cli/chunks/{chunk-3AICELMQ.js → chunk-FIONYUVH.js} +2 -2
- package/dist/cli/chunks/{chunk-UROPIIB2.js → chunk-FNQCWEVJ.js} +2 -2
- package/dist/cli/chunks/{chunk-5DJAJPBG.js → chunk-FV2MU6CY.js} +2 -2
- package/dist/cli/chunks/{chunk-QTS2DS42.js → chunk-FWEYOD3S.js} +2 -2
- package/dist/cli/chunks/{chunk-XK6YXCS7.js → chunk-G6AJMFWL.js} +3 -3
- package/dist/cli/chunks/{chunk-R57J3O6I.js → chunk-G6VVOUUF.js} +2 -2
- package/dist/cli/chunks/{chunk-2O5TT3UT.js → chunk-G77CYF7H.js} +3 -3
- package/dist/cli/chunks/{chunk-TULNR2AH.js → chunk-H7YKTJMY.js} +2 -2
- package/dist/cli/chunks/{chunk-GEXVUFK4.js → chunk-HGWQC7PR.js} +2 -2
- package/dist/cli/chunks/{chunk-QLNS6DGB.js → chunk-HHBFI3YA.js} +2 -2
- package/dist/cli/chunks/{chunk-WP6X67YI.js → chunk-HPQZSXED.js} +1 -1
- package/dist/cli/chunks/{chunk-HA7N45KB.js → chunk-HR6NX6DW.js} +2 -2
- package/dist/cli/chunks/{chunk-HB52S6IV.js → chunk-I6Q6BPVH.js} +1 -1
- package/dist/cli/chunks/{chunk-BM73MJLE.js → chunk-IGEZVFOM.js} +2 -2
- package/dist/cli/chunks/{chunk-QBDXUI2H.js → chunk-IGQPGXP7.js} +2 -2
- package/dist/cli/chunks/{chunk-Q26GG6WO.js → chunk-IJQJV7BC.js} +3 -3
- package/dist/cli/chunks/chunk-JDW6GN3A.js +2 -0
- package/dist/cli/chunks/{chunk-GZ3U2QT2.js → chunk-JRYNHFZA.js} +1 -1
- package/dist/cli/chunks/{chunk-MV3NUANS.js → chunk-KHZRNJ3A.js} +1 -1
- package/dist/cli/chunks/chunk-LHDTXTS7.js +2 -0
- package/dist/cli/chunks/{chunk-52TRKIAQ.js → chunk-LI2IOJMM.js} +1 -1
- package/dist/cli/chunks/{heartbeat-scheduler-CNJBAO5C.js → chunk-LR5VW3OS.js} +2 -2
- package/dist/cli/chunks/{chunk-2NFGUFYU.js → chunk-LTSNDM5N.js} +2 -2
- package/dist/cli/chunks/{chunk-3EP2YZSY.js → chunk-M5PYPGBC.js} +2 -2
- package/dist/cli/chunks/{chunk-JCWHX4XV.js → chunk-MEHNT37H.js} +2 -2
- package/dist/cli/chunks/{chunk-QHKK2H4H.js → chunk-MERMCKPG.js} +1 -1
- package/dist/cli/chunks/{chunk-Q53UMLLC.js → chunk-MIHQIAVK.js} +2 -2
- package/dist/cli/chunks/{chunk-VOBNJWZF.js → chunk-MMVSERJQ.js} +2 -2
- package/dist/cli/chunks/{chunk-37I6K7QO.js → chunk-MQQANXFS.js} +2 -2
- package/dist/cli/chunks/{chunk-YKFURJNP.js → chunk-MTOHV22P.js} +1 -1
- package/dist/cli/chunks/{chunk-MOLOWMON.js → chunk-NVZHCAEB.js} +2 -2
- package/dist/cli/chunks/{chunk-YXR5RYRE.js → chunk-NW5FYGDE.js} +2 -2
- package/dist/cli/chunks/{chunk-NMBHF7ZD.js → chunk-NZRJWK5H.js} +61 -121
- package/dist/cli/chunks/chunk-O5NEZCTB.js +2 -0
- package/dist/cli/chunks/{chunk-E7UHOKKL.js → chunk-O5UGJ3OI.js} +2 -2
- package/dist/cli/chunks/{chunk-Q4HJRYQB.js → chunk-OK2TFTXP.js} +2 -2
- package/dist/cli/chunks/{chunk-FGDEM4HU.js → chunk-OKEHGXIS.js} +2 -2
- package/dist/cli/chunks/{chunk-C6TNYLD7.js → chunk-OKRY4LNE.js} +3 -3
- package/dist/cli/chunks/{chunk-3WIU2E2Y.js → chunk-OMOGD2NN.js} +2 -2
- package/dist/cli/chunks/{chunk-DJRWVNHK.js → chunk-ONNTJXU7.js} +2 -2
- package/dist/cli/chunks/chunk-OPOGZAN5.js +14 -0
- package/dist/cli/chunks/{chunk-OTFJCZNY.js → chunk-PG5F2VHA.js} +2 -2
- package/dist/cli/chunks/{chunk-MYF7F3ZP.js → chunk-PHRMWRXA.js} +2 -2
- package/dist/cli/chunks/{chunk-7D2DM23U.js → chunk-PIXUX2NR.js} +2 -2
- package/dist/cli/chunks/{chunk-IWC6GR24.js → chunk-PLGMPG7S.js} +2 -2
- package/dist/cli/chunks/{chunk-T2DIMSQF.js → chunk-PPS6VN24.js} +1 -1
- package/dist/cli/chunks/{chunk-AUNNGKLN.js → chunk-PQAYCK2U.js} +2 -2
- package/dist/cli/chunks/{chunk-FU74OETU.js → chunk-PS6ISBED.js} +2 -2
- package/dist/cli/chunks/{chunk-JNRRDG7O.js → chunk-QPYNQSWD.js} +2 -2
- package/dist/cli/chunks/{chunk-MHPK4ZPK.js → chunk-QRTZ67BC.js} +2 -2
- package/dist/cli/chunks/{chunk-Z3TXQOS7.js → chunk-REW3W3ZW.js} +1 -1
- package/dist/cli/chunks/{chunk-3PZDXE5E.js → chunk-RHXYZ6AZ.js} +127 -127
- package/dist/cli/chunks/{chunk-IEGAEXQX.js → chunk-RZXAXWBD.js} +2 -2
- package/dist/cli/chunks/{chunk-4UZQSPR4.js → chunk-S4M7U6CZ.js} +2 -2
- package/dist/cli/chunks/{chunk-H27XUYWZ.js → chunk-SJETAUZA.js} +1 -1
- package/dist/cli/chunks/{chunk-MZ7M2CDV.js → chunk-SLH7LFVY.js} +2 -2
- package/dist/cli/chunks/{chunk-6EP3GHED.js → chunk-SRJ5N7LD.js} +2 -2
- package/dist/cli/chunks/{chunk-XDYTQPJM.js → chunk-T5ADVYPH.js} +1 -1
- package/dist/cli/chunks/{chunk-TYZGEVP6.js → chunk-THYGFSTA.js} +12 -6
- package/dist/cli/chunks/{chunk-XKH4E2IQ.js → chunk-TX2DBLTL.js} +1 -1
- package/dist/cli/chunks/{chunk-HJDHQBMJ.js → chunk-UJMGNO6L.js} +1 -1
- package/dist/cli/chunks/{chunk-MCXRS2TZ.js → chunk-UUQ3SOKM.js} +1 -1
- package/dist/cli/chunks/{chunk-USN2JKUW.js → chunk-V5RLGPEW.js} +2 -2
- package/dist/cli/chunks/chunk-V6HM2BKJ.js +2 -0
- package/dist/cli/chunks/{chunk-R5IW5ARI.js → chunk-V7I6FTLG.js} +1 -1
- package/dist/cli/chunks/{chunk-2MKSEL6F.js → chunk-V7ZBPSVG.js} +1 -1
- package/dist/cli/chunks/{chunk-IOINZWNA.js → chunk-VJL7DNUU.js} +29 -17
- package/dist/cli/chunks/{chunk-JCDEMPJS.js → chunk-VKCWWR6C.js} +1 -1
- package/dist/cli/chunks/chunk-VKNCMGOJ.js +29 -0
- package/dist/cli/chunks/{chunk-GRPEDIYG.js → chunk-W2VTHUDK.js} +2 -2
- package/dist/cli/chunks/{chunk-SAVITYEX.js → chunk-W3JB3G7C.js} +2 -2
- package/dist/cli/chunks/{chunk-WTXRPYNN.js → chunk-WQ4MT74X.js} +1 -1
- package/dist/cli/chunks/{chunk-GY4EGQO3.js → chunk-WTNM7NA4.js} +1 -1
- package/dist/cli/chunks/chunk-XB3SIYGU.js +62 -0
- package/dist/cli/chunks/{chunk-IHRFR5SV.js → chunk-XCUNQ3FK.js} +2 -2
- package/dist/cli/chunks/{chunk-ITBPDVK5.js → chunk-XHQFVTFD.js} +1 -1
- package/dist/cli/chunks/{chunk-KJZXBZQR.js → chunk-YBUUAFKR.js} +1 -1
- package/dist/cli/chunks/{chunk-KR2PGNXX.js → chunk-YJV6TTCW.js} +2 -2
- package/dist/cli/chunks/{chunk-BQLFOJ5G.js → chunk-YUSGT2CU.js} +1 -1
- package/dist/cli/chunks/{chunk-5E3YCZC5.js → chunk-YUTSN5BK.js} +2 -2
- package/dist/cli/chunks/{chunk-DDMFTEJP.js → chunk-YVMJTBXB.js} +3 -3
- package/dist/cli/chunks/chunk-YVQ4PR4H.js +2 -0
- package/dist/cli/chunks/{chunk-RYMHYTOK.js → chunk-Z2EDNMCQ.js} +3 -3
- package/dist/cli/chunks/{chunk-QNSUPXUU.js → chunk-ZESMMAKZ.js} +2 -2
- package/dist/cli/chunks/chunk-ZIVOT3B7.js +2 -0
- package/dist/cli/chunks/{ci-BYCH3NPL.js → ci-NSF6OHB4.js} +2 -2
- package/dist/cli/chunks/{ci-output-P7P4XH6F.js → ci-output-ZPDJ42U3.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-VLX556ZI.js → circuit-breaker-Y2RUJDYG.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-JPR425PL.js → claude-flow-setup-OH6G6KM2.js} +2 -2
- package/dist/cli/chunks/client-QQGRKAY7.js +2 -0
- package/dist/cli/chunks/{cline-installer-FOY47NSH.js → cline-installer-IHH4F27G.js} +2 -2
- package/dist/cli/chunks/{code-57SN4ZDY.js → code-SFAHWFTX.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-GT7UFRYU.js → code-index-extractor-GXECMOM2.js} +2 -2
- package/dist/cli/chunks/{codex-installer-JAGWONAV.js → codex-installer-UPMSAFCQ.js} +2 -2
- package/dist/cli/chunks/{completions-7YLHPGSV.js → completions-5TX6LDHY.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-TQUF6BEI.js → complexity-analyzer-J2ZR3XZB.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-TICV6IGT.js → continuedev-installer-GWYZKB5A.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-A6PDMI52.js → copilot-installer-DQZMQWI7.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-NZPNHNV2.js → cost-tracker-V7KIGCLZ.js} +2 -2
- package/dist/cli/chunks/{coverage-HBEB2LKS.js → coverage-3X6LA2GZ.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +2 -0
- package/dist/cli/chunks/{cursor-installer-R4FM7MGN.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-2L7VCYZ3.js → dag-attention-scheduler-JOSCDRZC.js} +2 -2
- package/dist/cli/chunks/{detect-EEWB4IYE.js → detect-KWZX3OMK.js} +2 -2
- package/dist/cli/chunks/{dist-node-7RM6BB2X.js → dist-node-R4U2PJ47.js} +2 -2
- package/dist/cli/chunks/{domain-handler-RVGHBDUJ.js → domain-handler-BMYYZO2L.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-M5MERQG5.js → domain-transfer-MSDBBDLC.js} +2 -2
- package/dist/cli/chunks/dream-OCZK42FM.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-MS55QS73.js → embed-and-insert-pattern-MFINPOLS.js} +2 -2
- package/dist/cli/chunks/{eval-MBTMI7KN.js → eval-OER6UNUY.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-Z5XB7D6A.js → experience-capture-middleware-F5I77ECG.js} +3 -3
- package/dist/cli/chunks/{fast-paths-FSWLHI4I.js → fast-paths-P3KT5DUQ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-QUPNH2J5.js → feature-flags-5EBWQ5WU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-ATYOPR5D.js → feature-flags-DYFZSQLV.js} +2 -2
- package/dist/cli/chunks/{file-discovery-SOJJEQ2E.js → file-discovery-MOBVABSM.js} +2 -2
- package/dist/cli/chunks/{fleet-PWBTDWVG.js → fleet-J3R3NQNC.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-2N67VQOQ.js → gnn-wrapper-QD76SULF.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-5PSG2UPO.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-YIXH5T4U.js → hnsw-legacy-bridge-5VRM5N7K.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-3U2AVWQ3.js → hnswlib-node-BWUH4OQT.js} +2 -2
- package/dist/cli/chunks/hooks-7PMVKQOE.js +248 -0
- package/dist/cli/chunks/{hybrid-router-RL47S47Z.js → hybrid-router-2K2LW45J.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-XW2IHFWW.js → hypergraph-engine-2CQ735JO.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-AQXKY4UF.js → hypergraph-handler-AQ53GVIW.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +2 -0
- package/dist/cli/chunks/{init-handler-KXYGJQI5.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-VSULDGRO.js → kilocode-installer-GWQCNLKI.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-SH4D2UXW.js → kiro-installer-6KVES4MO.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +2 -0
- package/dist/cli/chunks/learning-6XMNWXRT.js +117 -0
- package/dist/cli/chunks/{llm-router-YXXSQX5K.js → llm-router-GS4AZJJC.js} +4 -4
- package/dist/cli/chunks/{load-S52R2SLL.js → load-FEMEQNE6.js} +2 -2
- package/dist/cli/chunks/load-test-3MEJ43U2.js +2 -0
- package/dist/cli/chunks/{mcp-ZWMAJIU7.js → mcp-6V2H7EXU.js} +2 -2
- package/dist/cli/chunks/{memory-4YTWWDK7.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-F3VEM2UF.js → multi-model-executor-SL2EKAH2.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-Z2CUJQ6D.js → opencode-installer-ADOJVGNA.js} +2 -2
- package/dist/cli/chunks/{orchestrator-UPXR2XOF.js → orchestrator-O4IWW2VU.js} +37 -18
- package/dist/cli/chunks/{pipeline-6MEMAIXM.js → pipeline-5BD5YQNQ.js} +2 -2
- package/dist/cli/chunks/{platform-H72FLOM7.js → platform-HXSUOOJH.js} +2 -2
- package/dist/cli/chunks/{plugin-GIMQFDVR.js → plugin-HOLH5CUH.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-DM5FR5SV.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-YW3N333B.js → protocol-handler-K27YGLC7.js} +2 -2
- package/dist/cli/chunks/{prove-IJY524KK.js → prove-MHCLHQQ6.js} +2 -2
- package/dist/cli/chunks/{provider-manager-FNG6YR2V.js → provider-manager-3645PPXX.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +2 -0
- package/dist/cli/chunks/{quality-EZLAMSCP.js → quality-NDE6EDOY.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +2 -0
- package/dist/cli/chunks/{real-embeddings-MFRCC6GH.js → real-embeddings-VD3EVV3U.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-H3ZIRGWU.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-T2A7FYHW.js → routing-handler-76XISU2E.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-TCLWBP2M.js → ruvector-commands-AEKOZZHZ.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-BE3JCPYC.js → rvf-dual-writer-4DMUIZQF.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-MLUX5YGR.js → rvf-migration-adapter-YUTXFOZ3.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-OAQXTASZ.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-SHWJWJ4M.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-BKSR2FFK.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-QK5KMKYC.js → status-handler-57JQMPY5.js} +2 -2
- package/dist/cli/chunks/{structural-health-3BRNCAYQ.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-VH2CLUIA.js → task-handler-4RF57637.js} +2 -2
- package/dist/cli/chunks/{task-handlers-BUZNV2VX.js → task-handlers-BRSK7HDE.js} +3 -3
- package/dist/cli/chunks/{test-K24JQQZ2.js → test-GMUW2VR3.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-MHXRV5VI.js → test-scheduling-7LF24IFV.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-3NZDLG52.js → token-bootstrap-VYT4RTHU.js} +2 -2
- package/dist/cli/chunks/{token-usage-C4BGA2O7.js → token-usage-NFNCPQGW.js} +2 -2
- package/dist/cli/chunks/{transformers-ZIIFB2V4.js → transformers-GGD5GIEY.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-GES2AV7A.js → tree-sitter-wasm-parser-GKYG6NKT.js} +2 -2
- package/dist/cli/chunks/{types-L3MO5VNC.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-EKJYS5S5.js → upgrade-IMBT4F6K.js} +2 -2
- package/dist/cli/chunks/{validate-WYWWB5PQ.js → validate-76OVF45Z.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-SBSWKJ3H.js → validate-swarm-HH2ZYWXA.js} +2 -2
- package/dist/cli/chunks/{vibium-VEMTLNFV.js → vibium-74WQNDBX.js} +2 -2
- package/dist/cli/chunks/visual-security-IBAUX2K5.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-STW2WR2J.js → web-tree-sitter-W6RGE4SL.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-6ZXMJASZ.js → windsurf-installer-7DMSFCA2.js} +2 -2
- package/dist/cli/chunks/{witness-chain-PTULB4MR.js → witness-chain-BLZ4ZKAD.js} +2 -2
- package/dist/cli/chunks/witness-chain-GNNF23XU.js +2 -0
- package/dist/cli/chunks/{workflow-TEBAAHNR.js → workflow-RNSDKRZ4.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +2 -0
- package/dist/cli/chunks/{wrappers-DVMVRKXK.js → wrappers-J7RXMIOY.js} +2 -2
- package/dist/cli/commands/hooks-handlers/editing-hooks.js +9 -3
- package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +16 -24
- package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +1 -1
- package/dist/cli/commands/hooks-handlers/hooks-shared.js +8 -1
- package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -3
- package/dist/cli/commands/hooks-handlers/task-hooks.js +37 -46
- package/dist/cli/commands/learning.js +194 -0
- package/dist/domains/learning-optimization/services/learning-coordinator.js +37 -17
- package/dist/init/phases/10-workers.js +20 -1
- package/dist/kernel/hybrid-backend.d.ts +17 -7
- package/dist/kernel/hybrid-backend.js +24 -10
- package/dist/kernel/interfaces.d.ts +33 -6
- package/dist/kernel/kernel.d.ts +1 -0
- package/dist/kernel/kernel.js +57 -0
- package/dist/kernel/memory-backend.d.ts +5 -5
- package/dist/kernel/memory-backend.js +14 -7
- package/dist/kernel/unified-memory-schemas.d.ts +1 -1
- package/dist/kernel/unified-memory-schemas.js +7 -1
- package/dist/learning/agent-routing.d.ts +134 -1
- package/dist/learning/agent-routing.js +185 -2
- package/dist/learning/dream/dream-insights-pruner.d.ts +49 -0
- package/dist/learning/dream/dream-insights-pruner.js +53 -0
- package/dist/learning/dream/dream-scheduler.js +17 -0
- package/dist/learning/loop-health.d.ts +84 -0
- package/dist/learning/loop-health.js +91 -0
- package/dist/learning/pattern-usage-recorder.d.ts +58 -0
- package/dist/learning/pattern-usage-recorder.js +72 -0
- package/dist/learning/qe-reasoning-bank-types.d.ts +11 -0
- package/dist/learning/qe-reasoning-bank.d.ts +11 -0
- package/dist/learning/qe-reasoning-bank.js +86 -3
- package/dist/learning/routing-topology-gate.d.ts +40 -0
- package/dist/learning/routing-topology-gate.js +55 -0
- package/dist/learning/sqlite-persistence.d.ts +6 -1
- package/dist/learning/sqlite-persistence.js +14 -20
- package/dist/mcp/bundle.js +3837 -3811
- package/dist/mcp/handlers/core-handlers.js +21 -0
- package/dist/routing/routing-feedback.js +7 -3
- package/dist/routing/routing-outcomes-migration.d.ts +31 -0
- package/dist/routing/routing-outcomes-migration.js +60 -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.d.ts +28 -0
- package/dist/workers/workers/learning-consolidation.js +302 -71
- package/package.json +3 -1
- package/dist/cli/chunks/adapter-HV42JOZD.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-GL22PE2V.js +0 -2
- package/dist/cli/chunks/base-4KQ2FGUX.js +0 -2
- package/dist/cli/chunks/browser-workflow-CTE7BDM4.js +0 -2
- package/dist/cli/chunks/chunk-3NGNSKL3.js +0 -14
- package/dist/cli/chunks/chunk-6HSFZ6SL.js +0 -180
- package/dist/cli/chunks/chunk-7Z3GBQNV.js +0 -2
- package/dist/cli/chunks/chunk-AQJ6XS34.js +0 -2
- package/dist/cli/chunks/chunk-H2IMXQCJ.js +0 -2
- package/dist/cli/chunks/chunk-SPCANEJY.js +0 -95
- package/dist/cli/chunks/client-FRVNMXQO.js +0 -2
- package/dist/cli/chunks/cross-domain-router-BVCPAWG2.js +0 -2
- package/dist/cli/chunks/daemon-PHIZPZIE.js +0 -19
- package/dist/cli/chunks/dream-77ODIFIF.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-CQGQS3V7.js +0 -2
- package/dist/cli/chunks/hnsw-index-2ACF6FOJ.js +0 -2
- package/dist/cli/chunks/hooks-YROFO6PE.js +0 -259
- package/dist/cli/chunks/impact-analyzer-LWEGK23B.js +0 -2
- package/dist/cli/chunks/init-wizard-7BS3QMWR.js +0 -2
- package/dist/cli/chunks/kernel-TX67WXSI.js +0 -2
- package/dist/cli/chunks/knowledge-graph-TDSP2UE2.js +0 -2
- package/dist/cli/chunks/learning-RRWV3SEL.js +0 -107
- package/dist/cli/chunks/load-test-GEBBBUMV.js +0 -2
- package/dist/cli/chunks/memory-backend-WQS2MLW2.js +0 -2
- package/dist/cli/chunks/memory-handlers-RTY5MBA5.js +0 -2
- package/dist/cli/chunks/protocol-executor-DT7XHMLL.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-LDNETZVA.js +0 -2
- package/dist/cli/chunks/queen-coordinator-AF7HCQSM.js +0 -2
- package/dist/cli/chunks/router-OWQ5EI72.js +0 -2
- package/dist/cli/chunks/routing-feedback-B43DEQMK.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-XBJDXHNI.js +0 -2
- package/dist/cli/chunks/safe-db-RT3LEDUG.js +0 -2
- package/dist/cli/chunks/schedule-EHUDCKS2.js +0 -2
- package/dist/cli/chunks/scheduler-GEGZ4J3C.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-LNBUNRAM.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-3DGRJH3K.js +0 -2
- package/dist/cli/chunks/sync-5CDYOT3H.js +0 -23
- package/dist/cli/chunks/unified-memory-ZSBX4LYU.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-Y6EKAMRP.js +0 -2
- package/dist/cli/chunks/unified-persistence-2PDVU2U5.js +0 -2
- package/dist/cli/chunks/visual-security-RHMFLKVQ.js +0 -2
- package/dist/cli/chunks/witness-chain-QO237QOF.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-RHM5MIGE.js +0 -2
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{a as W}from"./chunk-ND6VCNN5.js";import{c as V,d as q}from"./chunk-DDMFTEJP.js";import{c as M}from"./chunk-IHRFR5SV.js";import{a as $}from"./chunk-7Z3GBQNV.js";import{c as N}from"./chunk-3WIU2E2Y.js";import{b as D,d as H}from"./chunk-Q4HJRYQB.js";import{a as E,c as k}from"./chunk-RNO6CE7I.js";import{i as y}from"./chunk-GY4EGQO3.js";import{a as R,b as U,d as J}from"./chunk-37I6K7QO.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};H();k();var A=class{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...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
|
-
INSERT INTO concept_nodes
|
|
4
|
-
(id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`)),this.prepared.set("getNode",this.db.prepare(`
|
|
7
|
-
SELECT * FROM concept_nodes WHERE id = ?
|
|
8
|
-
`)),this.prepared.set("updateActivation",this.db.prepare(`
|
|
9
|
-
UPDATE concept_nodes
|
|
10
|
-
SET activation_level = ?, last_activated = datetime('now')
|
|
11
|
-
WHERE id = ?
|
|
12
|
-
`)),this.prepared.set("getActiveNodes",this.db.prepare(`
|
|
13
|
-
SELECT * FROM concept_nodes
|
|
14
|
-
WHERE activation_level >= ?
|
|
15
|
-
ORDER BY activation_level DESC
|
|
16
|
-
`)),this.prepared.set("getNodesByType",this.db.prepare(`
|
|
17
|
-
SELECT * FROM concept_nodes WHERE concept_type = ?
|
|
18
|
-
`)),this.prepared.set("getAllNodes",this.db.prepare(`
|
|
19
|
-
SELECT * FROM concept_nodes
|
|
20
|
-
`)),this.prepared.set("insertEdge",this.db.prepare(`
|
|
21
|
-
INSERT INTO concept_edges
|
|
22
|
-
(id, source, target, edge_type, weight, evidence)
|
|
23
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
24
|
-
`)),this.prepared.set("getEdge",this.db.prepare(`
|
|
25
|
-
SELECT * FROM concept_edges WHERE source = ? AND target = ?
|
|
26
|
-
`)),this.prepared.set("updateEdge",this.db.prepare(`
|
|
27
|
-
UPDATE concept_edges
|
|
28
|
-
SET weight = ?, evidence = evidence + 1, updated_at = datetime('now')
|
|
29
|
-
WHERE source = ? AND target = ?
|
|
30
|
-
`)),this.prepared.set("getOutgoingEdges",this.db.prepare(`
|
|
31
|
-
SELECT * FROM concept_edges WHERE source = ?
|
|
32
|
-
`)),this.prepared.set("getIncomingEdges",this.db.prepare(`
|
|
33
|
-
SELECT * FROM concept_edges WHERE target = ?
|
|
34
|
-
`)),this.prepared.set("countNodes",this.db.prepare(`
|
|
35
|
-
SELECT COUNT(*) as count FROM concept_nodes
|
|
36
|
-
`)),this.prepared.set("countEdges",this.db.prepare(`
|
|
37
|
-
SELECT COUNT(*) as count FROM concept_edges
|
|
38
|
-
`)),this.prepared.set("countByType",this.db.prepare(`
|
|
39
|
-
SELECT concept_type, COUNT(*) as count FROM concept_nodes GROUP BY concept_type
|
|
40
|
-
`))}async addNode(e){this.ensureInitialized();let t=y(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let a=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,a,0,n,e.patternId||null,e.metadata?JSON.stringify(e.metadata):null),this.config.debug&&console.log(`[ConceptGraph] Added node: ${t} (${e.conceptType})`),t}async getNode(e){this.ensureInitialized();let t=this.prepared.get("getNode");if(!t)throw new Error("Prepared statement not found: getNode");let n=t.get(e);return n?this.rowToNode(n):null}async updateActivation(e,t){this.ensureInitialized();let n=this.prepared.get("updateActivation");if(!n)throw new Error("Prepared statement not found: updateActivation");let i=Math.max(0,Math.min(1,t));n.run(i,e)}async getActiveNodes(e=.1){this.ensureInitialized();let t=this.prepared.get("getActiveNodes");if(!t)throw new Error("Prepared statement not found: getActiveNodes");return t.all(e).map(i=>this.rowToNode(i))}async getNodesByType(e){this.ensureInitialized();let t=this.prepared.get("getNodesByType");if(!t)throw new Error("Prepared statement not found: getNodesByType");return t.all(e).map(i=>this.rowToNode(i))}async addEdge(e,t,n,i=1){this.ensureInitialized();let a=await this.getEdgeBetween(e,t);if(a)return await this.strengthenEdge(e,t,.1),a.id;let r=y(),o=this.prepared.get("insertEdge");if(!o)throw new Error("Prepared statement not found: insertEdge");return o.run(r,e,t,n,Math.max(0,Math.min(1,i)),1),this.config.debug&&console.log(`[ConceptGraph] Added edge: ${e} -> ${t} (${n})`),r}async strengthenEdge(e,t,n=.1){this.ensureInitialized();let i=await this.getEdgeBetween(e,t);if(!i)return;let a=Math.min(1,i.weight+n),r=this.prepared.get("updateEdge");if(!r)throw new Error("Prepared statement not found: updateEdge");r.run(a,e,t)}async getNeighbors(e){this.ensureInitialized();let t=[],n=this.prepared.get("getOutgoingEdges");if(!n)throw new Error("Prepared statement not found: getOutgoingEdges");let i=n.all(e);for(let o of i){let s=await this.getNode(o.target);s&&t.push({node:s,edge:this.rowToEdge(o)})}let a=this.prepared.get("getIncomingEdges");if(!a)throw new Error("Prepared statement not found: getIncomingEdges");let r=a.all(e);for(let o of r){let s=await this.getNode(o.source);s&&t.push({node:s,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,a=[{nodeId:e,path:[e]}];for(;a.length>0;){let r=a.shift();if(r.nodeId===t){let s=[];for(let c of r.path){let p=await this.getNode(c);p&&s.push(p)}return s}if(r.path.length>n||i.has(r.nodeId))continue;i.add(r.nodeId);let o=await this.getNeighbors(r.nodeId);for(let{node:s}of o)i.has(s.id)||a.push({nodeId:s.id,path:[...r.path,s.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],a=async(r,o)=>{if(n.has(r)||o>t)return;n.add(r);let s=await this.getNode(r);if(s&&(i.push(s),o<t)){let c=await this.getNeighbors(r);for(let{node:p}of c)await a(p.id,o+1)}};return await a(e,0),i}async loadFromPatterns(e){this.ensureInitialized();let t=0,n=[],i=new Map;for(let a of e)try{if(await this.findNodeByPatternId(a.id))continue;let o=await this.addNode({conceptType:"pattern",content:`${a.name}: ${a.description}`,patternId:a.id,metadata:{domain:a.domain,patternType:a.patternType,confidence:a.confidence,successRate:a.successRate}});t++,n.push(o);let s=a.domain||"unknown";i.has(s)||i.set(s,[]),i.get(s).push(o);let c=await this.findDomainNode(a.domain);if(!c){let p=await this.addNode({conceptType:"domain",content:a.domain,metadata:{patternCount:1}});c=await this.getNode(p)}c&&await this.addEdge(o,c.id,"co_occurrence",.8)}catch(r){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${a.id}`,r)}if(t>0){let a=await this.discoverSameDomainEdges(i),r=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${a} same-domain edges, pruned ${r}`)}return console.log(`[ConceptGraph] Loaded ${t} new patterns (${e.length-t} already existed)`),t}async discoverSameDomainEdges(e){if(this.ensureInitialized(),!this.db)return 0;let t=15,n=5e3,i=0;if(e&&e.size>0)for(let[a,r]of e){let o=this.countDomainSimilarityEdges(a);if(o>=n){console.log(`[ConceptGraph] Domain '${a}' already at edge cap (${o}/${n}), skipping`);continue}let s=new Set(r),c=n-o,d=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all().filter(u=>{if(s.has(u.id))return!1;let m=u.metadata?D(u.metadata):{};return String(m.domain||"unknown")===a}),l=this.db.transaction(()=>{let u=0;for(let m of r){let v=0;for(let f of d){if(v>=t||u>=c)break;if(!this.prepared.get("getEdge")?.get(m,f.id)){let w=y();this.prepared.get("insertEdge").run(w,m,f.id,"similarity",.6,1),u++,v++}}if(u>=c)break}for(let m=0;m<r.length&&u<c;m++){let v=0;for(let f=m+1;f<r.length&&u<c&&!(v>=t);f++)if(!this.prepared.get("getEdge")?.get(r[m],r[f])){let w=y();this.prepared.get("insertEdge").run(w,r[m],r[f],"similarity",.6,1),u++,v++}}return u});i+=l()}else{let a=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),r=new Map;for(let s of a){let c=s.metadata?D(s.metadata):{},p=String(c.domain||"unknown");r.has(p)||r.set(p,[]),r.get(p).push(s)}let o=this.db.transaction(()=>{let s=0;for(let[c,p]of r){let d=this.countDomainSimilarityEdges(c);if(d>=n)continue;let l=0,u=n-d;for(let m=0;m<p.length&&l<u;m++){let v=0;for(let f=m+1;f<p.length&&l<u&&!(v>=t);f++)if(!this.prepared.get("getEdge")?.get(p[m].id,p[f].id)){let w=y();this.prepared.get("insertEdge").run(w,p[m].id,p[f].id,"similarity",.6,1),s++,l++,v++}}}return s});i+=o()}return i}countDomainSimilarityEdges(e){return this.db?this.db.prepare(`
|
|
41
|
-
SELECT COUNT(*) as count FROM concept_edges e
|
|
42
|
-
JOIN concept_nodes n ON e.source = n.id
|
|
43
|
-
WHERE e.edge_type = 'similarity'
|
|
44
|
-
AND n.concept_type = 'pattern'
|
|
45
|
-
AND json_extract(n.metadata, '$.domain') = ?
|
|
46
|
-
`).get(e).count:0}async pruneEdges(e=15,t=.3){if(this.ensureInitialized(),!this.db)return 0;let n=0;return n=this.db.transaction(()=>{let a=0,r=this.db.prepare(`
|
|
47
|
-
DELETE FROM concept_edges
|
|
48
|
-
WHERE edge_type = 'similarity' AND weight < ?
|
|
49
|
-
`).run(t);a+=r.changes;let o=this.db.prepare(`
|
|
50
|
-
SELECT source, COUNT(*) as cnt FROM concept_edges
|
|
51
|
-
WHERE edge_type = 'similarity'
|
|
52
|
-
GROUP BY source
|
|
53
|
-
HAVING cnt > ?
|
|
54
|
-
`).all(e);for(let{source:s}of o){let c=this.db.prepare(`
|
|
55
|
-
DELETE FROM concept_edges
|
|
56
|
-
WHERE id IN (
|
|
57
|
-
SELECT id FROM concept_edges
|
|
58
|
-
WHERE source = ? AND edge_type = 'similarity'
|
|
59
|
-
ORDER BY weight DESC
|
|
60
|
-
LIMIT -1 OFFSET ?
|
|
61
|
-
)
|
|
62
|
-
`).run(s,e);a+=c.changes}return a})(),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,a=t.get().count,r={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)r[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:a,byType:r,avgEdgesPerNode:i>0?a/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 K(h){return new A(h)}J();function Z(h,e){if(e<0||e>=h.length)return h[0]??0;let t=0,n=h.length-1;for(;t<n;){let i=t+n>>1;if(h[i]<h[t]){let s=h[t];h[t]=h[i],h[i]=s}if(h[n]<h[t]){let s=h[t];h[t]=h[n],h[n]=s}if(h[i]<h[n]){let s=h[i];h[i]=h[n],h[n]=s}let a=h[n],r=t;for(let s=t;s<n;s++)if(h[s]<=a){let c=h[r];h[r]=h[s],h[s]=c,r++}let o=h[r];if(h[r]=h[n],h[n]=o,r===e)return h[r];r<e?t=r+1:n=r-1}return h[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},S=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(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let a=0,r=t,o=0,s=0;for(;a<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),l=this.graph.getActiveNodes(this.config.threshold);for(let u of l)u.activationLevel>r&&(r=u.activationLevel);if(l.length===o&&d===0){if(s++,s>=3)break}else s=0;o=l.length,a++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,l)=>l.activation-d.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:a,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,a=0,r=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 d=U(0,o.length),l=o[d];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>a&&(a=f.peakActivation);for(let b of f.activatedNodes)r.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),p=Array.from(r).map(d=>{let l=this.graph.getConcept(d);return{nodeId:d,activation:l?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,l)=>l.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:p.length,peakActivation:a,activatedNodes:p,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((r,o)=>o.activationLevel-r.activationLevel).slice(0,i));let a=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let s=n[r],c=n[o],p=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),l=this.graph.getEdge(c.id,s.id),u=d!==void 0||l!==void 0,m=d?.weight??l?.weight??0,v=!u||m<.3;p>.3&&(a.push({source:s,target:c,coActivation:p,isNovel:v}),this.trackCoActivation(s.id,c.id))}return a.sort((r,o)=>r.isNovel!==o.isNovel?r.isNovel?-1:1:o.coActivation-r.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<=B)return;let e=Math.floor(B*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=Z(n,t-1),a=[];for(let[r,o]of this.coActivationCounts){if(a.length>=t)break;o<=i&&a.push(r)}for(let r of a)this.coActivationCounts.delete(r)}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 a=this.graph.getEdges(i.id);for(let r of a){let o=this.graph.getConcept(r.target);if(!o)continue;let s=i.activationLevel*r.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,p=Math.min(1,c+s);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let a=this.graph.getConcept(i.nodeId);a&&i.newActivation>a.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(":"),a=t.get(i);(!a||n.strength>a.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 ee}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 a=await this.detectPatternMerges(i);for(let c of a)c.cycleId=e,n.push(c);let r=await this.detectNovelAssociations(t.novelAssociations);for(let c of r)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,p)=>p.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 a=i+1;a<n.length;a++){let r=n[i],o=n[a],s=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(r.content,o.content),l=Math.sqrt(r.activationLevel*o.activationLevel),u=p*.4+d*.3+l*.3;if(u>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),v=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:d,coActivation:l});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,u),noveltyScore:m,confidenceScore:v,actionable:v>=this.config.minConfidence,applied:!1,suggestedAction:v>=this.config.minConfidence?`Merge "${this.truncate(r.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),a=this.graph.getConcept(n.target);if(!i||!a)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==a.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,a,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(a.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??{},a=i.successRate,r=i.executionCount,o=i.confidence,s=a!==void 0&&a<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(s||c&&p){let d=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,a,r),noveltyScore:d,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 a=i.conceptType??"pattern";n[a]||(n[a]=[]),n[a].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(a=>a.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=ee().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),a=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),s=a.size+r.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 a=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 ${a}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};H();k();$();import{existsSync as te,unlinkSync as ne}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-QUPNH2J5.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 a=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(a),o=i;o._rvfBranchPath=a,o._rvfChildAdapter=r}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(),a=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-a/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,l=new Float32Array(d);for(let m=0;m<d;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 p=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:p,patternCountDelta:a,avgConfidenceDelta:r,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&&te(n)&&ne(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 a=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,a)}}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 r of e)t[r.conceptType]=(t[r.conceptType]??0)+1,n+=this.activationLevels.get(r.id)??r.activationLevel;let i=0,a=Array.from(this.edgeCache.values());for(let r of a)i+=r.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(),a=new Set(i.map(s=>s.name)),r=a.has("insight_type"),o=a.has("source_concepts");if(!r)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 a=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(a),this.emitBranchEvent("dream:branch_created",i)}try{let a=await this.graph.getActiveNodes(0);if(a.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${a.length} < ${this.config.minConceptsRequired}`);let r=new z(this.graph);await r.loadIntoMemory(30);let s=await new S(r,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 r.persistActivations();let p=await new I(r,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=p.length;for(let l of p)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 d={cycle:{...this.currentCycle},insights:p,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(a){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(a),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,a}}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
|
-
confidence, success_rate as successRate
|
|
64
|
-
FROM qe_patterns
|
|
65
|
-
WHERE confidence >= 0.3
|
|
66
|
-
ORDER BY quality_score DESC
|
|
67
|
-
LIMIT 200`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let n=`dream-pattern-${y()}`;return this.db.prepare(`
|
|
68
|
-
UPDATE dream_insights
|
|
69
|
-
SET applied = 1, pattern_id = ?
|
|
70
|
-
WHERE id = ?
|
|
71
|
-
`).run(n,e),{success:!0,patternId:n}}catch(t){return{success:!1,error:E(t)}}}async getPendingInsights(e){this.ensureInitialized();let t=e??20;return this.db.prepare(`
|
|
72
|
-
SELECT * FROM dream_insights
|
|
73
|
-
WHERE applied = 0 AND actionable = 1
|
|
74
|
-
ORDER BY novelty_score DESC, confidence_score DESC
|
|
75
|
-
LIMIT ?
|
|
76
|
-
`).all(t).map(a=>this.rowToInsight(a))}async getDreamHistory(e){this.ensureInitialized();let t=e??20;return this.db.prepare(`
|
|
77
|
-
SELECT * FROM dream_cycles
|
|
78
|
-
ORDER BY start_time DESC
|
|
79
|
-
LIMIT ?
|
|
80
|
-
`).all(t).map(a=>this.rowToCycle(a))}async cancelDream(){this.cancelled=!0}isDreaming(){return this.currentCycle!==null&&this.currentCycle.status==="running"}getCurrentCycle(){return this.currentCycle?{...this.currentCycle}:null}async saveCycle(e){if(!this.db)return;this.db.prepare(`
|
|
81
|
-
INSERT INTO dream_cycles
|
|
82
|
-
(id, start_time, end_time, duration_ms, concepts_processed, associations_found,
|
|
83
|
-
insights_generated, status, error, created_at)
|
|
84
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
85
|
-
`).run(e.id,e.startTime.toISOString(),e.endTime?.toISOString()??null,e.durationMs??null,e.conceptsProcessed,e.associationsFound,e.insightsGenerated,e.status,e.error??null,e.startTime.toISOString())}async updateCycle(e){if(!this.db)return;this.db.prepare(`
|
|
86
|
-
UPDATE dream_cycles
|
|
87
|
-
SET end_time = ?, duration_ms = ?, concepts_processed = ?, associations_found = ?,
|
|
88
|
-
insights_generated = ?, status = ?, error = ?
|
|
89
|
-
WHERE id = ?
|
|
90
|
-
`).run(e.endTime?.toISOString()??null,e.durationMs??null,e.conceptsProcessed,e.associationsFound,e.insightsGenerated,e.status,e.error??null,e.id)}async saveInsight(e){if(!this.db)return;this.db.prepare(`
|
|
91
|
-
INSERT INTO dream_insights
|
|
92
|
-
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
93
|
-
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
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 ie(h){let e=new _(h);return import("./feature-flags-QUPNH2J5.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-LNBUNRAM.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var re=_;$();var g=N.create("DreamScheduler"),Y={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},L=class h{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={...Y,...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});try{let t=await this.dreamEngine.ensureConceptsLoaded();t>0&&g.info("Auto-loaded concepts for dream",{loaded:t});let n=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=n,this.totalDreamsCompleted++,this.clearExperienceBuffer(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(n),await this.publishDreamCompletedEvent(n),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(i){g.warn("Post-dream meta-learning failed (non-critical)",{error:i instanceof Error?i.message:String(i)})}return this.running&&this.scheduleNextDream(),g.info("Dream completed",{insightsGenerated:n.insights.length}),n}finally{this.dreaming=!1}}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>h.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>h.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 ae(h,e){return new L(h,e)}var se=[{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}}],G=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(),a=[];for(let s of e){let c=await this.executeStrategy(s,i,t);a.push(c)}let r=a.filter(s=>s.validation.passed),o=null;if(r.length>0){o=r.reduce((c,p)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(p.validation)>d?p: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:a,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,a=this.branchManager.createBranch(i),r=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(a,t);return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:o,selected:!1,durationMs:Date.now()-r}}catch{return this.branchManager.discardBranch(a),{strategy:e,branch:a,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-r}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{P as a,A as b,K as c,B as d,O as e,F as f,j as g,S as h,Q as i,I as j,T as k,C as l,X as m,_ as n,ie as o,re as p,Y as q,L as r,ae as s,se as t,G as u};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{c as a,d as b,e as c}from"./chunk-YETPSL6H.js";import"./chunk-FI4HRS2G.js";import"./chunk-RNO6CE7I.js";import"./chunk-ITBPDVK5.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{a,b}from"./chunk-ER6BT4GS.js";import"./chunk-XDYTQPJM.js";import"./chunk-LDGNVPBZ.js";import"./chunk-GY4EGQO3.js";import"./chunk-ITBPDVK5.js";export{a as CrossDomainEventRouter,b as createCrossDomainRouter};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{a as N}from"./chunk-L7X3A36M.js";import"./chunk-ITBPDVK5.js";import{Command as ae}from"commander";import s from"chalk";import{cpus as ne,freemem as ie,totalmem as re,loadavg as se}from"os";var f=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let o=this.queues[t];for(;o.length>0;){let n=o.shift();if(!(n.ttlMs&&e-n.createdAt>n.ttlMs))return n}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let o=this.queues[t];for(let n of o)if(!n.ttlMs||e-n.createdAt<=n.ttlMs)return n}}drainPriority(e){let t=this.queues[e].splice(0),o=Date.now();return t.filter(n=>!n.ttlMs||o-n.createdAt<=n.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let o of["now","next","later"]){let n=this.queues[o].length;this.queues[o]=this.queues[o].filter(i=>!i.ttlMs||t-i.createdAt<=i.ttlMs),e+=n-this.queues[o].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as E}from"fs";import{execFile as L}from"child_process";import{promisify as U}from"util";import{resolve as W,join as z}from"path";import{existsSync as j,readFileSync as B}from"fs";var M=U(L),J={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},y=class{constructor(e,t){this.queue=e;this.options={...J,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=W(this.options.repoRoot,".git","refs","heads");if(!j(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=E(e,{recursive:!0},(o,n)=>{n&&this.handleRefChange(n)}):this.pollTimer=setInterval(()=>{this.poll().catch(o=>{console.debug("[GitWatcher] Poll error:",o)})},this.options.pollIntervalMs),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await M("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let o of t.trim().split(`
|
|
3
|
-
`)){if(!o)continue;let[n,i]=o.split(" "),r=this.lastKnownHeads.get(n);r&&r!==i&&(e.push(n),await this.enqueueCommitAnalysis(n,i)),this.lastKnownHeads.set(n,i)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),o=W(this.options.repoRoot,".git","refs","heads"),n=z(o,e),i;try{i=B(n,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==i&&(this.lastKnownHeads.set(t,i),await this.enqueueCommitAnalysis(t,i))}async enqueueCommitAnalysis(e,t){let o=[];try{let{stdout:r}=await M("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});o=r.trim().split(`
|
|
4
|
-
`).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let n={type:"git_commit",branch:e,commitHash:t,changedFiles:o},i={id:`git-${t}-${Date.now()}`,priority:"next",payload:n,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(i)}async snapshotHeads(){try{let{stdout:e}=await M("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
|
|
5
|
-
`)){if(!t)continue;let[o,n]=t.split(" ");this.lastKnownHeads.set(o,n)}}catch{}}};var V={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},v=class{constructor(e,t){this.queue=e;this.options={...V,...t}}queue;options;async analyze(e,t,o){let n=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!n)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let i=n,r={line:e.overall.line-i.overall.line,branch:e.overall.branch-i.overall.branch,function:e.overall.function-i.overall.function,statement:e.overall.statement-i.overall.statement},a=r.line<-this.options.regressionThreshold||r.branch<-this.options.regressionThreshold,c=o??Object.keys(e.files),d=[],h=[];for(let g of c){let m=e.files[g],p=i.files[g];if(!m)continue;let R=p?m.line-p.line:0,$=p?m.branch-p.branch:0,I=p?m.uncoveredLines.filter(_=>!p.uncoveredLines.includes(_)):m.uncoveredLines;if((R!==0||$!==0||I.length>0)&&d.push({file:g,lineDelta:R,branchDelta:$,newUncoveredLines:I}),m.line<this.options.gapThreshold){let _=this.computeRiskScore(m,I.length);h.push({file:g,uncoveredLines:m.uncoveredLines,currentCoverage:m.line,riskScore:_})}}return(a||h.length>0)&&this.enqueueTestSuggestion(e,i,h),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:r,regressionDetected:a,affectedFileCount:d.length,gapCount:h.length}),{regressionDetected:a,overallDelta:r,affectedFiles:d,newGaps:h}}async buildSnapshot(e){let t=await e.get("coverage:latest");if(t)return{timestamp:Date.now(),overall:{line:t.line,branch:t.branch,function:t.function,statement:t.statement},files:t.files??{}}}computeRiskScore(e,t){let n=1-Math.min(100,Math.max(0,e.line))/100,i=Math.min(t/50,1);return Math.min(1,n*.6+i*.4)}enqueueTestSuggestion(e,t,o){let n={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},i={id:`coverage-delta-${Date.now()}`,priority:o.some(r=>r.riskScore>.8)?"now":"next",payload:n,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(i)}};import{execFile as K}from"child_process";import{promisify as Y}from"util";var X=Y(K),Z={runsPerWorkflow:10,flakyThreshold:3,repo:""},w=class{constructor(e,t){this.queue=e;this.options={...Z,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),o=[],n=[],i=0;for(let[a,c]of Object.entries(t)){let d=c.filter(p=>p.conclusion==="failure").length,h=c.length>0?(c.length-d)/c.length*100:100,g=this.countConsecutiveFailures(c),m=c[0]?.conclusion??"unknown";m==="failure"&&i++,g>=this.options.flakyThreshold&&(n.push(a),this.enqueueFailureAlert(a,c[0])),o.push({name:a,recentRuns:c.length,failedRuns:d,successRate:Math.round(h*10)/10,lastConclusion:m,consecutiveFailures:g})}let r=this.calculateHealthScore(o);return{timestamp:Date.now(),workflows:o,failingWorkflows:i,flakyWorkflows:n,healthScore:r}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await X("gh",e,{timeout:15e3});return JSON.parse(t).map(n=>({name:n.name,status:n.status,conclusion:n.conclusion??"pending",headBranch:n.headBranch,runNumber:n.number,databaseId:n.databaseId,createdAt:n.createdAt}))}catch{return[]}}groupByWorkflow(e){let t={};for(let o of e)t[o.name]||(t[o.name]=[]),t[o.name].push(o);for(let o of Object.keys(t))t[o]=t[o].slice(0,this.options.runsPerWorkflow);return t}countConsecutiveFailures(e){let t=0;for(let o of e)if(o.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((o,n)=>o+n.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let o={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},n={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:o,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(n)}};var ee={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},b=class{options;constructor(e){this.options={...ee,...e}}async suggest(e,t,o){let n=[],i=e.filter(a=>a.riskScore>=this.options.minRiskScore);for(let a of i){let c=t.includes(a.file),d=this.determinePriority(a,c),h=this.determineTestType(a.file),g=this.estimateEffort(a);n.push({id:`suggestion-${Date.now()}-${n.length}`,file:a.file,uncoveredLines:a.uncoveredLines.slice(0,50),suggestedTestType:h,description:this.generateDescription(a,h),priority:d,estimatedEffort:g,createdAt:Date.now(),status:"pending"})}n.sort((a,c)=>{let d={high:0,medium:1,low:2};return d[a.priority]-d[c.priority]});let r=n.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(r,o),r}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(o=>o.status==="pending")}async updateStatus(e,t,o){let n=await o.get(`${this.options.memoryPrefix}:list`);if(!n)return!1;let i=n.findIndex(a=>a.id===e);if(i===-1)return!1;let r=n.map((a,c)=>c===i?{...a,status:t}:a);return await o.set(`${this.options.memoryPrefix}:list`,r),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let o=e.uncoveredLines.length,n=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${o} uncovered lines, ${n}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let i=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(r=>r.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,i),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:i.length,lastUpdated:Date.now()})}};var te={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},k=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let o=Date.now(),n=new Date().toISOString().split("T")[0],i=await this.consolidatePatterns(e),r=await this.pruneExpired(e),a=this.generateReport(n,t);await e.set(`${this.options.memoryPrefix}:report:${n}`,a),this.lastRunDate=n;let c={timestamp:Date.now(),patternsConsolidated:i,entriesPruned:r,reportGenerated:!0,durationMs:Date.now()-o};return await e.set(`${this.options.memoryPrefix}:last-result`,c),c}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),o=0;return await e.get("quality-daemon:suggestions:count")&&o++,await e.get("quality-daemon:coverage:delta")&&o++,o}async pruneExpired(e){let t=await e.search("quality-daemon:*"),o=0,n=Date.now();for(let i of t){if(i.endsWith(":snapshot")||i.endsWith(":list"))continue;let r=await e.get(i);r&&typeof r.timestamp=="number"&&n-r.timestamp>this.options.maxEntryAge&&(await e.set(i,{pruned:!0,prunedAt:n}),o++)}return o}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};import{writeFileSync as A,mkdirSync as Q,readdirSync as P,readFileSync as F,unlinkSync as G}from"fs";import{join as C,resolve as oe}from"path";var O={notificationsDir:oe(process.cwd(),".agentic-qe","notifications"),maxNotifications:200},S=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??O.notificationsDir,this.maxNotifications=e?.maxNotifications??O.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){Q(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let o=P(this.notificationsDir).filter(i=>i.endsWith(".json")).sort().reverse(),n=[];for(let i of o){if(n.length>=t)break;try{let r=F(C(this.notificationsDir,i),"utf-8"),a=JSON.parse(r);if(e?.unreadOnly&&a.read||e?.type&&a.type!==e.type)continue;n.push(a)}catch{}}return n}catch{return[]}}markRead(e){try{let t=P(this.notificationsDir).filter(r=>r.endsWith(`-${e}.json`));if(t.length===0)return!1;let o=C(this.notificationsDir,t[0]),i={...JSON.parse(F(o,"utf-8")),read:!0};return A(o,JSON.stringify(i,null,2)),!0}catch{return!1}}clear(){try{let e=P(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)G(C(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{Q(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,o=C(this.notificationsDir,t);A(o,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=P(this.notificationsDir).filter(o=>o.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let o of t)G(C(this.notificationsDir,o))}catch{}}};var q="quality-daemon",D=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,q)}async set(e,t){await this.backend.kvSet(e,t,q)}async search(e){return this.backend.kvSearch(e,q)}};var T={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},x=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??T.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??T.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??T.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??T.cpuThreshold,memoryThreshold:e?.memoryThreshold??T.memoryThreshold},this.queue=new f,this.gitWatcher=new y(this.queue,e?.git),this.coverageDelta=new v(this.queue,e?.coverage),this.ciMonitor=new w(this.queue,e?.ci),this.testSuggester=new b(e?.suggestions),this.nightlyConsolidation=new k(this.queue,e?.nightly),this.notificationService=new S(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs))}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,o=10;for(;t<o&&!this.queue.isEmpty;){let n=this.queue.dequeue();if(!n)break;await this.handleQueueItem(n,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let o of t)await this.handleQueueItem(o,e)}async handleQueueItem(e,t){let o=e.payload;switch(o.type){case"git_commit":this._commitsAnalyzed++;let n=await this.coverageDelta.buildSnapshot(t);if(n){let i=await this.coverageDelta.analyze(n,t,o.changedFiles);if(i.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${i.overallDelta.line.toFixed(1)}% (${i.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:i.overallDelta,commit:o.commitHash}}),i.newGaps.length>0){let r=await this.testSuggester.suggest(i.newGaps,o.changedFiles,t);this._suggestionsGenerated+=r.length,r.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${r.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:r.length}})}}break;case"coverage_delta":{let i=await this.testSuggester.getPending(t);i.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${i.length} test suggestions awaiting review`,severity:"info",metadata:{count:i.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${o.gateName}`,message:`Score ${o.score} below threshold ${o.threshold}`,severity:"critical",metadata:{gate:o.gateName,score:o.score,threshold:o.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${o.workflowName}`,message:`Workflow ${o.workflowName} run #${o.runId} concluded: ${o.conclusion}`,severity:"high",metadata:{workflow:o.workflowName,runId:o.runId}});break;case"nightly":{let i={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,i);break}default:console.warn("[QualityDaemon] Unhandled payload type:",o.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let o=await this.ciMonitor.check();this._ciHealth=o.healthScore,this._lastCICheck=t,o.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${o.flakyWorkflows.length} workflows showing repeated failures: ${o.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:o.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let o=await this.coverageDelta.buildSnapshot(e);o&&(this._coverageHealth=Math.round((o.overall.line+o.overall.branch+o.overall.function+o.overall.statement)/4),this._lastCoverageCheck=t)}catch{}}isResourceConstrained(){if(1-ie()/re()>this.config.memoryThreshold)return!0;let t=ne().length;return(t>0?se()[0]/t:0)>this.config.cpuThreshold}};var u;function Ke(){let l=new ae("daemon").description("Manage the QE Quality Daemon").addHelpText("after",`
|
|
6
|
-
Examples:
|
|
7
|
-
aqe daemon start Start daemon in foreground
|
|
8
|
-
aqe daemon stop Stop running daemon
|
|
9
|
-
aqe daemon status Show daemon health and queue depth
|
|
10
|
-
aqe daemon notifications List recent notifications
|
|
11
|
-
aqe daemon clear-notifications Clear all notifications
|
|
12
|
-
`);return l.command("start").description("Start the QE Quality Daemon").option("--tick-interval <ms>","Tick interval in milliseconds","30000").option("--ci-interval <ms>","CI poll interval in milliseconds","300000").action(async e=>{if(u?.running){console.log(s.yellow("Daemon is already running"));let r=u.getStatus();console.log(s.gray(` Uptime: ${r.uptimeSeconds}s, Ticks: ${r.tickCount}`));return}let t={tickIntervalMs:parseInt(e.tickInterval,10),ciPollIntervalMs:parseInt(e.ciInterval,10),notifications:{urlValidator:r=>{try{let c=new URL(r).hostname.replace(/^\[|\]$/g,"");return!N(c)}catch{return!1}}}};u=new x(t);let o;try{let{UnifiedMemoryManager:r}=await import("./unified-memory-ZSBX4LYU.js"),a=await r.getInstanceAsync();o=new D(a),console.log(s.gray(" Storage: SQLite (persistent)"))}catch{let r=new Map;o={async get(a){return r.get(a)},async set(a,c){r.set(a,c)},async search(a){let c=a.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(c.replace(/\*/g,".*"));return Array.from(r.keys()).filter(h=>d.test(h))}},console.log(s.yellow(" Storage: in-memory (no SQLite available, state will not persist)"))}console.log(s.green("Starting QE Quality Daemon...")),await u.start(o),console.log(s.green("QE Quality Daemon started")),console.log(s.gray(` Tick interval: ${t.tickIntervalMs}ms`)),console.log(s.gray(` CI poll interval: ${t.ciPollIntervalMs}ms`)),console.log(s.gray(` PID: ${process.pid}`)),console.log(s.gray(`
|
|
13
|
-
Press Ctrl+C to stop`));let n=setInterval(()=>{u?.running||clearInterval(n)},5e3),i=async()=>{console.log(s.yellow(`
|
|
14
|
-
Stopping QE Quality Daemon...`)),await u?.stop(),clearInterval(n),console.log(s.green("Daemon stopped")),process.exit(0)};process.once("SIGINT",i),process.once("SIGTERM",i)}),l.command("stop").description("Stop the QE Quality Daemon").action(async()=>{if(!u?.running){console.log(s.yellow("No running daemon found"));return}await u.stop(),console.log(s.green("Daemon stopped")),u=void 0}),l.command("status").description("Show daemon health and queue status").action(()=>{if(!u){console.log(s.yellow("No daemon instance (start with: aqe daemon start)"));return}let e=u.getStatus();console.log(s.bold(`
|
|
15
|
-
QE Quality Daemon Status`)),console.log(s.gray("\u2500".repeat(40))),console.log(` Running: ${e.running?s.green("yes"):s.red("no")}`),console.log(` Uptime: ${le(e.uptimeSeconds)}`),console.log(` Ticks: ${e.tickCount}`),console.log(` Throttled: ${e.throttled?s.yellow("yes"):s.green("no")}`),console.log(s.bold(`
|
|
16
|
-
Queue Depth`)),console.log(` Now: ${e.queueDepth.now}`),console.log(` Next: ${e.queueDepth.next}`),console.log(` Later: ${e.queueDepth.later}`),console.log(s.bold(`
|
|
17
|
-
Health`)),console.log(` CI: ${H(e.ciHealth)}${e.ciHealth}%${s.reset("")}`),console.log(` Coverage: ${H(e.coverageHealth)}${e.coverageHealth}%${s.reset("")}`),console.log(s.bold(`
|
|
18
|
-
Activity`)),console.log(` Commits: ${e.commitsAnalyzed}`),console.log(` Suggestions: ${e.suggestionsGenerated}`),console.log(` Notifications: ${e.notificationsSent}`),console.log()}),l.command("notifications").description("List recent notifications").option("--unread","Show only unread notifications").option("--limit <n>","Maximum notifications to show","20").option("--type <type>","Filter by type (gate_failure, coverage_drop, flaky_detected, etc.)").action(e=>{if(!u){console.log(s.yellow("No daemon instance"));return}let t=u.notificationService.list({unreadOnly:e.unread,limit:parseInt(e.limit,10),type:e.type});if(t.length===0){console.log(s.gray("No notifications"));return}console.log(s.bold(`
|
|
19
|
-
Notifications (${t.length})`)),console.log(s.gray("\u2500".repeat(60)));for(let o of t){let n=ce(o.severity),i=new Date(o.timestamp).toLocaleString(),r=o.read?s.gray("\u2713"):s.yellow("\u25CF");console.log(`${r} ${n} ${s.bold(o.title)}`),console.log(` ${o.message}`),console.log(s.gray(` ${i} [${o.type}]`)),console.log()}}),l.command("clear-notifications").description("Clear all notifications").action(()=>{if(!u){console.log(s.yellow("No daemon instance"));return}let e=u.notificationService.clear();console.log(s.green(`Cleared ${e} notifications`))}),l}function le(l){if(l<60)return`${l}s`;if(l<3600)return`${Math.floor(l/60)}m ${l%60}s`;let e=Math.floor(l/3600),t=Math.floor(l%3600/60);return`${e}h ${t}m`}function H(l){return l>=80?s.green(""):l>=60?s.yellow(""):s.red("")}function ce(l){switch(l){case"critical":return s.red("!!");case"high":return s.red("!");case"medium":return s.yellow("~");case"low":return s.blue("-");case"info":return s.gray("i");default:return" "}}export{Ke as createDaemonCommand};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u}from"./chunk-SPCANEJY.js";import"./chunk-ND6VCNN5.js";import"./chunk-DDMFTEJP.js";import"./chunk-HA7N45KB.js";import"./chunk-WVODEWH5.js";import"./chunk-VRP4GB4Y.js";import"./chunk-R5IW5ARI.js";import"./chunk-2GBBZLXT.js";import"./chunk-QHKK2H4H.js";import"./chunk-IOINZWNA.js";import"./chunk-Y57V4FDT.js";import"./chunk-3AICELMQ.js";import"./chunk-QTS2DS42.js";import"./chunk-5DJAJPBG.js";import"./chunk-4UZQSPR4.js";import"./chunk-IHRFR5SV.js";import"./chunk-TYZGEVP6.js";import"./chunk-DJRWVNHK.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-7D2DM23U.js";import"./chunk-37I6K7QO.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";export{t as BUILT_IN_STRATEGIES,b as ConceptGraph,g as DEFAULT_ACTIVATION_CONFIG,a as DEFAULT_CONCEPT_GRAPH_CONFIG,m as DEFAULT_DREAM_CONFIG,q as DEFAULT_DREAM_SCHEDULER_CONFIG,i as DEFAULT_INSIGHT_CONFIG,k as DEFAULT_VALIDATION_THRESHOLDS,n as DreamEngine,r as DreamScheduler,f as HISTORY_TRIM_TARGET_RATIO,j as InsightGenerator,d as MAX_ACTIVATION_HISTORY_ENTRIES,e as MAX_COACTIVATION_ENTRIES,l as RVCOWBranchManager,u as SpeculativeDreamer,h as SpreadingActivation,c as createConceptGraph,o as createDreamEngine,s as createDreamScheduler,p as default};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{a,c as b}from"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";b();export{a as HnswAdapter};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
|
|
2
|
-
import{a,b,c,d}from"./chunk-IEGAEXQX.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-37I6K7QO.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";export{a as DEFAULT_HNSW_CONFIG,b as HNSWIndex,d as benchmarkHNSW,c as createHNSWIndex};
|