agentic-qe 3.9.32 → 3.9.34
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 +120 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-OXCJPHRI.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-WKS3E6KT.js → agent-booster-wasm-UD3YB7FC.js} +2 -2
- package/dist/cli/chunks/{agent-handler-LYCAWE7S.js → agent-handler-BNBGQS6N.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-XF7IOMRK.js → agent-memory-branch-NJHROVKY.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-HDAC5FJJ.js +2 -0
- package/dist/cli/chunks/{audit-D2AY3HFP.js → audit-4Y7M2S2O.js} +2 -2
- package/dist/cli/chunks/base-JY364ZUA.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-BWUH4OQT.js → better-sqlite3-4JUNP7IW.js} +2 -2
- package/dist/cli/chunks/{brain-handler-NNW4TAO2.js → brain-handler-VWRD34M6.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-OM5HNZKV.js → branch-enumerator-H4WLPOU3.js} +2 -2
- package/dist/cli/chunks/{browser-Y2FU2NV4.js → browser-Y7ZNFLEU.js} +2 -2
- package/dist/cli/chunks/browser-workflow-DAGIWFJE.js +2 -0
- package/dist/cli/chunks/{chunk-O5UGJ3OI.js → chunk-26BODPAN.js} +2 -2
- package/dist/cli/chunks/{chunk-OKEHGXIS.js → chunk-2C6LRXLU.js} +2 -2
- package/dist/cli/chunks/{chunk-WQ4MT74X.js → chunk-2MC2YH4J.js} +1 -1
- package/dist/cli/chunks/{chunk-M5PYPGBC.js → chunk-3K3QGBH7.js} +2 -2
- package/dist/cli/chunks/{chunk-5R5WOLZM.js → chunk-3OTG4IXK.js} +1 -1
- package/dist/cli/chunks/{chunk-PS6ISBED.js → chunk-3PRHEG4B.js} +2 -2
- package/dist/cli/chunks/{chunk-7PTW3M67.js → chunk-45SJSOSI.js} +2 -2
- package/dist/cli/chunks/{chunk-PPS6VN24.js → chunk-4AIJOXQJ.js} +1 -1
- package/dist/cli/chunks/{chunk-62UXGD5J.js → chunk-4FW4ZWPB.js} +5 -5
- package/dist/cli/chunks/{chunk-YVMJTBXB.js → chunk-4GHSIVTA.js} +3 -3
- package/dist/cli/chunks/{chunk-A6VI5BZU.js → chunk-4GSUSYZK.js} +4 -4
- package/dist/cli/chunks/{chunk-MEHNT37H.js → chunk-4JILSEZT.js} +2 -2
- package/dist/cli/chunks/{chunk-VKNCMGOJ.js → chunk-4K5KVC7R.js} +4 -4
- package/dist/cli/chunks/{chunk-HPQZSXED.js → chunk-4W2GGE4Z.js} +1 -1
- package/dist/cli/chunks/{chunk-EFEJLZDN.js → chunk-4YDLD5TW.js} +1 -1
- package/dist/cli/chunks/{chunk-PG5F2VHA.js → chunk-53Y6ZKPN.js} +2 -2
- package/dist/cli/chunks/{chunk-2L5GAOST.js → chunk-54HTQ3KQ.js} +2 -2
- package/dist/cli/chunks/{chunk-WTNM7NA4.js → chunk-5H44TVAY.js} +1 -1
- package/dist/cli/chunks/{chunk-3R4CMTWF.js → chunk-5Y3P6IAQ.js} +2 -2
- package/dist/cli/chunks/{chunk-XCUNQ3FK.js → chunk-67Y5HBMW.js} +2 -2
- package/dist/cli/chunks/{chunk-5XY6SULI.js → chunk-6FMMHW2R.js} +2 -2
- package/dist/cli/chunks/{chunk-XHQFVTFD.js → chunk-6FNPEC2I.js} +1 -1
- package/dist/cli/chunks/{chunk-A4UNK5SY.js → chunk-6UUNB4AW.js} +2 -2
- package/dist/cli/chunks/{chunk-VJL7DNUU.js → chunk-6XI7MNHH.js} +22 -16
- package/dist/cli/chunks/{chunk-SLH7LFVY.js → chunk-7AEFEPFH.js} +2 -2
- package/dist/cli/chunks/{chunk-ZIVOT3B7.js → chunk-7II46WAF.js} +2 -2
- package/dist/cli/chunks/chunk-7IUNZ653.js +9 -0
- package/dist/cli/chunks/{chunk-IGEZVFOM.js → chunk-7QTMWILQ.js} +2 -2
- package/dist/cli/chunks/{chunk-DFY7F4TE.js → chunk-7YM2AZXK.js} +1 -1
- package/dist/cli/chunks/{chunk-REW3W3ZW.js → chunk-7ZE5BXCN.js} +1 -1
- package/dist/cli/chunks/{chunk-FNQCWEVJ.js → chunk-A2FZAEIU.js} +2 -2
- package/dist/cli/chunks/{chunk-JDW6GN3A.js → chunk-AGHBG5E4.js} +2 -2
- package/dist/cli/chunks/{chunk-NW5FYGDE.js → chunk-AHEHD3AP.js} +2 -2
- package/dist/cli/chunks/{chunk-NZRJWK5H.js → chunk-AIQHS7D2.js} +9 -9
- package/dist/cli/chunks/{chunk-MIHQIAVK.js → chunk-ARKWPPBZ.js} +2 -2
- package/dist/cli/chunks/{chunk-7AISRWBS.js → chunk-AX7F6CNY.js} +2 -2
- package/dist/cli/chunks/{chunk-2Z2IQBIJ.js → chunk-AYLTFMTW.js} +1 -1
- package/dist/cli/chunks/{chunk-6EKXBWJD.js → chunk-BBULBXTO.js} +2 -2
- package/dist/cli/chunks/{chunk-BQML7B4W.js → chunk-BP45DZKL.js} +3 -3
- package/dist/cli/chunks/{chunk-PLGMPG7S.js → chunk-CKJGWNIS.js} +2 -2
- package/dist/cli/chunks/{chunk-Z2EDNMCQ.js → chunk-CWM5LSLQ.js} +2 -2
- package/dist/cli/chunks/{chunk-667I4RTC.js → chunk-DGEXLCOX.js} +1 -1
- package/dist/cli/chunks/{chunk-W3JB3G7C.js → chunk-DIX6AR2P.js} +2 -2
- package/dist/cli/chunks/{chunk-45N22VAB.js → chunk-DKA5WC6T.js} +2 -2
- package/dist/cli/chunks/chunk-DOKH4EJX.js +2 -0
- package/dist/cli/chunks/{chunk-ONNTJXU7.js → chunk-DXKZQYBK.js} +2 -2
- package/dist/cli/chunks/chunk-DXOFPU3A.js +2 -0
- package/dist/cli/chunks/{chunk-FWEYOD3S.js → chunk-E2IC6PHO.js} +2 -2
- package/dist/cli/chunks/{chunk-H7YKTJMY.js → chunk-EPETDHDV.js} +2 -2
- package/dist/cli/chunks/{chunk-G77CYF7H.js → chunk-EWVKCXV3.js} +3 -3
- package/dist/cli/chunks/{chunk-V6HM2BKJ.js → chunk-FAQSUNVC.js} +1 -1
- package/dist/cli/chunks/{chunk-JRYNHFZA.js → chunk-FCWQRUXQ.js} +1 -1
- package/dist/cli/chunks/{chunk-FFBF5BLQ.js → chunk-FW3EEASU.js} +1 -1
- package/dist/cli/chunks/{chunk-NVZHCAEB.js → chunk-GCMCU54O.js} +2 -2
- package/dist/cli/chunks/{chunk-OKRY4LNE.js → chunk-GW7T2ABB.js} +3 -3
- package/dist/cli/chunks/{chunk-KHZRNJ3A.js → chunk-GYJAPCP2.js} +1 -1
- package/dist/cli/chunks/{chunk-PQAYCK2U.js → chunk-HIZWO4J3.js} +2 -2
- package/dist/cli/chunks/{chunk-5WR42V5O.js → chunk-I74WDBHS.js} +2 -2
- package/dist/cli/chunks/{chunk-XB3SIYGU.js → chunk-IH5MVTLA.js} +2 -2
- package/dist/cli/chunks/{chunk-4VAZSCTZ.js → chunk-IPEUGCUK.js} +2 -2
- package/dist/cli/chunks/{chunk-6SYP7QX6.js → chunk-IPRUAUGV.js} +4 -4
- package/dist/cli/chunks/{chunk-I6Q6BPVH.js → chunk-IT7TOO52.js} +1 -1
- package/dist/cli/chunks/{chunk-ZESMMAKZ.js → chunk-IUZNVWCR.js} +2 -2
- package/dist/cli/chunks/{chunk-V7ZBPSVG.js → chunk-JFGKC6D4.js} +1 -1
- package/dist/cli/chunks/{chunk-PIXUX2NR.js → chunk-JH5HQ2HW.js} +2 -2
- package/dist/cli/chunks/{chunk-7IDPVSTF.js → chunk-JNLDMRUK.js} +1 -1
- package/dist/cli/chunks/{chunk-SRJ5N7LD.js → chunk-JNURLIOU.js} +2 -2
- package/dist/cli/chunks/{chunk-DBE2LIYG.js → chunk-JOOI3M6I.js} +2 -2
- package/dist/cli/chunks/{chunk-HR6NX6DW.js → chunk-JRCHYAB7.js} +2 -2
- package/dist/cli/chunks/{chunk-5DSANX6S.js → chunk-JZBBCQ7Y.js} +2 -2
- package/dist/cli/chunks/{chunk-3MHWBCSC.js → chunk-K5KL5MPG.js} +1 -1
- package/dist/cli/chunks/{chunk-G6VVOUUF.js → chunk-K7EU2KJF.js} +2 -2
- package/dist/cli/chunks/{chunk-PHRMWRXA.js → chunk-KN6QHR7J.js} +2 -2
- package/dist/cli/chunks/{chunk-S4M7U6CZ.js → chunk-L5W7KTBW.js} +2 -2
- package/dist/cli/chunks/{chunk-LTSNDM5N.js → chunk-LBKEWXMR.js} +2 -2
- package/dist/cli/chunks/{chunk-RZXAXWBD.js → chunk-LH372B74.js} +2 -2
- package/dist/cli/chunks/{chunk-W2VTHUDK.js → chunk-LIIG3F7K.js} +2 -2
- package/dist/cli/chunks/{chunk-MERMCKPG.js → chunk-LUU2O2AZ.js} +1 -1
- package/dist/cli/chunks/{chunk-EVSUZKD5.js → chunk-LYOAIGIT.js} +2 -2
- package/dist/cli/chunks/{chunk-5A6LBGRU.js → chunk-M6NSPXHR.js} +2 -2
- package/dist/cli/chunks/{chunk-IGQPGXP7.js → chunk-MIH7Y46H.js} +2 -2
- package/dist/cli/chunks/{chunk-ESNBKAT6.js → chunk-NKBLXHVM.js} +2 -2
- package/dist/cli/chunks/{chunk-6ZG6TBWF.js → chunk-O4DJLMRE.js} +4 -4
- package/dist/cli/chunks/{chunk-V5RLGPEW.js → chunk-P22YWOM2.js} +2 -2
- package/dist/cli/chunks/{chunk-OMOGD2NN.js → chunk-PMFV3ZFP.js} +2 -2
- package/dist/cli/chunks/{chunk-THYGFSTA.js → chunk-PYQ7VCH2.js} +13 -13
- package/dist/cli/chunks/{chunk-V7I6FTLG.js → chunk-QFBPVPYA.js} +1 -1
- package/dist/cli/chunks/{chunk-33PGBYTC.js → chunk-QPH72S4A.js} +2 -2
- package/dist/cli/chunks/{chunk-BBPOTFIY.js → chunk-QX74JLGO.js} +2 -2
- package/dist/cli/chunks/{chunk-YBUUAFKR.js → chunk-R7IYH6X2.js} +1 -1
- package/dist/cli/chunks/{chunk-6YGFAJ3X.js → chunk-RASEXZD3.js} +1 -1
- package/dist/cli/chunks/{chunk-YJV6TTCW.js → chunk-REVCXO2R.js} +2 -2
- package/dist/cli/chunks/{chunk-HHBFI3YA.js → chunk-RGQ2AOYV.js} +2 -2
- package/dist/cli/chunks/{chunk-O5NEZCTB.js → chunk-RJUWW4XE.js} +1 -1
- package/dist/cli/chunks/{chunk-MTOHV22P.js → chunk-RVG3DAU3.js} +1 -1
- package/dist/cli/chunks/{chunk-LI2IOJMM.js → chunk-RXQCDEDD.js} +1 -1
- package/dist/cli/chunks/{chunk-HGWQC7PR.js → chunk-RYFQYSVF.js} +2 -2
- package/dist/cli/chunks/{chunk-OPOGZAN5.js → chunk-S43X3HTH.js} +2 -2
- package/dist/cli/chunks/{chunk-YUSGT2CU.js → chunk-SLHE7BA3.js} +1 -1
- package/dist/cli/chunks/chunk-TH7BP4KG.js +2 -0
- package/dist/cli/chunks/{chunk-LR5VW3OS.js → chunk-TZFIBU6S.js} +2 -2
- package/dist/cli/chunks/{chunk-2XC4XVCI.js → chunk-UAKD7J72.js} +1 -1
- package/dist/cli/chunks/{chunk-UJMGNO6L.js → chunk-UCBDYSNE.js} +1 -1
- package/dist/cli/chunks/{chunk-4H4PEZUX.js → chunk-ULXDULD6.js} +2 -2
- package/dist/cli/chunks/{chunk-BGRC4676.js → chunk-UZZKBGGQ.js} +3 -3
- package/dist/cli/chunks/{chunk-SJETAUZA.js → chunk-VB2ZBN46.js} +1 -1
- package/dist/cli/chunks/{chunk-YUTSN5BK.js → chunk-VID5XDDQ.js} +2 -2
- package/dist/cli/chunks/{chunk-OK2TFTXP.js → chunk-VR65KHTH.js} +2 -2
- package/dist/cli/chunks/chunk-VSNLUVQI.js +15 -0
- package/dist/cli/chunks/{chunk-IJQJV7BC.js → chunk-WGEKHWCJ.js} +3 -3
- package/dist/cli/chunks/{chunk-BV3SGEV7.js → chunk-WGMA22FN.js} +1 -1
- package/dist/cli/chunks/{chunk-T5ADVYPH.js → chunk-WM6MDDHR.js} +1 -1
- package/dist/cli/chunks/{chunk-6R6QCGNU.js → chunk-WUDJA3B6.js} +2 -2
- package/dist/cli/chunks/{chunk-UUQ3SOKM.js → chunk-XK2IKEXP.js} +1 -1
- package/dist/cli/chunks/{chunk-TX2DBLTL.js → chunk-XLDGQJWP.js} +1 -1
- package/dist/cli/chunks/chunk-XM6CMEQK.js +2 -0
- package/dist/cli/chunks/chunk-XWD7QYS5.js +2 -0
- package/dist/cli/chunks/{chunk-QRTZ67BC.js → chunk-YG5HLQAB.js} +2 -2
- package/dist/cli/chunks/{chunk-MQQANXFS.js → chunk-YIVJD5IY.js} +2 -2
- package/dist/cli/chunks/{chunk-MMVSERJQ.js → chunk-Z6IQMLD7.js} +2 -2
- package/dist/cli/chunks/{chunk-LHDTXTS7.js → chunk-ZQZ4NYTM.js} +1 -1
- package/dist/cli/chunks/{chunk-BDXEL3GM.js → chunk-ZSOPY44S.js} +2 -2
- package/dist/cli/chunks/{chunk-RHXYZ6AZ.js → chunk-ZYF6F4MA.js} +145 -145
- package/dist/cli/chunks/{ci-NSF6OHB4.js → ci-SIPIBCBR.js} +2 -2
- package/dist/cli/chunks/{ci-output-ZPDJ42U3.js → ci-output-TDKJNSD4.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-Y2RUJDYG.js → circuit-breaker-4JC4THEE.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-OH6G6KM2.js → claude-flow-setup-7LCBF65N.js} +2 -2
- package/dist/cli/chunks/client-N53TFCGN.js +2 -0
- package/dist/cli/chunks/{cline-installer-IHH4F27G.js → cline-installer-X3RPF536.js} +2 -2
- package/dist/cli/chunks/{code-SFAHWFTX.js → code-QWSERFVQ.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-GXECMOM2.js → code-index-extractor-B6C35JTM.js} +2 -2
- package/dist/cli/chunks/{codex-installer-UPMSAFCQ.js → codex-installer-A427S2HR.js} +2 -2
- package/dist/cli/chunks/{completions-5TX6LDHY.js → completions-77KS3LAM.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-J2ZR3XZB.js → complexity-analyzer-SJUYVCGS.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-GWYZKB5A.js → continuedev-installer-HQMJQXFA.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-DQZMQWI7.js → copilot-installer-JVWVXFRV.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-V7KIGCLZ.js → cost-tracker-ATJWY2ZJ.js} +2 -2
- package/dist/cli/chunks/{coverage-3X6LA2GZ.js → coverage-OVUELXVF.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-3TYSHECB.js +2 -0
- package/dist/cli/chunks/{cursor-installer-ENDG4JIU.js → cursor-installer-HMRQMVDC.js} +2 -2
- package/dist/cli/chunks/{daemon-4XVAO7GT.js → daemon-KSWTELMB.js} +3 -3
- package/dist/cli/chunks/{daemon-TC65CQFK.js → daemon-PJLXQV52.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-JOSCDRZC.js → dag-attention-scheduler-U2ENVYTQ.js} +2 -2
- package/dist/cli/chunks/{detect-KWZX3OMK.js → detect-TMMIVPON.js} +2 -2
- package/dist/cli/chunks/{dist-node-R4U2PJ47.js → dist-node-ELGZENVQ.js} +2 -2
- package/dist/cli/chunks/{domain-handler-BMYYZO2L.js → domain-handler-XERZXZL6.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-MSDBBDLC.js → domain-transfer-QRERMYSJ.js} +2 -2
- package/dist/cli/chunks/dream-EU6ZE7N7.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-MFINPOLS.js → embed-and-insert-pattern-Q2PARYU4.js} +2 -2
- package/dist/cli/chunks/{eval-OER6UNUY.js → eval-A2QR6KW4.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-F5I77ECG.js → experience-capture-middleware-CQWPD3DM.js} +3 -3
- package/dist/cli/chunks/{fast-paths-P3KT5DUQ.js → fast-paths-IAOUZHSJ.js} +2 -2
- package/dist/cli/chunks/{feature-flags-DYFZSQLV.js → feature-flags-3D74EHP5.js} +2 -2
- package/dist/cli/chunks/{feature-flags-5EBWQ5WU.js → feature-flags-CODLAMZU.js} +2 -2
- package/dist/cli/chunks/{file-discovery-MOBVABSM.js → file-discovery-ZUBZH4Q6.js} +2 -2
- package/dist/cli/chunks/{fleet-J3R3NQNC.js → fleet-TTADPVN2.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-QD76SULF.js → gnn-wrapper-ZFDW3ZAW.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-AJEWTPZ4.js → heartbeat-handler-IV67NVZW.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-JN775DB4.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-PHMYMEDW.js +2 -0
- package/dist/cli/chunks/hnsw-index-BS65TOXD.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-5VRM5N7K.js → hnsw-legacy-bridge-GMFHJ4OK.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-K2VWFDKT.js → hnswlib-node-3LBUPOTX.js} +2 -2
- package/dist/cli/chunks/{hooks-7PMVKQOE.js → hooks-DOGCENUA.js} +34 -34
- package/dist/cli/chunks/{hybrid-router-2K2LW45J.js → hybrid-router-LQO3U6IH.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-2CQ735JO.js → hypergraph-engine-KHKAUWVL.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-AQ53GVIW.js → hypergraph-handler-T6X4F24T.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-BR25PT76.js +2 -0
- package/dist/cli/chunks/{init-handler-ZOVJPAWO.js → init-handler-JTXMI2GF.js} +13 -12
- package/dist/cli/chunks/init-wizard-42IYSTTD.js +2 -0
- package/dist/cli/chunks/kernel-JFSTL7NN.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-GWQCNLKI.js → kilocode-installer-P2WDAIOD.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-6KVES4MO.js → kiro-installer-CLTOWLVB.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-JYRFHKO2.js +2 -0
- package/dist/cli/chunks/{learning-6XMNWXRT.js → learning-CNDBY3JP.js} +3 -3
- package/dist/cli/chunks/{llm-router-GS4AZJJC.js → llm-router-SJOZ6EIJ.js} +4 -4
- package/dist/cli/chunks/load-GXZWRYTU.js +2 -0
- package/dist/cli/chunks/load-test-K7XFH5AD.js +2 -0
- package/dist/cli/chunks/{mcp-6V2H7EXU.js → mcp-LLMLANLC.js} +2 -2
- package/dist/cli/chunks/{memory-YLGPOB2H.js → memory-MEBFXR4C.js} +5 -5
- package/dist/cli/chunks/memory-backend-5O4Y5PKW.js +2 -0
- package/dist/cli/chunks/memory-handlers-46WKVXKK.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-SL2EKAH2.js → multi-model-executor-ZO35ZPDR.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-ADOJVGNA.js → opencode-installer-EG2MFPDZ.js} +2 -2
- package/dist/cli/chunks/{orchestrator-O4IWW2VU.js → orchestrator-PXA5IT5X.js} +5 -5
- package/dist/cli/chunks/{pipeline-5BD5YQNQ.js → pipeline-T3XOEAKT.js} +2 -2
- package/dist/cli/chunks/{platform-HXSUOOJH.js → platform-CPKBJ4I6.js} +2 -2
- package/dist/cli/chunks/{plugin-HOLH5CUH.js → plugin-YDP2IK3D.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-PJTL7OLS.js → prime-radiant-advanced-wasm-GDN5WBH2.js} +2 -2
- package/dist/cli/chunks/protocol-executor-VACEWXHI.js +2 -0
- package/dist/cli/chunks/{protocol-handler-K27YGLC7.js → protocol-handler-32QLWTY3.js} +2 -2
- package/dist/cli/chunks/{prove-MHCLHQQ6.js → prove-7JFRIBOM.js} +2 -2
- package/dist/cli/chunks/{provider-manager-3645PPXX.js → provider-manager-TNR7QM6Z.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-4A5MKOA5.js +2 -0
- package/dist/cli/chunks/{quality-NDE6EDOY.js → quality-G36Z4FD3.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-FF3W2BLZ.js +2 -0
- package/dist/cli/chunks/{real-embeddings-VD3EVV3U.js → real-embeddings-RYVIB5N2.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-63Y45UUG.js → roocode-installer-ZANTFQAH.js} +2 -2
- package/dist/cli/chunks/router-OTSEMLFG.js +2 -0
- package/dist/cli/chunks/routing-feedback-PHWP7EO3.js +2 -0
- package/dist/cli/chunks/{routing-handler-76XISU2E.js → routing-handler-6YNDHLBC.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-AEKOZZHZ.js → ruvector-commands-E42JA573.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-4DMUIZQF.js → rvf-dual-writer-SQDEXP45.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-YUTXFOZ3.js → rvf-migration-adapter-DMI4QBRX.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-XJ5N2W37.js → rvf-migration-coordinator-AUEOD5MP.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-E4XSLZPD.js +2 -0
- package/dist/cli/chunks/safe-db-ESTCAWF2.js +2 -0
- package/dist/cli/chunks/schedule-VJYEPFI4.js +2 -0
- package/dist/cli/chunks/scheduler-2SVKVACS.js +2 -0
- package/dist/cli/chunks/{security-6YS6GQGO.js → security-BJTKEGXZ.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-RWX6AAVO.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-MH2Y65HA.js → shared-rvf-dual-writer-PIZFXKKE.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-KGN5AIVX.js +2 -0
- package/dist/cli/chunks/{status-handler-57JQMPY5.js → status-handler-BSQJAFH2.js} +2 -2
- package/dist/cli/chunks/{structural-health-34D5VWRD.js → structural-health-ZL4KQNQX.js} +2 -2
- package/dist/cli/chunks/{sync-TTQ6ZB5D.js → sync-BM32HBUY.js} +2 -2
- package/dist/cli/chunks/{sync-HJD2US5P.js → sync-KH3IIPKB.js} +2 -2
- package/dist/cli/chunks/{task-handler-4RF57637.js → task-handler-SWMZVIZ5.js} +2 -2
- package/dist/cli/chunks/{task-handlers-BRSK7HDE.js → task-handlers-PJD6QWQP.js} +3 -3
- package/dist/cli/chunks/{test-GMUW2VR3.js → test-ACQ2N7AK.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-7LF24IFV.js → test-scheduling-BCSHQHZO.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-VYT4RTHU.js → token-bootstrap-7DAATWOU.js} +2 -2
- package/dist/cli/chunks/{token-usage-NFNCPQGW.js → token-usage-AYPCJN77.js} +2 -2
- package/dist/cli/chunks/{transformers-GGD5GIEY.js → transformers-ZYSRJRXA.js} +2 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-HXHBILDS.js +2 -0
- package/dist/cli/chunks/{types-WJ3ZTRD5.js → types-O5ODR3WQ.js} +2 -2
- package/dist/cli/chunks/unified-memory-UBGLIO43.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-BJMFYCFZ.js +2 -0
- package/dist/cli/chunks/unified-persistence-Q54OKOYY.js +2 -0
- package/dist/cli/chunks/{upgrade-IMBT4F6K.js → upgrade-ULP5J35D.js} +2 -2
- package/dist/cli/chunks/{validate-76OVF45Z.js → validate-JS6WD4S5.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-HH2ZYWXA.js → validate-swarm-NCO5QBTJ.js} +2 -2
- package/dist/cli/chunks/{vibium-74WQNDBX.js → vibium-RGRUK6EW.js} +2 -2
- package/dist/cli/chunks/visual-security-RRVHQBRP.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-W6RGE4SL.js → web-tree-sitter-NGX5C2HB.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-7DMSFCA2.js → windsurf-installer-KRAE3JB2.js} +2 -2
- package/dist/cli/chunks/witness-chain-2YIUBXAF.js +2 -0
- package/dist/cli/chunks/{witness-chain-BLZ4ZKAD.js → witness-chain-62V6YLTM.js} +2 -2
- package/dist/cli/chunks/{workflow-RNSDKRZ4.js → workflow-BVMZE2FE.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-VGNC5PFE.js +2 -0
- package/dist/cli/chunks/{wrappers-J7RXMIOY.js → wrappers-SEDAPKCG.js} +2 -2
- package/dist/cli/commands/hooks-handlers/hooks-shared.js +12 -21
- package/dist/cli/handlers/init-handler.js +47 -0
- package/dist/domains/learning-optimization/coordinator-helpers.js +7 -1
- package/dist/domains/learning-optimization/coordinator.js +5 -1
- package/dist/domains/learning-optimization/services/learning-coordinator.js +6 -1
- package/dist/domains/learning-optimization/services/metrics-optimizer.js +4 -1
- package/dist/domains/learning-optimization/services/production-intel.js +14 -5
- package/dist/domains/learning-optimization/services/transfer-specialist.js +12 -4
- package/dist/integrations/embeddings/base/EmbeddingGenerator.d.ts +1 -1
- package/dist/integrations/embeddings/base/EmbeddingGenerator.js +14 -5
- package/dist/integrations/ruvector/rvf-dual-writer.d.ts +22 -0
- package/dist/integrations/ruvector/rvf-dual-writer.js +21 -0
- package/dist/integrations/ruvector/rvf-native-adapter.d.ts +18 -1
- package/dist/integrations/ruvector/rvf-native-adapter.js +15 -1
- package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +46 -1
- package/dist/integrations/ruvector/shared-rvf-adapter.js +137 -0
- package/dist/kernel/hybrid-backend.d.ts +14 -3
- package/dist/kernel/hybrid-backend.js +16 -3
- package/dist/kernel/unified-memory.d.ts +3 -1
- package/dist/kernel/unified-memory.js +28 -3
- package/dist/learning/dream/dream-scheduler.d.ts +18 -0
- package/dist/learning/dream/dream-scheduler.js +68 -0
- package/dist/learning/qe-reasoning-bank.js +19 -2
- package/dist/learning/real-embeddings.js +1 -1
- package/dist/learning/sqlite-persistence.d.ts +11 -0
- package/dist/learning/sqlite-persistence.js +30 -0
- package/dist/mcp/bundle.js +404 -398
- package/dist/shared/parsers/tree-sitter-wasm-parser.js +8 -3
- package/dist/shared/utils/index.d.ts +1 -0
- package/dist/shared/utils/index.js +1 -0
- package/dist/shared/utils/kv-date-rehydrate.d.ts +51 -0
- package/dist/shared/utils/kv-date-rehydrate.js +78 -0
- package/dist/workers/workers/learning-consolidation.js +7 -1
- package/package.json +21 -10
- package/dist/cli/chunks/adapter-CDQOF5TF.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +0 -2
- package/dist/cli/chunks/base-UGH6TVO4.js +0 -2
- package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +0 -2
- package/dist/cli/chunks/chunk-FIONYUVH.js +0 -2
- package/dist/cli/chunks/chunk-FV2MU6CY.js +0 -2
- package/dist/cli/chunks/chunk-G6AJMFWL.js +0 -15
- package/dist/cli/chunks/chunk-QPYNQSWD.js +0 -9
- package/dist/cli/chunks/chunk-VKCWWR6C.js +0 -2
- package/dist/cli/chunks/chunk-YVQ4PR4H.js +0 -2
- package/dist/cli/chunks/client-QQGRKAY7.js +0 -2
- package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +0 -2
- package/dist/cli/chunks/dream-OCZK42FM.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-EAVZR6TJ.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-BY4XB7FB.js +0 -2
- package/dist/cli/chunks/hnsw-index-657CZRG7.js +0 -2
- package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +0 -2
- package/dist/cli/chunks/init-wizard-HOH577MH.js +0 -2
- package/dist/cli/chunks/kernel-JDYBG5GE.js +0 -2
- package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +0 -2
- package/dist/cli/chunks/load-FEMEQNE6.js +0 -2
- package/dist/cli/chunks/load-test-3MEJ43U2.js +0 -2
- package/dist/cli/chunks/memory-backend-2A47ZRGO.js +0 -2
- package/dist/cli/chunks/memory-handlers-UBTBC7D2.js +0 -2
- package/dist/cli/chunks/protocol-executor-3FR7FBVM.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +0 -2
- package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +0 -2
- package/dist/cli/chunks/router-23HRN2Z6.js +0 -2
- package/dist/cli/chunks/routing-feedback-R6A4B6ZG.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-QINEJZM7.js +0 -2
- package/dist/cli/chunks/safe-db-YXMCSKFH.js +0 -2
- package/dist/cli/chunks/schedule-XVFD27P5.js +0 -2
- package/dist/cli/chunks/scheduler-NWH2IDEU.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-FTZY35WI.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-BR6YJF5P.js +0 -2
- package/dist/cli/chunks/tree-sitter-wasm-parser-GKYG6NKT.js +0 -2
- package/dist/cli/chunks/unified-memory-AT3Z4CY7.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-6FOIGINN.js +0 -2
- package/dist/cli/chunks/unified-persistence-TCJB7MQS.js +0 -2
- package/dist/cli/chunks/visual-security-IBAUX2K5.js +0 -2
- package/dist/cli/chunks/witness-chain-GNNF23XU.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +0 -2
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as v}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{a as v}from"./chunk-LUU2O2AZ.js";import{a as h}from"./chunk-DXOFPU3A.js";import{c as E}from"./chunk-PMFV3ZFP.js";import{a as y,c as b}from"./chunk-I74WDBHS.js";b();h();var l=E.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function Q(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-UBGLIO43.js");o=c().getDatabase().prepare(`
|
|
3
3
|
SELECT u.pattern_id, u.success, u.feedback
|
|
4
4
|
FROM qe_pattern_usage u
|
|
5
5
|
JOIN qe_patterns p ON u.pattern_id = p.id
|
|
6
6
|
WHERE p.qe_domain = 'test-generation'
|
|
7
7
|
ORDER BY u.created_at DESC
|
|
8
8
|
LIMIT 10
|
|
9
|
-
`).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-
|
|
9
|
+
`).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-UBGLIO43.js");r=n().getDatabase().prepare(`
|
|
10
10
|
SELECT u.pattern_id, u.success, u.feedback
|
|
11
11
|
FROM qe_pattern_usage u
|
|
12
12
|
JOIN qe_patterns p ON u.pattern_id = p.id
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{e as a}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{e as a}from"./chunk-GCMCU54O.js";import{b as w,d as y}from"./chunk-VR65KHTH.js";import{a as f,c as P}from"./chunk-I74WDBHS.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as r}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{c as r}from"./chunk-6FNPEC2I.js";function o(n){return n instanceof Error?n.message:String(n)}function e(n){return n instanceof Error?n:new Error(String(n))}var t=r(()=>{"use strict"});export{o as a,e as b,t as c};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{p as D,q as z}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{p as D,q as z}from"./chunk-6FMMHW2R.js";import{k as A,o as R}from"./chunk-PYQ7VCH2.js";import{i as g}from"./chunk-5H44TVAY.js";import{b as w,c as T}from"./chunk-RYFQYSVF.js";import{g as S}from"./chunk-6FNPEC2I.js";R();var b=null;function I(){if(b)return b;let m=(z(),S(D));if(!m.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return b=m.HierarchicalNSW,b}function M(){return!0}var E=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.initialized=new Set,this.nextId=new Map,this.useUnified=M(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=(T(),S(w)),o=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,o),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=I(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let d=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,d),n}let s=this.indexes.get(t),o=this.toFloatArray(e.vector);return s.addPoint(o,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(a=>({id:a.id,distance:1-a.score}))}let s=this.indexes.get(t),o=this.toFloatArray(e.vector),d=s.searchKnn(o,n);return d.neighbors.map((l,h)=>({id:l,distance:d.distances[h]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=I(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var H={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02},N=class{config;db=null;initialized=!1;constructor(e={}){this.config={...H,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=A();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:o}of n){let d=await this.consolidateDomain(s,o);i.merged+=d.merged,i.qualityUpdated+=d.qualityUpdated,i.archived+=d.archived,i.hardDeleted+=d.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};t.merged=await this.clusterAndMerge(e),t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let n=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,r=0;return n>this.config.hardThreshold&&(r=this.hardDeleteExcess(e,n),t.archived+=r),t.activeRemaining=n-r,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
|
|
3
3
|
SELECT id, task, domain, quality, success, application_count,
|
|
4
4
|
consolidation_count, reuse_success_count, reuse_failure_count,
|
|
5
5
|
embedding, embedding_dimension, started_at
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as t,q as r}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{a as t,q as r}from"./chunk-EPETDHDV.js";import{c as l}from"./chunk-6FNPEC2I.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as ne}from"./chunk-
|
|
3
|
-
`)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}m.getValueByPointer=Y;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new m.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new m.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new m.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new m.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof m.JsonPatchError)return i;throw i}}m.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Rt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-BR6YJF5P.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};De();Te();F();function nt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function it(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ot(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ne(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=at(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{a as ne}from"./chunk-7YM2AZXK.js";import{d as B,e as W,f as re,g as j}from"./chunk-LUU2O2AZ.js";import{g as et,h as tt}from"./chunk-XM6CMEQK.js";import{a as xe,d as Ce,e as Ze,f as De}from"./chunk-TH7BP4KG.js";import{b as v,c as w}from"./chunk-4YDLD5TW.js";import{a as y,b as Ae,c as Te}from"./chunk-I74WDBHS.js";import{i as C}from"./chunk-5H44TVAY.js";import{B as q,D as H,G as te,P as M,S as F,b as D}from"./chunk-QPH72S4A.js";import{a as Ee,d as J,f as Ke,g as Re}from"./chunk-6FNPEC2I.js";var V=J(S=>{var ut=S&&S.__extends||(function(){var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},n(e,t)};return function(e,t){n(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}})();Object.defineProperty(S,"__esModule",{value:!0});var ht=Object.prototype.hasOwnProperty;function le(n,e){return ht.call(n,e)}S.hasOwnProperty=le;function ke(n){if(Array.isArray(n)){for(var e=new Array(n.length),t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(n);var r=[];for(var i in n)le(n,i)&&r.push(i);return r}S._objectKeys=ke;function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}S._deepClone=dt;function ft(n){for(var e=0,t=n.length,r;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}S.isInteger=ft;function oe(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}S.escapePathComponent=oe;function pt(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}S.unescapePathComponent=pt;function ue(n,e){var t;for(var r in n)if(le(n,r)){if(n[r]===e)return oe(r)+"/";if(typeof n[r]=="object"&&(t=ue(n[r],e),t!=""))return oe(r)+"/"+t}return""}S._getPathRecursive=ue;function mt(n,e){if(n===e)return"/";var t=ue(n,e);if(t==="")throw new Error("Object not found in root");return"/"+t}S.getPath=mt;function ce(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(var e=0,t=n.length;e<t;e++)if(ce(n[e]))return!0}else if(typeof n=="object"){for(var r=ke(n),i=r.length,s=0;s<i;s++)if(ce(n[r[s]]))return!0}}return!1}S.hasUndefined=ce;function Le(n,e){var t=[n];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&t.push(r+": "+i)}return t.join(`
|
|
3
|
+
`)}var gt=(function(n){ut(e,n);function e(t,r,i,s,a){var c=this.constructor,u=n.call(this,Le(t,{name:r,index:i,operation:s,tree:a}))||this;return u.name=r,u.index=i,u.operation=s,u.tree=a,Object.setPrototypeOf(u,c.prototype),u.message=Le(t,{name:r,index:i,operation:s,tree:a}),u}return e})(Error);S.PatchError=gt});var he=J(m=>{Object.defineProperty(m,"__esModule",{value:!0});var b=V();m.JsonPatchError=b.PatchError;m.deepClone=b._deepClone;var L={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){var r=Y(t,this.path);r&&(r=b._deepClone(r));var i=I(t,{op:"remove",path:this.from}).removed;return I(t,{op:"add",path:this.path,value:i}),{newDocument:t,removed:r}},copy:function(n,e,t){var r=Y(t,this.from);return I(t,{op:"add",path:this.path,value:b._deepClone(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:z(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}},yt={add:function(n,e,t){return b.isInteger(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:L.move,copy:L.copy,test:L.test,_get:L._get};function Y(n,e){if(e=="")return n;var t={op:"_get",path:e};return I(n,t),t.value}m.getValueByPointer=Y;function I(n,e,t,r,i,s){if(t===void 0&&(t=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),s===void 0&&(s=0),t&&(typeof t=="function"?t(e,0,n,e.path):K(e,0)),e.path===""){var a={newDocument:n};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=n,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Y(n,e.from),e.op==="move"&&(a.removed=n),a;if(e.op==="test"){if(a.test=z(n,e.value),a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a.newDocument=n,a}else{if(e.op==="remove")return a.removed=n,a.newDocument=null,a;if(e.op==="_get")return e.value=n,a;if(t)throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,n);return a}}else{r||(n=b._deepClone(n));var c=e.path||"",u=c.split("/"),o=n,l=1,h=u.length,f=void 0,d=void 0,p=void 0;for(typeof t=="function"?p=t:p=K;;){if(d=u[l],d&&d.indexOf("~")!=-1&&(d=b.unescapePathComponent(d)),i&&(d=="__proto__"||d=="prototype"&&l>0&&u[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(t&&f===void 0&&(o[d]===void 0?f=u.slice(0,l).join("/"):l==h-1&&(f=e.path),f!==void 0&&p(e,0,n,f)),l++,Array.isArray(o)){if(d==="-")d=o.length;else{if(t&&!b.isInteger(d))throw new m.JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,n);b.isInteger(d)&&(d=~~d)}if(l>=h){if(t&&e.op==="add"&&d>o.length)throw new m.JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,n);var a=yt[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}}else if(l>=h){var a=L[e.op].call(e,o,d,n);if(a.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",s,e,n);return a}if(o=o[d],t&&l<h&&(!o||typeof o!="object"))throw new m.JsonPatchError("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,n)}}}m.applyOperation=I;function Ue(n,e,t,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),t&&!Array.isArray(e))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=b._deepClone(n));for(var s=new Array(e.length),a=0,c=e.length;a<c;a++)s[a]=I(n,e[a],t,!0,i,a),n=s[a].newDocument;return s.newDocument=n,s}m.applyPatch=Ue;function vt(n,e,t){var r=I(n,e);if(r.test===!1)throw new m.JsonPatchError("Test operation failed","TEST_OPERATION_FAILED",t,e,n);return r.newDocument}m.applyReducer=vt;function K(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new m.JsonPatchError("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(L[n.op]){if(typeof n.path!="string")throw new m.JsonPatchError("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new m.JsonPatchError('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new m.JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&b.hasUndefined(n.value))throw new m.JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var i=n.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new m.JsonPatchError("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new m.JsonPatchError("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var a={op:"_get",path:n.from,value:void 0},c=qe([a],t);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new m.JsonPatchError("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new m.JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}m.validator=K;function qe(n,e,t){try{if(!Array.isArray(n))throw new m.JsonPatchError("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ue(b._deepClone(e),b._deepClone(n),t||!0);else{t=t||K;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(i){if(i instanceof m.JsonPatchError)return i;throw i}}m.validate=qe;function z(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),i,s,a;if(t&&r){if(s=n.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!z(n[i],e[i]))return!1;return!0}if(t!=r)return!1;var c=Object.keys(n);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(a=c[i],!z(n[a],e[a]))return!1;return!0}return n!==n&&e!==e}m._areEquals=z});var Qe=J(k=>{Object.defineProperty(k,"__esModule",{value:!0});var P=V(),wt=he(),fe=new WeakMap,Pt=(function(){function n(e){this.observers=new Map,this.obj=e}return n})(),St=(function(){function n(e,t){this.callback=e,this.observer=t}return n})();function bt(n){return fe.get(n)}function Et(n,e){return n.observers.get(e)}function Rt(n,e){n.observers.delete(e.callback)}function At(n,e){e.unobserve()}k.unobserve=At;function Tt(n,e){var t=[],r,i=bt(n);if(!i)i=new Pt(n),fe.set(n,i);else{var s=Et(i,e);r=s&&s.observer}if(r)return r;if(r={},i.value=P._deepClone(n),e){r.callback=e,r.next=null;var a=function(){de(r)},c=function(){clearTimeout(r.next),r.next=setTimeout(a)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return r.patches=t,r.object=n,r.unobserve=function(){de(r),clearTimeout(r.next),Rt(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new St(e,r)),r}k.observe=Tt;function de(n,e){e===void 0&&(e=!1);var t=fe.get(n.object);pe(t.value,n.object,n.patches,"",e),n.patches.length&&wt.applyPatch(t.value,n.patches);var r=n.patches;return r.length>0&&(n.patches=[],n.callback&&n.callback(r)),r}k.generate=de;function pe(n,e,t,r,i){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=P._objectKeys(e),a=P._objectKeys(n),c=!1,u=!1,o=a.length-1;o>=0;o--){var l=a[o],h=n[l];if(P.hasOwnProperty(e,l)&&!(e[l]===void 0&&h!==void 0&&Array.isArray(e)===!1)){var f=e[l];typeof h=="object"&&h!=null&&typeof f=="object"&&f!=null&&Array.isArray(h)===Array.isArray(f)?pe(h,f,t,r+"/"+P.escapePathComponent(l),i):h!==f&&(c=!0,i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"replace",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(f)}))}else Array.isArray(n)===Array.isArray(e)?(i&&t.push({op:"test",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(h)}),t.push({op:"remove",path:r+"/"+P.escapePathComponent(l)}),u=!0):(i&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}),c=!0)}if(!(!u&&s.length==a.length))for(var o=0;o<s.length;o++){var l=s[o];!P.hasOwnProperty(n,l)&&e[l]!==void 0&&t.push({op:"add",path:r+"/"+P.escapePathComponent(l),value:P._deepClone(e[l])})}}}function xt(n,e,t){t===void 0&&(t=!1);var r=[];return pe(n,e,r,"",t),r}k.compare=xt});var ze=J(O=>{var Ct=he();Object.assign(O,Ct);var Dt=Qe();Object.assign(O,Dt);var Z=V();O.JsonPatchError=Z.PatchError;O.deepClone=Z._deepClone;O.escapePathComponent=Z.escapePathComponent;O.unescapePathComponent=Z.unescapePathComponent});Te();var Q=class{constructor(e,t){this.createAdapter=e;this.config=t?.base??X,this.rvfPath=t?.rvfPath??".agentic-qe/patterns.rvf",this.skipCloseOnDispose=t?.skipCloseOnDispose??!1}createAdapter;config;rvfPath;skipCloseOnDispose;adapter=null;sqliteStore=null;initialized=!1;rvfInitError=null;searchOps=0;totalSearchMs=0;setSqliteStore(e){this.sqliteStore=e}getAdapter(){return this.adapter}async initialize(){if(!this.initialized){try{this.adapter=this.createAdapter(this.rvfPath,this.config.embeddingDimension),this.initialized=!0,console.log(`[RvfPatternStore] Initialized: ${this.rvfPath} (dim=${this.config.embeddingDimension})`)}catch(e){this.rvfInitError=y(e),console.error(`[RvfPatternStore] ERROR: RVF native init failed \u2014 vector search is DISABLED. Cause: ${this.rvfInitError}. Fix: install @ruvector/rvf-node native bindings, or set useRVFPatternStore=false to use SQLite HNSW.`),this.adapter=null,this.initialized=!0}if(!this.sqliteStore)try{let{createSQLitePatternStore:e}=await import("./sqlite-persistence-KGN5AIVX.js"),t=e();await t.initialize(),this.sqliteStore=t}catch{}await this.purgeOrphanedVectors()}}async purgeOrphanedVectors(){if(!(!this.adapter||!this.sqliteStore))try{let e=this.adapter.status()?.totalVectors??0,t=this.sqliteStore.getStats()?.totalPatterns??0;if(e<=t)return;let{readFileSync:r,existsSync:i}=await import("node:fs"),s=`${this.rvfPath}.idmap.json`;if(!i(s))return;let a=JSON.parse(r(s,"utf-8")),c=new Set((a.entries??[]).map(l=>Array.isArray(l)?l[0]:void 0).filter(l=>typeof l=="string")),u=new Set(this.sqliteStore.getPatterns({limit:1e4}).map(l=>l.id)),o=[...c].filter(l=>!u.has(l));if(o.length===0)return;this.adapter.delete(o),console.log(`[RvfPatternStore] Removed ${o.length} ghost vectors (index ${e} > DB ${t})`)}catch(e){console.warn(`[RvfPatternStore] orphan purge skipped: ${y(e)}`)}}async dispose(){if(this.adapter&&!this.skipCloseOnDispose)try{this.adapter.close()}catch{}this.adapter=null,this.initialized=!1}async store(e){await this.ensureInitialized();let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));if(this.sqliteStore)try{let r=this.sqliteStore.storePattern(e,e.embedding);r&&r!==e.id&&(e.id=r)}catch(r){console.warn(`[RvfPatternStore] SQLite persist failed for ${e.id}:`,y(r))}if(e.embedding&&this.adapter)try{let r=e.embedding instanceof Float32Array?e.embedding:new Float32Array(e.embedding);this.adapter.ingest([{id:e.id,vector:r}])}catch(r){console.warn(`[RvfPatternStore] RVF ingest failed for ${e.id}:`,y(r))}return v(e.id)}async create(e){let t=e.confidence??.5,r=e.qeDomain??"test-generation",i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:t,usageCount:0,successRate:0,qualityScore:B({confidence:t,usageCount:0,successRate:0}),context:{tags:[],...e.context},template:{example:"",...e.template},embedding:e.embedding,tier:"short-term",createdAt:new Date,lastUsedAt:new Date,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}async get(e){if(this.sqliteStore)try{return this.sqliteStore.getPattern(e)??null}catch{return null}return null}async search(e,t={}){await this.ensureInitialized();let r=performance.now(),i=t.limit??10,s=[];if(Array.isArray(e)&&this.adapter)try{let c=e instanceof Float32Array?e:new Float32Array(e),u=this.adapter.search(c,i*2);for(let o of u){let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.score);s.push({pattern:l,score:o.score,matchType:"vector",similarity:o.score,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch(c){console.warn("[RvfPatternStore] RVF search failed:",y(c))}if(Array.isArray(e)&&!this.adapter&&this.sqliteStore&&s.length===0)try{let c=this.sqliteStore.getPatterns({limit:i*4}),u=e,o=Math.sqrt(u.reduce((l,h)=>l+h*h,0));if(o>0)for(let l of c){if(!this.matchesFilters(l,t))continue;let h=this.sqliteStore.getPattern(l.id),f=h?.embedding;if(!f||f.length!==u.length)continue;let d=0,p=0;for(let R=0;R<u.length;R++)d+=u[R]*f[R],p+=f[R]*f[R];if(p=Math.sqrt(p),p===0)continue;let g=d/(o*p),E=this.calculateReuseInfo(h,g);s.push({pattern:h,score:g,matchType:"vector",similarity:g,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}catch{}if(typeof e=="string"&&!e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.getPatterns({limit:i*2}),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id)||!this.matchesFilters(o,t))continue;let l=this.calculateReuseInfo(o,o.confidence);s.push({pattern:o,score:o.confidence,matchType:"exact",similarity:o.confidence,canReuse:l.canReuse,estimatedTokenSavings:l.estimatedTokenSavings,reuseConfidence:l.reuseConfidence})}}catch{}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let c=this.sqliteStore.searchFTS(e,i*2),u=new Set(s.map(o=>o.pattern.id));for(let o of c){if(u.has(o.id))continue;let l=await this.get(o.id);if(l&&this.matchesFilters(l,t)){let h=this.calculateReuseInfo(l,o.ftsScore);s.push({pattern:l,score:.5*o.ftsScore,matchType:"exact",similarity:o.ftsScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}}catch{}s.sort((c,u)=>u.score-c.score);let a=performance.now()-r;return this.searchOps++,this.totalSearchMs+=a,v(s.slice(0,i))}async recordUsage(e,t){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.recordUsage(e,t),v(void 0)}catch(r){return w(new Error(`recordUsage failed: ${y(r)}`))}}async promote(e){if(!this.sqliteStore)return w(new Error("No SQLite store attached"));try{return this.sqliteStore.promotePattern(e),v(void 0)}catch(t){return w(new Error(`promote failed: ${y(t)}`))}}async delete(e){if(this.adapter)try{this.adapter.delete([e])}catch(t){console.warn(`[RvfPatternStore] RVF delete failed for ${e}:`,y(t))}if(this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(t){return w(new Error(`SQLite delete failed: ${y(t)}`))}return v(void 0)}async getStats(){let e=this.adapter?.status(),t=e?.totalVectors??0;if(t===0&&this.sqliteStore)try{t=this.sqliteStore.getStats().totalPatterns}catch{}return{totalPatterns:t,byTier:{shortTerm:0,longTerm:0},byDomain:{},byType:{},avgConfidence:0,avgQualityScore:0,avgSuccessRate:0,searchOperations:this.searchOps,avgSearchLatencyMs:this.searchOps>0?this.totalSearchMs/this.searchOps:0,hnswStats:{nativeAvailable:this.adapter!==null,vectorCount:e?.totalVectors??0,indexSizeBytes:e?.fileSizeBytes??0,...this.rvfInitError?{rvfInitError:this.rvfInitError}:{}}}}async cleanup(){if(!this.sqliteStore)return{removed:0,promoted:0};let e=0,t=0;try{let r=this.sqliteStore.getPatterns({limit:1e4});for(let i of r)i.confidence<this.config.minConfidence&&i.usageCount>3?(await this.delete(i.id),e++):i.tier==="short-term"&&i.successfulUses>=W&&(await this.promote(i.id),t++)}catch(r){console.warn("[RvfPatternStore] Cleanup error:",y(r))}return{removed:e,promoted:t}}async ensureInitialized(){this.initialized||await this.initialize()}matchesFilters(e,t){return!(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence&&e.confidence<t.minConfidence||t.minQualityScore&&e.qualityScore<t.minQualityScore)}calculateReuseInfo(e,t){let r=this.config.reuseOptimization,i=r.enabled&&t>=r.minSimilarityForReuse&&e.successRate>=r.minSuccessRateForReuse;return{canReuse:i,estimatedTokenSavings:i?500:0,reuseConfidence:i?t*e.successRate:0}}};De();Te();F();function nt(n,e){let r=[n.pattern,n];for(let i of r){let s=e.split("."),a=i;for(let c of s){if(a==null)break;if(typeof a=="object")a=a[c];else{a=void 0;break}}if(a!==void 0)return a}}function it(n,e,t){switch(e){case"eq":return n===t;case"gt":return typeof n=="number"&&typeof t=="number"&&n>t;case"lt":return typeof n=="number"&&typeof t=="number"&&n<t;case"gte":return typeof n=="number"&&typeof t=="number"&&n>=t;case"lte":return typeof n=="number"&&typeof t=="number"&&n<=t;case"in":return Array.isArray(t)?t.includes(n):!1;case"contains":return Array.isArray(n)||typeof n=="string"&&typeof t=="string"?n.includes(t):!1;case"between":{if(typeof n!="number"||!Array.isArray(t)||t.length!==2){if(n instanceof Date&&Array.isArray(t)&&t.length===2){let s=n.getTime(),a=t[0]instanceof Date?t[0].getTime():Number(t[0]),c=t[1]instanceof Date?t[1].getTime():Number(t[1]);return s>=a&&s<=c}return!1}let[r,i]=t;return n>=r&&n<=i}default:return!1}}function G(n,e){switch(e.type){case"AND":return(e.children??[]).every(r=>G(n,r));case"OR":{let t=e.children??[];return t.length===0?!0:t.some(r=>G(n,r))}case"NOT":return e.child?!G(n,e.child):!0;case"FIELD":{if(!e.field||!e.operator)return!0;let t=nt(n,e.field);return it(t,e.operator,e.value)}default:return!0}}function Fe(n,e){return e?n.filter(t=>G(t,e)):n}F();F();var Oe=1e4,_e=2166136261;function Ne(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}var ae=new Uint8Array(256);for(let n=0;n<256;n++){let e=0,t=n;for(;t;)e++,t&=t-1;ae[n]=e}var Ie="0123456789abcdef";function st(n){let e=Math.min(n.length,16),t="";for(let r=0;r<e;r++){let i=n[r];t+=Ie[i>>4]+Ie[i&15]}return t}function at(n,e){if(n.length!==e.length)throw new Error(`Cannot bind vectors of different lengths: ${n.length} vs ${e.length}`);let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function ot(n){if(n.length===0)throw new Error("Cannot bundle zero vectors");let e=n[0].length;for(let i=1;i<n.length;i++)if(n[i].length!==e)throw new Error(`Vector length mismatch at index ${i}: expected ${e}, got ${n[i].length}`);let t=new Uint8Array(e),r=n.length/2;for(let i=0;i<e;i++){let s=0;for(let a=0;a<8;a++){let c=0,u=1<<a;for(let o=0;o<n.length;o++)n[o][i]&u&&c++;c>=r&&(s|=u)}t[i]=s}return t}function ct(n,e,t){if(n.length!==e.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${n.length} vs ${e.length}`);let r=0;for(let s=0;s<n.length;s++)r+=ae[n[s]^e[s]];let i=t??n.length*8;return i>0?r/i:0}function lt(n,e,t){return 1-ct(n,e,t)}var ie=class{dimensions;baseSeed;byteLen;tokenCache=new Map;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.byteLen=Math.ceil(this.dimensions/8),this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}tokenToHypervector(e){let t=this.tokenCache.get(e);if(t)return new Uint8Array(t);let r=Ne(e)^this.baseSeed,i=this.generateSeededVector(r);return this.tokenCache.set(e,i),new Uint8Array(i)}fingerprintPattern(e){if(e.length===0)return new Uint8Array(this.byteLen);let t=this.tokenToHypervector(e[0]);for(let r=1;r<e.length;r++)t=at(t,this.tokenToHypervector(e[r]));return t}fingerprintWithContext(e,t){let r=this.fingerprintPattern(e);if(t.length===0)return r;let i=this.fingerprintPattern(t);return ot([r,i])}similarity(e,t){return lt(e,t,this.dimensions)}generateSeededVector(e){let t=new Uint8Array(this.byteLen),r=new ne(e),i=0;for(;i<this.byteLen;){let a=r.next(),c=Math.min(4,this.byteLen-i);for(let u=0;u<c;u++)t[i++]=a>>>u*8&255}let s=this.dimensions%8;return s>0&&(t[this.byteLen-1]&=(1<<s)-1),t}},se=class{dimensions;baseSeed;constructor(e){if(this.dimensions=e?.dimensions??Oe,this.baseSeed=e?.seed??_e,this.dimensions<=0)throw new Error(`HDC dimensions must be positive, got ${this.dimensions}`)}fingerprint(e){let t=`${e.id}|${e.domain}|${e.type}|${e.content??""}`,r=Ne(t)^this.baseSeed,i=this.generateVector(r);return{vector:i,dimensions:this.dimensions,hash:st(i)}}compositionalBind(e,t){if(e.length!==t.length)throw new Error(`Cannot bind vectors of different lengths: ${e.length} vs ${t.length}`);let r=new Uint8Array(e.length);for(let i=0;i<e.length;i++)r[i]=e[i]^t[i];return r}hammingDistance(e,t){if(e.length!==t.length)throw new Error(`Cannot compute Hamming distance for vectors of different lengths: ${e.length} vs ${t.length}`);let r=0;for(let i=0;i<e.length;i++)r+=ae[e[i]^t[i]];return r}similarity(e,t){return 1-this.hammingDistance(e,t)/this.dimensions}batchFingerprint(e){return e.map(t=>this.fingerprint(t))}generateVector(e){let t=Math.ceil(this.dimensions/8),r=new Uint8Array(t),i=new ne(e),s=0;for(;s<t;){let c=i.next(),u=t-s,o=u<4?u:4;for(let l=0;l<o;l++)r[s++]=c>>>l*8&255}let a=this.dimensions%8;return a>0&&(r[t-1]&=(1<<a)-1),r}};function He(n){return new se(n)}function Me(n){return q()?new ie(n):null}var $=Ke(ze(),1),Ft=`
|
|
4
4
|
CREATE TABLE IF NOT EXISTS pattern_deltas (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
pattern_id TEXT NOT NULL,
|
|
@@ -46,7 +46,7 @@ import{a as ne}from"./chunk-DFY7F4TE.js";import{d as B,e as W,f as re,g as j}fro
|
|
|
46
46
|
WHERE pattern_id = ? AND version != 0
|
|
47
47
|
ORDER BY version ASC
|
|
48
48
|
LIMIT ?
|
|
49
|
-
)`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(kt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=je)return new Float32Array(e);let r=je/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-5VRM5N7K.js"),{HnswAdapter:c}=await import("./hnsw-adapter-BY4XB7FB.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-657CZRG7.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
|
|
49
|
+
)`).run(e,e,s)}}};F();var Ot={maxHistoryPerPattern:50,snapshotInterval:10,batchSize:20,epsilon:1e-7},me=class{config;history=new Map;snapshots=new Map;versions=new Map;buffer=[];constructor(e){this.config={...Ot,...e}}recordGenesis(e,t,r){if(this.versions.has(e))throw new Error(`Genesis already exists for pattern ${e} (version ${this.versions.get(e)})`);let i=this.computeSparseChanges(new Array(t.length).fill(0),t),s={patternId:e,version:0,timestamp:Date.now(),deltaType:"genesis",sparseChanges:i,metadata:r,compressedSize:i.length},a={patternId:e,version:0,fullVector:[...t],timestamp:s.timestamp};return this.versions.set(e,0),this.getOrCreate(this.history,e).push(s),this.getOrCreate(this.snapshots,e).push(a),this.buffer.push(s),s}recordDelta(e,t,r,i){let s=this.versions.get(e);if(s===void 0)throw new Error(`No genesis found for pattern ${e}. Call recordGenesis() first.`);let a=s+1,c=this.computeSparseChanges(t,r),u={patternId:e,version:a,timestamp:Date.now(),deltaType:"update",sparseChanges:c,metadata:i,compressedSize:c.length};return this.versions.set(e,a),this.getOrCreate(this.history,e).push(u),this.buffer.push(u),a%this.config.snapshotInterval===0&&this.getOrCreate(this.snapshots,e).push({patternId:e,version:a,fullVector:[...r],timestamp:u.timestamp}),this.enforceRetention(e),u}getHistory(e,t){let r=this.history.get(e);if(!r||r.length===0)return[];let i=[...r].reverse();return t!==void 0&&t>0?i.slice(0,t):i}rollback(e,t){let r=this.reconstructAtVersion(e,t);return r===null?null:{patternId:e,version:t,fullVector:r,timestamp:Date.now()}}getVersion(e){return this.versions.get(e)??-1}reconstructAtVersion(e,t){let r=this.history.get(e);if(!r||r.length===0)return null;let i=this.versions.get(e);if(t<0||t>i)return null;let s=this.snapshots.get(e)||[],a=null;for(let o=s.length-1;o>=0;o--)if(s[o].version<=t){a=s[o];break}if(!a)return null;let c=[...a.fullVector],u=a.version+1;for(let o of r)if(!(o.version<u)){if(o.version>t)break;this.applySparseForward(c,o.sparseChanges)}return c}pruneHistory(e,t){let r=t??this.config.maxHistoryPerPattern,i=this.history.get(e);if(!i||i.length<=r)return 0;let s=i.length-r,a=i.slice(0,s),c=i.slice(s),u=a.findIndex(h=>h.deltaType==="genesis");u>=0&&(c.unshift(a[u]),a.splice(u,1)),this.history.set(e,c);let o=c[0]?.version??0,l=this.snapshots.get(e);return l&&this.snapshots.set(e,l.filter(h=>h.version===0||h.version>=o)),a.length}getStats(){let e=0;for(let r of this.history.values())e+=r.length;let t=this.history.size;return{totalPatterns:t,totalDeltas:e,avgDeltasPerPattern:t>0?e/t:0}}flush(){let e=[...this.buffer];return this.buffer.length=0,e}getBufferSize(){return this.buffer.length}clear(){this.history.clear(),this.snapshots.clear(),this.versions.clear(),this.buffer.length=0}computeSparseChanges(e,t){let r=[],i=Math.max(e.length,t.length);for(let s=0;s<i;s++){let a=s<e.length?e[s]:0,c=s<t.length?t[s]:0;Math.abs(a-c)>this.config.epsilon&&r.push({index:s,oldValue:a,newValue:c})}return r}applySparseForward(e,t){for(let r of t){for(;e.length<=r.index;)e.push(0);e[r.index]=r.newValue}}enforceRetention(e){this.pruneHistory(e,this.config.maxHistoryPerPattern)}getOrCreate(e,t){let r=e.get(t);return r||(r=[],e.set(t,r)),r}};function Be(n){return H()?new me(n):null}F();var _t=128,Nt=8,Ht=1e4,ge=class{dimension;beta;maxPatterns;patterns;constructor(e){if(this.dimension=e?.dimension??_t,this.beta=e?.beta??Nt,this.maxPatterns=e?.maxPatterns??Ht,this.patterns=[],this.dimension<=0)throw new Error(`Hopfield dimension must be positive, got ${this.dimension}`);if(this.beta<=0)throw new Error(`Hopfield beta must be positive, got ${this.beta}`);if(this.maxPatterns<=0)throw new Error(`Hopfield maxPatterns must be positive, got ${this.maxPatterns}`)}store(e,t){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Pattern dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.dotProduct(e,e)===0)throw new Error("Cannot store zero-magnitude pattern in Hopfield memory");let i=this.normalize(e);this.patterns.length>=this.maxPatterns&&this.patterns.shift(),this.patterns.push({pattern:i,metadata:t??{},storedAt:Date.now()})}recall(e){if(this.assertEnabled(),e.length!==this.dimension)throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(this.patterns.length===0)return null;let t=this.normalize(e),r=new Float32Array(this.patterns.length);for(let l=0;l<this.patterns.length;l++)r[l]=this.beta*this.dotProduct(this.patterns[l].pattern,t);let i=this.softmax(r),s=0,a=i[0];for(let l=1;l<i.length;l++)i[l]>a&&(a=i[l],s=l);let c=this.patterns[s],u=this.getEnergy(t),o=this.cosineSimilarity(t,c.pattern);return{pattern:new Float32Array(c.pattern),metadata:{...c.metadata},energy:u,similarity:o}}batchRecall(e){return this.assertEnabled(),e.map(t=>this.recall(t))}getPatternCount(){return this.patterns.length}clear(){this.patterns.length=0}getEnergy(e){if(e.length!==this.dimension)throw new Error(`State dimension mismatch: expected ${this.dimension}, got ${e.length}`);let t=this.normalize(e);if(this.patterns.length===0)return .5*this.dotProduct(t,t);let r=new Float32Array(this.patterns.length);for(let o=0;o<this.patterns.length;o++)r[o]=this.dotProduct(this.patterns[o].pattern,t);let i=new Float32Array(this.patterns.length),s=-1/0;for(let o=0;o<this.patterns.length;o++)i[o]=this.beta*r[o],i[o]>s&&(s=i[o]);let a=0;for(let o=0;o<this.patterns.length;o++)a+=Math.exp(i[o]-s);let c=1/this.beta*(s+Math.log(a)),u=this.dotProduct(t,t);return-c+.5*u}softmax(e){let t=new Float32Array(e.length),r=-1/0;for(let s=0;s<e.length;s++)e[s]>r&&(r=e[s]);let i=0;for(let s=0;s<e.length;s++)t[s]=Math.exp(e[s]-r),i+=t[s];if(i>0)for(let s=0;s<t.length;s++)t[s]/=i;return t}dotProduct(e,t){let r=0;for(let i=0;i<e.length;i++)r+=e[i]*t[i];return r}cosineSimilarity(e,t){let r=this.dotProduct(e,t),i=Math.sqrt(this.dotProduct(e,e)),s=Math.sqrt(this.dotProduct(t,t));return i===0||s===0?0:r/(i*s)}normalize(e){let t=Math.sqrt(this.dotProduct(e,e)),r=new Float32Array(e.length);if(t>0)for(let i=0;i<e.length;i++)r[i]=e[i]/t;return r}assertEnabled(){if(!D().useHopfieldMemory)throw new Error("Hopfield memory is disabled (useHopfieldMemory feature flag is false)")}};function We(n){return new ge(n)}F();var Mt={dimensions:32,curvature:-1,maxElements:1e4,efConstruction:200,M:16},_=1e-5,je=1-_;function Lt(n,e){let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t}function A(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return e}function kt(n,e){let t=new Float32Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]-e[r];return t}var T=class n{static poincareDistance(e,t){let r=A(kt(e,t)),i=Math.max(_,1-A(e)),s=Math.max(_,1-A(t));return Math.acosh(Math.max(1,1+2*r/(i*s)))}static mobiusAdd(e,t){let r=Lt(e,t),i=A(e),s=A(t),a=Math.max(_,1+2*r+i*s),c=1+2*r+s,u=1-i,o=new Float32Array(e.length);for(let l=0;l<e.length;l++)o[l]=(c*e[l]+u*t[l])/a;return n.project(o)}static expMap(e,t){let r=2/Math.max(_,1-A(e)),i=Math.sqrt(A(t));if(i<_)return new Float32Array(e);let s=Math.tanh(r*i/2),a=new Float32Array(t.length);for(let c=0;c<t.length;c++)a[c]=s/i*t[c];return n.mobiusAdd(e,a)}static project(e){let t=Math.sqrt(A(e));if(t<=je)return new Float32Array(e);let r=je/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return i}static euclideanToHyperbolic(e){let t=Math.sqrt(A(e));if(t<_)return new Float32Array(e.length);let r=Math.tanh(t)/t,i=new Float32Array(e.length);for(let s=0;s<e.length;s++)i[s]=e[s]*r;return n.project(i)}},ye=class{config;points=new Map;constructor(e){if(this.config={...Mt,...e},this.config.dimensions<=0)throw new Error(`dimensions must be positive, got ${this.config.dimensions}`);if(this.config.curvature>=0)throw new Error(`curvature must be negative for hyperbolic space, got ${this.config.curvature}`);if(this.config.maxElements<=0)throw new Error(`maxElements must be positive, got ${this.config.maxElements}`)}insert(e,t,r){if(t.length!==this.config.dimensions)throw new Error(`Dimension mismatch: expected ${this.config.dimensions}, got ${t.length}`);if(this.points.size>=this.config.maxElements)throw new Error(`Maximum elements (${this.config.maxElements}) reached`);this.points.set(e,{id:e,coordinates:T.project(t),metadata:r?{...r}:void 0})}search(e,t){if(e.length!==this.config.dimensions)throw new Error(`Query dimension mismatch: expected ${this.config.dimensions}, got ${e.length}`);let r=T.project(e),i=[];for(let s of this.points.values())i.push({id:s.id,distance:T.poincareDistance(r,s.coordinates),point:s});return i.sort((s,a)=>s.distance-a.distance),i.slice(0,Math.max(0,t))}embedHierarchy(e){let t=new Map;if(e.length===0)return t;let r=this.config.dimensions,i=new Map,s=new Map,a=[];for(let u of e)if(s.set(u.id,u),!u.parentId)a.push(u.id);else{let o=i.get(u.parentId);o||(o=[],i.set(u.parentId,o)),o.push(u.id)}let c=a.map((u,o)=>({id:u,depth:0,angOff:2*Math.PI*o/Math.max(1,a.length),angSpan:2*Math.PI/Math.max(1,a.length)}));for(;c.length>0;){let{id:u,depth:o,angOff:l,angSpan:h}=c.shift(),f=Math.tanh(.3*(o+.1)),d=l+h/2,p=new Float32Array(r);p[0]=f*Math.cos(d),p[1]=f*Math.sin(d);let g=s.get(u);if(g&&g.features.length>0){let N=f*.1;for(let x=2;x<r&&x-2<g.features.length;x++)p[x]=g.features[x-2]*N}let E=T.project(p);t.set(u,E),this.points.set(u,{id:u,coordinates:E,metadata:{depth:o,parentId:g?.parentId}});let R=i.get(u)??[];for(let N=0;N<R.length;N++){let x=h/Math.max(1,R.length);c.push({id:R[N],depth:o+1,angOff:l+N*x,angSpan:x})}}return t}getStats(){return{elementCount:this.points.size,dimensions:this.config.dimensions,curvature:this.config.curvature}}};function Xe(n){return Ut()?new ye(n):null}function Ut(){return D().useHyperbolicHnsw}F();var ve=class{index=null;initialized=!1;config;constructor(e){this.config=e??{}}ensureInitialized(){if(this.initialized)return this.index!==null;if(this.initialized=!0,!M())return!1;try{return this.index=Xe(this.config),this.index!==null}catch(e){return console.warn("[HyperbolicPatternIndex] Failed to create HyperbolicHNSW:",e instanceof Error?e.message:e),this.index=null,!1}}get isAvailable(){return this.index!==null}indexPattern(e,t,r){if(!(!this.ensureInitialized()||!this.index))try{let i=t instanceof Float32Array?t:new Float32Array(t),s=T.euclideanToHyperbolic(i);this.index.insert(e,s,r)}catch(i){console.debug(`[HyperbolicPatternIndex] Failed to index pattern ${e}:`,i instanceof Error?i.message:i)}}search(e,t){if(!this.ensureInitialized()||!this.index)return[];try{let r=e instanceof Float32Array?e:new Float32Array(e),i=T.euclideanToHyperbolic(r);return this.index.search(i,t).map(a=>({patternId:a.id,distance:a.distance,metadata:a.point.metadata}))}catch(r){return console.warn("[HyperbolicPatternIndex] Search failed:",r instanceof Error?r.message:r),[]}}getStats(){return this.index?this.index.getStats():null}reset(){this.index=null,this.initialized=!1}};function Ge(n){return new ve(n)}var we=null;function Ve(){return we||(we=He({dimensions:1e4})),we}var Pe;function qt(){return Pe===void 0&&(Pe=Me()),Pe}var U=null,Se=0;function Ye(n){return(!U||Se!==n)&&(U=We({dimension:n,maxPatterns:1e4}),Se=n),U}var X={namespace:"qe-patterns",embeddingDimension:384,hnsw:{M:16,efConstruction:200,efSearch:100,maxElements:5e4},promotionThreshold:W,minConfidence:.3,maxPatternsPerDomain:5e3,autoCleanup:!0,cleanupIntervalMs:36e5,tokenTracking:{enabled:!0,trackInputOutput:!0,estimateCosts:!0,costPerInputToken:3e-6,costPerOutputToken:15e-6},reuseOptimization:{enabled:!0,minSimilarityForReuse:.85,minSuccessRateForReuse:.9,maxAgeForReuse:7}},be=class{constructor(e,t={}){this.memory=e;this.config={...X,...t}}memory;config;initialized=!1;cleanupTimer;sqliteStore=null;loadingPromise=null;patternCache=new Map;domainIndex=new Map;typeIndex=new Map;tierIndex=new Map;hnswIndex=null;hnswAvailable=!1;hnswInitPromise=null;hdcCache=new Map;hdcTokenCache=new Map;deltaTracker=null;vectorDeltaTracker=void 0;hyperbolicIndex=null;stats={searchOperations:0,searchLatencies:[]};setSqliteStore(e){if(this.sqliteStore=e,H()&&!this.deltaTracker)try{let t=e.getDb();this.deltaTracker=new ee(t),this.deltaTracker.initialize(),console.log("[PatternStore] Delta event sourcing initialized")}catch(t){console.warn("[PatternStore] Delta tracker init failed:",t instanceof Error?t.message:t)}this.initialized&&(this.loadingPromise=this.loadPatterns().catch(t=>console.warn("[PatternStore] Failed to load patterns after setSqliteStore:",t)).finally(()=>{this.loadingPromise=null}))}async initialize(){this.initialized||(this.tierIndex.set("short-term",new Set),this.tierIndex.set("long-term",new Set),await this.loadPatterns(),this.config.autoCleanup&&(this.cleanupTimer=setInterval(()=>this.cleanup(),this.config.cleanupIntervalMs)),this.initialized=!0)}async ensureHNSW(){return this.hnswIndex!==null?this.hnswIndex:this.hnswAvailable===!1&&this.hnswInitPromise===null&&!(this.hnswIndex===null&&this.hnswAvailable===!1)?null:this.hnswInitPromise?(await this.hnswInitPromise,this.hnswIndex):(this.hnswInitPromise=this.initializeHNSWInternal(),await this.hnswInitPromise,this.hnswInitPromise=null,this.hnswIndex)}async initializeHNSWInternal(){try{if(D().useUnifiedHnsw)try{let{HnswLegacyBridge:a}=await import("./hnsw-legacy-bridge-GMFHJ4OK.js"),{HnswAdapter:c}=await import("./hnsw-adapter-PHMYMEDW.js"),u=new c("patterns",{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,metric:"cosine"});this.hnswIndex=new a(u),this.hnswAvailable=!0,console.log("[PatternStore] Using unified HNSW via HnswLegacyBridge (ADR-071)"),await this.loadEmbeddingsIntoHNSW();return}catch(a){console.warn("[PatternStore] Unified HNSW bridge failed, falling back:",a)}let{HNSWIndex:t}=await import("./hnsw-index-BS65TOXD.js");this.hnswIndex=new t(this.memory,{dimensions:this.config.embeddingDimension,M:this.config.hnsw.M,efConstruction:this.config.hnsw.efConstruction,efSearch:this.config.hnsw.efSearch,maxElements:this.config.hnsw.maxElements,namespace:`${this.config.namespace}:hnsw`,metric:"cosine"});let r=5e3,i=this.hnswIndex.initialize(),s=new Promise((a,c)=>setTimeout(()=>c(new Error("HNSW init timeout")),r));await Promise.race([i,s]),this.hnswAvailable=this.hnswIndex.isNativeAvailable(),await this.loadEmbeddingsIntoHNSW(),console.log(`[PatternStore] HNSW lazy-initialized (native: ${this.hnswAvailable})`)}catch(e){console.warn("[PatternStore] HNSW not available, using memory backend search:",y(e)),this.hnswIndex=null,this.hnswAvailable=!1}}async loadEmbeddingsIntoHNSW(){if(!(!this.hnswIndex||!this.sqliteStore))try{let e=this.sqliteStore.getAllEmbeddings(),t=this.config.hnsw.maxElements,r=0,i=0;for(let{patternId:s,embedding:a}of e){if(r>=t)break;if(!a||a.length!==this.config.embeddingDimension){i++;continue}let c=this.patternCache.get(s);if(!c){i++;continue}try{await this.hnswIndex.insert(s,a,{filePath:c.patternType,lineCoverage:c.confidence*100,branchCoverage:c.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-c.confidence,lastUpdated:Date.now(),totalLines:0}),r++}catch{i++}}r>0&&console.log(`[PatternStore] Loaded ${r} embeddings into HNSW (skipped ${i})`)}catch(e){console.warn("[PatternStore] Failed to load SQLite embeddings into HNSW:",y(e))}}getVectorDeltaTracker(){return this.vectorDeltaTracker===void 0&&(this.vectorDeltaTracker=Be()),this.vectorDeltaTracker}async loadPatterns(){if(this.sqliteStore)try{let e=this.sqliteStore.getPatterns({limit:5e4});for(let t of e)this.indexPattern(t);e.length>0&&console.log(`[PatternStore] Loaded ${e.length} patterns from SQLite into memory cache`)}catch(e){console.warn("[PatternStore] Failed to load patterns from SQLite:",y(e))}}indexPattern(e){this.patternCache.set(e.id,e),this.domainIndex.has(e.qeDomain)||this.domainIndex.set(e.qeDomain,new Set),this.domainIndex.get(e.qeDomain).add(e.id),this.typeIndex.has(e.patternType)||this.typeIndex.set(e.patternType,new Set),this.typeIndex.get(e.patternType).add(e.id);let t=e.tier==="long-term"?"long-term":"short-term";e.tier!==t&&(e.tier=t),this.tierIndex.get(t).add(e.id)}unindexPattern(e){this.patternCache.delete(e.id),this.domainIndex.get(e.qeDomain)?.delete(e.id),this.typeIndex.get(e.patternType)?.delete(e.id),this.tierIndex.get(e.tier)?.delete(e.id),this.hdcCache.delete(e.id),this.hdcTokenCache.delete(e.id)}async store(e){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let t=j(e);if(!t.valid)return w(new Error(`Invalid pattern: ${t.errors.join(", ")}`));if(e.confidence<this.config.minConfidence)return w(new Error(`Pattern confidence ${e.confidence} below threshold ${this.config.minConfidence}`));(this.domainIndex.get(e.qeDomain)?.size||0)>=this.config.maxPatternsPerDomain&&await this.cleanupDomain(e.qeDomain);let i=this.patternCache.get(e.id)??null;if(this.indexPattern(e),this.sqliteStore)try{this.sqliteStore.storePattern(e,e.embedding)}catch(s){console.warn(`[PatternStore] SQLite persist failed for ${e.id}:`,y(s))}if(e.embedding){let s=await this.ensureHNSW();if(s)try{await s.insert(e.id,e.embedding,{filePath:e.patternType,lineCoverage:e.confidence*100,branchCoverage:e.qualityScore*100,functionCoverage:0,statementCoverage:0,uncoveredLineCount:0,uncoveredBranchCount:0,riskScore:1-e.confidence,lastUpdated:Date.now(),totalLines:0})}catch(a){console.warn(`[PatternStore] Failed to index embedding for ${e.id}:`,a)}}if(q())try{let a=Ve().fingerprint({id:e.id,domain:e.qeDomain,type:e.patternType,content:e.description});this.hdcCache.set(e.id,a.vector)}catch(s){console.debug(`[PatternStore] HDC fingerprint failed for ${e.id}:`,y(s))}try{let s=qt();if(s){let a=[e.patternType,e.qeDomain];e.context?.tags&&a.push(...e.context.tags),e.name&&a.push(e.name);let c=s.fingerprintPattern(a);this.hdcTokenCache.set(e.id,c)}}catch(s){console.debug(`[PatternStore] HDC token fingerprint failed for ${e.id}:`,y(s))}if(te()&&e.embedding)try{Ye(e.embedding.length).store(new Float32Array(e.embedding),{id:e.id,name:e.name,domain:e.qeDomain})}catch(s){console.debug(`[PatternStore] Hopfield store failed for ${e.id}:`,y(s))}if(H()&&this.deltaTracker)try{let s={id:e.id,name:e.name,confidence:e.confidence,qualityScore:e.qualityScore,usageCount:e.usageCount,successRate:e.successRate,tier:e.tier};this.deltaTracker.createGenesis(e.id,s)}catch(s){console.debug(`[PatternStore] Delta genesis for ${e.id}:`,y(s))}if(e.embedding)try{let s=this.getVectorDeltaTracker();s&&(i?.embedding?s.recordDelta(e.id,i.embedding,e.embedding):s.getVersion(e.id)<0&&s.recordGenesis(e.id,e.embedding))}catch(s){console.debug(`[PatternStore] VectorDeltaTracker for ${e.id}:`,y(s))}try{M()&&e.embedding&&this.indexHyperbolic(e.id,e.embedding,{domain:e.qeDomain,type:e.patternType,name:e.name})}catch{}return v(e.id)}async create(e){let t=new Date,r=e.qeDomain||this.detectDomainFromType(e.patternType),i={id:C(),patternType:e.patternType,qeDomain:r,domain:r,name:e.name,description:e.description,confidence:e.confidence??.5,usageCount:0,successRate:0,qualityScore:.25,context:{...e.context,tags:e.context?.tags||[]},template:{...e.template,example:void 0},embedding:e.embedding,tier:"short-term",createdAt:t,lastUsedAt:t,successfulUses:0,reusable:!1,reuseCount:0,averageTokenSavings:0},s=await this.store(i);return s.success?v(i):w(s.error)}detectDomainFromType(e){return{"test-template":"test-generation","assertion-pattern":"test-generation","mock-pattern":"test-generation","coverage-strategy":"coverage-analysis","mutation-strategy":"test-generation","api-contract":"contract-testing","visual-baseline":"visual-accessibility","a11y-check":"visual-accessibility","perf-benchmark":"chaos-resilience","flaky-fix":"test-execution","refactor-safe":"code-intelligence","error-handling":"test-generation","meta-optimization":"learning-optimization"}[e]||"test-generation"}async get(e){return this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise,this.patternCache.get(e)??null}async search(e,t={}){this.initialized||await this.initialize(),this.loadingPromise&&await this.loadingPromise;let r=performance.now(),i=t.limit||10,s=[];try{if(Array.isArray(e)&&te())try{let h=Ye(e.length);if(h.getPatternCount()>0){let f=h.recall(new Float32Array(e));if(f&&f.similarity>.98){let d=f.metadata.id,p=await this.get(d);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,f.similarity);s.push({pattern:p,score:f.similarity,matchType:"vector",similarity:f.similarity,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}catch(h){console.debug("[PatternStore] Hopfield recall failed:",y(h))}if(Array.isArray(e)&&t.useVectorSearch!==!1){let h=await this.ensureHNSW();if(h){let f=await h.search(e,i*2);for(let d of f){let p=await this.get(d.key);if(p&&this.matchesFilters(p,t)){let g=this.calculateReuseInfo(p,d.score);s.push({pattern:p,score:d.score,matchType:"vector",similarity:d.score,canReuse:g.canReuse,estimatedTokenSavings:g.estimatedTokenSavings,reuseConfidence:g.reuseConfidence})}}}}if(typeof e=="string"&&e.trim()&&this.sqliteStore)try{let h=this.sqliteStore.searchFTS(e,i*2);if(h.length>0){let f=new Map(h.map(p=>[p.id,p.ftsScore])),d=new Set(s.map(p=>p.pattern.id));for(let p of s){let g=f.get(p.pattern.id);g!==void 0&&(p.score=.75*p.score+.25*g)}for(let p of h){if(d.has(p.id))continue;let g=await this.get(p.id);if(g&&this.matchesFilters(g,t)){let E=this.calculateReuseInfo(g,p.ftsScore);s.push({pattern:g,score:.5*p.ftsScore,matchType:"exact",similarity:p.ftsScore,canReuse:E.canReuse,estimatedTokenSavings:E.estimatedTokenSavings,reuseConfidence:E.reuseConfidence})}}}}catch{}if(typeof e=="string"||s.length<i){let h=await this.searchByText(typeof e=="string"?e:"",t,i-s.length),f=new Set(s.map(d=>d.pattern.id));for(let d of h)f.has(d.pattern.id)||s.push(d)}let a=720*60*60*1e3,c=Date.now();for(let h of s){let f=h.pattern.lastUsedAt?.getTime()??h.pattern.createdAt.getTime(),d=c-f,p=Math.pow(.5,d/a),g=h.pattern.usageCount>0?p:.5;h.score=h.score*(.7+.3*g)}s.sort((h,f)=>f.score-h.score);let u=s;t.filter&&(u=Fe(s,t.filter));let o=u.slice(0,i),l=performance.now()-r;return this.recordSearchLatency(l),v(o)}catch(a){return w(Ae(a))}}async searchByText(e,t,r){let i=[],s=e.toLowerCase(),a;t.domain?a=this.domainIndex.get(t.domain)||new Set:t.patternType?a=this.typeIndex.get(t.patternType)||new Set:t.tier?a=this.tierIndex.get(t.tier)||new Set:a=new Set(this.patternCache.keys());let c=[...a];if(q()&&s&&this.hdcCache.size>0)try{let u=Ve(),o=u.fingerprint({id:"query",domain:t.domain??"unknown",type:t.patternType??"unknown",content:e}),l=c.filter(d=>this.hdcCache.has(d)).map(d=>({id:d,similarity:u.similarity(o.vector,this.hdcCache.get(d))}));l.sort((d,p)=>p.similarity-d.similarity);let h=l.map(d=>d.id),f=c.filter(d=>!this.hdcCache.has(d));c=[...h,...f]}catch{}for(let u of c){if(i.length>=r)break;let o=this.patternCache.get(u);if(!o||!this.matchesFilters(o,t))continue;let l=0;if(s){let h=o.name.toLowerCase(),f=o.description.toLowerCase();h.includes(s)&&(l+=.5),f.includes(s)&&(s.length/f.length>.3?l+=.5:l+=.3);for(let d of o.context.tags)if(d.toLowerCase().includes(s)){l+=.2;break}l=Math.min(l,1)}else l=o.qualityScore;if(l>0||!s){let h=this.calculateReuseInfo(o,l);i.push({pattern:o,score:l||o.qualityScore,matchType:s?"exact":"context",similarity:l||o.qualityScore,canReuse:h.canReuse,estimatedTokenSavings:h.estimatedTokenSavings,reuseConfidence:h.reuseConfidence})}}return i}calculateReuseInfo(e,t){let{reuseOptimization:r}=this.config,i=t>=r.minSimilarityForReuse,s=e.successRate>=r.minSuccessRateForReuse,a=e.lastUsedAt instanceof Date?e.lastUsedAt.getTime():new Date(e.lastUsedAt).getTime(),u=(Date.now()-a)/(1e3*60*60*24)<=r.maxAgeForReuse,o=r.enabled&&e.reusable&&i&&s&&u,l=o?e.averageTokenSavings>0?e.averageTokenSavings:e.tokensUsed||0:0,h=t,f=e.successRate,d=Math.min(e.reuseCount/10,1),p=o?h*.4+f*.4+d*.2:0;return{canReuse:o,estimatedTokenSavings:l,reuseConfidence:p}}matchesFilters(e,t){if(t.patternType&&e.patternType!==t.patternType||t.domain&&e.qeDomain!==t.domain||t.tier&&e.tier!==t.tier||t.minConfidence!==void 0&&e.confidence<t.minConfidence||t.minQualityScore!==void 0&&e.qualityScore<t.minQualityScore)return!1;if(t.context){let r=t.context;if(r.language&&e.context.language!==r.language||r.framework&&e.context.framework!==r.framework||r.testType&&e.context.testType!==r.testType)return!1}return!0}async recordUsage(e,t){let r=await this.get(e);if(!r)return w(new Error(`Pattern not found: ${e}`));let i=new Date,s=r.usageCount+1,a=r.successfulUses+(t?1:0),c=a/s,u=t?.02:-.01,o=Math.max(.1,Math.min(1,r.confidence+u)),l=B({confidence:o,usageCount:s,successRate:c}),h={...r,usageCount:s,successfulUses:a,successRate:c,confidence:o,qualityScore:l,lastUsedAt:i};if(this.sqliteStore)try{this.sqliteStore.recordUsage(e,t)}catch(p){console.warn(`[PatternStore] SQLite recordUsage failed for ${e}:`,y(p))}if(H()&&this.deltaTracker)try{let p={id:r.id,name:r.name,confidence:r.confidence,qualityScore:r.qualityScore,usageCount:r.usageCount,successRate:r.successRate,tier:r.tier},g={id:h.id,name:h.name,confidence:h.confidence,qualityScore:h.qualityScore,usageCount:h.usageCount,successRate:h.successRate,tier:h.tier};this.deltaTracker.recordDelta(e,p,g,{success:t})}catch(p){console.debug(`[PatternStore] Delta recordDelta for ${e}:`,y(p))}let f=re(h);return f.meetsUsageCriteria&&f.meetsQualityCriteria&&f.meetsCoherenceCriteria&&h.tier==="short-term"?await this.promote(e):this.patternCache.set(e,h),v(void 0)}async promote(e){let t=await this.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(t.tier==="long-term")return v(void 0);let r={...t,tier:"long-term",confidence:Math.min(1,t.confidence+.1)};if(this.tierIndex.get("short-term")?.delete(e),this.tierIndex.get("long-term")?.add(e),this.patternCache.set(e,r),this.sqliteStore)try{this.sqliteStore.promotePattern(e)}catch(i){console.debug("[PatternStore] SQLite promotion error:",i instanceof Error?i.message:i)}return console.log(`[PatternStore] Promoted pattern ${e} (${t.name}) to long-term storage`),v(void 0)}async delete(e){let t=this.patternCache.get(e);if(!t)return w(new Error(`Pattern not found: ${e}`));if(this.unindexPattern(t),this.sqliteStore)try{this.sqliteStore.deletePattern(e)}catch(r){console.debug("[PatternStore] SQLite deletion error:",r instanceof Error?r.message:r)}if(this.hnswIndex!==null)try{await this.hnswIndex.delete(e)}catch(r){console.debug("[PatternStore] HNSW deletion error:",r instanceof Error?r.message:r)}return v(void 0)}async getStats(){let e={},t={};for(let[o,l]of this.domainIndex)e[o]=l.size;for(let[o,l]of this.typeIndex)t[o]=l.size;let r=0,i=0,s=0,a=0;for(let o of this.patternCache.values())r+=o.confidence,i+=o.qualityScore,s+=o.successRate,a++;let c=await this.ensureHNSW(),u=c!==null?await c.getStats():{nativeHNSW:!1,vectorCount:0,indexSizeBytes:0,lazyLoaded:!0};return{totalPatterns:this.patternCache.size,byTier:{shortTerm:this.tierIndex.get("short-term")?.size||0,longTerm:this.tierIndex.get("long-term")?.size||0},byDomain:e,byType:t,avgConfidence:a>0?r/a:0,avgQualityScore:a>0?i/a:0,avgSuccessRate:a>0?s/a:0,searchOperations:this.stats.searchOperations,avgSearchLatencyMs:this.calculateAvgLatency(),hnswStats:{nativeAvailable:u.nativeHNSW,vectorCount:u.vectorCount,indexSizeBytes:u.indexSizeBytes}}}async cleanup(){let e=0,t=0,r=[],i=[];for(let s of this.patternCache.values()){let a=re(s);if(a.meetsUsageCriteria&&a.meetsQualityCriteria&&a.meetsCoherenceCriteria){i.push(s.id);continue}if(s.tier==="short-term"){let u=s.createdAt instanceof Date?s.createdAt.getTime():new Date(s.createdAt).getTime(),o=Date.now()-u,l=o>10080*60*1e3,h=s.qualityScore<.2,f=s.usageCount===0&&o>1440*60*1e3;(l&&h||f)&&r.push(s.id)}}for(let s of i)(await this.promote(s)).success&&t++;for(let s of r)(await this.delete(s)).success&&e++;return console.log(`[PatternStore] Cleanup: removed ${e}, promoted ${t}`),{removed:e,promoted:t}}async cleanupDomain(e){let t=this.domainIndex.get(e);if(!t||t.size<this.config.maxPatternsPerDomain)return;let r=[];for(let a of t){let c=this.patternCache.get(a);c&&r.push(c)}r.sort((a,c)=>a.qualityScore-c.qualityScore);let i=Math.ceil(r.length*.1),s=0;for(let a of r){if(s>=i)break;a.tier==="short-term"&&(await this.delete(a.id),s++)}}recordSearchLatency(e){this.stats.searchOperations++,this.stats.searchLatencies.push(e),this.stats.searchLatencies.length>1e3&&(this.stats.searchLatencies=this.stats.searchLatencies.slice(-1e3))}calculateAvgLatency(){return this.stats.searchLatencies.length===0?0:this.stats.searchLatencies.reduce((t,r)=>t+r,0)/this.stats.searchLatencies.length}async dispose(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0),this.patternCache.clear(),this.domainIndex.clear(),this.typeIndex.clear(),this.tierIndex.clear(),this.hdcCache.clear(),this.deltaTracker=null,this.hyperbolicIndex&&(this.hyperbolicIndex.reset(),this.hyperbolicIndex=null),U&&(U.clear(),U=null,Se=0),this.initialized=!1}indexHyperbolic(e,t,r){if(M())try{this.hyperbolicIndex||(this.hyperbolicIndex=Ge({dimensions:this.config.embeddingDimension,maxElements:this.config.hnsw.maxElements})),this.hyperbolicIndex.indexPattern(e,t,r)}catch(i){console.debug(`[PatternStore] Hyperbolic indexing failed for ${e}:`,i instanceof Error?i.message:i)}}async searchHyperbolic(e,t=10){if(!M()||!this.hyperbolicIndex)return v([]);try{let r=this.hyperbolicIndex.search(e,t),i=[];for(let s of r){let a=await this.get(s.patternId);if(!a)continue;let c=Math.exp(-s.distance),u=this.calculateReuseInfo(a,c);i.push({pattern:a,score:c,matchType:"vector",similarity:c,canReuse:u.canReuse,estimatedTokenSavings:u.estimatedTokenSavings,reuseConfidence:u.reuseConfidence})}return v(i)}catch(r){return console.warn("[PatternStore] Hyperbolic search failed, returning empty results:",r instanceof Error?r.message:r),v([])}}};function kr(n,e){try{if(D().useRVFPatternStore&&Ce()){let{existsSync:r}=Ee("fs"),i=".agentic-qe/patterns.rvf",s=Ee("path").dirname(i);if(r(s)){let a={...X,...e},c=!1;try{let{getSharedRvfAdapter:u}=(tt(),Re(et)),o=u(s,a.embeddingDimension);if(o){c=!0;let l=new Q(()=>o,{rvfPath:i,base:a,skipCloseOnDispose:!0});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),l}}catch{}if(!c){let u=new Q((o,l)=>{let{openRvfStore:h}=(De(),Re(Ze)),f=()=>{try{return h(o)}catch{return null}},d=f();if(d){if(d.dimension()!==l){try{d.close()}catch{}throw new Error(`RVF dimension mismatch (file=${d.dimension()}, requested=${l})`)}return d}try{return xe(o,l)}catch(p){if(d=f(),d&&d.dimension()===l)return d;throw p}},{rvfPath:i,base:a});return console.log("[PatternStore] Using RVF-backed store (ADR-066)"),u}}}}catch(t){console.warn("[PatternStore] RVF store unavailable, using in-memory HNSW:",t instanceof Error?t.message:t)}return new be(n,e)}export{kr as a};
|
|
50
50
|
/*! Bundled license information:
|
|
51
51
|
|
|
52
52
|
fast-json-patch/commonjs/helpers.js:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
2
|
var l=["ECONNREFUSED","ETIMEOUT","ENOMEM","ENOSPC"];var s={successRate:.1,failureRate:1,viabilityThreshold:.3,rehabilitationThreshold:10,maxQuarantineDurationMs:6048e5,domainOverrides:{"security-compliance":{successRate:.05,failureRate:1,viabilityThreshold:.5},"test-generation":{successRate:.15,failureRate:1,viabilityThreshold:.2},"quality-assessment":{successRate:.1,failureRate:1,viabilityThreshold:.4}}},a=class{config;_witnessChain=null;set witnessChain(e){this._witnessChain=e}constructor(e={}){this.config={...s,...e,domainOverrides:{...s.domainOverrides,...e.domainOverrides}}}computeConfidenceUpdate(e,r,i){let{successRate:u,failureRate:o}=this.getConfigForDomain(i),n=r==="success"?u:-o;if(r==="failure")try{this._witnessChain?.append("HEBBIAN_PENALTY",{previousConfidence:e,delta:n,domain:i},"asymmetric-learning")}catch{}return c(e+n,0,1)}shouldQuarantine(e,r){let{viabilityThreshold:i}=this.getConfigForDomain(r);return{shouldQuarantine:e<i,confidence:e,viabilityThreshold:i,domain:r}}classifyFailure(e){if(e.infrastructureHealthy===!1||e.durationMs!==void 0&&e.durationMs>3e4)return"infrastructure";if(e.errorMessage){let r=e.errorMessage.toUpperCase();for(let i of l)if(r.includes(i))return"infrastructure"}return e.failureCategory==="infrastructure"?"infrastructure":(e.failureCategory==="pattern","pattern")}checkRehabilitation(e,r){let i=this.config.rehabilitationThreshold;return{canRehabilitate:e>=i,consecutiveSuccesses:e,requiredSuccesses:i,domain:r}}getConfigForDomain(e){return e&&this.config.domainOverrides?.[e]?this.config.domainOverrides[e]:{successRate:this.config.successRate,failureRate:this.config.failureRate,viabilityThreshold:this.config.viabilityThreshold}}getAsymmetryRatio(e){let{successRate:r,failureRate:i}=this.getConfigForDomain(e);return r===0?1/0:i/r}};function c(t,e,r){return t<e?e:t>r?r:t}export{a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{c as t,e as o}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{c as t,e as o}from"./chunk-6FNPEC2I.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>m,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>g,TensorCompress:()=>c,default:()=>i,differentiableSearch:()=>l,getCompressionLevel:()=>s,hierarchicalForward:()=>p,init:()=>u,pipeline:()=>v});import{createRequire as n}from"module";var r,e,i,a,c,l,p,s,u,m,d,A,f,h,_,g,v,b=t(()=>{r=n(import.meta.url),e=r("@ruvector/gnn"),i=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:p,getCompressionLevel:s,init:u,FlashAttention:m,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:g,pipeline:v}=e||{}});export{L as a,b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
2
|
var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as N,d 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.9.34");process.exit(0)}
|
|
2
|
+
import{a as N,d as P}from"./chunk-YIVJD5IY.js";import{b,e as k}from"./chunk-QX74JLGO.js";import{a as p,d as F}from"./chunk-REVCXO2R.js";import{a as T,c as E}from"./chunk-RYFQYSVF.js";import{a as H,b as O}from"./chunk-IUZNVWCR.js";import{c as z,g as S}from"./chunk-6FNPEC2I.js";function x(l){let e=0;for(let t=0;t<l.length;t++)e+=l[t]*l[t];return Math.sqrt(e)}function C(l,e,t,s){let n=t*s;if(n===0)return 0;let o=0;for(let r=0;r<l.length;r++)o+=l[r]*e[r];return o/n}function U(l={}){let{name:e="default",...t}=l;return new M(e,t)}var f,w,v,I,A,M,D=z(()=>{F();P();k();E();f=null,w=null;try{let l=(O(),S(H));f=l.differentiableSearch,w=l.init}catch{}v=class{data=[];compareFn;constructor(e){this.compareFn=e}push(e){this.data.push(e),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;let e=this.data[0],t=this.data.pop();return this.data.length>0&&(this.data[0]=t,this.sinkDown(0)),e}peek(){return this.data[0]}size(){return this.data.length}bubbleUp(e){for(;e>0;){let t=e-1>>1;if(this.compareFn(this.data[e],this.data[t])<0)[this.data[e],this.data[t]]=[this.data[t],this.data[e]],e=t;else break}}sinkDown(e){let t=this.data.length;for(;;){let s=e,n=2*e+1,o=2*e+2;if(n<t&&this.compareFn(this.data[n],this.data[s])<0&&(s=n),o<t&&this.compareFn(this.data[o],this.data[s])<0&&(s=o),s!==e)[this.data[e],this.data[s]]=[this.data[s],this.data[e]],e=s;else break}}},I=class{nodes=new Map;M=b.M_CONNECTIONS;Mmax0=b.M_CONNECTIONS*2;efConstruction=b.EF_CONSTRUCTION;efSearch=b.EF_SEARCH;mL=1/Math.log(b.M_CONNECTIONS);maxLevel=16;entryPoint=null;currentMaxLevel=-1;randomLevel(){return Math.min(Math.floor(-Math.log(N())*this.mL),this.maxLevel)}similarity(e,t){let s=this.nodes.get(t);return s?p(e,s.embedding):-1}searchLayer(e,t,s){let n=t,o=this.similarity(e,n),r=!0;for(;r;){r=!1;let a=this.nodes.get(n);if(!a)break;let h=a.neighbors.get(s)??[];for(let d of h){if(!this.nodes.has(d))continue;let i=this.similarity(e,d);i>o&&(n=d,o=i,r=!0)}}return n}searchLayerBeam(e,t,s,n){let o=new Set(t),r=t.filter(i=>this.nodes.has(i)).map(i=>({id:i,score:this.similarity(e,i)})),a=new v((i,c)=>c.score-i.score),h=new v((i,c)=>i.score-c.score);for(let i of r)a.push(i),h.push(i);for(;a.size()>0;){let i=a.pop();if(h.size()>=n&&i.score<h.peek().score)break;let c=this.nodes.get(i.id);if(!c)continue;let u=c.neighbors.get(s)??[];for(let m of u){if(o.has(m)||(o.add(m),!this.nodes.has(m)))continue;let g=this.similarity(e,m),y=h.size()>=n?h.peek().score:-1/0;if(h.size()<n||g>y){let L={id:m,score:g};a.push(L),h.push(L),h.size()>n&&h.pop()}}}let d=[];for(;h.size()>0;)d.push(h.pop());return d.reverse(),d}selectNeighbors(e,t,s){return t.sort((n,o)=>o.score-n.score).slice(0,s).map(n=>n.id)}getMaxConnections(e){return e===0?this.Mmax0:this.M}add(e,t){this.nodes.has(e)&&this.remove(e);let s=this.randomLevel(),n={id:e,embedding:t,neighbors:new Map};for(let r=0;r<=s;r++)n.neighbors.set(r,[]);if(this.nodes.set(e,n),this.entryPoint===null){this.entryPoint=e,this.currentMaxLevel=s;return}let o=this.entryPoint;for(let r=this.currentMaxLevel;r>s;r--)o=this.searchLayer(t,o,r);for(let r=Math.min(s,this.currentMaxLevel);r>=0;r--){let a=this.getMaxConnections(r),h=this.searchLayerBeam(t,[o],r,this.efConstruction),d=this.selectNeighbors(t,h,a);n.neighbors.set(r,[...d]);for(let i of d){let c=this.nodes.get(i);if(!c)continue;let u=c.neighbors.get(r)??[];if(u.push(e),u.length>a){let m=u.filter(g=>this.nodes.has(g)).map(g=>({id:g,score:p(c.embedding,this.nodes.get(g).embedding)}));m.sort((g,y)=>y.score-g.score),c.neighbors.set(r,m.slice(0,a).map(g=>g.id))}else c.neighbors.set(r,u)}h.length>0&&(o=h[0].id)}s>this.currentMaxLevel&&(this.entryPoint=e,this.currentMaxLevel=s)}remove(e){let t=this.nodes.get(e);if(!t)return!1;for(let[s,n]of t.neighbors.entries())for(let o of n){let r=this.nodes.get(o);if(!r)continue;let a=r.neighbors.get(s);if(!a)continue;let h=a.indexOf(e);h!==-1&&a.splice(h,1);let d=this.getMaxConnections(s);if(a.length<d){for(let i of n)if(i!==o&&i!==e&&this.nodes.has(i)&&!a.includes(i)){a.push(i);let c=this.nodes.get(i);if(c){let u=c.neighbors.get(s)??[];!u.includes(o)&&u.length<d&&(u.push(o),c.neighbors.set(s,u))}if(a.length>=d)break}}r.neighbors.set(s,a)}if(this.nodes.delete(e),this.entryPoint===e)if(this.nodes.size===0)this.entryPoint=null,this.currentMaxLevel=-1;else{let s=null,n=-1;for(let[o,r]of this.nodes.entries()){let a=-1;for(let h of r.neighbors.keys())h>a&&(a=h);a>n&&(n=a,s=o)}this.entryPoint=s,this.currentMaxLevel=n}return!0}search(e,t){if(this.nodes.size===0||this.entryPoint===null)return[];if(this.nodes.size===1){let r=this.nodes.get(this.entryPoint);return[{id:r.id,score:p(e,r.embedding)}]}let s=this.entryPoint;for(let r=this.currentMaxLevel;r>0;r--)s=this.searchLayer(e,s,r);let n=Math.max(this.efSearch,t);return this.searchLayerBeam(e,[s],0,n).slice(0,t)}size(){return this.nodes.size}clear(){this.nodes.clear(),this.entryPoint=null,this.currentMaxLevel=-1}};A=class{ids=[];vectors=[];norms=[];idToIndex=new Map;initialized=!1;constructor(){if(w&&!this.initialized)try{w(),this.initialized=!0}catch{this.initialized=f!==null}}add(e,t){let s=new Float32Array(t),n=x(s);if(this.idToIndex.has(e)){let r=this.idToIndex.get(e);this.vectors[r]=s,this.norms[r]=n;return}let o=this.ids.length;this.ids.push(e),this.vectors.push(s),this.norms.push(n),this.idToIndex.set(e,o)}search(e,t){if(this.ids.length===0)return[];let s=Math.min(t,this.ids.length),n=this.vectors.length>0?this.vectors[0].length:0,o=e.length,r=n===o;if(f&&this.vectors.length>0&&r){let i=new Float32Array(e),c=x(i);return f(i,this.vectors,s,1).indices.map(m=>({id:this.ids[m],score:C(i,this.vectors[m],c,this.norms[m])}))}let a=new Float32Array(e),h=x(a),d=[];for(let i=0;i<this.ids.length;i++){let c=this.vectors[i];if(c.length!==a.length){i===0&&console.warn(`[RuvectorFlatIndex] Dimension mismatch: query=${a.length}, stored=${c.length}. Skipping ${this.ids.length} mismatched vectors. Re-index with correct dimensions.`);continue}else d.push({id:this.ids[i],score:C(a,c,h,this.norms[i])})}return d.sort((i,c)=>c.score-i.score),d.slice(0,s)}remove(e){let t=this.idToIndex.get(e);if(t===void 0)return!1;let s=this.ids.length-1;if(t!==s){let n=this.ids[s];this.ids[t]=n,this.vectors[t]=this.vectors[s],this.norms[t]=this.norms[s],this.idToIndex.set(n,t)}return this.ids.pop(),this.vectors.pop(),this.norms.pop(),this.idToIndex.delete(e),!0}clear(){this.ids=[],this.vectors=[],this.norms=[],this.idToIndex.clear()}size(){return this.ids.length}},M=class{adapter;constructor(e,t){this.adapter=T.create(e,t)}add(e,t){this.adapter.addByStringId(e,t)}search(e,t){return this.adapter.searchByArray(e,t)}remove(e){return this.adapter.removeByStringId(e)}clear(){this.adapter.clear()}size(){return this.adapter.size()}recall(){return this.adapter.recall()}getProvider(){return this.adapter}}});export{v as a,I as b,A as c,M as d,U as e,D as f};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
2
|
import a from"chalk";import{existsSync as m,statSync as V}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&V(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}defaultValue;description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var S=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
|
|
3
3
|
Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,S as j};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as T,c as N}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.34");process.exit(0)}
|
|
2
|
+
import{a as T,c as N}from"./chunk-I74WDBHS.js";import{b as D,c as L,d as V}from"./chunk-YIVJD5IY.js";N();V();import*as C from"fs";import*as v from"path";import*as W from"yaml";var q=5,H=4,Q=3e4,K=".claude/skills",B=5e3,J=500,$=100,Y=1e3,F=500,z=.8,X=.2,Z=.1,w=.1,ee=.1,te=.1,se=.1,re=200,ne=500,ae=300,ie=1,oe=.9,U={maxWorkers:q,batchSize:H,retryFailedTests:!0,timeout:Q,skillsDir:K,progressIntervalMs:B},S=class{async execute(e,r,t){let s=L($,J+$);return await new Promise(o=>setTimeout(o,s)),{output:this.generateMockResponse(e),tokensUsed:D(F,Y+F),durationMs:s}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
|
|
3
3
|
Recommendations: Implement proper ${r[0]} attributes for better accessibility.
|
|
4
4
|
Severity: ${e.includes("critical")?"critical":"serious"}`}},M=class{constructor(e,r,t){this.executor=r;this.config=t;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let t of e){this.lastHeartbeat=Date.now();try{let s=await this.executeTestCase(t);if(r.push(s),s.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!s.passed){let n=await this.executeTestCase(t,!0);n.passed&&(r[r.length-1]=n,this.tasksCompleted++,this.tasksFailed--)}}catch(s){this.tasksFailed++,r.push({testId:t.testCaseId,passed:!1,expectedPatterns:t.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:t.testCase.category,priority:t.testCase.priority,error:T(s)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let t=Date.now(),s=this.buildPrompt(e),n=await this.executor.execute(s,e.model,{timeout:this.config.timeout}),o=this.validateResponse(n.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:o.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:o.foundPatterns,reasoningQuality:o.reasoningQuality,executionTimeMs:Date.now()-t,category:e.testCase.category,priority:e.testCase.priority,error:o.error}}buildPrompt(e){let{testCase:r}=e,t=r.input.context;return`Analyze the following ${t.language||"HTML"} code for accessibility issues.
|
|
5
5
|
Context: ${t.description||r.description}
|