agentic-qe 3.15.14 → 3.15.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/agents/v3/templates/qx-report-template.html +1 -1
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +46 -0
- package/assets/agents/v3/templates/qx-report-template.html +1 -1
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +6 -6
- package/dist/cli/chunks/adapter-QU6INSKP.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-EUF4XVUC.js +2 -0
- package/dist/cli/chunks/{agent-handler-P3IY7XEE.js → agent-handler-MOX6PSIQ.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-WWKC2H3G.js → agent-memory-branch-AEXKIGDG.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-PAJPENJD.js +2 -0
- package/dist/cli/chunks/{arena-EIV5OALF.js → arena-IQ5ZZDRF.js} +2 -2
- package/dist/cli/chunks/{arena-4BMFF6BS.js → arena-M7GA3CVG.js} +4 -4
- package/dist/cli/chunks/{audit-DNTI453H.js → audit-4IPBMKWB.js} +3 -3
- package/dist/cli/chunks/base-OTGSN6IC.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-TQBQGNC6.js → better-sqlite3-IKDKJ2IE.js} +2 -2
- package/dist/cli/chunks/{brain-handler-HY57CNAO.js → brain-handler-5NQUDH4W.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-THPMZPHQ.js → branch-enumerator-KSXELWRC.js} +2 -2
- package/dist/cli/chunks/{browser-O6JJOZCK.js → browser-6LACARWE.js} +2 -2
- package/dist/cli/chunks/browser-workflow-WLZGR6SB.js +2 -0
- package/dist/cli/chunks/{chunk-7724KXM2.js → chunk-22UKJGGN.js} +3 -3
- package/dist/cli/chunks/{chunk-3XACRXBY.js → chunk-27HE2BHC.js} +2 -2
- package/dist/cli/chunks/{chunk-3TF27MG5.js → chunk-2CKERSMB.js} +2 -2
- package/dist/cli/chunks/{chunk-TOJF3ZG4.js → chunk-2IIXCEMS.js} +2 -2
- package/dist/cli/chunks/{chunk-3FITMWWJ.js → chunk-2LUTPMBO.js} +2 -2
- package/dist/cli/chunks/{chunk-MB4UKUBV.js → chunk-2ZFLULL4.js} +2 -2
- package/dist/cli/chunks/{chunk-6NIGSY5L.js → chunk-337Z52QM.js} +2 -2
- package/dist/cli/chunks/{chunk-4T7XV5KQ.js → chunk-3CYNZFKH.js} +1 -1
- package/dist/cli/chunks/chunk-3HVFIITW.js +2 -0
- package/dist/cli/chunks/{chunk-2QLE6NDW.js → chunk-3J3RNJNX.js} +1 -1
- package/dist/cli/chunks/{chunk-E3QIQMMN.js → chunk-4ATQP3PR.js} +1 -1
- package/dist/cli/chunks/{chunk-EIEEST4T.js → chunk-4D4CWP72.js} +2 -2
- package/dist/cli/chunks/{chunk-WCM6WE7G.js → chunk-4HKAD25N.js} +3 -3
- package/dist/cli/chunks/{chunk-HEDGFKC5.js → chunk-4X3SWKBA.js} +2 -2
- package/dist/cli/chunks/{chunk-IQRPR4KB.js → chunk-5AFVEWMT.js} +2 -2
- package/dist/cli/chunks/{chunk-VCVRZD4Y.js → chunk-5C62XMJR.js} +3 -3
- package/dist/cli/chunks/{chunk-UDSB3XCG.js → chunk-5G4UFTV4.js} +2 -2
- package/dist/cli/chunks/{chunk-BNG4J3CE.js → chunk-5I7357KS.js} +2 -2
- package/dist/cli/chunks/{chunk-DRLSJJIC.js → chunk-5KA5TVPR.js} +2 -2
- package/dist/cli/chunks/{chunk-WZQADC5R.js → chunk-5PTAFGJT.js} +2 -2
- package/dist/cli/chunks/{chunk-M2TG7VDK.js → chunk-6BRQPHMZ.js} +1 -1
- package/dist/cli/chunks/{chunk-J35JWDJE.js → chunk-6KCSKGVY.js} +1 -1
- package/dist/cli/chunks/{chunk-QUZ745UQ.js → chunk-6LE362LZ.js} +2 -2
- package/dist/cli/chunks/{chunk-L752CNG3.js → chunk-6NBRMD25.js} +3 -3
- package/dist/cli/chunks/{chunk-56NSE3LJ.js → chunk-6RBTS3NF.js} +2 -2
- package/dist/cli/chunks/{chunk-E7OR6V3V.js → chunk-6YVMX2TC.js} +2 -2
- package/dist/cli/chunks/{chunk-WKI46WWN.js → chunk-73PBAWAF.js} +2 -2
- package/dist/cli/chunks/{chunk-HSDWPQQY.js → chunk-74YG72NQ.js} +3 -3
- package/dist/cli/chunks/{chunk-5PLBQZ5J.js → chunk-76P32JVU.js} +1 -1
- package/dist/cli/chunks/{chunk-FTYRPEJS.js → chunk-7ACCBHRB.js} +1 -1
- package/dist/cli/chunks/{chunk-O3ERGUXH.js → chunk-7BLZHFKD.js} +1 -1
- package/dist/cli/chunks/{chunk-BM3EJLMV.js → chunk-7O45RQHF.js} +2 -2
- package/dist/cli/chunks/{chunk-JSSU4RIK.js → chunk-7XB3FCKM.js} +2 -2
- package/dist/cli/chunks/{chunk-7TH4PJSU.js → chunk-AHMWD6JG.js} +2 -2
- package/dist/cli/chunks/{chunk-X7CUI7KH.js → chunk-AJPROCDW.js} +2 -2
- package/dist/cli/chunks/{chunk-TW6Z6W4X.js → chunk-AKZO6GGG.js} +13 -13
- package/dist/cli/chunks/{chunk-L7PC675Y.js → chunk-AOKKUB5F.js} +1 -1
- package/dist/cli/chunks/{chunk-UNYTHZDZ.js → chunk-AP2W7Z3A.js} +1 -1
- package/dist/cli/chunks/{chunk-VG32EEUG.js → chunk-BBRROA3Z.js} +2 -2
- package/dist/cli/chunks/{chunk-2IJO3657.js → chunk-BDKEAGQ2.js} +2 -2
- package/dist/cli/chunks/{chunk-YEFTK4HD.js → chunk-BFQTLF5X.js} +2 -2
- package/dist/cli/chunks/{chunk-JB7R77SH.js → chunk-BLL2XU7A.js} +2 -2
- package/dist/cli/chunks/{chunk-UMHFTQTR.js → chunk-BP5T3OEV.js} +2 -2
- package/dist/cli/chunks/{chunk-C3OIBFAA.js → chunk-BQ47GQPK.js} +2 -2
- package/dist/cli/chunks/{chunk-IDBA5GK2.js → chunk-BU4UQR36.js} +2 -2
- package/dist/cli/chunks/{chunk-U6IOQKCT.js → chunk-BZULJMGH.js} +2 -2
- package/dist/cli/chunks/{chunk-X6NJOT3V.js → chunk-C4KLXFJP.js} +1 -1
- package/dist/cli/chunks/{chunk-KJ5A54ZH.js → chunk-C4RTAVC6.js} +2 -2
- package/dist/cli/chunks/{chunk-ZUE524JL.js → chunk-C5CXL3JP.js} +2 -2
- package/dist/cli/chunks/{chunk-YE54T2NQ.js → chunk-CAOUV5GZ.js} +2 -2
- package/dist/cli/chunks/{chunk-7MISCSL5.js → chunk-CBK5CT6T.js} +2 -2
- package/dist/cli/chunks/{chunk-Z54G2YOL.js → chunk-DEKR3CTS.js} +2 -2
- package/dist/cli/chunks/{chunk-57DRT6UA.js → chunk-DKX4GNRU.js} +2 -2
- package/dist/cli/chunks/{chunk-HTVGHHX2.js → chunk-DUKE27HC.js} +2 -2
- package/dist/cli/chunks/{chunk-O756AOUX.js → chunk-DURD37JZ.js} +2 -2
- package/dist/cli/chunks/{chunk-OGEIHS76.js → chunk-E3MRDIZF.js} +1 -1
- package/dist/cli/chunks/{chunk-N736GLWZ.js → chunk-E56PVVWC.js} +2 -2
- package/dist/cli/chunks/{chunk-GY4P7KAI.js → chunk-E5G4WZ2T.js} +1 -1
- package/dist/cli/chunks/{chunk-JI67T6Q2.js → chunk-EBTNMQSS.js} +2 -2
- package/dist/cli/chunks/{chunk-P2TPH3TC.js → chunk-EFUJDMNC.js} +2 -2
- package/dist/cli/chunks/{chunk-7T6L3LFN.js → chunk-EKP2SC77.js} +2 -2
- package/dist/cli/chunks/{chunk-WRC3HLUY.js → chunk-EMSZVUYA.js} +3 -3
- package/dist/cli/chunks/{chunk-NZQYJCO6.js → chunk-ERN56H6S.js} +1 -1
- package/dist/cli/chunks/{chunk-INGXD5IX.js → chunk-FOOW4JVS.js} +2 -2
- package/dist/cli/chunks/{chunk-PGN4TARY.js → chunk-FTRSS64D.js} +2 -2
- package/dist/cli/chunks/{chunk-LTGQJYYO.js → chunk-G242G224.js} +2 -2
- package/dist/cli/chunks/{chunk-ARRBXCII.js → chunk-G6RDCCFV.js} +2 -2
- package/dist/cli/chunks/{chunk-7SQTLUEN.js → chunk-GCHYOPRZ.js} +2 -2
- package/dist/cli/chunks/{chunk-G7HGUQAE.js → chunk-GGQGCT4Y.js} +2 -2
- package/dist/cli/chunks/{chunk-AYLEH2UF.js → chunk-GKSMRBHU.js} +1 -1
- package/dist/cli/chunks/{chunk-JO26SG47.js → chunk-GQABPCQE.js} +2 -2
- package/dist/cli/chunks/{chunk-O2AAYJUV.js → chunk-GV2QE5TO.js} +1 -1
- package/dist/cli/chunks/{chunk-K2SMP4OD.js → chunk-H5DER3JY.js} +1 -1
- package/dist/cli/chunks/{chunk-HAYKLXCT.js → chunk-HH4ED4F7.js} +11 -11
- package/dist/cli/chunks/{chunk-L5VSLPMW.js → chunk-HL2ANKN3.js} +2 -2
- package/dist/cli/chunks/{chunk-USAKCGHC.js → chunk-HTZSRMHW.js} +2 -2
- package/dist/cli/chunks/{chunk-MR2OPUSA.js → chunk-IXL5ZHWJ.js} +1 -1
- package/dist/cli/chunks/{chunk-6P4Q4RTC.js → chunk-J3FP5UGL.js} +1 -1
- package/dist/cli/chunks/{chunk-6OI5SK7M.js → chunk-JCQGJGGZ.js} +1 -1
- package/dist/cli/chunks/{chunk-NKOLILT7.js → chunk-JCZCJE6X.js} +2 -2
- package/dist/cli/chunks/{chunk-VGZOPQQY.js → chunk-JKJOB65O.js} +1 -1
- package/dist/cli/chunks/{chunk-43XHGWYH.js → chunk-JUDUBQHA.js} +2 -2
- package/dist/cli/chunks/{chunk-NHEG2DLN.js → chunk-JW74KRBC.js} +2 -2
- package/dist/cli/chunks/{chunk-ZJGFQK27.js → chunk-K3WZICFA.js} +1 -1
- package/dist/cli/chunks/{chunk-5Y7UFHJD.js → chunk-K3XBQC3R.js} +1 -1
- package/dist/cli/chunks/{chunk-JJHLGGPP.js → chunk-KCQNFBBR.js} +1 -1
- package/dist/cli/chunks/{chunk-U4TML2VD.js → chunk-KJBPB7P5.js} +2 -2
- package/dist/cli/chunks/{chunk-6O63ZTVX.js → chunk-KLTMOXIK.js} +2 -2
- package/dist/cli/chunks/{chunk-XMCSKYDE.js → chunk-L32JNNKL.js} +1 -1
- package/dist/cli/chunks/{chunk-UPWLMIDY.js → chunk-LB2LGEDP.js} +2 -2
- package/dist/cli/chunks/{chunk-4RPBODN5.js → chunk-LHMQIZ6B.js} +2 -2
- package/dist/cli/chunks/{chunk-RE6JTSDM.js → chunk-LJMYRTJ7.js} +1 -1
- package/dist/cli/chunks/{chunk-57FX3GP6.js → chunk-LNX74WHQ.js} +1 -1
- package/dist/cli/chunks/{chunk-52KOPIMI.js → chunk-LTQVUAPH.js} +2 -2
- package/dist/cli/chunks/{chunk-H3C5FJRH.js → chunk-LVABQNRF.js} +2 -2
- package/dist/cli/chunks/{chunk-V3MGY76S.js → chunk-LYJHUNBK.js} +2 -2
- package/dist/cli/chunks/{chunk-QNQE3EOH.js → chunk-M4CJCPCQ.js} +2 -2
- package/dist/cli/chunks/{chunk-D5GB5PUU.js → chunk-M4WMSCAE.js} +1 -1
- package/dist/cli/chunks/{chunk-TWOV3I3A.js → chunk-MIA447GY.js} +1 -1
- package/dist/cli/chunks/{chunk-CAZM63TP.js → chunk-MPFPWJTH.js} +2 -2
- package/dist/cli/chunks/{chunk-BPDAQB3F.js → chunk-MV55NXTD.js} +2 -2
- package/dist/cli/chunks/{chunk-EC65UZ77.js → chunk-NQS3BWS6.js} +1 -1
- package/dist/cli/chunks/{chunk-DSQESXL4.js → chunk-NWIIYHT6.js} +2 -2
- package/dist/cli/chunks/{chunk-4WLIOPHX.js → chunk-O6EWL5DQ.js} +2 -2
- package/dist/cli/chunks/{chunk-QP2HLKTS.js → chunk-OBDONJQM.js} +2 -2
- package/dist/cli/chunks/{chunk-BQJ7CV53.js → chunk-OLZH5LRT.js} +12 -12
- package/dist/cli/chunks/{chunk-H4LYXLAT.js → chunk-OQG3UQQ7.js} +1 -1
- package/dist/cli/chunks/{chunk-E2JLAW3U.js → chunk-PFQCV6YS.js} +3 -3
- package/dist/cli/chunks/{chunk-JAOCHPYX.js → chunk-PS6UMZVK.js} +2 -2
- package/dist/cli/chunks/{chunk-K7GFYFBO.js → chunk-PXATBHWN.js} +2 -2
- package/dist/cli/chunks/{chunk-CPPYZYXC.js → chunk-PYPS65P7.js} +2 -2
- package/dist/cli/chunks/{chunk-HHBF2BZC.js → chunk-Q6I4SIUU.js} +4 -4
- package/dist/cli/chunks/{chunk-QP6GL3O5.js → chunk-QFGYH6HD.js} +1 -1
- package/dist/cli/chunks/{chunk-BBYJBZHG.js → chunk-QGBGSQ2E.js} +2 -2
- package/dist/cli/chunks/{chunk-XTZGAG6P.js → chunk-QRKTBSZT.js} +2 -2
- package/dist/cli/chunks/{chunk-FJOIBZUB.js → chunk-R6LHJ7ME.js} +2 -2
- package/dist/cli/chunks/{chunk-Z2S7DNFP.js → chunk-RBKUU7WF.js} +2 -2
- package/dist/cli/chunks/{chunk-PWQWKYBG.js → chunk-RDMRY7CT.js} +1 -1
- package/dist/cli/chunks/{chunk-65EE2EST.js → chunk-RIRZHOS2.js} +2 -2
- package/dist/cli/chunks/{chunk-D3ZZ2NLL.js → chunk-SHRI7TKJ.js} +2 -2
- package/dist/cli/chunks/{chunk-CIINJHOX.js → chunk-SJCKCSN3.js} +1 -1
- package/dist/cli/chunks/{chunk-X6Q2N5S5.js → chunk-SON6ZRH3.js} +2 -2
- package/dist/cli/chunks/{chunk-2UZBLC5H.js → chunk-SZAZQZWI.js} +2 -2
- package/dist/cli/chunks/{chunk-2W5MQDHM.js → chunk-T4GE7MPI.js} +2 -2
- package/dist/cli/chunks/{chunk-JK6PMLQQ.js → chunk-T66PPF4D.js} +2 -2
- package/dist/cli/chunks/{chunk-OLUOVNUF.js → chunk-T67R2MUN.js} +2 -2
- package/dist/cli/chunks/{chunk-O32BFQV4.js → chunk-TDQWTSBS.js} +2 -2
- package/dist/cli/chunks/{chunk-YGOSSVY5.js → chunk-TODNOP7C.js} +2 -2
- package/dist/cli/chunks/{chunk-WBC6WB32.js → chunk-TX2CHQD7.js} +2 -2
- package/dist/cli/chunks/{chunk-FHPNWHY7.js → chunk-TZIHDJZD.js} +2 -2
- package/dist/cli/chunks/{chunk-WUGXXNK4.js → chunk-U62OUXBF.js} +1 -1
- package/dist/cli/chunks/{chunk-A2T56XVL.js → chunk-UAQZI6N4.js} +2 -2
- package/dist/cli/chunks/{chunk-MKYOE7NE.js → chunk-UE2J6MA5.js} +1 -1
- package/dist/cli/chunks/{chunk-K7RT6ITZ.js → chunk-UGYM4U44.js} +1 -1
- package/dist/cli/chunks/{chunk-7QUSNBAA.js → chunk-UJABDXST.js} +2 -2
- package/dist/cli/chunks/{chunk-VJBJRFUO.js → chunk-UORB2QDU.js} +9 -9
- package/dist/cli/chunks/{chunk-O5CEL447.js → chunk-UQPA33UK.js} +2 -2
- package/dist/cli/chunks/{chunk-7MUO4DEH.js → chunk-UUBIQR6A.js} +3 -3
- package/dist/cli/chunks/{chunk-WCPSR4MJ.js → chunk-UXIY4IAI.js} +2 -2
- package/dist/cli/chunks/{chunk-UFP7SN5V.js → chunk-VCXI4XC4.js} +2 -2
- package/dist/cli/chunks/{chunk-OCN53CCK.js → chunk-VMAM46HQ.js} +2 -2
- package/dist/cli/chunks/{chunk-MQXWG55U.js → chunk-VY4U6DPO.js} +3 -3
- package/dist/cli/chunks/{chunk-M5JEA6ZY.js → chunk-W27AJ5B4.js} +2 -2
- package/dist/cli/chunks/{chunk-YGC5QKQ4.js → chunk-W5ZJG2OU.js} +2 -2
- package/dist/cli/chunks/{chunk-AJVLVF7V.js → chunk-W62OOK7A.js} +2 -2
- package/dist/cli/chunks/{chunk-WM2QRIRD.js → chunk-WNTA4YKE.js} +2 -2
- package/dist/cli/chunks/{chunk-7Y3LXH57.js → chunk-WUOOX7UG.js} +2 -2
- package/dist/cli/chunks/{chunk-PCQZIAXB.js → chunk-WVXJ2QIG.js} +2 -2
- package/dist/cli/chunks/{chunk-PNRPVQGI.js → chunk-X33CWRDF.js} +2 -2
- package/dist/cli/chunks/{chunk-TSP6SU5V.js → chunk-XG4F4XH4.js} +2 -2
- package/dist/cli/chunks/{chunk-V6SE2ZU2.js → chunk-XH4JMX5O.js} +1 -1
- package/dist/cli/chunks/{chunk-R5RRWLRI.js → chunk-XHHWABJV.js} +2 -2
- package/dist/cli/chunks/{chunk-DLTB5KCR.js → chunk-XHLYGXYE.js} +2 -2
- package/dist/cli/chunks/{chunk-NPCXGX7N.js → chunk-XIVVTYM2.js} +2 -2
- package/dist/cli/chunks/{chunk-E7QTWGPI.js → chunk-XM6ZVFM5.js} +10 -10
- package/dist/cli/chunks/{chunk-XN3KCKAM.js → chunk-XWIAZG3C.js} +2 -2
- package/dist/cli/chunks/{chunk-J6ASX536.js → chunk-Y2OX6KGN.js} +2 -2
- package/dist/cli/chunks/{chunk-HV43NX4A.js → chunk-YUS6TWAL.js} +2 -2
- package/dist/cli/chunks/{chunk-2HPNGK7A.js → chunk-ZIPAB5J6.js} +2 -2
- package/dist/cli/chunks/{chunk-XSPMLJCQ.js → chunk-ZSOMUTNL.js} +1 -1
- package/dist/cli/chunks/{chunk-IRPNEXOU.js → chunk-ZWBGYJ7K.js} +2 -2
- package/dist/cli/chunks/{chunk-5Z4MO2F3.js → chunk-ZYJB6FML.js} +1 -1
- package/dist/cli/chunks/{ci-UMA2SMNW.js → ci-UCUJOSBW.js} +2 -2
- package/dist/cli/chunks/{ci-config-UQSILJFQ.js → ci-config-2XILD3XG.js} +2 -2
- package/dist/cli/chunks/{ci-output-U6YZLLKH.js → ci-output-BL6KWOHW.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ATYQP6X2.js → circuit-breaker-5XLIOXE5.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-6YHFD7AN.js → claude-flow-setup-4IMP6ACS.js} +2 -2
- package/dist/cli/chunks/client-KKRNPX4F.js +2 -0
- package/dist/cli/chunks/{cline-installer-EPE7IOZE.js → cline-installer-RYLHCDK7.js} +2 -2
- package/dist/cli/chunks/{code-NUEJ4XYO.js → code-WY3GJXHX.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-D4DBT6OL.js → code-index-extractor-Y4MZBZCW.js} +2 -2
- package/dist/cli/chunks/{codex-installer-633SM4LR.js → codex-installer-SCJ3T3DX.js} +4 -4
- package/dist/cli/chunks/{completions-WUKVIW3L.js → completions-CN2DXQFU.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-F73ACR5H.js → complexity-analyzer-7MDPPIBH.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-QH42TKMS.js → continuedev-installer-GCEJRK34.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-Y3XC7BTT.js → copilot-installer-BHPDSELY.js} +2 -2
- package/dist/cli/chunks/core-handlers-47MPMED7.js +2 -0
- package/dist/cli/chunks/{cost-tracker-57QPV7E3.js → cost-tracker-VO5MFWR6.js} +2 -2
- package/dist/cli/chunks/{coverage-IBCHMBCR.js → coverage-LYFQYNH6.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-U6MBFHEC.js +2 -0
- package/dist/cli/chunks/{cursor-installer-F4UYQHIN.js → cursor-installer-KP4HA7TV.js} +2 -2
- package/dist/cli/chunks/{daemon-XR4Q6YZF.js → daemon-7RC7TS57.js} +3 -3
- package/dist/cli/chunks/{daemon-BYYPIJ7G.js → daemon-AXLVPKVO.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-ZR5ZD3TW.js → dag-attention-scheduler-NKA44RSR.js} +2 -2
- package/dist/cli/chunks/{detect-GEGYURLL.js → detect-CMYAJWYF.js} +2 -2
- package/dist/cli/chunks/{dist-node-JU3KT2JO.js → dist-node-EN3PYEGW.js} +2 -2
- package/dist/cli/chunks/{domain-handler-7QI3FJGE.js → domain-handler-EXSZCX7A.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-O2YRM2PD.js → domain-plugins-HCQFSNL7.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-7J3S2OS6.js → domain-transfer-3LGSNTPO.js} +2 -2
- package/dist/cli/chunks/dream-76L6EEN7.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-URES5Q6J.js → embed-and-insert-pattern-B6MNHICW.js} +2 -2
- package/dist/cli/chunks/{eval-RVMCIUOR.js → eval-OQELIWJK.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-SYJQSBKE.js → experience-capture-middleware-SUFILYPW.js} +3 -3
- package/dist/cli/chunks/{fast-paths-QUKPKWKZ.js → fast-paths-UV4NDEWM.js} +2 -2
- package/dist/cli/chunks/{feature-flags-K7JXNKJI.js → feature-flags-CKTYX67J.js} +2 -2
- package/dist/cli/chunks/{feature-flags-5JCSKL2P.js → feature-flags-H7H33B6C.js} +2 -2
- package/dist/cli/chunks/file-discovery-VSFKZ3LJ.js +2 -0
- package/dist/cli/chunks/{fleet-II4Q6HXK.js → fleet-ZJBCAKRG.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-M7VO2EMS.js → gnn-wrapper-RUE2QZRG.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-ND5CY26N.js → heartbeat-handler-XRV327M7.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-NIK3KKEH.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-WJG7LUJJ.js +2 -0
- package/dist/cli/chunks/hnsw-index-D6PRI5HC.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-N3AUUUU7.js → hnsw-legacy-bridge-UJID6ZZ4.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-NZY3E5EN.js → hnswlib-node-WS43R4AX.js} +2 -2
- package/dist/cli/chunks/{hooks-QVJDTII5.js → hooks-YZNJKXAJ.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-RIUR3I7F.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-ZRY6MTDV.js → hypergraph-engine-XQJSIMTS.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-56DO4XZQ.js → hypergraph-handler-ZD2NYXMR.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-C36YYTJ5.js +2 -0
- package/dist/cli/chunks/{init-guard-DTF4EVUY.js → init-guard-DSRUAVRT.js} +2 -2
- package/dist/cli/chunks/{init-handler-M6CNQHMX.js → init-handler-RJU5QMAP.js} +6 -6
- package/dist/cli/chunks/init-wizard-JCKNGIGT.js +2 -0
- package/dist/cli/chunks/kernel-F7ILJTYD.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-IJN7XKBH.js → kilocode-installer-BCPOCVMC.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-UKKPGPDC.js → kiro-installer-GFCWCB2S.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-VTXDBHB2.js +2 -0
- package/dist/cli/chunks/{learning-W2HETWQ4.js → learning-FZTD72CF.js} +3 -3
- package/dist/cli/chunks/{llm-router-Y546K4VX.js → llm-router-GJVKGRJL.js} +4 -4
- package/dist/cli/chunks/llm-router-service-TNOWQINA.js +2 -0
- package/dist/cli/chunks/{load-MKAB2AXE.js → load-YKTPOYBE.js} +2 -2
- package/dist/cli/chunks/load-test-FPVBK2EV.js +2 -0
- package/dist/cli/chunks/{mcp-AZKUS6K3.js → mcp-LT6R2IKS.js} +2 -2
- package/dist/cli/chunks/{memory-ZDOQN2KU.js → memory-4HKKOLRY.js} +5 -5
- package/dist/cli/chunks/memory-backend-2QE7O67A.js +2 -0
- package/dist/cli/chunks/{memory-handlers-3SQVY7FE.js → memory-handlers-X4CMVBXB.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-WWVXDHG4.js → multi-model-executor-2YPM2WTK.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-YUJNXXWS.js → opencode-installer-WBAJMH5K.js} +2 -2
- package/dist/cli/chunks/{orchestrator-Z6PWPLRE.js → orchestrator-5W5WVMVJ.js} +17 -17
- package/dist/cli/chunks/pattern-null-store-UI35ORHW.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-TPWPX32U.js → pattern-usage-recorder-GXRMNPAZ.js} +2 -2
- package/dist/cli/chunks/{pipeline-4BBGTE4M.js → pipeline-2NA4DRDA.js} +2 -2
- package/dist/cli/chunks/{platform-5GSHXCV5.js → platform-BGERNQ5V.js} +2 -2
- package/dist/cli/chunks/{plugin-OFDVF5HS.js → plugin-L4EPVENR.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-NC6MUYGJ.js → prime-radiant-advanced-wasm-RTQRTPTM.js} +2 -2
- package/dist/cli/chunks/project-root-S7WDFTMU.js +2 -0
- package/dist/cli/chunks/protocol-executor-OPANXQVB.js +2 -0
- package/dist/cli/chunks/{protocol-handler-MPOAAEPA.js → protocol-handler-SYQXM6JK.js} +2 -2
- package/dist/cli/chunks/{prove-CDKMAIVM.js → prove-5O7GPJCU.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-3OTF4DYQ.js +2 -0
- package/dist/cli/chunks/{quality-ZH4F7R7R.js → quality-KIIDHGNF.js} +2 -2
- package/dist/cli/chunks/{quality-gate-IDRMW6OE.js → quality-gate-H65VECD3.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-WTYH4TAN.js +2 -0
- package/dist/cli/chunks/{real-embeddings-I2UVNNB3.js → real-embeddings-DYIOLKQ3.js} +2 -2
- package/dist/cli/chunks/{ref-validation-Z5GCGVXK.js → ref-validation-CSBJOMZM.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-IZ2S7PH2.js → roocode-installer-G7OVYXEN.js} +2 -2
- package/dist/cli/chunks/router-DBBW4NC2.js +2 -0
- package/dist/cli/chunks/routing-feedback-W35QHCL4.js +2 -0
- package/dist/cli/chunks/{routing-handler-NAX35VUW.js → routing-handler-ZNZPPI5Y.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-5YW2SOFF.js → ruvector-commands-C6IG3OY3.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-X3NSL25Z.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-TZR7GDOK.js +2 -0
- package/dist/cli/chunks/{rvf-migration-coordinator-VUIZHTVG.js → rvf-migration-coordinator-4ATTHGHD.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-HD25ZYV5.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-IPGCAT6C.js → rvf-store-integrity-3G6LFLT3.js} +2 -2
- package/dist/cli/chunks/safe-db-ZS2QKANY.js +2 -0
- package/dist/cli/chunks/schedule-ZH6VNA32.js +2 -0
- package/dist/cli/chunks/scheduler-T6CD74B6.js +2 -0
- package/dist/cli/chunks/{security-3IH4BO5Z.js → security-A3IMVLFM.js} +3 -3
- package/dist/cli/chunks/{shared-rvf-adapter-ABY7PAY2.js → shared-rvf-adapter-VHWQ6US5.js} +2 -2
- package/dist/cli/chunks/{shared-rvf-dual-writer-6KENLN2W.js → shared-rvf-dual-writer-JB3QS7IG.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-47WU5EKZ.js +2 -0
- package/dist/cli/chunks/{standalone-memory-RLFAUGOW.js → standalone-memory-DDNXCSBD.js} +2 -2
- package/dist/cli/chunks/{status-handler-FCOZBPE5.js → status-handler-2HK7XPEK.js} +2 -2
- package/dist/cli/chunks/{structural-health-4RDA5UUM.js → structural-health-DSJVLEPV.js} +2 -2
- package/dist/cli/chunks/{sync-54LUAUTK.js → sync-3MUV6S5E.js} +2 -2
- package/dist/cli/chunks/{sync-KGEEXXCC.js → sync-NTUR53PI.js} +2 -2
- package/dist/cli/chunks/{task-handler-K3OXHYKU.js → task-handler-74MZN2EO.js} +2 -2
- package/dist/cli/chunks/{task-handlers-6H7L2UT4.js → task-handlers-VJR6EHRZ.js} +3 -3
- package/dist/cli/chunks/{test-S7IG6EIX.js → test-O6FK3FVF.js} +4 -4
- package/dist/cli/chunks/test-runner-process-2NPW3UDQ.js +2 -0
- package/dist/cli/chunks/{test-scheduling-7XYXI4L2.js → test-scheduling-Q6QEEOS6.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-3QMABE45.js → token-bootstrap-TTRCECLP.js} +2 -2
- package/dist/cli/chunks/{token-usage-Y2YTPOFE.js → token-usage-YEEFWSSI.js} +2 -2
- package/dist/cli/chunks/{transformers-UCJ3HHHC.js → transformers-BZCHJJJT.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-RZAND65G.js +2 -0
- package/dist/cli/chunks/{types-6CMFPETH.js → types-4AOKZYOX.js} +2 -2
- package/dist/cli/chunks/unified-memory-FZ5K2C7W.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-VREWX56M.js +2 -0
- package/dist/cli/chunks/unified-persistence-YZGMKX6B.js +2 -0
- package/dist/cli/chunks/{upgrade-K25DN6WU.js → upgrade-2MWW6BT2.js} +2 -2
- package/dist/cli/chunks/{validate-T4V3TBY3.js → validate-PAEV3GT5.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-XSRC576T.js → validate-swarm-ZIXACK5K.js} +2 -2
- package/dist/cli/chunks/visual-security-GXGSFBVA.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-YOZXHRTN.js → web-tree-sitter-VLTXZFAB.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-ITPU2IYL.js → windsurf-installer-VELMLOZF.js} +2 -2
- package/dist/cli/chunks/witness-chain-MRJKVCOW.js +2 -0
- package/dist/cli/chunks/witness-chain-WWHJKITG.js +2 -0
- package/dist/cli/chunks/{witness-chain-repair-YUG7E3UX.js → witness-chain-repair-5SAXPETG.js} +2 -2
- package/dist/cli/chunks/{witness-chain-verifier-DTDSVKOG.js → witness-chain-verifier-MIDWD4JS.js} +2 -2
- package/dist/cli/chunks/{witness-key-manager-EWACWGAW.js → witness-key-manager-OSVCWOB2.js} +2 -2
- package/dist/cli/chunks/{workflow-ZIQ4FV42.js → workflow-MK7A7QCX.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-SG7DV72E.js +2 -0
- package/dist/cli/chunks/{wrappers-PW2O27LL.js → wrappers-5QFMCKXL.js} +2 -2
- package/dist/init/init-wizard-hooks.d.ts +1 -1
- package/dist/init/init-wizard-hooks.js +7 -8
- package/dist/init/phases/08-mcp.js +9 -0
- package/dist/init/settings-merge.d.ts +13 -0
- package/dist/init/settings-merge.js +49 -2
- package/dist/integrations/agent-booster-wasm/agent_booster_wasm.js +849 -0
- package/dist/integrations/agent-booster-wasm/agent_booster_wasm_bg.wasm +0 -0
- package/dist/integrations/agent-booster-wasm/index.d.ts +8 -0
- package/dist/integrations/agent-booster-wasm/index.js +25 -2
- package/dist/integrations/agent-booster-wasm/package.json +16 -0
- package/dist/learning/dream/dream-engine.d.ts +3 -2
- package/dist/learning/dream/dream-engine.js +42 -24
- package/dist/learning/dream/dream-lock-retry.d.ts +38 -0
- package/dist/learning/dream/dream-lock-retry.js +66 -0
- package/dist/learning/dream/speculative-dreamer.js +1 -1
- package/dist/mcp/bundle.js +419 -419
- package/package.json +4 -2
- package/dist/cli/chunks/adapter-23KA2YW7.js +0 -2
- package/dist/cli/chunks/agent-booster-wasm-2DLAEZK6.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-MUICAXW5.js +0 -2
- package/dist/cli/chunks/base-XPWGYDKD.js +0 -2
- package/dist/cli/chunks/browser-workflow-UMQVBVGK.js +0 -2
- package/dist/cli/chunks/chunk-YKQWIXUY.js +0 -2
- package/dist/cli/chunks/client-E43GWLQH.js +0 -2
- package/dist/cli/chunks/core-handlers-R5A3SQDY.js +0 -2
- package/dist/cli/chunks/cross-domain-router-LLYVPZF6.js +0 -2
- package/dist/cli/chunks/dream-6C4NURSE.js +0 -2
- package/dist/cli/chunks/file-discovery-J5IE5KP7.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-FC5PBTMN.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-47UIVOBG.js +0 -2
- package/dist/cli/chunks/hnsw-index-3AKVLOZQ.js +0 -2
- package/dist/cli/chunks/hybrid-backend-YAOSNX47.js +0 -2
- package/dist/cli/chunks/impact-analyzer-4FMJXM4M.js +0 -2
- package/dist/cli/chunks/init-wizard-RTLCRWDT.js +0 -2
- package/dist/cli/chunks/kernel-2OWIGGGT.js +0 -2
- package/dist/cli/chunks/knowledge-graph-25XXKDJN.js +0 -2
- package/dist/cli/chunks/llm-router-service-G3EIN4UB.js +0 -2
- package/dist/cli/chunks/load-test-D6QYNIVT.js +0 -2
- package/dist/cli/chunks/memory-backend-LDFFZMEQ.js +0 -2
- package/dist/cli/chunks/pattern-null-store-KDVRM7PW.js +0 -2
- package/dist/cli/chunks/project-root-DDGBWDP6.js +0 -2
- package/dist/cli/chunks/protocol-executor-KBOLLCWA.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-GRXBT7FC.js +0 -2
- package/dist/cli/chunks/queen-coordinator-L2QWMJ5Q.js +0 -2
- package/dist/cli/chunks/router-FT5WJPUH.js +0 -2
- package/dist/cli/chunks/routing-feedback-EO2MKOUX.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-WHBFQJVU.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-YT3APF2I.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-37PUFKQD.js +0 -2
- package/dist/cli/chunks/safe-db-TDZKUOZJ.js +0 -2
- package/dist/cli/chunks/schedule-CRKTRY2A.js +0 -2
- package/dist/cli/chunks/scheduler-6ZBDVQWN.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-FFJQAIKW.js +0 -2
- package/dist/cli/chunks/test-runner-process-OTQDAJLN.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-D6JTTHTP.js +0 -2
- package/dist/cli/chunks/unified-memory-QARWQKJ2.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-LHY3DXCP.js +0 -2
- package/dist/cli/chunks/unified-persistence-WEYYGLHM.js +0 -2
- package/dist/cli/chunks/visual-security-O4ALMCXQ.js +0 -2
- package/dist/cli/chunks/witness-chain-B3YW5NMS.js +0 -2
- package/dist/cli/chunks/witness-chain-PIYR72HJ.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-3ZN2BCGY.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
|
|
2
|
+
import{a as oe,g as ce,h as de,j as pe}from"./chunk-JCZCJE6X.js";import{c as se,d as ae}from"./chunk-VY4U6DPO.js";import{a as re}from"./chunk-Q6I4SIUU.js";import{c as x}from"./chunk-HTZSRMHW.js";import{b as T,d as Z}from"./chunk-XWIAZG3C.js";import{b as te,c as ne,e as be}from"./chunk-5G4UFTV4.js";import{a as M,b as ee,d as Ee}from"./chunk-W62OOK7A.js";import{i as D}from"./chunk-QFGYH6HD.js";import{a as ie,d as Te}from"./chunk-G242G224.js";import{a as J}from"./chunk-3HVFIITW.js";import{c as N}from"./chunk-BQ47GQPK.js";import{a as v,e as z}from"./chunk-HL2ANKN3.js";var G={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};Z();z();var A=class d{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...G,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),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: ${v(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
|
|
3
3
|
INSERT INTO concept_nodes
|
|
4
4
|
(id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -37,7 +37,7 @@ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,
|
|
|
37
37
|
SELECT COUNT(*) as count FROM concept_edges
|
|
38
38
|
`)),this.prepared.set("countByType",this.db.prepare(`
|
|
39
39
|
SELECT concept_type, COUNT(*) as count FROM concept_nodes GROUP BY concept_type
|
|
40
|
-
`))}async addNode(e){this.ensureInitialized();let t=D(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let s=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,s,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 s=await this.getEdgeBetween(e,t);if(s)return await this.strengthenEdge(e,t,.1),s.id;let r=D(),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 s=Math.min(1,i.weight+n),r=this.prepared.get("updateEdge");if(!r)throw new Error("Prepared statement not found: updateEdge");r.run(s,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 a=await this.getNode(o.target);a&&t.push({node:a,edge:this.rowToEdge(o)})}let s=this.prepared.get("getIncomingEdges");if(!s)throw new Error("Prepared statement not found: getIncomingEdges");let r=s.all(e);for(let o of r){let a=await this.getNode(o.source);a&&t.push({node:a,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,s=[{nodeId:e,path:[e]}];for(;s.length>0;){let r=s.shift();if(r.nodeId===t){let a=[];for(let c of r.path){let p=await this.getNode(c);p&&a.push(p)}return a}if(r.path.length>n||i.has(r.nodeId))continue;i.add(r.nodeId);let o=await this.getNeighbors(r.nodeId);for(let{node:a}of o)i.has(a.id)||s.push({nodeId:a.id,path:[...r.path,a.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],s=async(r,o)=>{if(n.has(r)||o>t)return;n.add(r);let a=await this.getNode(r);if(a&&(i.push(a),o<t)){let c=await this.getNeighbors(r);for(let{node:p}of c)await s(p.id,o+1)}};return await s(e,0),i}static TECHNIQUE_PATTERN_TYPES=new Set(["coverage-strategy","mutation-strategy","refactor-safe","error-handling","meta-optimization"]);async loadFromPatterns(e){this.ensureInitialized();let t=0,n=[],i=new Map;for(let s of e)try{if(await this.findNodeByPatternId(s.id))continue;let o=s.patternType&&d.TECHNIQUE_PATTERN_TYPES.has(s.patternType)?"technique":"pattern",a=await this.addNode({conceptType:o,content:`${s.name}: ${s.description}`,patternId:s.id,metadata:{domain:s.domain,patternType:s.patternType,confidence:s.confidence,successRate:s.successRate}});t++,n.push(a);let c=s.domain||"unknown";i.has(c)||i.set(c,[]),i.get(c).push(a);let p=await this.findDomainNode(s.domain);if(!p){let u=await this.addNode({conceptType:"domain",content:s.domain,metadata:{patternCount:1}});p=await this.getNode(u)}p&&await this.addEdge(a,p.id,"co_occurrence",.8)}catch(r){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${s.id}`,r)}if(t>0){let s=await this.discoverSameDomainEdges(i),r=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${s} 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[s,r]of e){let o=this.countDomainSimilarityEdges(s);if(o>=n){console.log(`[ConceptGraph] Domain '${s}' already at edge cap (${o}/${n}), skipping`);continue}let a=new Set(r),c=n-o,u=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type IN ('pattern', 'technique')").all().filter(l=>{if(a.has(l.id))return!1;let g=l.metadata?
|
|
40
|
+
`))}async addNode(e){this.ensureInitialized();let t=D(),n=new Date().toISOString(),i=this.prepared.get("insertNode");if(!i)throw new Error("Prepared statement not found: insertNode");let s=e.embedding?Buffer.from(new Float32Array(e.embedding).buffer):null;return i.run(t,e.conceptType,e.content,s,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 s=await this.getEdgeBetween(e,t);if(s)return await this.strengthenEdge(e,t,.1),s.id;let r=D(),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 s=Math.min(1,i.weight+n),r=this.prepared.get("updateEdge");if(!r)throw new Error("Prepared statement not found: updateEdge");r.run(s,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 a=await this.getNode(o.target);a&&t.push({node:a,edge:this.rowToEdge(o)})}let s=this.prepared.get("getIncomingEdges");if(!s)throw new Error("Prepared statement not found: getIncomingEdges");let r=s.all(e);for(let o of r){let a=await this.getNode(o.source);a&&t.push({node:a,edge:this.rowToEdge(o)})}return t}async findPath(e,t,n=5){this.ensureInitialized();let i=new Set,s=[{nodeId:e,path:[e]}];for(;s.length>0;){let r=s.shift();if(r.nodeId===t){let a=[];for(let c of r.path){let p=await this.getNode(c);p&&a.push(p)}return a}if(r.path.length>n||i.has(r.nodeId))continue;i.add(r.nodeId);let o=await this.getNeighbors(r.nodeId);for(let{node:a}of o)i.has(a.id)||s.push({nodeId:a.id,path:[...r.path,a.id]})}return[]}async getCluster(e,t=2){this.ensureInitialized();let n=new Set,i=[],s=async(r,o)=>{if(n.has(r)||o>t)return;n.add(r);let a=await this.getNode(r);if(a&&(i.push(a),o<t)){let c=await this.getNeighbors(r);for(let{node:p}of c)await s(p.id,o+1)}};return await s(e,0),i}static TECHNIQUE_PATTERN_TYPES=new Set(["coverage-strategy","mutation-strategy","refactor-safe","error-handling","meta-optimization"]);async loadFromPatterns(e){this.ensureInitialized();let t=0,n=[],i=new Map;for(let s of e)try{if(await this.findNodeByPatternId(s.id))continue;let o=s.patternType&&d.TECHNIQUE_PATTERN_TYPES.has(s.patternType)?"technique":"pattern",a=await this.addNode({conceptType:o,content:`${s.name}: ${s.description}`,patternId:s.id,metadata:{domain:s.domain,patternType:s.patternType,confidence:s.confidence,successRate:s.successRate}});t++,n.push(a);let c=s.domain||"unknown";i.has(c)||i.set(c,[]),i.get(c).push(a);let p=await this.findDomainNode(s.domain);if(!p){let u=await this.addNode({conceptType:"domain",content:s.domain,metadata:{patternCount:1}});p=await this.getNode(u)}p&&await this.addEdge(a,p.id,"co_occurrence",.8)}catch(r){this.config.debug&&console.error(`[ConceptGraph] Failed to load pattern: ${s.id}`,r)}if(t>0){let s=await this.discoverSameDomainEdges(i),r=await this.pruneEdges();this.config.debug&&console.log(`[ConceptGraph] Discovered ${s} 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[s,r]of e){let o=this.countDomainSimilarityEdges(s);if(o>=n){console.log(`[ConceptGraph] Domain '${s}' already at edge cap (${o}/${n}), skipping`);continue}let a=new Set(r),c=n-o,u=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type IN ('pattern', 'technique')").all().filter(l=>{if(a.has(l.id))return!1;let g=l.metadata?T(l.metadata):{};return String(g.domain||"unknown")===s}),m=this.db.transaction(()=>{let l=0;for(let g of r){let f=0;for(let y of u){if(f>=t||l>=c)break;if(!this.prepared.get("getEdge")?.get(g,y.id)){let b=D();this.prepared.get("insertEdge").run(b,g,y.id,"similarity",.6,1),l++,f++}}if(l>=c)break}for(let g=0;g<r.length&&l<c;g++){let f=0;for(let y=g+1;y<r.length&&l<c&&!(f>=t);y++)if(!this.prepared.get("getEdge")?.get(r[g],r[y])){let b=D();this.prepared.get("insertEdge").run(b,r[g],r[y],"similarity",.6,1),l++,f++}}return l});i+=m()}else{let s=this.db.prepare("SELECT id, metadata FROM concept_nodes WHERE concept_type = 'pattern'").all(),r=new Map;for(let a of s){let c=a.metadata?T(a.metadata):{},p=String(c.domain||"unknown");r.has(p)||r.set(p,[]),r.get(p).push(a)}let o=this.db.transaction(()=>{let a=0;for(let[c,p]of r){let u=this.countDomainSimilarityEdges(c);if(u>=n)continue;let m=0,l=n-u;for(let g=0;g<p.length&&m<l;g++){let f=0;for(let y=g+1;y<p.length&&m<l&&!(f>=t);y++)if(!this.prepared.get("getEdge")?.get(p[g].id,p[y].id)){let b=D();this.prepared.get("insertEdge").run(b,p[g].id,p[y].id,"similarity",.6,1),a++,m++,f++}}}return a});i+=o()}return i}connectToDomainMates(e,t,n,i=10){if(!this.db)return;let s=this.db.prepare(`SELECT id FROM concept_nodes
|
|
41
41
|
WHERE concept_type IN ('pattern', 'technique')
|
|
42
42
|
AND json_extract(metadata, '$.domain') = ?
|
|
43
43
|
AND (pattern_id IS NULL OR pattern_id != ?)
|
|
@@ -63,7 +63,7 @@ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,
|
|
|
63
63
|
ORDER BY weight DESC
|
|
64
64
|
LIMIT -1 OFFSET ?
|
|
65
65
|
)
|
|
66
|
-
`).run(a,e);s+=c.changes}return s})(),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,s=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 a=0;return i>0&&(a=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:s,byType:r,avgEdgesPerNode:i>0?s/i:0,avgActivation:a}}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?A(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 Ce(d){return new T(d)}fe();function De(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let a=d[t];d[t]=d[i],d[i]=a}if(d[n]<d[t]){let a=d[t];d[t]=d[n],d[n]=a}if(d[i]<d[n]){let a=d[i];d[i]=d[n],d[n]=a}let s=d[n],r=t;for(let a=t;a<n;a++)if(d[a]<=s){let c=d[r];d[r]=d[a],d[a]=c,r++}let o=d[r];if(d[r]=d[n],d[n]=o,r===e)return d[r];r<e?t=r+1:n=r-1}return d[t]}var z=1e4,G=5e4,H=.8,ce={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={...ce,...t}}async spread(e,t=1,n){let i=e.filter(u=>this.graph.getConcept(u)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let u of i)this.graph.setActivation(u,t),this.recordActivation(u,t);let s=0,r=t,o=0,a=0;for(;s<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let u=await this.spreadIteration(),m=this.graph.getActiveNodes(this.config.threshold);for(let l of m)l.activationLevel>r&&(r=l.activationLevel);if(m.length===o&&u===0){if(a++,a>=3)break}else a=0;o=m.length,s++}let c=this.graph.getActiveNodes(this.config.threshold).map(u=>({nodeId:u.id,activation:u.activationLevel})).sort((u,m)=>m.activation-u.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:s,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(u=>({source:u.source.id,target:u.target.id,strength:u.coActivation}))}}async dream(e,t){let n=Date.now(),i=[],s=0,r=0,o=new Set,a=this.graph.getAllConcepts(0);if(a.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let c=n+e;for(;Date.now()<c&&!t?.aborted;){let m=J(0,a.length),l=a[m];if(l){let g=this.config.noiseLevel+N()*this.config.noiseLevel*2,f=l.activationLevel,v=Math.min(1,f+g+.3);this.graph.setActivation(l.id,v);let y=await this.spread([l.id],v,c);s+=y.iterations,y.peakActivation>r&&(r=y.peakActivation);for(let b of y.activatedNodes)o.add(b.nodeId);for(let b of y.novelAssociations)i.push(b)}if(Date.now()>=c||t?.aborted)break;await this.sleep(50+N()*50,t)}let p=this.deduplicateAssociations(i),u=Array.from(o).map(m=>{let l=this.graph.getConcept(m);return{nodeId:m,activation:l?.activationLevel??0}}).filter(m=>m.activation>0).sort((m,l)=>l.activation-m.activation);return this.trimHistory(),{iterations:s,nodesActivated:u.length,peakActivation:r,activatedNodes:u,novelAssociations:p.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 s=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let a=n[r],c=n[o],p=Math.sqrt(a.activationLevel*c.activationLevel),u=this.graph.getEdge(a.id,c.id),m=this.graph.getEdge(c.id,a.id),l=u!==void 0||m!==void 0,g=u?.weight??m?.weight??0,f=!l||g<.3;p>.3&&(s.push({source:a,target:c,coActivation:p,isNovel:f}),this.trackCoActivation(a.id,c.id))}return s.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<=z)return;let e=Math.floor(z*H),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<=G)return;let e=Math.floor(G*H),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=De(n,t-1),s=[];for(let[r,o]of this.coActivationCounts){if(s.length>=t)break;o<=i&&s.push(r)}for(let r of s)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 s=this.graph.getEdges(i.id);for(let r of s){let o=this.graph.getConcept(r.target);if(!o)continue;let a=i.activationLevel*r.weight*this.config.spreadFactor;if(a>.01){let c=o.activationLevel,p=Math.min(1,c+a);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let s=this.graph.getConcept(i.nodeId);s&&i.newActivation>s.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=(N()-.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(":"),s=t.get(i);(!s||n.strength>s.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e,t){return new Promise(n=>{let i=setTimeout(s,e);function s(){clearTimeout(i),t?.removeEventListener("abort",s),n()}t?.addEventListener("abort",s,{once:!0})})}};ve();import{randomUUID as Ee}from"crypto";var de={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},I=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...de,...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 s=await this.detectPatternMerges(i);for(let c of s)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 a=await this.detectGaps(i);for(let c of a)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 s=i+1;s<n.length;s++){let r=n[i],o=n[s],a=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(a?.weight??0,c?.weight??0),u=this.calculateContentSimilarity(r.content,o.content),m=Math.sqrt(r.activationLevel*o.activationLevel),l=p*.4+u*.3+m*.3;if(l>.5){let g=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),f=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:u,coActivation:m});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,l),noveltyScore:g,confidenceScore:f,actionable:f>=this.config.minConfidence,applied:!1,suggestedAction:f>=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),s=this.graph.getConcept(n.target);if(!i||!s)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==s.conceptType,a=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,s,n.strength,o),noveltyScore:a,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(s.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??{},s=i.successRate,r=i.executionCount,o=i.confidence,a=s!==void 0&&s<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(a||c&&p){let u=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c}),m=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,s,r),noveltyScore:u,confidenceScore:m,actionable:m>=this.config.minConfidence,applied:!1,suggestedAction:m>=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 s=i.conceptType??"pattern",r=K(n,s)??[];Z(n,s,r),r.push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let a=this.graph.getConcept(o.target);return a&&(a.conceptType==="pattern"||a.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),a=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:a,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 a=this.graph.getConcept(o.target);return a&&a.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),a=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:a,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(s=>s.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+/),s=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),a=s.size+r.size-o.length;return a===0?0:o.length/a}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 s=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 ${s}% 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}}};X();F();Y();ye();import{existsSync as be,unlinkSync as Ae}from"fs";var x={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},$=class{constructor(e,t=x){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-5JCSKL2P.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 s=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(s),o=i;o._rvfBranchPath=s,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(),s=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,a=[],c=!0;if(n.patternCount>0){let u=-s/n.patternCount;u>this.thresholds.maxPatternCountDrop&&(c=!1,a.push(`Pattern count dropped by ${(u*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,a.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let u=o/n.highConfidenceCount;u>this.thresholds.maxHighConfidenceLoss&&(c=!1,a.push(`${o} high-confidence patterns lost (${(u*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let u=this.rvfAdapter.dimension?.()??384,m=new Float32Array(u);for(let g=0;g<u;g++)m[g]=Math.sin(g*.1);let l=this.rvfAdapter.search?.(m,10)??[];l.length<Math.min(5,n.patternCount)&&a.push(`Search recall degraded: only ${l.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${a.join("; ")}`;return{passed:c,reason:p,patternCountDelta:s,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&&be(n)&&Ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};function U(d,e){let t=d.prepare(`
|
|
66
|
+
`).run(a,e);s+=c.changes}return s})(),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,s=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 a=0;return i>0&&(a=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:s,byType:r,avgEdgesPerNode:i>0?s/i:0,avgActivation:a}}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?T(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 Ae(d){return new A(d)}Ee();function Se(d,e){if(e<0||e>=d.length)return d[0]??0;let t=0,n=d.length-1;for(;t<n;){let i=t+n>>1;if(d[i]<d[t]){let a=d[t];d[t]=d[i],d[i]=a}if(d[n]<d[t]){let a=d[t];d[t]=d[n],d[n]=a}if(d[i]<d[n]){let a=d[i];d[i]=d[n],d[n]=a}let s=d[n],r=t;for(let a=t;a<n;a++)if(d[a]<=s){let c=d[r];d[r]=d[a],d[a]=c,r++}let o=d[r];if(d[r]=d[n],d[n]=o,r===e)return d[r];r<e?t=r+1:n=r-1}return d[t]}var H=1e4,$=5e4,U=.8,ue={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={...ue,...t}}async spread(e,t=1,n){let i=e.filter(u=>this.graph.getConcept(u)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let u of i)this.graph.setActivation(u,t),this.recordActivation(u,t);let s=0,r=t,o=0,a=0;for(;s<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let u=await this.spreadIteration(),m=this.graph.getActiveNodes(this.config.threshold);for(let l of m)l.activationLevel>r&&(r=l.activationLevel);if(m.length===o&&u===0){if(a++,a>=3)break}else a=0;o=m.length,s++}let c=this.graph.getActiveNodes(this.config.threshold).map(u=>({nodeId:u.id,activation:u.activationLevel})).sort((u,m)=>m.activation-u.activation),p=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:s,nodesActivated:c.length,peakActivation:r,activatedNodes:c,novelAssociations:p.map(u=>({source:u.source.id,target:u.target.id,strength:u.coActivation}))}}async dream(e,t){let n=Date.now(),i=[],s=0,r=0,o=new Set,a=this.graph.getAllConcepts(0);if(a.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let c=n+e;for(;Date.now()<c&&!t?.aborted;){let m=ee(0,a.length),l=a[m];if(l){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,f=l.activationLevel,y=Math.min(1,f+g+.3);this.graph.setActivation(l.id,y);let C=await this.spread([l.id],y,c);s+=C.iterations,C.peakActivation>r&&(r=C.peakActivation);for(let b of C.activatedNodes)o.add(b.nodeId);for(let b of C.novelAssociations)i.push(b)}if(Date.now()>=c||t?.aborted)break;await this.sleep(50+M()*50,t)}let p=this.deduplicateAssociations(i),u=Array.from(o).map(m=>{let l=this.graph.getConcept(m);return{nodeId:m,activation:l?.activationLevel??0}}).filter(m=>m.activation>0).sort((m,l)=>l.activation-m.activation);return this.trimHistory(),{iterations:s,nodesActivated:u.length,peakActivation:r,activatedNodes:u,novelAssociations:p.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 s=[];for(let r=0;r<n.length;r++)for(let o=r+1;o<n.length;o++){let a=n[r],c=n[o],p=Math.sqrt(a.activationLevel*c.activationLevel),u=this.graph.getEdge(a.id,c.id),m=this.graph.getEdge(c.id,a.id),l=u!==void 0||m!==void 0,g=u?.weight??m?.weight??0,f=!l||g<.3;p>.3&&(s.push({source:a,target:c,coActivation:p,isNovel:f}),this.trackCoActivation(a.id,c.id))}return s.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<=H)return;let e=Math.floor(H*U),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<=$)return;let e=Math.floor($*U),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=Se(n,t-1),s=[];for(let[r,o]of this.coActivationCounts){if(s.length>=t)break;o<=i&&s.push(r)}for(let r of s)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 s=this.graph.getEdges(i.id);for(let r of s){let o=this.graph.getConcept(r.target);if(!o)continue;let a=i.activationLevel*r.weight*this.config.spreadFactor;if(a>.01){let c=o.activationLevel,p=Math.min(1,c+a);n.push({nodeId:r.target,newActivation:p})}}}for(let i of n){let s=this.graph.getConcept(i.nodeId);s&&i.newActivation>s.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=(M()-.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(":"),s=t.get(i);(!s||n.strength>s.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e,t){return new Promise(n=>{let i=setTimeout(s,e);function s(){clearTimeout(i),t?.removeEventListener("abort",s),n()}t?.addEventListener("abort",s,{once:!0})})}};be();import{randomUUID as _e}from"crypto";var le={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...le,...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 s=await this.detectPatternMerges(i);for(let c of s)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 a=await this.detectGaps(i);for(let c of a)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 s=i+1;s<n.length;s++){let r=n[i],o=n[s],a=this.graph.getEdge(r.id,o.id),c=this.graph.getEdge(o.id,r.id),p=Math.max(a?.weight??0,c?.weight??0),u=this.calculateContentSimilarity(r.content,o.content),m=Math.sqrt(r.activationLevel*o.activationLevel),l=p*.4+u*.3+m*.3;if(l>.5){let g=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[r.id,o.id]}),f=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[r.id,o.id],edgeWeight:p,contentSimilarity:u,coActivation:m});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[r.id,o.id],description:this.generatePatternMergeDescription(r,o,l),noveltyScore:g,confidenceScore:f,actionable:f>=this.config.minConfidence,applied:!1,suggestedAction:f>=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),s=this.graph.getConcept(n.target);if(!i||!s)continue;let r=this.graph.getEdge(n.source,n.target);if(r&&r.weight>.5)continue;let o=i.conceptType!==s.conceptType,a=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,s,n.strength,o),noveltyScore:a,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(s.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??{},s=i.successRate,r=i.executionCount,o=i.confidence,a=s!==void 0&&s<.7,c=r!==void 0&&r>10,p=o!==void 0&&o<.6;if(a||c&&p){let u=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c}),m=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:a,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,s,r),noveltyScore:u,confidenceScore:m,actionable:m>=this.config.minConfidence,applied:!1,suggestedAction:m>=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 s=i.conceptType??"pattern",r=te(n,s)??[];ne(n,s,r),r.push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let a=this.graph.getConcept(o.target);return a&&(a.conceptType==="pattern"||a.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),a=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:a,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 a=this.graph.getConcept(o.target);return a&&a.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),a=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:a,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(s=>s.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=_e().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),s=new Set(n),r=new Set(i),o=n.filter(c=>r.has(c)),a=s.size+r.size-o.length;return a===0?0:o.length/a}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 s=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 ${s}% 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}}};Z();z();J();Te();function q(d){let e=d?.code;if(typeof e=="string"&&/^SQLITE_(BUSY|LOCKED)/.test(e))return!0;let t=d instanceof Error?d.message:String(d);return/database is locked|database table is locked|SQLITE_BUSY/i.test(t)}function w(d,e,t){let n=d.pragma("busy_timeout",{simple:!0});d.pragma(`busy_timeout = ${e}`);try{return t()}finally{try{d.pragma(`busy_timeout = ${n}`)}catch{}}}async function L(d,e,t={}){let n=t.waitMs??200,i=t.budgetMs??6e4,s=t.sleep??(c=>new Promise(p=>setTimeout(p,c))),r=t.now??Date.now,o=r(),a=25;for(;;){if(t.shouldContinue&&!t.shouldContinue())throw t.cancelledError?.()??new Error("Cancelled while waiting for a locked database");try{return w(d,n,e)}catch(c){if(!q(c)||r()-o+a>=i)throw c}await s(a),a=Math.min(a*2,1e3)}}var me=1e3;import{existsSync as we,unlinkSync as Ie}from"fs";var P={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},W=class{constructor(e,t=P){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-H7H33B6C.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 s=`/tmp/dream-branch-${t}.rvf`,r=this.rvfAdapter.derive(s),o=i;o._rvfBranchPath=s,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(),s=i.patternCount-n.patternCount,r=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,a=[],c=!0;if(n.patternCount>0){let u=-s/n.patternCount;u>this.thresholds.maxPatternCountDrop&&(c=!1,a.push(`Pattern count dropped by ${(u*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(r<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,a.push(`Avg confidence dropped by ${(-r).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let u=o/n.highConfidenceCount;u>this.thresholds.maxHighConfidenceLoss&&(c=!1,a.push(`${o} high-confidence patterns lost (${(u*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let u=this.rvfAdapter.dimension?.()??384,m=new Float32Array(u);for(let g=0;g<u;g++)m[g]=Math.sin(g*.1);let l=this.rvfAdapter.search?.(m,10)??[];l.length<Math.min(5,n.patternCount)&&a.push(`Search recall degraded: only ${l.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let p=c?"All quality checks passed":`Validation failed: ${a.join("; ")}`;return{passed:c,reason:p,patternCountDelta:s,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&&we(n)&&Ie(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{}}};function V(d,e){let t=d.prepare(`
|
|
67
67
|
UPDATE concept_nodes
|
|
68
68
|
SET activation_level = ?, last_activated = datetime('now')
|
|
69
69
|
WHERE id = ? AND (? IS NULL OR COALESCE(activation_level, 0) = ?)
|
|
@@ -83,13 +83,13 @@ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,
|
|
|
83
83
|
associations_found = excluded.associations_found,
|
|
84
84
|
insights_generated = excluded.insights_generated,
|
|
85
85
|
status = excluded.status, error = excluded.error
|
|
86
|
-
`),s=d.transaction(()=>{let{cycle:a}=e;i.run(a.id,a.startTime.toISOString(),a.endTime?.toISOString()??null,a.durationMs??null,a.conceptsProcessed,a.associationsFound,a.insightsGenerated,a.status,a.error??null);let c=0;for(let[p,u,m]of e.activations){let l=m??null;c+=t.run(Math.max(0,Math.min(1,u)),p,l,l).changes}for(let p of e.insights)n.run(p.id,p.cycleId,p.type,JSON.stringify(p.sourceConcepts),p.description,p.noveltyScore,p.confidenceScore,p.actionable?1:0,p.suggestedAction??null);return{activationsWritten:c,activationsSkipped:e.activations.length-c,insightsWritten:e.insights.length}}),r=performance.now();return{...s.immediate(),commitDurationMs:performance.now()-r}}var
|
|
86
|
+
`),s=d.transaction(()=>{let{cycle:a}=e;i.run(a.id,a.startTime.toISOString(),a.endTime?.toISOString()??null,a.durationMs??null,a.conceptsProcessed,a.associationsFound,a.insightsGenerated,a.status,a.error??null);let c=0;for(let[p,u,m]of e.activations){let l=m??null;c+=t.run(Math.max(0,Math.min(1,u)),p,l,l).changes}for(let p of e.insights)n.run(p.id,p.cycleId,p.type,JSON.stringify(p.sourceConcepts),p.description,p.noveltyScore,p.confidenceScore,p.actionable?1:0,p.suggestedAction??null);return{activationsWritten:c,activationsSkipped:e.activations.length-c,insightsWritten:e.insights.length}}),r=performance.now();return{...s.immediate(),commitDurationMs:performance.now()-r}}var O=600*1e3,Re="abandoned: process exited";function j(d,e=O,t=Date.now()){let n=new Date(t-e).toISOString();return d.prepare(`
|
|
87
87
|
UPDATE dream_cycles
|
|
88
88
|
SET status = 'interrupted',
|
|
89
89
|
error = ?,
|
|
90
90
|
end_time = COALESCE(end_time, ?)
|
|
91
91
|
WHERE status = 'running' AND start_time < ?
|
|
92
|
-
`).run(
|
|
92
|
+
`).run(Re,new Date(t).toISOString(),n).changes}var E=N.create("dream-engine"),ge=!1,Ne=1e3,fe={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!1,branchValidationThresholds:{...P}},Me=6e4,B=class extends Error{constructor(t){super(`A dream cycle is already running (cycle ${t}); wait for it to finish or cancel it`);this.cycleId=t;this.name="DreamAlreadyRunningError"}cycleId},Y=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;loadedLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear(),this.loadedLevels.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),this.loadedLevels.set(n.id,n.activationLevel);for(let n of t){let s=(await this.graph.getNeighbors(n.id)).map(r=>r.edge);this.edgeCache.set(n.id,s)}}activationEntries(){return Array.from(this.activationLevels.entries(),([e,t])=>[e,t,this.loadedLevels.get(e)])}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,s=Array.from(this.edgeCache.values());for(let r of s)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}}},I=class{config;persistence=null;graph=null;db=null;interruptActiveDream=null;activeDream=null;activeAbort=null;currentCycle=null;initialized=!1;cancelled=!1;cancelRequests=0;closing=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}set rvfAdapter(e){}constructor(e){this.config={...fe,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),w(this.db,200,()=>this.migrateSchema()),this.graph=new A,await this.graph.initialize(),this.config.enableBranching&&E.warn("DreamConfig.enableBranching is deprecated and ignored (#1060): dream results are committed in one short transaction instead of a SAVEPOINT held across the dream");let e=this.db;try{let t=w(e,200,()=>j(e,Math.max(this.config.maxDurationMs,Me)+O));t>0&&E.info("Marked abandoned dream cycles as interrupted",{abandoned:t})}catch(t){if(!q(t))throw t;E.warn("Abandoned dream cycle sweep skipped: database is locked",{error:v(t)})}this.initialized=!0,this.closing=!1,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${v(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(a=>a.name==="duration_ms"),n=e.some(a=>a.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(),s=new Set(i.map(a=>a.name)),r=s.has("insight_type"),o=s.has("source_concepts");if(!r)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),E.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 '[]'"),E.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){E.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e,t={}){if(this.ensureInitialized(),this.closing)throw new Error("Dream engine is closing; no new dream is started");if(this.activeDream)throw new B(this.activeDream.cycleId);let n={id:D(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},i=this.runDream(n,e??this.config.maxDurationMs,t);this.activeDream={cycleId:n.id,done:i.catch(()=>{})};try{return await i}finally{this.activeDream?.cycleId===n.id&&(this.activeDream=null)}}async runDream(e,t,n){let i=this.db,s=this.graph,r=Date.now(),o=new AbortController;this.activeAbort=o,this.cancelled=!1,this.currentCycle=e;let a=n.commit!==!1,c=this.createCycleInterrupter(e,r,o);this.interruptActiveDream=c;let p=ie(c),u=()=>!this.cancelled&&!o.signal.aborted&&this.db===i,m=!1;try{if(a&&await this.saveCycle(e,u),!u())throw new Error("Dream cycle cancelled");let l=n.minConceptsRequired??this.config.minConceptsRequired,g=await s.getActiveNodes(0);if(g.length<l)throw new Error(`Insufficient concepts: ${g.length} < ${l}`);let f=new Y(s);await f.loadIntoMemory(30);let C=await new S(f,{...this.config.activationConfig,...n.activationConfig}).dream(t,o.signal);if(!u())throw new Error("Dream cycle cancelled");e.conceptsProcessed=C.nodesActivated,e.associationsFound=C.novelAssociations.length;let k=await new _(f,this.config.insightConfig).generateFromActivation(e.id,C);if(!u())throw new Error("Dream cycle cancelled");e.insightsGenerated=k.length,e.endTime=new Date,e.durationMs=Date.now()-r,e.status="completed";let X={cycle:e,activations:f.activationEntries(),insights:k},R={cycle:{...e},insights:k,activationStats:{totalIterations:C.iterations,peakActivation:C.peakActivation,nodesActivated:C.nodesActivated},patternsCreated:0};if(!a)return m=!0,{...R,pending:X};let K=await this.commitComputed(i,X,u);return m=!0,R.commitDurationMs=K.durationMs,R.retention=K.retention,R}catch(l){if(!m&&e.status!=="interrupted"&&(e.status=this.cancelled?"interrupted":"failed",e.error=v(l),e.endTime=new Date,e.durationMs=Date.now()-r,a&&this.db===i))try{await L(i,()=>this.updateCycleSync(e),{shouldContinue:()=>this.db===i})}catch{}if(!m&&a)try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:e.id,reason:v(l)},"dream-engine")}catch{}throw l}finally{p(),this.interruptActiveDream===c&&(this.interruptActiveDream=null),this.currentCycle===e&&(this.currentCycle=null),this.activeAbort===o&&(this.activeAbort=null)}}async commitDreamResult(e){if(this.ensureInitialized(),this.closing)throw new Error("Dream engine is closing; nothing is committed");if(!e.pending)throw new Error("Dream result has nothing pending to commit (it was already committed)");let t=this.db,n=await this.commitComputed(t,e.pending,()=>!this.closing&&this.db===t);return e.pending=void 0,e.commitDurationMs=n.durationMs,e.retention=n.retention,n.durationMs}async commitComputed(e,t,n){let i=await L(e,()=>V(e,t),{shouldContinue:n,cancelledError:()=>new Error("Dream cycle cancelled")});try{this._witnessChain?.append("DREAM_COMMIT",{cycleId:t.cycle.id,insights:i.insightsWritten,activations:i.activationsWritten,commitDurationMs:i.commitDurationMs},"dream-engine")}catch{}return{durationMs:i.commitDurationMs,retention:this.runDefaultRetention(e)}}runDefaultRetention(e){let t=ce();if(t.warnings.length>0&&!ge){ge=!0;for(let i of t.warnings)E.warn(i)}let n=e.pragma("busy_timeout",{simple:!0});try{e.pragma(`busy_timeout = ${Ne}`);let i=de(e,t);if(i.enabled)for(let s of i.steps)s.affected>0&&E.info(`Retention ${pe(s)}`);return i}catch(i){return E.warn("Dream retention skipped after dream commit",{error:v(i)}),{enabled:t.enabled,steps:[],error:v(i)}}finally{try{e.pragma(`busy_timeout = ${n}`)}catch{}}}createCycleInterrupter(e,t,n){return()=>{if(n.abort(),!(e.status!=="running"||!this.db)){e.status="interrupted",e.error="Interrupted: engine closed or process shut down during the dream cycle",e.endTime=new Date,e.durationMs=Date.now()-t;try{w(this.db,me,()=>this.updateCycleSync(e))}catch{}}}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
|
|
93
93
|
FROM qe_pattern_nulls n
|
|
94
94
|
JOIN qe_patterns p ON p.id = n.pattern_id
|
|
95
95
|
ORDER BY n.updated_at DESC
|
|
@@ -99,7 +99,7 @@ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,
|
|
|
99
99
|
JOIN qe_patterns p ON p.id = u.pattern_id
|
|
100
100
|
WHERE u.success = 1
|
|
101
101
|
ORDER BY u.created_at DESC
|
|
102
|
-
LIMIT 100`).all();i.length>0&&await this.graph.loadSuccessesAsOutcomes(i)}catch(n){process.env.DEBUG&&E.debug("Error/outcome concept loading skipped",{error:
|
|
102
|
+
LIMIT 100`).all();i.length>0&&await this.graph.loadSuccessesAsOutcomes(i)}catch(n){process.env.DEBUG&&E.debug("Error/outcome concept loading skipped",{error:v(n)})}if((await this.graph.getActiveNodes(0)).length>=this.config.minConceptsRequired)return 0;let t=this.db.prepare(`SELECT * FROM (
|
|
103
103
|
SELECT id, name, description, qe_domain as domain, pattern_type as patternType,
|
|
104
104
|
confidence, success_rate as successRate
|
|
105
105
|
FROM qe_patterns
|
|
@@ -115,11 +115,11 @@ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,
|
|
|
115
115
|
WHERE confidence >= 0.3 AND success_rate < 0.7
|
|
116
116
|
ORDER BY usage_count DESC
|
|
117
117
|
LIMIT 40
|
|
118
|
-
)`).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{getSharedMemoryBackend:n}=await import("./base-
|
|
118
|
+
)`).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{getSharedMemoryBackend:n}=await import("./base-OTGSN6IC.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-3OTF4DYQ.js"),s=await n(),r=i(s);await r.initialize();try{let{getSharedRvfDualWriter:m}=await import("./shared-rvf-dual-writer-JB3QS7IG.js"),l=await m();l&&r.setRvfDualWriter(l)}catch(m){process.env.DEBUG&&E.debug("RVF wiring skipped",{error:v(m)})}let o=[];try{o=T(t.source_concepts)}catch{}let a=await r.storePattern({patternType:xe(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}}),c=!a.success&&a.error instanceof re&&a.error.disposition==="COMMITTED_PENDING_INDEX"?a.error:null;if(!a.success&&!c)return{success:!1,error:`Failed to create pattern: ${a.error?.message??"unknown error"}`};let p=a.success?a.value.id:c.patternId;return c&&E.warn("Insight applied; pattern committed with vector index pending",{insightId:e,patternId:p,cause:v(c.cause)}),this.db.prepare(`
|
|
119
119
|
UPDATE dream_insights
|
|
120
120
|
SET applied = 1, pattern_id = ?
|
|
121
121
|
WHERE id = ?
|
|
122
|
-
`).run(p,e),c?{success:!0,patternId:p,indexPending:!0}:{success:!0,patternId:p}}catch(t){return{success:!1,error:
|
|
122
|
+
`).run(p,e),c?{success:!0,patternId:p,indexPending:!0}:{success:!0,patternId:p}}catch(t){return{success:!1,error:v(t)}}}async getPendingInsights(e){this.ensureInitialized();let t=e??20;return this.db.prepare(`
|
|
123
123
|
SELECT * FROM dream_insights
|
|
124
124
|
WHERE applied = 0 AND actionable = 1
|
|
125
125
|
ORDER BY novelty_score DESC, confidence_score DESC
|
|
@@ -128,14 +128,14 @@ import{a as re,g as se,h as ae,j as oe}from"./chunk-NKOLILT7.js";import{c as ne,
|
|
|
128
128
|
SELECT * FROM dream_cycles
|
|
129
129
|
ORDER BY start_time DESC
|
|
130
130
|
LIMIT ?
|
|
131
|
-
`).all(t).map(s=>this.rowToCycle(s))}get cancelCount(){return this.cancelRequests}async cancelDream(){this.cancelled=!0,this.cancelRequests++,this.activeAbort?.abort()}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(`
|
|
131
|
+
`).all(t).map(s=>this.rowToCycle(s))}get cancelCount(){return this.cancelRequests}async cancelDream(){this.cancelled=!0,this.cancelRequests++,this.activeAbort?.abort()}isDreaming(){return this.currentCycle!==null&&this.currentCycle.status==="running"}getCurrentCycle(){return this.currentCycle?{...this.currentCycle}:null}async saveCycle(e,t){if(!this.db)return;let n=this.db,i=this.db.prepare(`
|
|
132
132
|
INSERT INTO dream_cycles
|
|
133
133
|
(id, start_time, end_time, duration_ms, concepts_processed, associations_found,
|
|
134
134
|
insights_generated, status, error, created_at)
|
|
135
135
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
136
|
-
`).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())}updateCycleSync(e){if(!this.db)return;this.db.prepare(`
|
|
136
|
+
`);await L(n,()=>i.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()),{shouldContinue:t,cancelledError:()=>new Error("Dream cycle cancelled")})}updateCycleSync(e){if(!this.db)return;this.db.prepare(`
|
|
137
137
|
UPDATE dream_cycles
|
|
138
138
|
SET end_time = ?, duration_ms = ?, concepts_processed = ?, associations_found = ?,
|
|
139
139
|
insights_generated = ?, status = ?, error = ?
|
|
140
140
|
WHERE id = ?
|
|
141
|
-
`).run(e.endTime?.toISOString()??null,e.durationMs??null,e.conceptsProcessed,e.associationsFound,e.insightsGenerated,e.status,e.error??null,e.id)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return null}onBranchEvent(e){this.branchEventListeners.push(e)}async close(){this.closing=!0,this.cancelRequests++,this.interruptActiveDream?.(),this.interruptActiveDream=null,this.activeAbort?.abort();let e=this.activeDream?.done;if(e){let t;await Promise.race([e,new Promise(n=>{t=setTimeout(n,2e3)})]),clearTimeout(t)}this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=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:A(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 _e(d){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[d]||"test-template"}function we(d){let e=new _(d);return import("./feature-flags-5JCSKL2P.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-ABY7PAY2.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var Re=_;Y();var le="learning:loop-health";async function me(d,e,t){try{let n=new Date().toISOString(),i=await d.get(le)??{overallLastSuccess:"",bootedAt:n,components:{}},s=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(s.ticksSinceBoot+=1,t.success)s.lastSuccessAt=n,s.successesSinceBoot+=1,delete s.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);s.lastError={message:o,at:n}}i.components[e]=s;let r=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=r.length>0?r.sort().pop():"",await d.set(le,i)}catch{}}var h=R.create("DreamScheduler"),ge={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},he="dream-scheduler:hook-state",O=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...ge,...t},this.metaLearningEngine=new ie}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,h.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),h.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),h.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,h.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&&(h.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{h.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,h.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&h.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(s){h.warn("Post-dream meta-learning failed (non-critical)",{error:s instanceof Error?s.message:String(s)})}return this.running&&this.scheduleNextDream(),h.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await me(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&h.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){h.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-ABY7PAY2.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&h.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){h.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-6KENLN2W.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&h.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){h.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new re,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=ne.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){h.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)h.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>d.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:D(),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{h.debug("Failed to publish meta-learning insight event")}}}else h.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){h.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),h.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){h.info("Quality gate failed but cannot start dream yet");return}h.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){h.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){h.info("Milestone reached but cannot start dream yet");return}h.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){h.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:D(),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){h.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(he),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(he,t)}catch(e){h.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){h.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??[],h.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){h.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 Ne(d,e){return new O(d,e)}F();var Me=[{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}}],V=class{constructor(e){this.engine=e}engine;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=[],s=this.engine.cancelCount,r=()=>this.engine.cancelCount!==s;for(let c of e){if(r())break;i.push(await this.executeStrategy(c,t.durationMs))}if(r())return{strategies:i,winner:null,totalDurationMs:Date.now()-n,cancelled:!0};let o=null;for(let c of i)c.result&&(!o||c.score>o.score)&&(o=c);let a;if(o?.result)try{a=this.engine.commitDreamResult(o.result),o.selected=!0}catch(c){o.error=C(c),o=null}return{strategies:i,winner:o,totalDurationMs:Date.now()-n,commitDurationMs:a,cancelled:!1}}async executeStrategy(e,t){let n=Date.now();try{let i=await this.engine.dream(t,{activationConfig:e.activationConfig,commit:!1});return{strategy:e,result:i,score:this.scoreResult(i),selected:!1,durationMs:Date.now()-n}}catch(i){return{strategy:e,result:null,score:Number.NEGATIVE_INFINITY,error:C(i),selected:!1,durationMs:Date.now()-n}}}scoreResult(e){return e.insights.reduce((n,i)=>n+i.confidenceScore*i.noveltyScore,0)+e.cycle.associationsFound*.01}};export{me as a,ge as b,O as c,Ne as d,k as e,T as f,Ce as g,z as h,G as i,H as j,ce as k,S as l,de as m,I as n,x as o,$ as p,U as q,L as r,q as s,ue as t,P as u,_ as v,we as w,Re as x,Me as y,V as z};
|
|
141
|
+
`).run(e.endTime?.toISOString()??null,e.durationMs??null,e.conceptsProcessed,e.associationsFound,e.insightsGenerated,e.status,e.error??null,e.id)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return null}onBranchEvent(e){this.branchEventListeners.push(e)}async close(){this.closing=!0,this.cancelRequests++,this.interruptActiveDream?.(),this.interruptActiveDream=null,this.activeAbort?.abort();let e=this.activeDream?.done;if(e){let t;await Promise.race([e,new Promise(n=>{t=setTimeout(n,2e3)})]),clearTimeout(t)}this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=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:T(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 xe(d){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[d]||"test-template"}function Le(d){let e=new I(d);return import("./feature-flags-H7H33B6C.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-VHWQ6US5.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var Pe=I;J();var ye="learning:loop-health";async function ve(d,e,t){try{let n=new Date().toISOString(),i=await d.get(ye)??{overallLastSuccess:"",bootedAt:n,components:{}},s=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(s.ticksSinceBoot+=1,t.success)s.lastSuccessAt=n,s.successesSinceBoot+=1,delete s.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);s.lastError={message:o,at:n}}i.components[e]=s;let r=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=r.length>0?r.sort().pop():"",await d.set(ye,i)}catch{}}var h=N.create("DreamScheduler"),De={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},Ce="dream-scheduler:hook-state",F=class d{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...De,...t},this.metaLearningEngine=new ae}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,h.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),h.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),h.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,h.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&&(h.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{h.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,h.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&h.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(s){h.warn("Post-dream meta-learning failed (non-critical)",{error:s instanceof Error?s.message:String(s)})}return this.running&&this.scheduleNextDream(),h.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await ve(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&h.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){h.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-VHWQ6US5.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&h.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){h.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-JB3QS7IG.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&h.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){h.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new oe,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>d.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=se.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){h.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)h.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>d.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:D(),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{h.debug("Failed to publish meta-learning insight event")}}}else h.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){h.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),h.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){h.info("Quality gate failed but cannot start dream yet");return}h.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){h.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){h.info("Milestone reached but cannot start dream yet");return}h.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){h.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:D(),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){h.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(Ce),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(Ce,t)}catch(e){h.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){h.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??[],h.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){h.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function Oe(d,e){return new F(d,e)}z();var Be=[{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}}],Q=class{constructor(e){this.engine=e}engine;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=[],s=this.engine.cancelCount,r=()=>this.engine.cancelCount!==s;for(let c of e){if(r())break;i.push(await this.executeStrategy(c,t.durationMs))}if(r())return{strategies:i,winner:null,totalDurationMs:Date.now()-n,cancelled:!0};let o=null;for(let c of i)c.result&&(!o||c.score>o.score)&&(o=c);let a;if(o?.result)try{a=await this.engine.commitDreamResult(o.result),o.selected=!0}catch(c){o.error=v(c),o=null}return{strategies:i,winner:o,totalDurationMs:Date.now()-n,commitDurationMs:a,cancelled:!1}}async executeStrategy(e,t){let n=Date.now();try{let i=await this.engine.dream(t,{activationConfig:e.activationConfig,commit:!1});return{strategy:e,result:i,score:this.scoreResult(i),selected:!1,durationMs:Date.now()-n}}catch(i){return{strategy:e,result:null,score:Number.NEGATIVE_INFINITY,error:v(i),selected:!1,durationMs:Date.now()-n}}}scoreResult(e){return e.insights.reduce((n,i)=>n+i.confidenceScore*i.noveltyScore,0)+e.cycle.associationsFound*.01}};export{ve as a,De as b,F as c,Oe as d,G as e,A as f,Ae as g,H as h,$ as i,U as j,ue as k,S as l,le as m,_ as n,P as o,W as p,V as q,O as r,j as s,fe as t,B as u,I as v,Le as w,Pe as x,Be as y,Q as z};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
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.15.15");process.exit(0)}
|
|
2
2
|
var l=[{name:"aqe-plan-quality",default:!0},{name:"aqe-plan-work",default:!0},{name:"aqe-research",default:!0},{name:"aqe-review-quality",default:!0},{name:"aqe-test-change",default:!0},{name:"aqe-ruflo",default:!1,files:["SKILL.md"]}];function t(a={}){return l.filter(e=>e.default||e.name==="aqe-ruflo"&&a.includeRuflo===!0)}export{t as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{a as I,b as _,c as X,d as M,f as ee,h as ae}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
|
|
2
|
+
import{a as I,b as _,c as X,d as M,f as ee,h as ae}from"./chunk-RBKUU7WF.js";import{a as K,e as Z}from"./chunk-Q6I4SIUU.js";import{c as te,d as re,e as ne,f as ie}from"./chunk-UXIY4IAI.js";import{b as D,g as $,j as H}from"./chunk-KCQNFBBR.js";import{b as k}from"./chunk-TODNOP7C.js";import{c as Y,i as J}from"./chunk-YUS6TWAL.js";import{r as U,v as ve}from"./chunk-T66PPF4D.js";import{s as T}from"./chunk-6NBRMD25.js";import{c as C,d as E}from"./chunk-LJMYRTJ7.js";import{a as G}from"./chunk-3HVFIITW.js";import{c as A}from"./chunk-BQ47GQPK.js";import{S as ye,b as j}from"./chunk-6YVMX2TC.js";import{a as f,b as B,e as z}from"./chunk-HL2ANKN3.js";G();z();function oe(i,e,r,t){let n={missing:0,ingested:0,rejected:0,capped:!1};if(typeof i.has!="function")return n;let a=d=>d.filter(h=>!i.has(h)),o=a(e.getEmbeddingIdsInSpace(r));if(o.length===0)return n;let s=Number.isFinite(t)&&t>0?Math.floor(t):1e3;o.length>s&&(o=a(e.getEmbeddingIdsInSpace(r,{ordered:!0})));let l=o.slice(0,s),u=e.getEmbeddingsByIds(l).filter(({embedding:d})=>d&&d.length>0).map(({patternId:d,embedding:h})=>({id:d,vector:new Float32Array(h)})),{accepted:c,rejected:g}=u.length>0?i.ingest(u):{accepted:0,rejected:0};return{missing:o.length,ingested:c,rejected:g,capped:o.length>s}}var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
|
|
3
3
|
describe('{{methodName}}', () => {
|
|
4
4
|
it('should {{expectedBehavior}}', {{async}} () => {
|
|
5
5
|
// Arrange
|
|
@@ -317,4 +317,4 @@ On promotion:
|
|
|
317
317
|
AND agent_id = 'aqe-hook-router'
|
|
318
318
|
AND state_key = ?
|
|
319
319
|
AND action_key = ?
|
|
320
|
-
`);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-
|
|
320
|
+
`);return o=>{try{let s=a.get(e,o);return s?{qValue:s.q_value,visits:s.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return I(e)}generateContext(e,r){return M(e,r||{})}checkAntiPatterns(e,r){return X(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-DYIOLKQ3.js"),t=await r(e);if(t.length!==this.config.embeddingDimension)return me(t,this.config.embeddingDimension);let n=T()?.spaceId;return n&&this.embeddingProvenance.set(t,n),t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-DYIOLKQ3.js");if(t())throw r;process.env.DEBUG&&m.warn("ONNX embeddings unavailable, using hash fallback",{error:f(r)})}return ge(e,this.config.embeddingDimension)}async embedForPatterns(e){if(!this.embedderRecovery.isAvailable())return null;try{return await this.embed(e)}catch(r){let t=f(r),n="Embedder failed: storing and searching patterns by text only";return this.embedderRecovery.markUnavailable(t)?m.warn(n,{error:t}):m.debug(n,{error:t}),null}}getEmbedderFailure(){return this.embedderRecovery.unavailableReason}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let c of H)r[c]=e.byDomain[c]||0;let t=this.stats.routingRequests,n=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,a=this.stats.learningOutcomes,o=this.stats.measuredOutcomes,s=this.stats.learningOutcomes-this.stats.measuredOutcomes,l=this.stats.successfulOutcomes;try{let c=this.getSqliteStore().getAggregateOutcomeStats();c.routingRequests>t&&(t=c.routingRequests,n=c.avgRoutingConfidence),c.learningOutcomes>a&&(a=c.learningOutcomes,o=c.measuredOutcomes,s=c.unmeasuredOutcomes,l=c.successfulOutcomes)}catch{}let u=o>0?l/o:null;return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:n,learningOutcomes:a,measuredOutcomes:o,unmeasuredOutcomes:s,patternSuccessRate:u,...u===null?{evidenceStatus:"insufficient-evidence"}:{},patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function Dt(i,e,r,t){return new W(i,e,r,t)}export{N as a,q as b,x as c,ue as d,O as e,Q as f,W as g,Dt as h};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{i as t,j as s,l as a,n as m}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
|
|
2
|
+
import{i as t,j as s,l as a,n as m}from"./chunk-LTQVUAPH.js";m();var p={0:{tier:0,name:"Agent Booster",description:"Mechanical code transforms via Rust/WASM",useCases:["var-to-const conversion","add-types","remove-console statements","promise-to-async","cjs-to-esm","func-to-arrow"],typicalLatencyMs:1,relativeCost:0,exampleModels:["agent-booster-wasm","agent-booster-typescript"],requiresNetwork:!1,complexityRange:[0,10]},1:{tier:1,name:"Haiku",description:"Fast, cost-effective for simple tasks",useCases:["Simple bug fixes","Code formatting","Documentation updates","Basic refactoring","Test generation (simple)"],typicalLatencyMs:500,relativeCost:1,exampleModels:[a[1],"gpt-4o-mini","gemini-flash"],requiresNetwork:!0,complexityRange:[10,35]},2:{tier:2,name:"Sonnet",description:"Balanced capability for complex reasoning",useCases:["Feature implementation","Complex refactoring","Security analysis","Performance optimization","Test generation (complex)"],typicalLatencyMs:3e3,relativeCost:2,exampleModels:[t,"gpt-4o","gemini-pro"],requiresNetwork:!0,complexityRange:[35,70]},3:{tier:3,name:"Sonnet Extended",description:"Extended context for multi-step workflows",useCases:["Multi-file refactoring","Workflow orchestration","Cross-domain coordination","Large codebase analysis"],typicalLatencyMs:7e3,relativeCost:3,exampleModels:[t],requiresNetwork:!0,complexityRange:[60,85]},4:{tier:4,name:"Opus",description:"Maximum capability for critical decisions",useCases:["Architecture design","Security audits","Complex algorithm design","Critical bug analysis","System-wide refactoring"],typicalLatencyMs:5e3,relativeCost:4,exampleModels:[s,"gpt-4-turbo"],requiresNetwork:!0,complexityRange:[75,100]}},c={enabled:!0,tierBudgets:{0:{tier:0,maxCostPerRequest:0,maxRequestsPerHour:1e4,maxRequestsPerDay:1e5,maxDailyCostUsd:0,enabled:!0},1:{tier:1,maxCostPerRequest:.01,maxRequestsPerHour:100,maxRequestsPerDay:1e3,maxDailyCostUsd:5,enabled:!0},2:{tier:2,maxCostPerRequest:.1,maxRequestsPerHour:50,maxRequestsPerDay:500,maxDailyCostUsd:20,enabled:!0},3:{tier:3,maxCostPerRequest:.5,maxRequestsPerHour:20,maxRequestsPerDay:100,maxDailyCostUsd:30,enabled:!0},4:{tier:4,maxCostPerRequest:2,maxRequestsPerHour:10,maxRequestsPerDay:50,maxDailyCostUsd:50,enabled:!0}},maxDailyCostUsd:100,warningThreshold:.8,onBudgetExceeded:"downgrade",onBudgetWarning:"warn",allowCriticalOverrides:!0},b={budgetConfig:c,enableAgentBooster:!0,agentBoosterThreshold:.7,enableAutoRouting:!0,complexityThresholds:{0:10,1:35,2:70,3:85,4:100},allowManualOverrides:!0,enableDecisionCache:!0,decisionCacheTtlMs:300*1e3,enableMetrics:!0,maxDecisionTimeMs:10,fallbackTier:2,tierModels:{0:"agent-booster",...a}},r=class extends Error{constructor(e,i,y){super(e);this.code=i;this.cause=y;this.name="ModelRouterError"}code;cause},l=class extends r{constructor(e,i,y){super(e,"BUDGET_EXCEEDED");this.tier=i;this.usage=y;this.name="BudgetExceededError"}tier;usage},d=class extends r{constructor(o,e){super(o,"COMPLEXITY_ANALYSIS_ERROR",e),this.name="ComplexityAnalysisError"}},u=class extends r{constructor(e,i){super(e,"ROUTING_TIMEOUT");this.timeoutMs=i;this.name="RoutingTimeoutError"}timeoutMs};export{p as a,c as b,b as c,r as d,l as e,d as f,u as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{b as t,d as o}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
|
|
2
|
+
import{b as t,d as o}from"./chunk-XH4JMX5O.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.
|
|
2
|
-
import{e as U,h as W,i as G}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.15");process.exit(0)}
|
|
2
|
+
import{e as U,h as W,i as G}from"./chunk-UUBIQR6A.js";import{b as F}from"./chunk-2IIXCEMS.js";import{o as j,q as V}from"./chunk-O6EWL5DQ.js";import{b as D,c as $,d as Y}from"./chunk-W62OOK7A.js";import{a as T,e as N}from"./chunk-HL2ANKN3.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
|
|
3
3
|
Recommendations: Implement proper ${r[0]} attributes for better accessibility.
|
|
4
4
|
Severity: ${e.includes("critical")?"critical":"serious"}`}},P=class{constructor(e,r,s){this.executor=r;this.config=s;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let s of e){this.lastHeartbeat=Date.now();try{let t=await this.executeTestCase(s);if(r.push(t),t.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!t.passed){let a=await this.executeTestCase(s,!0);a.passed&&(r[r.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(t){this.tasksFailed++,r.push({testId:s.testCaseId,passed:!1,expectedPatterns:s.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:s.testCase.category,priority:s.testCase.priority,error:T(t)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let s=Date.now(),t=this.buildPrompt(e),a=await this.executor.execute(t,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-s,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:r}=e,s=r.input.context;return`Analyze the following ${s.language||"HTML"} code for accessibility issues.
|
|
5
5
|
Context: ${s.description||r.description}
|