agentic-qe 3.14.4 → 3.14.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +169 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/adapters/ag-ui/event-types.d.ts +1 -1
- package/dist/audit/witness-chain-hash.d.ts +18 -0
- package/dist/audit/witness-chain-hash.js +37 -0
- package/dist/audit/witness-chain-repair.d.ts +71 -0
- package/dist/audit/witness-chain-repair.js +203 -0
- package/dist/audit/witness-chain-verifier.d.ts +152 -0
- package/dist/audit/witness-chain-verifier.js +293 -0
- package/dist/audit/witness-chain.d.ts +10 -43
- package/dist/audit/witness-chain.js +43 -126
- package/dist/audit/witness-findings.js +4 -1
- package/dist/cli/bundle.js +13 -10
- package/dist/cli/chunks/adapter-UYOJPTOX.js +2 -0
- package/dist/cli/chunks/agent-booster-wasm-2YGML6OU.js +2 -0
- package/dist/cli/chunks/{agent-handler-RDNTK4CA.js → agent-handler-D5SSQYNU.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-NAAMBWIR.js → agent-memory-branch-YHPLTITV.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-JR5AVQXR.js +2 -0
- package/dist/cli/chunks/{arena-KXFHRWX4.js → arena-7BGOXGXO.js} +2 -2
- package/dist/cli/chunks/{arena-HXTWJ5YY.js → arena-MCE6EU7K.js} +4 -4
- package/dist/cli/chunks/audit-BMWTQECB.js +4 -0
- package/dist/cli/chunks/base-DRZ2LS6X.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-UICJZIDG.js → better-sqlite3-PMUNGASU.js} +2 -2
- package/dist/cli/chunks/brain-handler-QPUFYX7F.js +94 -0
- package/dist/cli/chunks/{branch-enumerator-SS7UNVIA.js → branch-enumerator-WKFDGRN4.js} +2 -2
- package/dist/cli/chunks/{browser-77GI6KBE.js → browser-VY5HKH5X.js} +2 -2
- package/dist/cli/chunks/browser-workflow-CJ7T3MXF.js +2 -0
- package/dist/cli/chunks/{chunk-PZJOPURC.js → chunk-257E2A5M.js} +5 -5
- package/dist/cli/chunks/{chunk-55RWDRJD.js → chunk-2JVWITNK.js} +4 -4
- package/dist/cli/chunks/{chunk-BOARZKU3.js → chunk-2NPKIBAZ.js} +2 -2
- package/dist/cli/chunks/chunk-2TMWAQQ3.js +13 -0
- package/dist/cli/chunks/{chunk-M4WJKGVK.js → chunk-2YXGBZWV.js} +1 -1
- package/dist/cli/chunks/{chunk-3VOQRIQM.js → chunk-3EA536JF.js} +2 -2
- package/dist/cli/chunks/{chunk-ZZDIMOOV.js → chunk-3EZOZN25.js} +2 -2
- package/dist/cli/chunks/{chunk-MNW6QGNJ.js → chunk-3HZS4M3O.js} +2 -2
- package/dist/cli/chunks/{chunk-EKQ673SA.js → chunk-3NIG7S5W.js} +1 -1
- package/dist/cli/chunks/{chunk-7D777LTF.js → chunk-4N23RFDU.js} +2 -2
- package/dist/cli/chunks/{chunk-BOZZYWCR.js → chunk-5J6W7SIA.js} +1 -1
- package/dist/cli/chunks/{chunk-HIVA55CJ.js → chunk-5OOMJGFN.js} +1 -1
- package/dist/cli/chunks/{chunk-W7BWUTVV.js → chunk-5QQSIGUA.js} +2 -2
- package/dist/cli/chunks/{chunk-PAWXJ73E.js → chunk-5VFPCSK7.js} +1 -1
- package/dist/cli/chunks/{chunk-KPA7MZ6C.js → chunk-62N4NUJH.js} +2 -2
- package/dist/cli/chunks/chunk-64VGZQLB.js +2 -0
- package/dist/cli/chunks/{chunk-64PFWE2F.js → chunk-66VWCR67.js} +2 -2
- package/dist/cli/chunks/{chunk-XRT2WRMS.js → chunk-6LIHFV7O.js} +2 -2
- package/dist/cli/chunks/{chunk-STJCATGN.js → chunk-6OS76PHI.js} +2 -2
- package/dist/cli/chunks/{chunk-ZNPKDCZR.js → chunk-6RE3X4V5.js} +2 -2
- package/dist/cli/chunks/{chunk-BFP7KO7P.js → chunk-6SH5VZUD.js} +2 -2
- package/dist/cli/chunks/chunk-6SQM2MUX.js +4 -0
- package/dist/cli/chunks/{chunk-IPR4QP3H.js → chunk-6U7LNMWZ.js} +2 -2
- package/dist/cli/chunks/{chunk-MIQTXNBG.js → chunk-72KXSMWI.js} +1 -1
- package/dist/cli/chunks/chunk-7CUQCCMD.js +27 -0
- package/dist/cli/chunks/chunk-7D3V65N5.js +2 -0
- package/dist/cli/chunks/{chunk-JZ3ORVZ3.js → chunk-7J6QC567.js} +3 -3
- package/dist/cli/chunks/{chunk-4OYFXLBK.js → chunk-7LPR6HJG.js} +2 -2
- package/dist/cli/chunks/{chunk-4MHXCAG2.js → chunk-7NITCZWD.js} +1 -1
- package/dist/cli/chunks/{chunk-M5QUBZY6.js → chunk-7Z5LHRC3.js} +2 -2
- package/dist/cli/chunks/{chunk-CSU5NYOX.js → chunk-AHKELLIO.js} +4 -4
- package/dist/cli/chunks/{chunk-DHJPWQBR.js → chunk-AIRGNL55.js} +2 -2
- package/dist/cli/chunks/{chunk-C2WU3533.js → chunk-AJRUJAAK.js} +1 -1
- package/dist/cli/chunks/{chunk-HIYXCDEP.js → chunk-AVBJYI5I.js} +1 -1
- package/dist/cli/chunks/{chunk-U5K45TFH.js → chunk-B6D2CHEH.js} +1 -1
- package/dist/cli/chunks/{chunk-FRH6VAUS.js → chunk-B6MOJC3X.js} +1 -1
- package/dist/cli/chunks/{chunk-HUWNIPZ5.js → chunk-BAMN2CHI.js} +1 -1
- package/dist/cli/chunks/{chunk-ONII3572.js → chunk-BBT64TII.js} +3 -3
- package/dist/cli/chunks/{chunk-KSKEF7LZ.js → chunk-BJTJLJRZ.js} +3 -3
- package/dist/cli/chunks/chunk-BMAPORJ7.js +15 -0
- package/dist/cli/chunks/{chunk-CIZ5JPDC.js → chunk-BPEDWS6O.js} +3 -3
- package/dist/cli/chunks/{chunk-Z3RHREWF.js → chunk-BVR7RMC5.js} +1 -1
- package/dist/cli/chunks/{chunk-HDSAM2RE.js → chunk-C6KWXUFJ.js} +2 -2
- package/dist/cli/chunks/{chunk-ZBAKA4YB.js → chunk-CCK4BF76.js} +1 -1
- package/dist/cli/chunks/{chunk-IFCLB7FJ.js → chunk-CD542DNJ.js} +1 -1
- package/dist/cli/chunks/{chunk-6KJABXAR.js → chunk-CF2ISEOJ.js} +2 -2
- package/dist/cli/chunks/chunk-CM7U6TAX.js +5 -0
- package/dist/cli/chunks/{chunk-3X3DJZJJ.js → chunk-D45SG6CP.js} +1 -1
- package/dist/cli/chunks/{chunk-DAEFDCJ4.js → chunk-D6CJIGRU.js} +89 -83
- package/dist/cli/chunks/{chunk-MVPCNSPY.js → chunk-DBDPRORT.js} +2 -2
- package/dist/cli/chunks/{chunk-AUXFKCQL.js → chunk-DHVX5UB2.js} +2 -2
- package/dist/cli/chunks/{chunk-GPLQ6DOK.js → chunk-DK4XN4CU.js} +2 -2
- package/dist/cli/chunks/{chunk-SRKETSFF.js → chunk-DPYSUDAO.js} +1 -1
- package/dist/cli/chunks/{chunk-CNG6GQEZ.js → chunk-DUYOVM5I.js} +2 -2
- package/dist/cli/chunks/{chunk-VIHTL3U2.js → chunk-DZ3AUAAB.js} +2 -2
- package/dist/cli/chunks/{chunk-CU46J64M.js → chunk-E6G2RD5H.js} +2 -2
- package/dist/cli/chunks/{chunk-5YPYDPBJ.js → chunk-EAY2JMZG.js} +2 -2
- package/dist/cli/chunks/{chunk-V3QLFNA2.js → chunk-ELLBS5RP.js} +4 -4
- package/dist/cli/chunks/chunk-ENGZ4D5V.js +2 -0
- package/dist/cli/chunks/chunk-FBMN7B46.js +4 -0
- package/dist/cli/chunks/{chunk-EDJ3O7RH.js → chunk-FWASDOT2.js} +2 -2
- package/dist/cli/chunks/{chunk-MDWCE7YW.js → chunk-FZOBD67M.js} +1 -1
- package/dist/cli/chunks/{chunk-A4FYONNU.js → chunk-GDSXITFH.js} +2 -2
- package/dist/cli/chunks/{chunk-2JW3BCGG.js → chunk-GGRHV6D7.js} +1 -1
- package/dist/cli/chunks/{chunk-ISDMD6EU.js → chunk-GPYVDFB3.js} +90 -90
- package/dist/cli/chunks/{chunk-CDKG6EI7.js → chunk-GSF6MB64.js} +2 -2
- package/dist/cli/chunks/{chunk-WLG5AJ4N.js → chunk-H52HZ67P.js} +2 -2
- package/dist/cli/chunks/{chunk-FGYMFUE2.js → chunk-H5BS5VH7.js} +2 -2
- package/dist/cli/chunks/{chunk-34WO57CW.js → chunk-H6ZM3PUT.js} +1 -1
- package/dist/cli/chunks/{chunk-6CQN24ZK.js → chunk-HM6ZSCPI.js} +1 -1
- package/dist/cli/chunks/{chunk-DPFRKBOG.js → chunk-HNFVJP4I.js} +2 -2
- package/dist/cli/chunks/{chunk-TPGED2IF.js → chunk-I33ERSGB.js} +2 -2
- package/dist/cli/chunks/{chunk-UEM7ZF5K.js → chunk-IAF6T27S.js} +2 -2
- package/dist/cli/chunks/{chunk-KCZR45PA.js → chunk-IB27QACC.js} +2 -2
- package/dist/cli/chunks/{chunk-SGYJ4NFZ.js → chunk-ICTXTNQZ.js} +1 -1
- package/dist/cli/chunks/chunk-IG5GNEC6.js +4 -0
- package/dist/cli/chunks/{chunk-KHFNNVJA.js → chunk-IQO7UCFR.js} +2 -2
- package/dist/cli/chunks/{chunk-3TW5W5LX.js → chunk-IV5UZOHH.js} +2 -2
- package/dist/cli/chunks/{chunk-7ZIOFPL3.js → chunk-JBTPOIAC.js} +2 -2
- package/dist/cli/chunks/{chunk-ZNEMGX5O.js → chunk-JIXUMYKZ.js} +1 -1
- package/dist/cli/chunks/{chunk-MTZH7AHC.js → chunk-JMONHE4B.js} +1 -1
- package/dist/cli/chunks/{chunk-TDZ53WO2.js → chunk-JVNTSNWU.js} +2 -2
- package/dist/cli/chunks/{chunk-PFR4G3DJ.js → chunk-JXGFRBUO.js} +2 -2
- package/dist/cli/chunks/chunk-JZOS5FCX.js +2 -0
- package/dist/cli/chunks/{chunk-STM3UDNO.js → chunk-KNNISEDY.js} +2 -2
- package/dist/cli/chunks/{chunk-TWAWHOP7.js → chunk-L4RUBPLR.js} +2 -2
- package/dist/cli/chunks/chunk-LL3IGZBI.js +2 -0
- package/dist/cli/chunks/{chunk-CIKSHTEQ.js → chunk-MBRHSU6W.js} +10 -10
- package/dist/cli/chunks/{chunk-G6T45OIC.js → chunk-MJS53PRX.js} +2 -2
- package/dist/cli/chunks/{chunk-PO3IXGMQ.js → chunk-MQROI74N.js} +2 -2
- package/dist/cli/chunks/{chunk-DOTK76IJ.js → chunk-MUOG6QXR.js} +2 -2
- package/dist/cli/chunks/{chunk-MVNP7GIR.js → chunk-MW2GGZZ5.js} +1 -1
- package/dist/cli/chunks/{chunk-FWGOHAAB.js → chunk-NHWGMJAP.js} +2 -2
- package/dist/cli/chunks/{chunk-ZBJ4XOOV.js → chunk-NMAIY4PX.js} +4 -4
- package/dist/cli/chunks/{chunk-CDHQFHRP.js → chunk-NQZ5AR3D.js} +2 -2
- package/dist/cli/chunks/{chunk-FLYOJOKN.js → chunk-P6OYS755.js} +1 -1
- package/dist/cli/chunks/{chunk-BGE6FOLM.js → chunk-PI7TJS62.js} +2 -2
- package/dist/cli/chunks/chunk-PX5YDCRH.js +4 -0
- package/dist/cli/chunks/{chunk-Q5DO24IJ.js → chunk-PZPWRQ2M.js} +3 -3
- package/dist/cli/chunks/{chunk-R4VL6E65.js → chunk-Q5XTSMWR.js} +2 -2
- package/dist/cli/chunks/{chunk-JBNEE5UH.js → chunk-Q7EAGKAE.js} +2 -2
- package/dist/cli/chunks/{chunk-R5NE6B2M.js → chunk-QDFTT3RF.js} +2 -2
- package/dist/cli/chunks/{chunk-DFZCKIGY.js → chunk-QGA55PFM.js} +3 -3
- package/dist/cli/chunks/{chunk-RJCYCLZV.js → chunk-QW6VMTBR.js} +2 -2
- package/dist/cli/chunks/{chunk-6VRA2QGL.js → chunk-QZANMBIT.js} +1 -1
- package/dist/cli/chunks/{chunk-MEGDYJPV.js → chunk-RETBYIAC.js} +4 -4
- package/dist/cli/chunks/{chunk-XJ7QNVI5.js → chunk-RFNPJK6N.js} +3 -3
- package/dist/cli/chunks/{chunk-NJBGXDQ7.js → chunk-RG52OKAM.js} +1 -1
- package/dist/cli/chunks/{chunk-DA5K5754.js → chunk-RSXXCL4A.js} +1 -1
- package/dist/cli/chunks/{chunk-HV2J7KKQ.js → chunk-RTFO5UQH.js} +2 -2
- package/dist/cli/chunks/{chunk-6UWGMOND.js → chunk-RZZCUIAI.js} +2 -2
- package/dist/cli/chunks/chunk-SDRHUMJB.js +2 -0
- package/dist/cli/chunks/{chunk-TSRSV3LD.js → chunk-SE4WIB26.js} +1 -1
- package/dist/cli/chunks/{chunk-ODKLFVYC.js → chunk-SESK3ARK.js} +2 -2
- package/dist/cli/chunks/{chunk-AWWNB2T7.js → chunk-SJUXE4IC.js} +2 -2
- package/dist/cli/chunks/{chunk-QGIU2WRL.js → chunk-SMDN3BQZ.js} +1 -1
- package/dist/cli/chunks/{chunk-VD6QRULW.js → chunk-SNOBH4AZ.js} +2 -2
- package/dist/cli/chunks/{chunk-OSLYSG3B.js → chunk-SPV2VKC5.js} +2 -2
- package/dist/cli/chunks/chunk-TCHGOB2N.js +2 -0
- package/dist/cli/chunks/{chunk-MOBNBMFW.js → chunk-TVYY3OCX.js} +1 -1
- package/dist/cli/chunks/{chunk-UGVHCMUN.js → chunk-UCFQALXO.js} +3 -3
- package/dist/cli/chunks/{chunk-3QHGWY7T.js → chunk-UKA2KOXE.js} +2 -2
- package/dist/cli/chunks/{chunk-MCUJEZT6.js → chunk-UNFFDHER.js} +16 -11
- package/dist/cli/chunks/{chunk-6QYNWR7U.js → chunk-UQ32JHES.js} +2 -2
- package/dist/cli/chunks/{chunk-OULHKEVH.js → chunk-V4DM6ELU.js} +2 -2
- package/dist/cli/chunks/{chunk-M2JBBZQB.js → chunk-VGFFFKGK.js} +2 -2
- package/dist/cli/chunks/{chunk-OCWWP5PL.js → chunk-VMNWDJIZ.js} +2 -2
- package/dist/cli/chunks/chunk-W6HXLH5G.js +180 -0
- package/dist/cli/chunks/{chunk-AIHDEEJO.js → chunk-WCJBU2KI.js} +2 -2
- package/dist/cli/chunks/{chunk-ZBQY5GLF.js → chunk-WGM35YWL.js} +2 -2
- package/dist/cli/chunks/chunk-WO4QMXIG.js +3 -0
- package/dist/cli/chunks/{chunk-3UPAMMCB.js → chunk-XAS3XRYM.js} +1 -1
- package/dist/cli/chunks/chunk-Y3LZ35OG.js +2 -0
- package/dist/cli/chunks/{chunk-5R3QL7WN.js → chunk-Y3UOUNHM.js} +2 -2
- package/dist/cli/chunks/{chunk-ZJ26AQA5.js → chunk-YFBSPLJG.js} +1 -1
- package/dist/cli/chunks/{chunk-BDESSCVR.js → chunk-YHKEDEAA.js} +3 -3
- package/dist/cli/chunks/{chunk-CXQPR5MY.js → chunk-YS4FCTWF.js} +1 -1
- package/dist/cli/chunks/{chunk-CLTMDCSE.js → chunk-YSLL6VSL.js} +2 -2
- package/dist/cli/chunks/chunk-Z6GGIRQQ.js +65 -0
- package/dist/cli/chunks/{chunk-F3SBRQC6.js → chunk-Z7WODOTH.js} +2 -2
- package/dist/cli/chunks/chunk-ZCRTRYXK.js +14 -0
- package/dist/cli/chunks/{chunk-XRYF6JV7.js → chunk-ZEV3YTO7.js} +2 -2
- package/dist/cli/chunks/{chunk-YNXS6CGV.js → chunk-ZL6SYKUK.js} +1 -1
- package/dist/cli/chunks/{chunk-5SJHQ2CO.js → chunk-ZSPU4MOS.js} +2 -2
- package/dist/cli/chunks/{chunk-UDHKLT4C.js → chunk-ZVWVV4EX.js} +1 -1
- package/dist/cli/chunks/{ci-464KPQNP.js → ci-W6K6G2KZ.js} +2 -2
- package/dist/cli/chunks/{ci-output-I7FX2RSO.js → ci-output-LDT24TS3.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-3FW237WW.js → circuit-breaker-F5V4KITU.js} +2 -2
- package/dist/cli/chunks/claude-flow-setup-DT6WQQVD.js +2 -0
- package/dist/cli/chunks/client-KHWJT6FB.js +2 -0
- package/dist/cli/chunks/{cline-installer-UWFHT6VY.js → cline-installer-G7TJOAEX.js} +2 -2
- package/dist/cli/chunks/{code-KQSUT3FS.js → code-PGE6A42V.js} +3 -3
- package/dist/cli/chunks/{code-index-extractor-PABBNUSC.js → code-index-extractor-RNITH372.js} +2 -2
- package/dist/cli/chunks/codex-installer-LBX77AI3.js +14 -0
- package/dist/cli/chunks/{completions-7RWHAUAR.js → completions-4AWLAARX.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-XPOAF33E.js → complexity-analyzer-ZPNSS476.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-V4F2FIZP.js → continuedev-installer-UAPWX6OA.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-JMICURQB.js → copilot-installer-BJN2YJGI.js} +2 -2
- package/dist/cli/chunks/core-handlers-HING5RRG.js +2 -0
- package/dist/cli/chunks/{cost-tracker-5OFHEYFJ.js → cost-tracker-MHP2VJ63.js} +2 -2
- package/dist/cli/chunks/{coverage-QKN57JDS.js → coverage-PQB4IEFG.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-PQTD6AZN.js +2 -0
- package/dist/cli/chunks/{cursor-installer-GBJ7YXSM.js → cursor-installer-ZXBWYAS3.js} +2 -2
- package/dist/cli/chunks/{daemon-GKP7CMEK.js → daemon-64C7R6OJ.js} +3 -3
- package/dist/cli/chunks/{daemon-IAVSO6HK.js → daemon-N2BEGEFY.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-S225TCI7.js → dag-attention-scheduler-SPZDAPNL.js} +2 -2
- package/dist/cli/chunks/{detect-IUYH422U.js → detect-LXJBSSZW.js} +2 -2
- package/dist/cli/chunks/{dist-node-2YRE6A7C.js → dist-node-U3TKZ2IZ.js} +2 -2
- package/dist/cli/chunks/{domain-handler-PL2TZC6H.js → domain-handler-3DDWUVSR.js} +2 -2
- package/dist/cli/chunks/{domain-plugins-HCGLXKIT.js → domain-plugins-JJVWI4OQ.js} +2 -2
- package/dist/cli/chunks/domain-transfer-M36KUJ2U.js +2 -0
- package/dist/cli/chunks/dream-WUGRSNCV.js +2 -0
- package/dist/cli/chunks/embed-and-insert-pattern-JPAR7TXX.js +3 -0
- package/dist/cli/chunks/{eval-WCK7KNFN.js → eval-SOLG23EA.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-2MSQWSAR.js → experience-capture-middleware-T7G2VOOD.js} +4 -4
- package/dist/cli/chunks/{fast-paths-VYOSIBKF.js → fast-paths-32N3ELI4.js} +2 -2
- package/dist/cli/chunks/{feature-flags-WCFUKHNQ.js → feature-flags-APJDQ4N7.js} +2 -2
- package/dist/cli/chunks/{feature-flags-UJRHFBRX.js → feature-flags-NAHKLDRN.js} +2 -2
- package/dist/cli/chunks/{file-discovery-JDGL4ZWS.js → file-discovery-YKVM3MDB.js} +2 -2
- package/dist/cli/chunks/{fleet-ROXVMZ2F.js → fleet-55M5CJS4.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-NIO4ZCO3.js → gnn-wrapper-UD6E6S6Z.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-PI42WD3C.js → heartbeat-handler-OYVW3VSC.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-33XX5XNQ.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-XQPERX3H.js +2 -0
- package/dist/cli/chunks/hnsw-index-2GNXTWHH.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-YLC7SPK2.js → hnsw-legacy-bridge-HBYIS3ZW.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-LG6OS3B7.js → hnswlib-node-EQPM42OU.js} +2 -2
- package/dist/cli/chunks/{hooks-WVALP5GX.js → hooks-5ZSSJWO6.js} +10 -10
- package/dist/cli/chunks/hybrid-backend-CCF7URKI.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-GJEMW3EG.js → hypergraph-engine-XBGVQ4PD.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-BLF6LXEV.js → hypergraph-handler-CAWAQ673.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-HGKAZWIG.js +2 -0
- package/dist/cli/chunks/{init-handler-K25RWRYY.js → init-handler-PRHXSARK.js} +6 -6
- package/dist/cli/chunks/init-wizard-72MFBI3G.js +2 -0
- package/dist/cli/chunks/kernel-BRCBVMSK.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-BXN6WZ7G.js → kilocode-installer-F7LXBM7I.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-PM362DLN.js → kiro-installer-NM723ZRG.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-DG44IPEI.js +2 -0
- package/dist/cli/chunks/{learning-CPERDDRG.js → learning-5QYIDHH3.js} +3 -3
- package/dist/cli/chunks/{llm-router-GOAV5FPI.js → llm-router-43HKWPSX.js} +4 -4
- package/dist/cli/chunks/llm-router-service-24KXFX32.js +2 -0
- package/dist/cli/chunks/{load-2BG6SHAK.js → load-5YDBWSCS.js} +2 -2
- package/dist/cli/chunks/load-test-N4TAYJY3.js +2 -0
- package/dist/cli/chunks/mcp-UMAPMNMY.js +2 -0
- package/dist/cli/chunks/{memory-4NHBYT6S.js → memory-FWCPCQFP.js} +6 -6
- package/dist/cli/chunks/memory-backend-NVYFYVAU.js +2 -0
- package/dist/cli/chunks/memory-handlers-UTWCNCHL.js +2 -0
- package/dist/cli/chunks/multi-model-executor-2XTBGLE4.js +14 -0
- package/dist/cli/chunks/{opencode-installer-ATZLLK74.js → opencode-installer-GIXOJ6NS.js} +2 -2
- package/dist/cli/chunks/orchestrator-VW6BKHLI.js +393 -0
- package/dist/cli/chunks/pattern-null-store-SBPNYDBR.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-7VE4XDAI.js → pattern-usage-recorder-7CEUC3J7.js} +2 -2
- package/dist/cli/chunks/{pipeline-LQZSNDD2.js → pipeline-IGUQPPPO.js} +2 -2
- package/dist/cli/chunks/platform-2P636I7B.js +2 -0
- package/dist/cli/chunks/{plugin-EJ6K2MGU.js → plugin-NY6SWDPE.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-OIHTKJMN.js → prime-radiant-advanced-wasm-2UUDTIO2.js} +2 -2
- package/dist/cli/chunks/project-root-IOISG5KX.js +2 -0
- package/dist/cli/chunks/protocol-executor-IBYEII5Q.js +2 -0
- package/dist/cli/chunks/{protocol-handler-NRBROAU7.js → protocol-handler-ZTPCRQ5W.js} +2 -2
- package/dist/cli/chunks/{prove-EJOGEGD3.js → prove-SQX5A3IG.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-7IETWW6W.js +2 -0
- package/dist/cli/chunks/{quality-E55UC73D.js → quality-DROILKRY.js} +2 -2
- package/dist/cli/chunks/{quality-gate-OIQATNT3.js → quality-gate-PWKWDJY2.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-NHUK2MWJ.js +2 -0
- package/dist/cli/chunks/real-embeddings-P5U3MGYC.js +2 -0
- package/dist/cli/chunks/{ref-validation-OPO6J7OL.js → ref-validation-KY73NQXD.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-ODY5KRWU.js → roocode-installer-6JPPRB3W.js} +2 -2
- package/dist/cli/chunks/router-SRSO3IHF.js +2 -0
- package/dist/cli/chunks/routing-feedback-PASRE5HY.js +2 -0
- package/dist/cli/chunks/{routing-handler-KQM6VWLC.js → routing-handler-VTJIVFUO.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-U2GVV6PF.js → ruvector-commands-C6RPSJJO.js} +2 -2
- package/dist/cli/chunks/rvf-dual-writer-4M4J67OU.js +2 -0
- package/dist/cli/chunks/rvf-migration-adapter-TSXGT5LF.js +2 -0
- package/dist/cli/chunks/rvf-migration-coordinator-R53URRIO.js +2 -0
- package/dist/cli/chunks/rvf-native-adapter-MOF3E7BR.js +2 -0
- package/dist/cli/chunks/{rvf-store-integrity-KMIHD3LP.js → rvf-store-integrity-MMXN5TEJ.js} +2 -2
- package/dist/cli/chunks/safe-db-QJLFO33B.js +2 -0
- package/dist/cli/chunks/schedule-YIVXW5O2.js +2 -0
- package/dist/cli/chunks/scheduler-AON7DWSJ.js +2 -0
- package/dist/cli/chunks/{security-P5NM353C.js → security-3B3R2NL4.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-VIJB7JUS.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-2CSG7C4W.js → shared-rvf-dual-writer-UVWGDUWC.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-75VHKKQB.js +2 -0
- package/dist/cli/chunks/standalone-memory-M4LWAAYZ.js +2 -0
- package/dist/cli/chunks/{status-handler-6TU6O37R.js → status-handler-YYFV6OZL.js} +2 -2
- package/dist/cli/chunks/{structural-health-KBIJSTXJ.js → structural-health-27E6LLKB.js} +2 -2
- package/dist/cli/chunks/sync-26CEGSTC.js +2 -0
- package/dist/cli/chunks/{sync-LNHI5SB7.js → sync-J3LJ56WN.js} +2 -2
- package/dist/cli/chunks/task-handler-4MCEBQZL.js +54 -0
- package/dist/cli/chunks/task-handlers-GYBAWKE2.js +9 -0
- package/dist/cli/chunks/{test-DHAAI3DU.js → test-MPC5HRH5.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-XDBZ3QC2.js → test-scheduling-ZJBFRZ3J.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-2Y2XITBX.js +2 -0
- package/dist/cli/chunks/{token-usage-Q2YG5YQN.js → token-usage-3X5WMTG2.js} +2 -2
- package/dist/cli/chunks/{transformers-F5UQTQCY.js → transformers-MVL4C5IX.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-SLW65ZFO.js +2 -0
- package/dist/cli/chunks/{types-JQ7EQO5Q.js → types-TG5P3CRS.js} +2 -2
- package/dist/cli/chunks/unified-memory-UCQ6AB32.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-IXYUMKRR.js +2 -0
- package/dist/cli/chunks/unified-persistence-7E6JQ4FZ.js +2 -0
- package/dist/cli/chunks/{upgrade-TJRVGHGD.js → upgrade-ETBHDEPY.js} +2 -2
- package/dist/cli/chunks/{validate-BWPCVHBN.js → validate-C2A73LZK.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-QVVKCQLP.js → validate-swarm-67XN42ML.js} +2 -2
- package/dist/cli/chunks/{vibium-ZFATIWHO.js → vibium-NILGKHLN.js} +2 -2
- package/dist/cli/chunks/visual-security-4VZXPEVG.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-KPLY7ONR.js → web-tree-sitter-USJN77P4.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-H7XM7ISA.js → windsurf-installer-5GGZXGJW.js} +2 -2
- package/dist/cli/chunks/witness-chain-IWS5ZHHL.js +2 -0
- package/dist/cli/chunks/witness-chain-JQA2VPZI.js +2 -0
- package/dist/cli/chunks/witness-chain-repair-4UA7IPS3.js +2 -0
- package/dist/cli/chunks/witness-chain-verifier-3GEADWPE.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-DFRL42GE.js → witness-key-manager-ZWEIK3VJ.js} +2 -2
- package/dist/cli/chunks/{workflow-2ZQO6WYI.js → workflow-KHMVVBBA.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-GI5NQH7C.js +2 -0
- package/dist/cli/chunks/wrappers-N6XIK5PT.js +2 -0
- package/dist/cli/commands/audit.d.ts +20 -2
- package/dist/cli/commands/audit.js +158 -16
- package/dist/cli/commands/claude-flow-setup.js +5 -4
- package/dist/cli/commands/mcp.js +6 -0
- package/dist/cli/commands/memory.d.ts +1 -1
- package/dist/cli/commands/memory.js +8 -8
- package/dist/cli/commands/platform.js +15 -2
- package/dist/cli/commands/upgrade.d.ts +3 -3
- package/dist/cli/commands/upgrade.js +3 -3
- package/dist/cli/handlers/init-handler.d.ts +10 -0
- package/dist/cli/handlers/task-handler.js +24 -3
- package/dist/cli/helpers/standalone-memory.d.ts +12 -0
- package/dist/cli/helpers/standalone-memory.js +46 -0
- package/dist/cli/index.js +39 -42
- package/dist/cli/log-gate.d.ts +66 -0
- package/dist/cli/log-gate.js +170 -0
- package/dist/init/agents-installer.d.ts +4 -0
- package/dist/init/agents-installer.js +24 -11
- package/dist/init/codex-installer.js +22 -8
- package/dist/init/idempotent-write.d.ts +53 -0
- package/dist/init/idempotent-write.js +160 -0
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/05-learning.js +3 -1
- package/dist/init/phases/07-hooks.js +32 -16
- package/dist/init/phases/08-mcp.js +4 -2
- package/dist/init/phases/09-assets.d.ts +10 -0
- package/dist/init/phases/09-assets.js +3 -0
- package/dist/init/phases/10-workers.js +7 -5
- package/dist/init/phases/12-verification.js +7 -2
- package/dist/init/project-analyzer.d.ts +9 -0
- package/dist/init/project-analyzer.js +20 -1
- package/dist/init/self-configurator.d.ts +5 -3
- package/dist/init/self-configurator.js +18 -29
- package/dist/init/skills-installer.js +4 -2
- package/dist/init/token-bootstrap.d.ts +1 -1
- package/dist/init/token-bootstrap.js +12 -2
- package/dist/init/types.d.ts +16 -0
- package/dist/init/types.js +20 -24
- package/dist/integrations/coherence/coherence-service.js +84 -24
- package/dist/integrations/coherence/vote-tally.d.ts +38 -0
- package/dist/integrations/coherence/vote-tally.js +39 -0
- package/dist/integrations/ruvector/brain-exporter.js +17 -0
- package/dist/integrations/ruvector/brain-import-audit.d.ts +20 -0
- package/dist/integrations/ruvector/brain-import-audit.js +22 -0
- package/dist/integrations/ruvector/brain-rvf-exporter.js +16 -0
- package/dist/integrations/ruvector/brain-shared.js +1 -1
- package/dist/integrations/ruvector/rvf-dual-writer.js +6 -1
- package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +23 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +24 -0
- package/dist/kernel/hybrid-backend.d.ts +6 -0
- package/dist/kernel/hybrid-backend.js +18 -0
- package/dist/kernel/kernel.js +12 -16
- package/dist/kernel/project-root.d.ts +1 -1
- package/dist/kernel/project-root.js +24 -3
- package/dist/learning/embedder-identity-store.js +4 -3
- package/dist/learning/pattern-store.d.ts +11 -0
- package/dist/learning/pattern-store.js +31 -9
- package/dist/learning/qe-patterns.d.ts +6 -0
- package/dist/learning/qe-patterns.js +7 -1
- package/dist/learning/qe-reasoning-bank.js +3 -0
- package/dist/learning/real-embeddings.d.ts +8 -0
- package/dist/learning/real-embeddings.js +16 -0
- package/dist/learning/rvf-pattern-store.js +30 -10
- package/dist/learning/sqlite-persistence.d.ts +8 -1
- package/dist/learning/sqlite-persistence.js +49 -9
- package/dist/logging/console-logger.d.ts +2 -5
- package/dist/logging/console-logger.js +10 -46
- package/dist/logging/index.d.ts +2 -0
- package/dist/logging/index.js +1 -0
- package/dist/logging/redaction.d.ts +27 -0
- package/dist/logging/redaction.js +170 -0
- package/dist/mcp/bundle.js +463 -449
- package/dist/mcp/entry.js +2 -0
- package/dist/mcp/handlers/core-handlers.js +5 -4
- package/dist/mcp/handlers/memory-handlers.d.ts +6 -1
- package/dist/mcp/handlers/memory-handlers.js +44 -22
- package/dist/mcp/handlers/task-handlers.js +14 -1
- package/dist/mcp/protocol-server.js +3 -1
- package/dist/mcp/services/session-store.js +5 -1
- package/dist/mcp/tools/base.d.ts +9 -2
- package/dist/mcp/tools/base.js +7 -0
- package/dist/mcp/tools/coherence/consensus.js +51 -2
- package/dist/mcp/tools/planning/goap-plan.d.ts +20 -7
- package/dist/mcp/tools/planning/goap-plan.js +92 -20
- package/dist/mcp/tools/planning/goap-status.d.ts +37 -12
- package/dist/mcp/tools/planning/goap-status.js +52 -23
- package/dist/mcp/tools/planning/world-state.d.ts +101 -0
- package/dist/mcp/tools/planning/world-state.js +274 -0
- package/dist/mcp/types.d.ts +4 -2
- package/dist/planning/goap-planner.d.ts +60 -4
- package/dist/planning/goap-planner.js +218 -60
- package/dist/planning/index.d.ts +1 -1
- package/dist/planning/index.js +1 -1
- package/dist/planning/plan-executor.d.ts +20 -1
- package/dist/planning/plan-executor.js +209 -100
- package/dist/planning/types.d.ts +16 -0
- package/dist/planning/types.js +17 -0
- package/dist/plugins/cache.d.ts +2 -0
- package/dist/plugins/cache.js +15 -2
- package/dist/plugins/lifecycle.js +15 -2
- package/dist/plugins/manifest.js +7 -5
- package/dist/plugins/resolver.d.ts +13 -22
- package/dist/plugins/resolver.js +169 -61
- package/dist/plugins/version-policy.d.ts +13 -0
- package/dist/plugins/version-policy.js +18 -0
- package/dist/shared/types/index.d.ts +6 -0
- package/dist/shared/types/index.js +8 -0
- package/package.json +2 -1
- package/dist/cli/chunks/adapter-TNNNJRDG.js +0 -2
- package/dist/cli/chunks/agent-booster-wasm-5PC7D2FW.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-5ZRMYJLB.js +0 -2
- package/dist/cli/chunks/audit-YSGA7UWT.js +0 -3
- package/dist/cli/chunks/base-KWZHOPSH.js +0 -2
- package/dist/cli/chunks/brain-handler-ET6YAP4B.js +0 -90
- package/dist/cli/chunks/browser-workflow-2FZTKDUL.js +0 -2
- package/dist/cli/chunks/chunk-33YYYWBQ.js +0 -4
- package/dist/cli/chunks/chunk-5Z6XZV7K.js +0 -65
- package/dist/cli/chunks/chunk-6J62K3SW.js +0 -2
- package/dist/cli/chunks/chunk-6TPKK7LD.js +0 -15
- package/dist/cli/chunks/chunk-DEYLEDJN.js +0 -27
- package/dist/cli/chunks/chunk-J6GNQS62.js +0 -5
- package/dist/cli/chunks/chunk-KGT36Z42.js +0 -14
- package/dist/cli/chunks/chunk-NA7B2QYB.js +0 -2
- package/dist/cli/chunks/chunk-NDPFGIMJ.js +0 -13
- package/dist/cli/chunks/chunk-OBAP2TXZ.js +0 -2
- package/dist/cli/chunks/chunk-PEPFCPES.js +0 -2
- package/dist/cli/chunks/chunk-T6BVLVI5.js +0 -2
- package/dist/cli/chunks/chunk-TT23RRB7.js +0 -2
- package/dist/cli/chunks/chunk-XC7DYDSY.js +0 -180
- package/dist/cli/chunks/chunk-XWMZ6D6N.js +0 -2
- package/dist/cli/chunks/chunk-Y3MW3YBC.js +0 -3
- package/dist/cli/chunks/claude-flow-setup-6JKMBPGU.js +0 -2
- package/dist/cli/chunks/client-7E4LM2WW.js +0 -2
- package/dist/cli/chunks/codex-installer-CQ24DTP5.js +0 -14
- package/dist/cli/chunks/core-handlers-IFG3757P.js +0 -2
- package/dist/cli/chunks/cross-domain-router-EK7W4PGP.js +0 -2
- package/dist/cli/chunks/domain-transfer-KQJRUPXA.js +0 -2
- package/dist/cli/chunks/dream-NFSCSLY7.js +0 -2
- package/dist/cli/chunks/embed-and-insert-pattern-ZPAG7235.js +0 -3
- package/dist/cli/chunks/heartbeat-scheduler-ZATCDJDK.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-WXQABRCA.js +0 -2
- package/dist/cli/chunks/hnsw-index-TPSWLEA5.js +0 -2
- package/dist/cli/chunks/impact-analyzer-HNIU45P5.js +0 -2
- package/dist/cli/chunks/init-wizard-JUIPBMHG.js +0 -2
- package/dist/cli/chunks/kernel-5BOZQ754.js +0 -2
- package/dist/cli/chunks/knowledge-graph-EWDAENWM.js +0 -2
- package/dist/cli/chunks/llm-router-service-3YT7JGBS.js +0 -2
- package/dist/cli/chunks/load-test-BP2CPLIV.js +0 -2
- package/dist/cli/chunks/mcp-5TTB37DC.js +0 -2
- package/dist/cli/chunks/memory-backend-4PYQBPRM.js +0 -2
- package/dist/cli/chunks/memory-handlers-2B27NITS.js +0 -2
- package/dist/cli/chunks/multi-model-executor-KCWSGCDT.js +0 -14
- package/dist/cli/chunks/orchestrator-RKB7XJRG.js +0 -393
- package/dist/cli/chunks/pattern-null-store-OYOQOV2O.js +0 -2
- package/dist/cli/chunks/platform-OD5H5U6G.js +0 -2
- package/dist/cli/chunks/protocol-executor-3ATJTXWG.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-LLMYZT4X.js +0 -2
- package/dist/cli/chunks/queen-coordinator-RN7L6KG5.js +0 -2
- package/dist/cli/chunks/real-embeddings-FPFFNOSZ.js +0 -2
- package/dist/cli/chunks/router-MDHITQ2V.js +0 -2
- package/dist/cli/chunks/routing-feedback-5XLNJ3Y3.js +0 -2
- package/dist/cli/chunks/rvf-dual-writer-JBW4O3II.js +0 -2
- package/dist/cli/chunks/rvf-migration-adapter-BPPQL4XJ.js +0 -2
- package/dist/cli/chunks/rvf-migration-coordinator-V2GHCJKN.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-S4562CG5.js +0 -2
- package/dist/cli/chunks/safe-db-FIRHSXVF.js +0 -2
- package/dist/cli/chunks/schedule-RVXFB4HK.js +0 -2
- package/dist/cli/chunks/scheduler-IKKAMAOO.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-LVIUOO4S.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-SQ3HCUQ7.js +0 -2
- package/dist/cli/chunks/sync-UHOX6RJW.js +0 -2
- package/dist/cli/chunks/task-handler-AVDHMLGI.js +0 -49
- package/dist/cli/chunks/task-handlers-KYK4VTRA.js +0 -9
- package/dist/cli/chunks/token-bootstrap-GUTTLPZX.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-DEGOHS6F.js +0 -2
- package/dist/cli/chunks/unified-memory-CXHLHB5I.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-I7WAE54M.js +0 -2
- package/dist/cli/chunks/unified-persistence-6CPF65WI.js +0 -2
- package/dist/cli/chunks/visual-security-GNPHME5H.js +0 -2
- package/dist/cli/chunks/witness-chain-RRN6NDCH.js +0 -2
- package/dist/cli/chunks/witness-chain-VT4UHHBR.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-DB3HIECD.js +0 -2
- package/dist/cli/chunks/wrappers-SUS6XEJD.js +0 -2
|
@@ -0,0 +1,94 @@
|
|
|
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.14.6");process.exit(0)}
|
|
2
|
+
import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-UCFQALXO.js";import{c as Ee}from"./chunk-7CUQCCMD.js";import{a as we,b as Re,c as H,d as V,f as tn}from"./chunk-JVNTSNWU.js";import{b as ve}from"./chunk-I33ERSGB.js";import{a as Se,d as ae,e as _e}from"./chunk-IG5GNEC6.js";import"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import{b as k,d as oe}from"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import"./chunk-SDRHUMJB.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import{a as F,b as nn}from"./chunk-PI7TJS62.js";import"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import"./chunk-64VGZQLB.js";import $ from"path";import o from"chalk";nn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;e.prepare(`
|
|
3
|
+
INSERT INTO witness_chain
|
|
4
|
+
(prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
|
|
5
|
+
VALUES (?, ?, 'BRAIN_IMPORT', ?, ?, 'brain-import', ?)
|
|
6
|
+
`).run(i,ae(r,t),t,new Date().toISOString(),r)}var an={rl_q_values:"includeQValues",dream_insights:"includeDreamInsights",dream_cycles:"includeDreamInsights",witness_chain:"includeWitnessChain",vectors:"includeVectors"};function sn(e,n){let r=an[e.tableName];return!(r&&n[r]===!1)}var ln=1e4;function cn(e,n,r,t){if(!sn(n,r))return le(D(t,n.fileName),[]),{count:0,rows:[]};let[a,i]=n.domainColumn?J(r.domains,n.domainColumn):[void 0,[]];if(r.domains&&r.domains.length>0&&!n.domainColumn){let s=r.domains.map(()=>"?").join(","),d=`manifest_id IN (SELECT id FROM learning_evidence_manifests WHERE task_family IN (${s}))`;["learning_evidence_segments","learning_segment_edges","learning_evidence_admissions"].includes(n.tableName)?(a=d,i=[...r.domains]):["pattern_manifest_lineage","pattern_segment_lineage"].includes(n.tableName)&&(a=`${d} AND pattern_id IN (SELECT id FROM qe_patterns WHERE qe_domain IN (${s}))`,i=[...r.domains,...r.domains])}if(se(e,n.tableName,a,i)>=ln){let s=n.blobColumns,d=s&&s.length>0?y=>W(y,s):void 0;return{count:Ie(D(t,n.fileName),xe(e,n.tableName,a,i),d)}}let l=Q(e,n.tableName,a,i);return n.blobColumns&&n.blobColumns.length>0&&(l=l.map(s=>W(s,n.blobColumns))),le(D(t,n.fileName),l),{count:l.length,rows:l}}function Be(e){let n=[];for(let r of _){let t=D(e,r.fileName);te(t)?n.push(A(ce(t,"utf-8"))):n.push(A(""))}return A(n.join(":"))}function Oe(e,n,r="memory.db"){let t=de(n.outputPath);te(t)||rn(t,{recursive:!0});let a=0,i={},c=new Set;for(let f of _){let y=cn(e,f,n,t);if(i[f.tableName]=y.count,a+=y.count,f.tableName==="qe_patterns"){if(y.rows)for(let h of y.rows)h.qe_domain&&c.add(h.qe_domain);else if(y.count>0){let[h,E]=f.domainColumn?J(n.domains,f.domainColumn):[void 0,[]],u=`SELECT DISTINCT qe_domain FROM qe_patterns ${h?`WHERE ${h} AND qe_domain IS NOT NULL`:"WHERE qe_domain IS NOT NULL"}`;try{let R=e.prepare(u).all(...E||[]);for(let g of R)c.add(g.qe_domain)}catch{}}}}let l=n.includeVectors!==!1?se(e,"vectors"):0,s=Be(t),d={version:"3.0",exportedAt:new Date().toISOString(),sourceDb:r,stats:{patternCount:i.qe_patterns||0,vectorCount:l,qValueCount:i.rl_q_values||0,dreamInsightCount:i.dream_insights||0,witnessChainLength:i.witness_chain||0,totalRecords:a},domains:[...c].sort(),checksum:s,tableRecordCounts:i};return on(D(t,"manifest.json"),JSON.stringify(d,null,2),"utf-8"),d}var dn=new Set(["qe_patterns","rl_q_values","dream_insights","witness_chain"]);function fn(e){return e==="1.0"?_.filter(n=>dn.has(n.tableName)):e==="3.0"?_:(console.warn(`[brain-import] Unknown manifest version '${e}'. Attempting full import \u2014 some files may be missing.`),_)}function Ae(e,n,r){let t=de(n),a=D(t,"manifest.json");if(!te(a))throw new Error(`Manifest not found at ${a}`);let i=k(ce(a,"utf-8")),c=Be(t);if(c!==i.checksum)throw new Error(`Checksum mismatch: expected ${i.checksum}, got ${c}. The export may have been tampered with or corrupted.`);let l=fn(i.version),s=0,d=0,f=0,y=()=>{let h=new Map,E=new Map,m=0;for(let u of l){let R=D(t,u.fileName),g=P(R,k);if(u.tableName==="witness_chain"){m+=g.length,d+=g.length;continue}u.blobColumns&&u.blobColumns.length>0&&(g=g.map(b=>G(b,u.blobColumns)));for(let b of g){let O=Y(b,h),x;if(u.dedupColumns&&u.dedupColumns.length>0)x=Z(e,u.tableName,O,u.dedupColumns,u.preserveId);else{let N=L[u.tableName]||"id",I=K[u.tableName],p=z[u.tableName];x=X(e,u.tableName,O,N,r.mergeStrategy,I,p,h,E,b.pattern_id)}s+=x.imported,d+=x.skipped,f+=x.conflicts}}ne(e,{sourceChecksum:i.checksum,sourceWitnessRows:m,importedRecords:s,skippedRecords:d,conflicts:f}),s+=1};return ee(e,r.dryRun??!1,y),{imported:s,skipped:d,conflicts:f}}function Ne(e){let n=de(e),r=D(n,"manifest.json");if(!te(r))throw new Error(`Manifest not found at ${r}`);return k(ce(r,"utf-8"))}tn();import{existsSync as j,readdirSync as mn,renameSync as un,statSync as pn,unlinkSync as fe,writeFileSync as gn}from"fs";import{basename as yn,dirname as hn,join as bn,resolve as re}from"path";var De=["",".idmap.json",".manifest.json"],wn=[...De,".lock"];function ke(e){for(let n of wn)try{let r=`${e}${n}`;j(r)&&fe(r)}catch{}}function Rn(e){let n=hn(e),r=`${yn(e)}.tmp.`,t;try{t=mn(n)}catch{return}for(let a of t){if(!a.startsWith(r))continue;let i=Number.parseInt(a.slice(r.length).split(".")[0],10);if(!(!Number.isInteger(i)||i<=0)&&!(i!==process.pid&&vn(i)))try{fe(bn(n,a))}catch{}}}function vn(e){try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function $e(e,n,r="memory.db"){if(!V())throw new Error("@ruvector/rvf-node is not available. Install it or use --format jsonl instead.");let t=re(n.outputPath),a=n.dimension??384,i=`${t}.tmp.${process.pid}`;Rn(t),ke(i);let c=we(i,a),l=!1;try{let s={},d=new Set,f=0;for(let p of _){let[S,w]=p.domainColumn?J(n.domains,p.domainColumn):[void 0,[]],C=Q(e,p.tableName,S,w);if(n.domains&&n.domains.length>0){let v=new Set((s.learning_evidence_manifests??[]).map(B=>B.id)),q=new Set((s.qe_patterns??[]).map(B=>B.id));["learning_evidence_segments","learning_segment_edges","learning_evidence_admissions"].includes(p.tableName)?C=C.filter(B=>v.has(B.manifest_id)):p.tableName==="pattern_manifest_lineage"?C=C.filter(B=>{let T=B;return v.has(T.manifest_id)&&q.has(T.pattern_id)}):p.tableName==="pattern_segment_lineage"&&(C=C.filter(B=>{let T=B;return v.has(T.manifest_id)&&q.has(T.pattern_id)}))}if(p.tableName==="qe_patterns")for(let v of C)v.qe_domain&&d.add(v.qe_domain);let M=ie[p.tableName];M&&M.length>0&&(C=C.map(v=>W(v,M))),s[p.tableName]=C,f+=C.length}let y=0,h=[];if(Ce(e,"qe_pattern_embeddings")){let p=e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(w=>w.name==="space_id"),S=e.prepare(`SELECT pattern_id, embedding, dimension, ${p?"space_id":"NULL"} AS space_id
|
|
7
|
+
FROM qe_pattern_embeddings`).all();for(let w of S)w.embedding&&w.dimension===a&&w.space_id&&h.push({id:`pe:${w.pattern_id}`,vector:new Float32Array(w.embedding.buffer,w.embedding.byteOffset,a),metadata:{tableName:"qe_pattern_embeddings",spaceId:w.space_id}})}h.length>0&&(y=c.ingest(h).accepted);let E={version:"3.0",format:"rvf",exportedAt:new Date().toISOString(),sourceDb:r,domains:[...d].sort(),tables:s},m=JSON.stringify(E),u=A(m),R=Buffer.from(m);c.embedKernel(R);let g=n.sign?c.sign(R)??void 0:void 0,b=g?n.signerKeyId??"default":void 0,O=c.fileId(),x=O?{fileId:O,parentId:c.parentId(),lineageDepth:c.lineageDepth()}:void 0,N=c.status(),I={version:"3.0",format:"rvf",exportedAt:E.exportedAt,sourceDb:r,stats:{patternCount:(s.qe_patterns||[]).length,embeddingCount:y,qValueCount:(s.rl_q_values||[]).length,dreamInsightCount:(s.dream_insights||[]).length,witnessChainLength:(s.witness_chain||[]).length,totalRecords:f,tableCounts:Object.fromEntries(_.map(({tableName:p})=>[p,s[p]?.length??0]))},domains:E.domains,checksum:u,rvfStatus:{totalVectors:N.totalVectors,totalSegments:N.totalSegments,fileSizeBytes:N.fileSizeBytes},...g?{signature:g,signerKeyId:b}:{},...x?{lineage:x}:{}};if(g)try{c.freeze()}catch{}if(gn(`${i}.manifest.json`,JSON.stringify(I,null,2),"utf-8"),c.close(),l=!0,j(t)&&!n.allowOverwriteRicher){let p;try{p=U(t)}catch(S){if(Sn(t)||!_n(S)){let w=S instanceof Error?S.message:String(S);throw new Error(`RVF_MIRROR_INSPECTION_AMBIGUOUS: the existing mirror is readable but its richness could not be established (${w}). Preserve/import it before retrying, or repeat with --force-overwrite-richer after preserving a backup.`)}}if(p){let S=p.stats.tableCounts,w=I.stats.tableCounts,C=_.map(({tableName:v})=>v).filter(v=>!S||!Number.isSafeInteger(S[v]));if(C.length>0)throw new Error(`RVF_MIRROR_INSPECTION_AMBIGUOUS: existing mirror lacks trustworthy counts for ${C.join(", ")}. Preserve/import it before retrying, or repeat with --force-overwrite-richer after preserving a backup.`);let M=_.map(({tableName:v})=>({tableName:v,existing:S[v],candidate:w[v]})).filter(({existing:v,candidate:q})=>v>q);if(M.length>0){let v=M.map(({tableName:q,existing:B,candidate:T})=>`${q} ${B} -> ${T}`).join(", ");throw new Error(`RVF_MIRROR_RICHER: refusing to replace richer mirrored tables: ${v}. Restore/import the mirror first, or repeat with --force-overwrite-richer after preserving a backup.`)}}}for(let p of[...De].reverse()){let S=`${i}${p}`,w=`${t}${p}`;j(S)?un(S,w):j(w)&&fe(w)}return I}catch(s){if(!l)try{c.close()}catch{}throw ke(i),s}}function Sn(e){let n;try{return n=H(re(e)),!!n.extractKernel()?.image}catch{return!1}finally{try{n?.close()}catch{}}}function _n(e){let n=e instanceof Error?e.message:String(e);return/ManifestNotFound|InvalidMagic|ChecksumMismatch|CorruptStore/i.test(n)}var En={patterns:"qe_patterns",qValues:"rl_q_values",dreamInsights:"dream_insights",witnessChain:"witness_chain"};function Te(e,n,r){if(!V())throw new Error("@ruvector/rvf-node is not available. Install it or use JSONL format.");let t=re(n);if(!j(t))throw new Error(`RVF file not found: ${t}`);let a=r.dryRun?H(t):Re(t);try{let i=a.verifyWitness();if(!i.valid&&(i.totalEntries>0||i.errors.length>0)){let m=i.errors.length>0?i.errors.join("; "):"unknown integrity error";throw new Error(`RVF witness verification failed: ${m}`)}let c=a.extractKernel();if(!c||!c.image)throw new Error("No brain data found in RVF file (missing kernel segment)");let l;try{l=JSON.parse(c.image.toString("utf-8"))}catch(m){throw new Error(`Failed to parse brain kernel data as JSON: ${m instanceof Error?m.message:m}`)}let s=0,d=0,f=0,y=0,h={};if(l.tables)Object.assign(h,l.tables);else for(let[m,u]of Object.entries(En)){let R=l[m];Array.isArray(R)&&(h[u]=R)}let E=()=>{let m=new Map,u=new Map,R=0;for(let g of _){let b=h[g.tableName];if(!b||!Array.isArray(b))continue;if(g.tableName==="witness_chain"){R+=b.length,d+=b.length;continue}let O=ie[g.tableName];O&&O.length>0&&(b=b.map(x=>G(x,O)));for(let x of b){let N=Y(x,m),I;if(g.dedupColumns&&g.dedupColumns.length>0)I=Z(e,g.tableName,N,g.dedupColumns,g.preserveId);else{let p=L[g.tableName]||"id",S=K[g.tableName],w=z[g.tableName];I=X(e,g.tableName,N,p,r.mergeStrategy,S,w,m,u,x.pattern_id)}if(I.imported)for(let p of O??[])N[p]instanceof Buffer&&y++;s+=I.imported,d+=I.skipped,f+=I.conflicts}}ne(e,{sourceChecksum:A(c.image.toString("utf-8")),sourceWitnessRows:R,importedRecords:s,skippedRecords:d,conflicts:f}),s+=1};if(ee(e,r.dryRun??!1,E),!r.dryRun&&f>0)try{a.compact()}catch{}return{imported:s,skipped:d,conflicts:f,embeddingsRestored:y}}finally{a.close()}}function U(e){if(!V())throw new Error("@ruvector/rvf-node is not available.");let n=re(e);if(!j(n))throw new Error(`RVF file not found: ${n}`);let r=H(n);try{let t=r.extractKernel();if(!t||!t.image)throw new Error("No brain data found in RVF file");let a=t.image.toString("utf-8"),i;try{i=JSON.parse(a)}catch(m){throw new Error(`Failed to parse brain kernel data as JSON: ${m instanceof Error?m.message:m}`)}let c=r.status(),l=pn(n).size,s=i.tables,d=s?s.qe_patterns?.length??0:i.patterns?.length??0,f=s?s.rl_q_values?.length??0:i.qValues?.length??0,y=s?s.dream_insights?.length??0:i.dreamInsights?.length??0,h=s?s.witness_chain?.length??0:i.witnessChain?.length??0,E=s&&typeof s=="object"&&!Array.isArray(s)?Object.fromEntries(Object.entries(s).filter(m=>Array.isArray(m[1])).map(([m,u])=>[m,u.length])):void 0;return{version:"3.0",format:"rvf",exportedAt:i.exportedAt??"unknown",sourceDb:i.sourceDb??"unknown",stats:{patternCount:d,embeddingCount:c.totalVectors,qValueCount:f,dreamInsightCount:y,witnessChainLength:h,...E?{tableCounts:E}:{}},domains:i.domains??[],checksum:A(a),rvfStatus:{totalVectors:c.totalVectors,totalSegments:c.totalSegments,fileSizeBytes:l}}}finally{r.close()}}function me(){return V()}oe();import{existsSync as pe,readFileSync as Cn,statSync as xn}from"fs";import{join as ue,resolve as Me}from"path";function Pe(e,n,r={}){let t=Me(e),a=Me(n),i=qe(t),c=qe(a),l=Fe(t,i),s=Fe(a,c),d=i==="jsonl"&&c==="jsonl",f=On({pathA:t,pathB:a,manifestA:l,manifestB:s,recordLevel:d,tableFilter:r.tableFilter,maxIdsPerBucket:r.maxIdsPerBucket??500}),y=new Set(l.domains),h=new Set(s.domains),E=l.domains.filter(b=>!h.has(b)),m=s.domains.filter(b=>!y.has(b)),u=l.checksum===s.checksum,R=l.version===s.version,g=u&&R&&f.every(b=>b.delta===0&&(b.added?.length??0)===0&&(b.removed?.length??0)===0&&(b.changed?.length??0)===0);return{pathA:t,pathB:a,formatA:i,formatB:c,manifestA:l,manifestB:s,checksumMatch:u,versionMatch:R,identical:g,recordLevel:d,tableDiffs:f,domainsOnlyInA:E,domainsOnlyInB:m}}function qe(e){if(!pe(e))throw new Error(`Path not found: ${e}`);if(e.endsWith(".rvf"))return"rvf";if(xn(e).isFile())throw new Error(`Unsupported brain export: ${e} (expected a .rvf file or a JSONL directory)`);return"jsonl"}function Fe(e,n){return n==="rvf"?Bn(e):In(e)}function In(e){let n=ue(e,"manifest.json");if(!pe(n))throw new Error(`Manifest not found at ${n}`);let r=k(Cn(n,"utf-8"));return je(r,"jsonl")}function Bn(e){let n=U(e);return je(n,"rvf")}function je(e,n){return{format:n,version:e.version??"unknown",exportedAt:e.exportedAt??"unknown",sourceDb:e.sourceDb??"unknown",checksum:e.checksum??"",totalRecords:e.stats?.totalRecords??0,domains:e.domains??[],tableRecordCounts:e.tableRecordCounts??{}}}function On(e){let n=e.tableFilter?_.filter(t=>t.tableName===e.tableFilter):_;if(e.tableFilter&&n.length===0)throw new Error(`Unknown table: ${e.tableFilter}`);let r=[];for(let t of n){let a=e.manifestA.tableRecordCounts[t.tableName]??0,i=e.manifestB.tableRecordCounts[t.tableName]??0,c=i-a,l,s,d;if(e.recordLevel&&An(t)){let f=Nn(ue(e.pathA,t.fileName),ue(e.pathB,t.fileName),t,e.maxIdsPerBucket);l=f.added,s=f.removed,d=f.changed}r.push({tableName:t.tableName,countA:a,countB:i,delta:c,...l!==void 0?{added:l}:{},...s!==void 0?{removed:s}:{},...d!==void 0?{changed:d}:{}})}return r}function An(e){return!0}function Nn(e,n,r,t){let a=Le(e,r),i=Le(n,r),c=[],l=[],s=[];for(let[d,f]of a){let y=i.get(d);if(y===void 0)l.length<t&&l.push(d);else if(y!==f){if(r.dedupColumns&&r.dedupColumns.length>0)continue;s.length<t&&s.push(d)}}for(let d of i.keys())a.has(d)||c.length<t&&c.push(d);return c.sort(),l.sort(),s.sort(),{added:c,removed:l,changed:s}}function Le(e,n){let r=new Map;if(!pe(e))return r;let t=P(e,k);for(let a of t){let i=kn(a,n);if(i===void 0)continue;let c=Dn(a);r.set(i,$n(c))}return r}function kn(e,n){if(n.dedupColumns&&n.dedupColumns.length>0){let a=[];for(let i of n.dedupColumns){let c=e[i];if(c==null)return;a.push(String(c))}return a.join("")}let r=L[n.tableName]??"id",t=e[r];if(t!=null)return String(t)}function Dn(e){let n=Object.keys(e).sort(),r={};for(let t of n)r[t]=e[t];return JSON.stringify(r)}function $n(e){return A(e)}oe();import{existsSync as ge,statSync as Tn}from"fs";import{join as Ve,resolve as Mn}from"path";var qn=20,Fn="qe_patterns";function We(e,n={}){let r=Mn(e);jn(r);let t=n.table??Fn,a=_.find(R=>R.tableName===t);if(!a)throw new Error(`Unknown table: ${t}`);let i=Ve(r,a.fileName);if(!ge(i))throw new Error(`Table file not found: ${a.fileName} (expected in ${r}). Was this export generated with --format jsonl?`);let c=P(i,k),l=a.domainColumn,s=Math.max(1,n.limit??qn),d=n.query?n.query.toLowerCase():void 0,f=n.domains&&n.domains.length>0?new Set(n.domains):void 0,y=n.since,h=n.until,E=n.patternType,m=0,u=[];for(let R of c)Ln(R,{domainColumn:l,domains:f,patternType:E,since:y,until:h,queryLower:d})&&(m++,u.length<s&&u.push(Pn(R,a.tableName,l)));return{table:t,inputPath:r,totalScanned:c.length,totalMatched:m,limit:s,hits:u,truncated:m>s}}function Ln(e,n){if(n.domains){if(!n.domainColumn)return!1;let r=e[n.domainColumn];if(typeof r!="string"||!n.domains.has(r))return!1}if(n.patternType!==void 0&&e.pattern_type!==n.patternType)return!1;if(n.since!==void 0||n.until!==void 0){let r=Je(e);if(r===void 0||n.since!==void 0&&r<n.since||n.until!==void 0&&r>n.until)return!1}if(n.queryLower!==void 0){let r=typeof e.name=="string"?e.name.toLowerCase():"",t=typeof e.description=="string"?e.description.toLowerCase():"";if(!r.includes(n.queryLower)&&!t.includes(n.queryLower))return!1}return!0}function Je(e){for(let n of["updated_at","created_at","timestamp"]){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function Pn(e,n,r){let t=(typeof e.id=="string"||typeof e.id=="number"?String(e.id):void 0)??`${n}:?`,a={name:typeof e.name=="string"?e.name:void 0,description:typeof e.description=="string"?e.description:void 0,domain:r&&typeof e[r]=="string"?e[r]:void 0,patternType:typeof e.pattern_type=="string"?e.pattern_type:void 0,confidence:typeof e.confidence=="number"?e.confidence:void 0,updatedAt:Je(e)};return{id:t,display:a,row:e}}function jn(e){if(!ge(e))throw new Error(`Path not found: ${e}`);if(Tn(e).isFile())throw e.endsWith(".rvf")?new Error("Brain search does not support RVF exports. Re-export with --format jsonl, or use `aqe brain info` for RVF summaries."):new Error(`Unsupported brain export: ${e} (expected a JSONL directory)`);let r=Ve(e,"manifest.json");if(!ge(r))throw new Error(`Manifest not found at ${r}. Is this a brain export directory?`)}function Ue(e,n){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return{created:0,skipped:0};e.exec(`
|
|
8
|
+
CREATE TEMP TABLE IF NOT EXISTS _covered_patterns (
|
|
9
|
+
pattern_id TEXT PRIMARY KEY
|
|
10
|
+
)
|
|
11
|
+
`),e.exec("DELETE FROM _covered_patterns"),e.exec(`
|
|
12
|
+
INSERT INTO _covered_patterns (pattern_id)
|
|
13
|
+
SELECT DISTINCT json_extract(action_data, '$.patternId')
|
|
14
|
+
FROM witness_chain
|
|
15
|
+
WHERE action_type = 'PATTERN_CREATE'
|
|
16
|
+
AND json_extract(action_data, '$.patternId') IS NOT NULL
|
|
17
|
+
`),e.exec(`
|
|
18
|
+
INSERT OR IGNORE INTO _covered_patterns (pattern_id)
|
|
19
|
+
SELECT DISTINCT json_extract(action_data, '$.pattern_id')
|
|
20
|
+
FROM witness_chain
|
|
21
|
+
WHERE action_type = 'PATTERN_CREATE'
|
|
22
|
+
AND json_extract(action_data, '$.pattern_id') IS NOT NULL
|
|
23
|
+
`);let t=e.prepare(`SELECT p.id, p.pattern_type, p.qe_domain, p.name, p.created_at
|
|
24
|
+
FROM qe_patterns p
|
|
25
|
+
LEFT JOIN _covered_patterns c ON p.id = c.pattern_id
|
|
26
|
+
WHERE c.pattern_id IS NULL
|
|
27
|
+
ORDER BY p.created_at ASC`).all(),i=e.prepare("SELECT COUNT(*) as count FROM qe_patterns").get().count-t.length,c=0;for(let l of t)n.append("PATTERN_CREATE",{patternId:l.id,patternType:l.pattern_type,qeDomain:l.qe_domain,name:l.name,originalCreatedAt:l.created_at,backfilled:!0},"system:backfill"),c++;return e.exec("DROP TABLE IF EXISTS _covered_patterns"),{created:c,skipped:i}}async function He(e,n){if(Vn(n.format)==="rvf"){let a=F(e,{readonly:!0});try{return $e(a,{outputPath:n.outputPath,domains:n.domains,allowOverwriteRicher:n.allowOverwriteRicher},e)}finally{a.close()}}let t=F(e,{readonly:!0});try{return Oe(t,n,e)}finally{t.close()}}async function ze(e,n,r){if(Xe(n,r.format)==="rvf"){let i=F(e);try{return Te(i,n,{mergeStrategy:r.mergeStrategy,dryRun:r.dryRun})}finally{i.close()}}let a=F(e);try{return Ae(a,n,r)}finally{a.close()}}async function Ke(e,n){return Xe(e,n)==="rvf"?U(e):Ne(e)}async function Ge(e,n,r={}){return Pe(e,n,r)}async function Qe(e,n={}){return We(e,n)}async function Ye(e){let n=F(e);try{let r=Ee(n,ve());return await r.initialize(),Ue(n,r)}finally{n.close()}}function Vn(e){if(e==="jsonl")return"jsonl";if(e==="rvf"){if(!me())throw new Error("RVF format requested but @ruvector/rvf-node is not available on this platform. Use --format jsonl instead.");return"rvf"}return me()?"rvf":"jsonl"}function Xe(e,n){return n==="rvf"?"rvf":n==="jsonl"?"jsonl":e.endsWith(".rvf")?"rvf":"jsonl"}var be=class{name="brain";description="Export, import, and inspect QE brain state";cleanupAndExit;ensureInitialized;constructor(n,r){this.cleanupAndExit=n,this.ensureInitialized=r}register(n,r){let t=n.command("brain").description(this.description);t.command("export").description("Export brain state to a portable directory").requiredOption("-o, --output <path>","Output directory path").option("--format <format>","Export format: rvf (default) or jsonl","rvf").option("--db <path>","Source database path").option("--force-overwrite-richer","Allow replacing an existing RVF with fewer patterns",!1).action(async a=>{await this.executeExport(a)}),t.command("import").description("Import brain state from an export directory").requiredOption("-i, --input <path>","Path to brain export directory").option("--strategy <strategy>","Merge strategy","skip-conflicts").option("--dry-run","Preview import without writing",!1).option("--db <path>","Target database path").action(async a=>{await this.executeImport(a)}),t.command("info").description("Show manifest info for a brain export").requiredOption("-i, --input <path>","Path to brain export directory").action(async a=>{await this.executeInfo(a)}),t.command("witness-backfill").description("Create witness chain entries for patterns that predate the witness chain").option("--db <path>","Database path").action(async a=>{await this.executeWitnessBackfill(a)}),t.command("diff").description("Compare two brain exports (JSONL directory or .rvf file)").argument("<a>","Path to first brain export").argument("<b>","Path to second brain export").option("--table <name>","Restrict comparison to a single table").option("--verbose","Show the IDs of added/removed/changed records",!1).option("--json","Emit the diff as JSON to stdout",!1).action(async(a,i,c)=>{await this.executeDiff(a,i,c)}),t.command("search").description("Search a JSONL brain export with filters").requiredOption("-i, --input <path>","Path to brain export directory (JSONL)").option("--table <name>","Table to search (default: qe_patterns)").option("--domain <name...>","Restrict to one or more domains").option("--pattern-type <type>","Restrict to a specific pattern_type (qe_patterns only)").option("--since <iso>","Include rows with timestamp \u2265 <iso>").option("--until <iso>","Include rows with timestamp \u2264 <iso>").option("-q, --query <text>","Substring match across name + description (case-insensitive)").option("-l, --limit <n>","Maximum results to return","20").option("--json","Emit results as JSON to stdout",!1).action(async a=>{await this.executeSearch(a)})}async executeExport(n){try{console.log(o.blue(`
|
|
28
|
+
Exporting brain state (format: ${n.format})...
|
|
29
|
+
`));let r=await ye(n.db),t=await He(r,{outputPath:$.resolve(n.output),format:n.format,allowOverwriteRicher:n.forceOverwriteRicher});if(console.log(o.green(" Export complete.")),console.log(` Format: ${o.cyan("format"in t?t.format??"jsonl":"jsonl")}`),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"embeddingCount"in t.stats?console.log(` Vectors: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`),"rvfStatus"in t){let a=t.rvfStatus;console.log(` RVF Size: ${o.cyan(Ze(a.fileSizeBytes))}`),console.log(` Segments: ${o.cyan(a.totalSegments)}`)}console.log(` Checksum: ${o.gray(t.checksum)}`),console.log(` Output: ${o.cyan($.resolve(n.output))}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
|
|
30
|
+
Brain export failed:`),r),await this.cleanupAndExit(1)}}async executeImport(n){try{n.dryRun?console.log(o.yellow(`
|
|
31
|
+
Dry-run mode \u2014 no data will be written.
|
|
32
|
+
`)):console.log(o.blue(`
|
|
33
|
+
Importing brain state...
|
|
34
|
+
`));let r=await ye(n.db),t=await ze(r,$.resolve(n.input),{mergeStrategy:n.strategy,dryRun:n.dryRun});console.log(o.green(" Import complete.")),console.log(` Imported: ${o.cyan(t.imported)}`),console.log(` Skipped: ${o.yellow(t.skipped)}`),console.log(` Conflicts: ${o.red(t.conflicts)}`),"embeddingsRestored"in t&&console.log(` Embeddings: ${o.cyan(t.embeddingsRestored)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
|
|
35
|
+
Brain import failed:`),r),await this.cleanupAndExit(1)}}async executeInfo(n){try{console.log(o.blue(`
|
|
36
|
+
Brain Export Info
|
|
37
|
+
`));let r=$.resolve(n.input),t=await Ke(r),a="format"in t?t.format??"jsonl":"jsonl";if(console.log(` Version: ${o.cyan(t.version)}`),console.log(` Format: ${o.cyan(a)}`),console.log(` Exported: ${o.cyan(t.exportedAt)}`),console.log(` Source DB: ${o.cyan(t.sourceDb)}`),console.log(o.blue(`
|
|
38
|
+
Learning Data:`)),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"qValueCount"in t.stats&&console.log(` Q-Values: ${o.cyan(t.stats.qValueCount)}`),"dreamInsightCount"in t.stats){let l=t.stats.dreamInsightCount,d=("tableRecordCounts"in t?t.tableRecordCounts:void 0)?.dream_cycles,f=d!==void 0?` (${d} cycles)`:"";console.log(` Dream Insights: ${o.cyan(l)}${o.gray(f)}`)}"witnessChainLength"in t.stats&&console.log(` Witness Chain: ${o.cyan(t.stats.witnessChainLength)} entries`),"embeddingCount"in t.stats?console.log(` Embeddings: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`);let i="tableRecordCounts"in t?t.tableRecordCounts:void 0;if(i){let l=Object.entries(i).filter(([s,d])=>d>0&&!["qe_patterns","rl_q_values","dream_insights","dream_cycles","witness_chain","vectors","qe_pattern_embeddings"].includes(s));if(l.length>0)for(let[s,d]of l){let y=`${s.replace(/_/g," ").replace(/\b\w/g,h=>h.toUpperCase())}:`.padEnd(15);console.log(` ${y}${o.cyan(d)}`)}}let c="totalRecords"in t.stats?t.stats.totalRecords:void 0;if(c!==void 0&&(console.log(o.blue(`
|
|
39
|
+
Summary:`)),console.log(` Total Records: ${o.cyan(c)}`)),"domains"in t&&Array.isArray(t.domains)&&t.domains.length>0&&(c||console.log(o.blue(`
|
|
40
|
+
Summary:`)),console.log(` Domains: ${o.cyan(t.domains.join(", "))}`)),"rvfStatus"in t){let l=t.rvfStatus;console.log(o.blue(`
|
|
41
|
+
RVF Details:`)),console.log(` File Size: ${o.cyan(Ze(l.fileSizeBytes))}`),console.log(` Vectors: ${o.cyan(l.totalVectors)}`),console.log(` Segments: ${o.cyan(l.totalSegments)}`)}if("lineage"in t){let l=t.lineage;l&&(console.log(o.blue(`
|
|
42
|
+
Lineage:`)),console.log(` File ID: ${o.cyan(l.fileId)}`),console.log(` Parent ID: ${o.cyan(l.parentId??"none (root)")}`),console.log(` Depth: ${o.cyan(l.lineageDepth)}`))}if("signature"in t){let l=t.signature,s=t.signerKeyId;console.log(o.blue(`
|
|
43
|
+
Signature:`)),l?(console.log(` Status: ${o.green("Signed")}`),console.log(` Key ID: ${o.cyan(s??"unknown")}`),console.log(` Signature: ${o.gray(l.slice(0,32)+"...")}`)):console.log(` Status: ${o.yellow("Unsigned")}`)}console.log(`
|
|
44
|
+
Checksum: ${o.gray(t.checksum)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
|
|
45
|
+
Failed to read brain info:`),r),await this.cleanupAndExit(1)}}async executeDiff(n,r,t){try{let a=await Ge($.resolve(n),$.resolve(r),{tableFilter:t.table});if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
|
|
46
|
+
`),await this.cleanupAndExit(a.identical?0:1);return}Un(a,t.verbose),await this.cleanupAndExit(a.identical?0:1)}catch(a){console.error(o.red(`
|
|
47
|
+
Brain diff failed:`),a),await this.cleanupAndExit(2)}}async executeSearch(n){try{let r=Wn(n.limit),t=Jn(n.domain),a=await Qe($.resolve(n.input),{table:n.table,domains:t,patternType:n.patternType,since:n.since,until:n.until,query:n.query,limit:r});if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
|
|
48
|
+
`),await this.cleanupAndExit(a.totalMatched>0?0:3);return}Kn(a),await this.cleanupAndExit(a.totalMatched>0?0:3)}catch(r){console.error(o.red(`
|
|
49
|
+
Brain search failed:`),r),await this.cleanupAndExit(2)}}async executeWitnessBackfill(n){try{console.log(o.blue(`
|
|
50
|
+
Running witness chain backfill...
|
|
51
|
+
`));let r=await ye(n.db),t=await Ye(r);console.log(o.green(" Backfill complete.")),console.log(` Created: ${o.cyan(t.created)} new witness entries`),console.log(` Skipped: ${o.cyan(t.skipped)} (already witnessed)`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
|
|
52
|
+
Witness backfill failed:`),r),await this.cleanupAndExit(1)}}getHelp(){return`
|
|
53
|
+
Export, import, and inspect QE brain state.
|
|
54
|
+
|
|
55
|
+
Formats:
|
|
56
|
+
rvf \u2014 Single portable .rvf file (default, requires @ruvector/rvf-node)
|
|
57
|
+
jsonl \u2014 JSONL directory format (fallback when native not available)
|
|
58
|
+
|
|
59
|
+
Usage:
|
|
60
|
+
aqe brain export -o brain.rvf [--format rvf] [--db <path>]
|
|
61
|
+
aqe brain export -o ./brain-dir --format jsonl [--db <path>]
|
|
62
|
+
aqe brain import -i brain.rvf [--strategy skip-conflicts] [--dry-run] [--db <path>]
|
|
63
|
+
aqe brain info -i brain.rvf
|
|
64
|
+
|
|
65
|
+
Subcommands:
|
|
66
|
+
export Export brain state to a portable .rvf file or JSONL directory
|
|
67
|
+
import Import a brain export into the local database
|
|
68
|
+
info Show manifest metadata for an existing brain export
|
|
69
|
+
diff Compare two brain exports (manifest always; record-level for JSONL)
|
|
70
|
+
search Filtered search over a JSONL brain export
|
|
71
|
+
|
|
72
|
+
Examples:
|
|
73
|
+
aqe brain export -o .agentic-qe/brain.rvf
|
|
74
|
+
aqe brain export -o .agentic-qe/brain.rvf --format rvf
|
|
75
|
+
aqe brain export -o ./brain-export --format jsonl
|
|
76
|
+
aqe brain import -i .agentic-qe/brain.rvf --strategy latest-wins
|
|
77
|
+
aqe brain import -i .agentic-qe/brain.rvf --dry-run
|
|
78
|
+
aqe brain info -i .agentic-qe/brain.rvf
|
|
79
|
+
aqe brain diff ./brain-a ./brain-b --verbose
|
|
80
|
+
aqe brain search -i ./brain-export --query oauth --domain test-generation
|
|
81
|
+
aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
|
|
82
|
+
`}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-UCQ6AB32.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
|
|
83
|
+
Brain Diff
|
|
84
|
+
`)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+en(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
|
|
85
|
+
Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
|
|
86
|
+
Note: record-level diff is only available when both sides are JSONL exports.
|
|
87
|
+
Per-table counts shown below; re-export with --format jsonl for added/removed/changed IDs.`)),console.log(o.blue(`
|
|
88
|
+
Tables:`));let r=e.tableDiffs.filter(Hn);if(r.length===0)console.log(o.gray(" (no differences)"));else for(let t of r)console.log(` ${t.tableName.padEnd(28)} ${o.cyan(String(t.countA).padStart(7))} \u2192 ${o.cyan(String(t.countB).padStart(7))} ${en(t.delta)}`+zn(t,n)),n&&(t.added&&t.added.length>0&&he("added",t.added),t.removed&&t.removed.length>0&&he("removed",t.removed),t.changed&&t.changed.length>0&&he("changed",t.changed));console.log(""),e.identical?console.log(o.green(` Result: identical
|
|
89
|
+
`)):console.log(o.yellow(` Result: differences found
|
|
90
|
+
`))}function Hn(e){return!!(e.delta!==0||e.added&&e.added.length>0||e.removed&&e.removed.length>0||e.changed&&e.changed.length>0)}function en(e){return e===0?o.gray("(\xB10)"):e>0?o.green(`(+${e})`):o.red(`(${e})`)}function zn(e,n){let r=[];return e.added&&e.added.length>0&&r.push(o.green(`+${e.added.length}`)),e.removed&&e.removed.length>0&&r.push(o.red(`-${e.removed.length}`)),e.changed&&e.changed.length>0&&r.push(o.yellow(`~${e.changed.length}`)),r.length===0?"":n?" "+r.join(" "):" "+o.gray("[")+r.join(" ")+o.gray("]")}function he(e,n){let r=n.slice(0,10).join(", "),t=n.length>10?o.gray(` \u2026(+${n.length-10} more)`):"";console.log(` ${o.gray(e+":")} ${r}${t}`)}function Kn(e){if(console.log(o.blue(`
|
|
91
|
+
Brain Search
|
|
92
|
+
`)),console.log(` Input: ${o.cyan(e.inputPath)}`),console.log(` Table: ${o.cyan(e.table)}`),console.log(` Scanned: ${o.cyan(e.totalScanned)} Matched: ${o.cyan(e.totalMatched)} Shown: ${o.cyan(e.hits.length)}`+(e.truncated?o.yellow(` (truncated to limit ${e.limit})`):"")),e.hits.length===0){console.log(o.yellow(`
|
|
93
|
+
No matching rows.
|
|
94
|
+
`));return}console.log("");for(let n of e.hits){let r=o.cyan(n.id)+(n.display.patternType?o.gray(` ${n.display.patternType}`):"")+(n.display.domain?o.gray(` [${n.display.domain}]`):"")+(n.display.confidence!==void 0?o.gray(` conf=${n.display.confidence.toFixed(2)}`):"");if(console.log(` ${r}`),n.display.name&&console.log(` ${o.bold(n.display.name)}`),n.display.description){let t=n.display.description.length>200?n.display.description.slice(0,200)+"\u2026":n.display.description;console.log(` ${o.gray(t)}`)}n.display.updatedAt&&console.log(` ${o.gray(n.display.updatedAt)}`),console.log("")}}function Dt(e,n){return new be(e,n)}export{be as BrainHandler,Dt as createBrainHandler};
|
|
@@ -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.14.
|
|
2
|
-
import"./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.14.6");process.exit(0)}
|
|
2
|
+
import"./chunk-64VGZQLB.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
|
|
3
3
|
`),l=!1;for(let i=0;i<n.length;i++){let d=n[i],t=d.trim(),c=i+1,u=d.length-d.trimStart().length+1;if(l){t.includes("*/")&&(l=!1);continue}if(t.startsWith("/*")){l=!t.includes("*/");continue}if(t.startsWith("//"))continue;if(/^\s*if\s*\(/.test(d)&&(this.findMatchingElse(n,i)||r.push({file:s,line:c,column:u,language:this.language,construct:"if-without-else",triggerCondition:"when condition is false",currentHandling:"falls through \u2014 no else branch",suggestedGuard:"Add else branch or document why falsy path is safe",severity:"medium"})),/^\s*switch\s*\(/.test(d)){let a=this.extractBlock(n,i);if(a&&!a.includes("default:")&&!a.includes("default :")&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-no-default",triggerCondition:"when value matches no case",currentHandling:"falls through \u2014 no default case",suggestedGuard:"Add default case with error handling or exhaustive check",severity:"high"}),a){let g=a.match(/case\s+[^:]+:/g)||[],h=a.match(/\b(break|return|throw|continue)\b/g)||[];g.length>0&&h.length<g.length&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-missing-break",triggerCondition:"when case falls through to next case",currentHandling:"fall-through \u2014 may execute unintended cases",suggestedGuard:"Add break/return to each case or add explicit // falls through comment",severity:"medium"})}}if(/\bcatch\s*\(/.test(t)||/\bcatch\s*\{/.test(t)){let a=this.extractBlock(n,i);if(a!==null){let g=a.replace(/[{}]/g,"").trim();(g.length===0||/^\s*\/\//.test(g))&&r.push({file:s,line:c,column:u,language:this.language,construct:"try-empty-catch",triggerCondition:"when exception is thrown",currentHandling:"exception silently swallowed",suggestedGuard:"Log the error or rethrow with context",severity:"high"})}}if(/\btry\s*\{/.test(t)&&this.extractBlock(n,i)&&(n.slice(i,Math.min(i+30,n.length)).join(`
|
|
4
4
|
`).includes("finally")||r.push({file:s,line:c,column:u,language:this.language,construct:"try-no-finally",triggerCondition:"when cleanup is needed regardless of success/failure",currentHandling:"no finally block \u2014 cleanup may be skipped on exception",suggestedGuard:"Add finally block for resource cleanup if applicable",severity:"low"})),t.includes("?.")){let a=t.match(/(\w+(?:\.\w+)*)\?\./g)||[];for(let g of a)if(!t.includes("??")&&!t.includes("|| ")&&!t.includes("if")){r.push({file:s,line:c,column:u,language:this.language,construct:"optional-chaining-null-path",triggerCondition:`when ${g.replace("?.","")} is null/undefined`,currentHandling:"returns undefined \u2014 may propagate",suggestedGuard:"Add ?? fallback or explicit null check",severity:"low"});break}}if(t.includes("??")&&!t.includes("?.")&&r.push({file:s,line:c,column:u,language:this.language,construct:"nullish-coalescing-fallback",triggerCondition:"when left side is null/undefined",currentHandling:"uses fallback value",suggestedGuard:"Verify fallback value is appropriate for all null cases",severity:"low"}),/\.\s*then\s*\(/.test(t)&&!t.includes(".catch")&&!t.includes("await")){let a=n.slice(i,Math.min(i+5,n.length)).join(" ");!a.includes(".catch")&&!a.includes("try")&&r.push({file:s,line:c,column:u,language:this.language,construct:"promise-no-catch",triggerCondition:"when promise rejects",currentHandling:"unhandled rejection \u2014 may crash process",suggestedGuard:"Add .catch() handler or use try/catch with await",severity:"high"})}let p=["map","filter","reduce","forEach","find","some","every","flatMap"];for(let a of p)if(new RegExp(`\\.${a}\\s*\\(`).test(t)){let h=n.slice(Math.max(0,i-3),i).join(" ");if(!h.includes(".length")&&!h.includes("if (")&&!h.includes("?.")){r.push({file:s,line:c,column:u,language:this.language,construct:"array-callback-empty",triggerCondition:`when array is empty before .${a}()`,currentHandling:a==="reduce"?"may throw without initial value":"returns empty result \u2014 may cause downstream issues",suggestedGuard:a==="reduce"?"Provide initial value or check array length":"Check array length or handle empty result",severity:a==="reduce"?"high":"low"});break}}/\|\|\s*['"`\d]/.test(t)&&!t.includes("??")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-or-falsy",triggerCondition:'when left side is falsy (0, "", false, null, undefined)',currentHandling:'uses fallback \u2014 may unintentionally override 0, "", or false',suggestedGuard:"Use ?? instead of || if only null/undefined should trigger fallback",severity:"medium"}),/&&\s*\w+\s*\(/.test(t)&&!t.includes("if")&&!t.includes("while")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-and-short-circuit",triggerCondition:"when left side is falsy \u2014 right side never executes",currentHandling:"short-circuits \u2014 function call skipped silently",suggestedGuard:"Use explicit if-statement for clarity when side effects matter",severity:"low"}),(t.match(/\?/g)||[]).length>=2&&t.includes(":")&&r.push({file:s,line:c,column:u,language:this.language,construct:"ternary-complex",triggerCondition:"when nested ternary conditions interact",currentHandling:"nested ternary \u2014 hard to read and maintain",suggestedGuard:"Refactor to if/else or switch for readability",severity:"medium"}),(/\btypeof\s+\w+\s*===?\s*['"]/.test(t)||/\binstanceof\b/.test(t))&&!t.includes("else")&&!this.findMatchingElse(n,i)&&r.push({file:s,line:c,column:u,language:this.language,construct:"type-guard-unhandled",triggerCondition:"when value does not match the guarded type",currentHandling:"unguarded type path \u2014 may cause runtime type errors",suggestedGuard:"Add else branch or exhaustive type checking",severity:"medium"})}return r}findMatchingElse(e,s){let r={depth:0};for(let n=s;n<Math.min(s+30,e.length);n++){let l=e[n];for(let i of l)i==="{"&&r.depth++,i==="}"&&r.depth--;if(r.depth===0&&n>s){if((e[n+1]?.trim()||"").startsWith("else")||e[n].trim().endsWith("else")||e[n].trim().endsWith("else {")||e[n].includes("} else"))return!0;break}}return!1}extractBlock(e,s){let r=0,n=!1,l=[];for(let i=s;i<Math.min(s+50,e.length);i++){let d=e[i];for(let t of d)t==="{"&&(r++,n=!0),t==="}"&&r--;if(n&&(l.push(d),r===0))return l.join(`
|
|
5
5
|
`)}return null}};function y(o,e,s){let r=Date.now(),n=s||(e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"javascript"),i=new f(n).enumerate(o,e);return{file:e,language:n,branches:i,totalConstructs:i.length,unhandledCount:i.length,duration:Date.now()-r}}function b(o){let e=[];if(e.push(`# Branch Enumeration Report: ${o.file}`),e.push(""),e.push(`**Language**: ${o.language} | **Branches**: ${o.unhandledCount} | **Duration**: ${o.duration}ms`),e.push(""),o.branches.length===0)return e.push("No unhandled branches detected."),e.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
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.14.
|
|
2
|
-
import{a as p}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.14.6");process.exit(0)}
|
|
2
|
+
import{a as p}from"./chunk-ZVWVV4EX.js";import"./chunk-64VGZQLB.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
|
|
3
3
|
${i.errors.join(`
|
|
4
4
|
`)}`);return this.cache.set(r,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}async list(){try{return(await k(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>y(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(r){if(r.code==="ENOENT")return[];throw r}}async validate(r){let e=[],n=[];if(r.name||e.push("Workflow must have a name"),r.version||e.push("Workflow must have a version"),r.description||n.push("Workflow should have a description"),Array.isArray(r.variables)?r.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(r.steps))e.push("Workflow must have a steps array");else if(r.steps.length===0)e.push("Workflow must have at least one step");else{r.steps.forEach((t,s)=>{t.name||e.push(`Step at index ${s} must have a name`),t.action||e.push(`Step ${t.name||s} must have an action`),(!t.config||typeof t.config!="object")&&e.push(`Step ${t.name||s} must have a config object`),t.assertions&&Array.isArray(t.assertions)&&t.assertions.forEach((f,u)=>{f.condition||e.push(`Assertion ${u} in step ${t.name||s} must have a condition`),f.message||n.push(`Assertion ${u} in step ${t.name||s} should have a message`)})});let o=r.steps.map(t=>t.name),i=o.filter((t,s)=>o.indexOf(t)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(r,e){let n=await this.load(r),o=n.variables.filter(t=>t.required&&!(t.name in e)).map(t=>t.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(t=>{t.name in e?i[t.name]=e[t.name]:"default"in t&&(i[t.name]=t.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:r}}}async getMetadata(r){try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}clearCache(){this.cache.clear()}async reload(r){return this.cache.delete(r),this.load(r)}},x=new l;function w(a,r){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),t=r;for(let s of i)if(t&&typeof t=="object"&&s in t)t=t[s];else return e;return t!=null?String(t):e})}function T(a,r){let e={...r.variables,result:r.results.get("__last_result__")},n=w(a,e);return p(n,e,!1)}var g=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],A={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},h={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function _(a){return h[a]}function P(a){return g.includes(a)}function L(){return g.map(a=>{let r=Object.entries(h).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:A[a],category:r}})}export{h as WORKFLOW_CATEGORIES,A as WORKFLOW_DESCRIPTIONS,g as WORKFLOW_TEMPLATES,l as WorkflowLoader,x as defaultWorkflowLoader,T as evaluateCondition,L as getAllWorkflowTemplates,_ as getWorkflowsByCategory,w as interpolateVariables,P as isValidWorkflowTemplate};
|
|
@@ -0,0 +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.14.6");process.exit(0)}
|
|
2
|
+
import{a}from"./chunk-RTFO5UQH.js";import"./chunk-5QQSIGUA.js";import"./chunk-BMAPORJ7.js";import"./chunk-2JVWITNK.js";import"./chunk-Q5XTSMWR.js";import"./chunk-AIRGNL55.js";import"./chunk-QW6VMTBR.js";import"./chunk-SDRHUMJB.js";import"./chunk-TCHGOB2N.js";import"./chunk-FBMN7B46.js";import"./chunk-ENGZ4D5V.js";import"./chunk-MJS53PRX.js";import"./chunk-DPYSUDAO.js";import"./chunk-WCJBU2KI.js";import"./chunk-PI7TJS62.js";import"./chunk-EAY2JMZG.js";import"./chunk-C6KWXUFJ.js";import"./chunk-IB27QACC.js";import"./chunk-6SH5VZUD.js";import"./chunk-SESK3ARK.js";import"./chunk-SNOBH4AZ.js";import"./chunk-IQO7UCFR.js";import"./chunk-DUYOVM5I.js";import"./chunk-64VGZQLB.js";export{a as BrowserWorkflowTool};
|
|
@@ -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.14.
|
|
2
|
-
import{a as q}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.14.6");process.exit(0)}
|
|
2
|
+
import{a as q}from"./chunk-3EA536JF.js";import{c as V,d as W}from"./chunk-AHKELLIO.js";import{c as x}from"./chunk-4N23RFDU.js";import{b as E,d as $}from"./chunk-AIRGNL55.js";import{a as G}from"./chunk-TCHGOB2N.js";import{e as R}from"./chunk-FBMN7B46.js";import{a as C,c as H}from"./chunk-MJS53PRX.js";import{i as v}from"./chunk-DPYSUDAO.js";import{a as M,b as U,d as ee}from"./chunk-IB27QACC.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=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: ${C(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 (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -63,7 +63,7 @@ import{a as q}from"./chunk-3VOQRIQM.js";import{c as V,d as W}from"./chunk-CSU5NY
|
|
|
63
63
|
ORDER BY weight DESC
|
|
64
64
|
LIMIT -1 OFFSET ?
|
|
65
65
|
)
|
|
66
|
-
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(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(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){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-UJRHFBRX.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.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 '[]'"),S.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){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async 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
|
|
66
|
+
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(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(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){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-NAHKLDRN.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.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 '[]'"),S.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){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async 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
|
|
67
67
|
FROM qe_pattern_nulls n
|
|
68
68
|
JOIN qe_patterns p ON p.id = n.pattern_id
|
|
69
69
|
ORDER BY n.updated_at DESC
|
|
@@ -89,7 +89,7 @@ import{a as q}from"./chunk-3VOQRIQM.js";import{c as V,d as W}from"./chunk-CSU5NY
|
|
|
89
89
|
WHERE confidence >= 0.3 AND success_rate < 0.7
|
|
90
90
|
ORDER BY usage_count DESC
|
|
91
91
|
LIMIT 40
|
|
92
|
-
)`).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-
|
|
92
|
+
)`).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-DRZ2LS6X.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-7IETWW6W.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-UVWGDUWC.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(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"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
|
|
93
93
|
UPDATE dream_insights
|
|
94
94
|
SET applied = 1, pattern_id = ?
|
|
95
95
|
WHERE id = ?
|
|
@@ -117,4 +117,4 @@ import{a as q}from"./chunk-3VOQRIQM.js";import{c as V,d as W}from"./chunk-CSU5NY
|
|
|
117
117
|
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
118
118
|
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
119
119
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
120
|
-
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-UJRHFBRX.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-LVIUOO4S.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}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,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.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,u.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&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.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,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.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-LVIUOO4S.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-2CSG7C4W.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),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{u.debug("Failed to publish meta-learning insight event")}}}else u.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){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.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){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),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){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.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){u.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??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.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 de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|
|
120
|
+
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-NAHKLDRN.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-VIJB7JUS.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}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,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.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,u.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&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.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,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.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-VIJB7JUS.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-UVWGDUWC.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),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{u.debug("Failed to publish meta-learning insight event")}}}else u.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){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.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){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),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){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.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){u.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??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.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 de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|