agentic-qe 3.9.3 → 3.9.5
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/CHANGELOG.md +40 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-HOBCL2VF.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-W6GGSB43.js → agent-booster-wasm-AW36VJXL.js} +2 -2
- package/dist/cli/chunks/{agent-handler-3IRN5WBS.js → agent-handler-AQFW2CMW.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-SO63CIPJ.js → agent-memory-branch-VA6A47U5.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-77FVV2ZJ.js +2 -0
- package/dist/cli/chunks/{audit-TONGHW5H.js → audit-WVJHTVUU.js} +2 -2
- package/dist/cli/chunks/base-2IXMPGJV.js +2 -0
- package/dist/cli/chunks/{better-sqlite3-OK5DP5FC.js → better-sqlite3-HCMGVEDO.js} +2 -2
- package/dist/cli/chunks/{brain-handler-MC2S3UHL.js → brain-handler-JZISBH2W.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-PRKJKPAE.js → branch-enumerator-3TQXIETD.js} +2 -2
- package/dist/cli/chunks/{browser-WTMMBSU3.js → browser-4GZXU4YT.js} +2 -2
- package/dist/cli/chunks/browser-workflow-AQYKV2NE.js +2 -0
- package/dist/cli/chunks/{chunk-OJKGRB6D.js → chunk-2XJRSIM5.js} +2 -2
- package/dist/cli/chunks/{chunk-ITFNPXZL.js → chunk-35DP6LX6.js} +2 -2
- package/dist/cli/chunks/{chunk-D5AQDGTS.js → chunk-3DGO7NJK.js} +1 -1
- package/dist/cli/chunks/{chunk-AS5WPUDR.js → chunk-3KYKE7B6.js} +1 -1
- package/dist/cli/chunks/{chunk-UC3RA5LW.js → chunk-3QH67ZYC.js} +2 -2
- package/dist/cli/chunks/{chunk-SFFI3MDN.js → chunk-3UE5GART.js} +2 -2
- package/dist/cli/chunks/{chunk-WDTFG5AG.js → chunk-3UFAEGSS.js} +1 -1
- package/dist/cli/chunks/{chunk-JTIWAUWW.js → chunk-3VNEMHOO.js} +1 -1
- package/dist/cli/chunks/{chunk-SDHZLA45.js → chunk-45WEXMKC.js} +2 -2
- package/dist/cli/chunks/{chunk-5YUNMBIH.js → chunk-4EOSDCDM.js} +1 -1
- package/dist/cli/chunks/{chunk-KV32LAKU.js → chunk-4FPCCKNQ.js} +1 -1
- package/dist/cli/chunks/{chunk-TPFE3BAI.js → chunk-4QGNSNQL.js} +2 -2
- package/dist/cli/chunks/{chunk-TUHIFT65.js → chunk-53J3R7PZ.js} +2 -2
- package/dist/cli/chunks/{chunk-M3EFT3XR.js → chunk-55EAFHVH.js} +3 -3
- package/dist/cli/chunks/{chunk-F6O5XLIE.js → chunk-5NBYV7FL.js} +1 -1
- package/dist/cli/chunks/{chunk-QAXJOCTW.js → chunk-673PL3DG.js} +1 -1
- package/dist/cli/chunks/{chunk-T5MWENBA.js → chunk-6AMXWB6Y.js} +2 -2
- package/dist/cli/chunks/{chunk-JF6AXXAL.js → chunk-6FM5DJHR.js} +4 -4
- package/dist/cli/chunks/{chunk-CF4T4YSL.js → chunk-6QKGLIIY.js} +2 -2
- package/dist/cli/chunks/{chunk-7HTSXZ77.js → chunk-6QR7GSNJ.js} +2 -2
- package/dist/cli/chunks/{chunk-MNZ2HHKI.js → chunk-6VB4VZCR.js} +2 -2
- package/dist/cli/chunks/{chunk-OBOCKH47.js → chunk-73LG5ELL.js} +2 -2
- package/dist/cli/chunks/{chunk-6B4CTO5D.js → chunk-74YG34UH.js} +2 -2
- package/dist/cli/chunks/{chunk-VNSRA5PY.js → chunk-7JQOOPA2.js} +2 -2
- package/dist/cli/chunks/{chunk-GGKV5IQR.js → chunk-ALX5RJSR.js} +2 -2
- package/dist/cli/chunks/{chunk-T4GTFSB2.js → chunk-BM7VSJTE.js} +2 -2
- package/dist/cli/chunks/{chunk-P4RYVWIR.js → chunk-BNYHBEDE.js} +2 -2
- package/dist/cli/chunks/{chunk-ERWNQ6NC.js → chunk-BQUN2NB4.js} +3 -3
- package/dist/cli/chunks/{chunk-2IU6WK32.js → chunk-BYD54ZUF.js} +2 -2
- package/dist/cli/chunks/{chunk-LMN72H3V.js → chunk-CGYOMD6X.js} +1 -1
- package/dist/cli/chunks/{chunk-FR26EINS.js → chunk-CGYTM7AB.js} +2 -2
- package/dist/cli/chunks/{chunk-CU36MONI.js → chunk-CNGRXBKO.js} +2 -2
- package/dist/cli/chunks/{chunk-PKIBG7OJ.js → chunk-CQT3IEEX.js} +2 -2
- package/dist/cli/chunks/{chunk-TA454OEB.js → chunk-DFOANC7Z.js} +1 -1
- package/dist/cli/chunks/{chunk-JXE2DFXM.js → chunk-DPEX4UOC.js} +1 -1
- package/dist/cli/chunks/{chunk-FSUS5TV6.js → chunk-DSOEKRQL.js} +2 -2
- package/dist/cli/chunks/{chunk-BRCCPQXN.js → chunk-E55RROAP.js} +1 -1
- package/dist/cli/chunks/{chunk-3GMN3PNP.js → chunk-EPH2GZQM.js} +2 -2
- package/dist/cli/chunks/{chunk-OZNJZMQL.js → chunk-ERV3OVUG.js} +2 -2
- package/dist/cli/chunks/{chunk-LHDR6E6F.js → chunk-FDFJHGRZ.js} +2 -2
- package/dist/cli/chunks/{chunk-P6OZKWNK.js → chunk-G7XBTBM7.js} +2 -2
- package/dist/cli/chunks/{chunk-COIFERYS.js → chunk-GFXAKQ77.js} +2 -2
- package/dist/cli/chunks/{chunk-ZTIPMKUS.js → chunk-GFZRXQWH.js} +1 -1
- package/dist/cli/chunks/{chunk-7ASGPJWU.js → chunk-GHFXURNS.js} +1 -1
- package/dist/cli/chunks/{chunk-SJLDTV5B.js → chunk-GSTDQLXR.js} +2 -2
- package/dist/cli/chunks/{chunk-PS6KLLLQ.js → chunk-HA4COQ66.js} +2 -2
- package/dist/cli/chunks/{chunk-LQDAH47F.js → chunk-HT5EZYPZ.js} +2 -2
- package/dist/cli/chunks/{chunk-O2O5RO4H.js → chunk-I27OTSC7.js} +2 -2
- package/dist/cli/chunks/{chunk-RRELDHZY.js → chunk-I4HGIQC2.js} +2 -2
- package/dist/cli/chunks/{chunk-TSS6LXJ6.js → chunk-IHXDXFUX.js} +1 -1
- package/dist/cli/chunks/{chunk-JZXSKPQB.js → chunk-IMCYFQWF.js} +2 -2
- package/dist/cli/chunks/{chunk-HJEWQD2B.js → chunk-IMGRYCAT.js} +1 -1
- package/dist/cli/chunks/{chunk-GBLX5XOH.js → chunk-ITIYGUIL.js} +2 -2
- package/dist/cli/chunks/{chunk-TTEXJW2U.js → chunk-J4SEGMXL.js} +2 -2
- package/dist/cli/chunks/{chunk-WAWCNUIJ.js → chunk-JUBICWL2.js} +1 -1
- package/dist/cli/chunks/{chunk-PRIWFNVU.js → chunk-JYJXVTUP.js} +2 -2
- package/dist/cli/chunks/{chunk-53YFAERL.js → chunk-KCQ2GFRN.js} +2 -2
- package/dist/cli/chunks/{chunk-X5C73DW5.js → chunk-KQ7VBUO4.js} +2 -2
- package/dist/cli/chunks/{chunk-YTBE2MEW.js → chunk-KUDPFLL4.js} +4 -4
- package/dist/cli/chunks/{chunk-66RCUQCI.js → chunk-KWIDDPKG.js} +2 -2
- package/dist/cli/chunks/{chunk-5B2KXDWF.js → chunk-LLXBL36X.js} +1 -1
- package/dist/cli/chunks/{chunk-2CPNZVGL.js → chunk-LPVQ6QCW.js} +2 -2
- package/dist/cli/chunks/{chunk-5UMSMRJC.js → chunk-MBXSHGDD.js} +2 -2
- package/dist/cli/chunks/{chunk-DTNXHRUF.js → chunk-MO3IIM7L.js} +1 -1
- package/dist/cli/chunks/{chunk-IOW7QTYT.js → chunk-MRTDOSHR.js} +2 -2
- package/dist/cli/chunks/{chunk-OXR2FPHK.js → chunk-MYIDAWGQ.js} +2 -2
- package/dist/cli/chunks/{chunk-EXTVDKH7.js → chunk-N66G743A.js} +3 -3
- package/dist/cli/chunks/{chunk-PD5YPC2A.js → chunk-NDWWN2YC.js} +4 -4
- package/dist/cli/chunks/{chunk-JI5MNJSU.js → chunk-NGP3DRFU.js} +1 -1
- package/dist/cli/chunks/{chunk-3Q5FG6M3.js → chunk-NHIQ5HP3.js} +2 -2
- package/dist/cli/chunks/{chunk-Z4V3XV7E.js → chunk-NNNH36RU.js} +2 -2
- package/dist/cli/chunks/{chunk-UVWKIP3U.js → chunk-OPOTKH42.js} +3 -3
- package/dist/cli/chunks/{chunk-6N26CWST.js → chunk-OQCEI7Q4.js} +2 -2
- package/dist/cli/chunks/{chunk-MSKVWOND.js → chunk-OTOQXMP6.js} +3 -3
- package/dist/cli/chunks/{chunk-AWSYGQEB.js → chunk-PGFHFPDP.js} +2 -2
- package/dist/cli/chunks/{chunk-M7PGW5Z5.js → chunk-PMFZHFCB.js} +2 -2
- package/dist/cli/chunks/{chunk-D5GIV6O7.js → chunk-PTAUZ3XL.js} +1 -1
- package/dist/cli/chunks/{chunk-DGRO6LSI.js → chunk-PVLOT5BL.js} +2 -2
- package/dist/cli/chunks/{chunk-ZVMAE5JD.js → chunk-QHMDETCU.js} +1 -1
- package/dist/cli/chunks/{chunk-WIY3V5VQ.js → chunk-QPW2O5TR.js} +9 -9
- package/dist/cli/chunks/{chunk-K2DDNM4V.js → chunk-REXMKRR2.js} +8 -8
- package/dist/cli/chunks/{chunk-ZQCU62JJ.js → chunk-S4F3CNSP.js} +2 -2
- package/dist/cli/chunks/{chunk-FIQ62VOQ.js → chunk-T4KMG3GJ.js} +1 -1
- package/dist/cli/chunks/{chunk-EVIXQR4O.js → chunk-TRO45ZLC.js} +1 -1
- package/dist/cli/chunks/{chunk-DBSVEWWL.js → chunk-TRPCOY3C.js} +1 -1
- package/dist/cli/chunks/{chunk-XJII5WMD.js → chunk-TRRJP27A.js} +1 -1
- package/dist/cli/chunks/{chunk-WSVWVIVR.js → chunk-TSA5MUTQ.js} +2 -2
- package/dist/cli/chunks/{chunk-5OL6UOBM.js → chunk-TUMXWCB7.js} +3 -3
- package/dist/cli/chunks/{chunk-J7QGH6PG.js → chunk-UO2R7ZN3.js} +2 -2
- package/dist/cli/chunks/{chunk-OV6H3TRU.js → chunk-UPFCV7MX.js} +2 -2
- package/dist/cli/chunks/{chunk-HVOOYPW6.js → chunk-VKT4STAE.js} +2 -2
- package/dist/cli/chunks/{chunk-2GZ4EG3L.js → chunk-W73AYMDP.js} +1 -1
- package/dist/cli/chunks/{chunk-ZMUVSL5Q.js → chunk-WIZOYPFT.js} +2 -2
- package/dist/cli/chunks/{chunk-U6QQS5Z3.js → chunk-WTGUS7DD.js} +2 -2
- package/dist/cli/chunks/{chunk-LRE4A464.js → chunk-WV7K5A7J.js} +2 -2
- package/dist/cli/chunks/{chunk-QB2LOM5O.js → chunk-X6J7VYVD.js} +2 -2
- package/dist/cli/chunks/{chunk-S23UV7FV.js → chunk-XG2JAIQT.js} +1 -1
- package/dist/cli/chunks/{chunk-SVXIAQRW.js → chunk-Y6XYH7EV.js} +2 -2
- package/dist/cli/chunks/{chunk-DBEU5ISS.js → chunk-YDBMYTOV.js} +2 -2
- package/dist/cli/chunks/{chunk-GGEVILIS.js → chunk-YGZBS4RW.js} +2 -2
- package/dist/cli/chunks/{chunk-WLK5UVRJ.js → chunk-YHKJYBWK.js} +1 -1
- package/dist/cli/chunks/{chunk-DKOOKULB.js → chunk-YHSIUFFY.js} +2 -2
- package/dist/cli/chunks/{chunk-7JBIDAXT.js → chunk-YQTPEQO6.js} +2 -2
- package/dist/cli/chunks/{chunk-BK445WWE.js → chunk-YZ3WB4TN.js} +2 -2
- package/dist/cli/chunks/chunk-Z2GK7COI.js +2 -0
- package/dist/cli/chunks/{chunk-LDLLHLKE.js → chunk-ZD2FS4Q7.js} +2 -2
- package/dist/cli/chunks/{chunk-GGQCAQM4.js → chunk-ZFCRDCHW.js} +2 -2
- package/dist/cli/chunks/{chunk-ELU576GE.js → chunk-ZJWDWM6B.js} +3 -3
- package/dist/cli/chunks/{chunk-NZLJWXXM.js → chunk-ZP237D7K.js} +2 -2
- package/dist/cli/chunks/{chunk-T4RR4YMH.js → chunk-ZWS7J73Q.js} +1 -1
- package/dist/cli/chunks/{ci-XQEZTRJN.js → ci-3ATT6NMC.js} +2 -2
- package/dist/cli/chunks/{ci-output-ZWGXOIUD.js → ci-output-2JR3J753.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-PFJFHZSD.js → claude-flow-setup-SG2BSEED.js} +2 -2
- package/dist/cli/chunks/client-3CA57H5P.js +2 -0
- package/dist/cli/chunks/{cline-installer-L3WC4KUM.js → cline-installer-A26SXDX6.js} +2 -2
- package/dist/cli/chunks/{code-QMDXXY6C.js → code-WIXKPGAQ.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-YTPMAZPU.js → code-index-extractor-W2NO6MR3.js} +2 -2
- package/dist/cli/chunks/{codex-installer-KO5G7LHQ.js → codex-installer-VBSJHXI4.js} +2 -2
- package/dist/cli/chunks/{completions-KVDPIXMY.js → completions-JFXIUS2V.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-KNIBPEC3.js → complexity-analyzer-GPO4ZAIZ.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-N2GWI5PC.js → continuedev-installer-OULSFVLB.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-EX3UTDQN.js → copilot-installer-QS7EG5DW.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-XX6OMP37.js → cost-tracker-D7LNB633.js} +2 -2
- package/dist/cli/chunks/{coverage-FHDDNCPO.js → coverage-YUQ4MQYK.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-GECFIALH.js +2 -0
- package/dist/cli/chunks/{cursor-installer-M47YCQU7.js → cursor-installer-UOZGHZHD.js} +2 -2
- package/dist/cli/chunks/{daemon-EV3RXWAG.js → daemon-27TMWDPY.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-J7JDWG5J.js → dag-attention-scheduler-PVAFQBDL.js} +2 -2
- package/dist/cli/chunks/{detect-4P5RKV5J.js → detect-FUKMZ37Y.js} +2 -2
- package/dist/cli/chunks/{domain-handler-Q35TYDGA.js → domain-handler-SP3QB5VN.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-XC34MV5U.js → domain-transfer-A2WL6HEJ.js} +2 -2
- package/dist/cli/chunks/dream-CJ4MKM5G.js +2 -0
- package/dist/cli/chunks/esm-node-X7U3YS4M.js +2 -0
- package/dist/cli/chunks/{eval-QZGRW7XD.js → eval-6MIZUXEO.js} +2 -2
- package/dist/cli/chunks/{fast-paths-O42GG56B.js → fast-paths-XT542LOU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-G6SJTDVO.js → feature-flags-NWACCWCB.js} +2 -2
- package/dist/cli/chunks/{feature-flags-GIGWUPEX.js → feature-flags-WBF5B6WE.js} +2 -2
- package/dist/cli/chunks/{file-discovery-D4NXB3JP.js → file-discovery-GKCJFWTD.js} +2 -2
- package/dist/cli/chunks/{fleet-ZXZ5AAPW.js → fleet-V2MKGNMG.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-YK6NAPJV.js → gnn-wrapper-HUUMTTSV.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-DD4T6U36.js → heartbeat-handler-UY3TCEN7.js} +4 -4
- package/dist/cli/chunks/{heartbeat-scheduler-CBPO5KUB.js → heartbeat-scheduler-YWXPSCH2.js} +2 -2
- package/dist/cli/chunks/hnsw-adapter-LJGOH772.js +2 -0
- package/dist/cli/chunks/hnsw-index-V6SST2MB.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-REKPPJ75.js → hnsw-legacy-bridge-IYYYSRK5.js} +2 -2
- package/dist/cli/chunks/{hnswlib-node-PMWK24KT.js → hnswlib-node-WDWAE74R.js} +2 -2
- package/dist/cli/chunks/{hooks-UDKFTCJ7.js → hooks-DTBJK6LL.js} +6 -6
- package/dist/cli/chunks/{hypergraph-engine-FIAZJD7K.js → hypergraph-engine-K47IBQNO.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-NN2EBNBW.js → hypergraph-handler-2NDPG2N4.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-MTOVFD3O.js +2 -0
- package/dist/cli/chunks/init-handler-VRZS6KO2.js +68 -0
- package/dist/cli/chunks/init-wizard-IH6PSRJY.js +2 -0
- package/dist/cli/chunks/kernel-3MC7WV5G.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-6XPW7IAO.js → kilocode-installer-XZAHWQEA.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-DOHZGTBZ.js → kiro-installer-53C7DXEF.js} +15 -15
- package/dist/cli/chunks/knowledge-graph-HLUQJ2GI.js +2 -0
- package/dist/cli/chunks/{learning-GRSMZRPZ.js → learning-XYW2EEVX.js} +3 -3
- package/dist/cli/chunks/{llm-router-MTZPLM7A.js → llm-router-64SKMJ7B.js} +2 -2
- package/dist/cli/chunks/{load-CQXXMUR7.js → load-HVL4O7EY.js} +2 -2
- package/dist/cli/chunks/load-test-VVVME7GZ.js +2 -0
- package/dist/cli/chunks/{mcp-IIPV4IWF.js → mcp-4H2NJ3EO.js} +2 -2
- package/dist/cli/chunks/{memory-GIODHUAL.js → memory-2CD4BAJK.js} +5 -5
- package/dist/cli/chunks/memory-backend-O3U2QDU3.js +2 -0
- package/dist/cli/chunks/{memory-handlers-O6UVJSAG.js → memory-handlers-XRYZBE5I.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-DDIIEIKL.js → opencode-installer-I23QAZC6.js} +2 -2
- package/dist/cli/chunks/{orchestrator-PAQTJDA3.js → orchestrator-7BL6R54P.js} +16 -16
- package/dist/cli/chunks/{pipeline-6HFLH75G.js → pipeline-7UN7LP6B.js} +2 -2
- package/dist/cli/chunks/{platform-UKK776G2.js → platform-P44YUHPK.js} +2 -2
- package/dist/cli/chunks/{plugin-ERW5YBXU.js → plugin-YWYR7FKS.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-WB5A4ULB.js → prime-radiant-advanced-wasm-A7CDGUK6.js} +2 -2
- package/dist/cli/chunks/protocol-executor-HLNTSRYC.js +2 -0
- package/dist/cli/chunks/{protocol-handler-AKDFZI6G.js → protocol-handler-BM7RLC4Z.js} +2 -2
- package/dist/cli/chunks/{prove-GT5XEWVF.js → prove-UVBYODRV.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-JK5CK4D4.js +2 -0
- package/dist/cli/chunks/{quality-VZAG6B54.js → quality-4L42LN5Q.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-FLF6XYLX.js +2 -0
- package/dist/cli/chunks/{real-embeddings-KOOT5MTA.js → real-embeddings-4CYZTWHT.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-KHGDU6QK.js → roocode-installer-UOSJS7KT.js} +2 -2
- package/dist/cli/chunks/router-DUFZW3WQ.js +2 -0
- package/dist/cli/chunks/routing-feedback-6U76TI6X.js +2 -0
- package/dist/cli/chunks/{routing-handler-HVCNYSJM.js → routing-handler-43G4D5UP.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-D46MOJ32.js → ruvector-commands-H7A7LG6Q.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-WASNBBMN.js → rvf-dual-writer-USU2IWO7.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-ESLGEE5X.js → rvf-migration-adapter-DZMYVJJY.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-S5NAMHTP.js → rvf-migration-coordinator-AZ5JDT33.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-4UD7SUMB.js +2 -0
- package/dist/cli/chunks/safe-db-32Q5RXHR.js +2 -0
- package/dist/cli/chunks/schedule-ZHCM3L6H.js +2 -0
- package/dist/cli/chunks/scheduler-HBSSLDOD.js +2 -0
- package/dist/cli/chunks/{security-4AHBDCJJ.js → security-RXG4H3UK.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-PLZVKKW7.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-ZFNW4C3N.js → shared-rvf-dual-writer-2PUFIGX5.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-YUZMB44Y.js +2 -0
- package/dist/cli/chunks/{status-handler-ZVC4HX5J.js → status-handler-SXQKG6VP.js} +2 -2
- package/dist/cli/chunks/{structural-health-DPFQ4GEF.js → structural-health-LPXOOMG3.js} +2 -2
- package/dist/cli/chunks/{sync-7A5JMQNB.js → sync-5NX7GQQY.js} +10 -10
- package/dist/cli/chunks/{task-handler-OFZ5YMXH.js → task-handler-Y4KVNCOI.js} +2 -2
- package/dist/cli/chunks/{task-handlers-IRSHSFQW.js → task-handlers-CG27Z3CP.js} +2 -2
- package/dist/cli/chunks/{test-F6XPB2DN.js → test-PWVTWOWS.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-CPHQ7DBP.js → test-scheduling-5S5EBVE7.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-5YD6K4LL.js → token-bootstrap-QMPUKGQC.js} +2 -2
- package/dist/cli/chunks/{token-usage-KQYGQAEK.js → token-usage-OZNRTJLE.js} +2 -2
- package/dist/cli/chunks/{transformers-P7TT2MJB.js → transformers-DRPOBWCW.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-SUSDXGOP.js → tree-sitter-wasm-parser-VLX6HQW2.js} +2 -2
- package/dist/cli/chunks/{types-OEGMO7AH.js → types-TUF6HUPE.js} +2 -2
- package/dist/cli/chunks/unified-memory-3D4VDY4G.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-AAQ5IA6M.js +2 -0
- package/dist/cli/chunks/unified-persistence-PY7MVJTL.js +2 -0
- package/dist/cli/chunks/{validate-XI4GTLQR.js → validate-H7QFV2CI.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-UZQR6AWZ.js → validate-swarm-BGH6YM4S.js} +2 -2
- package/dist/cli/chunks/{vibium-VPJH2KD5.js → vibium-DQOGR2PH.js} +2 -2
- package/dist/cli/chunks/visual-security-ZBNB7LEG.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-LUNFY67E.js → web-tree-sitter-TOI4XJIL.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-LTJCP7AT.js → windsurf-installer-EUMBFA42.js} +2 -2
- package/dist/cli/chunks/witness-chain-CS76OJFL.js +2 -0
- package/dist/cli/chunks/{witness-chain-YWBIN5MQ.js → witness-chain-MWPUR4Q2.js} +2 -2
- package/dist/cli/chunks/{workflow-UGXLNO36.js → workflow-V5HI3AQR.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-FS4HGYI7.js +2 -0
- package/dist/cli/chunks/{wrappers-LUJRP2YI.js → wrappers-VOU4IVAQ.js} +2 -2
- package/dist/cli/commands/init.js +2 -0
- package/dist/cli/commands/sync.js +25 -8
- package/dist/cli/handlers/init-handler.d.ts +1 -0
- package/dist/cli/handlers/init-handler.js +2 -0
- package/dist/init/governance-installer.js +46 -14
- package/dist/init/kiro-installer.js +15 -2
- package/dist/init/orchestrator.js +1 -0
- package/dist/init/phases/06-code-intelligence.d.ts +13 -0
- package/dist/init/phases/06-code-intelligence.js +46 -7
- package/dist/init/phases/phase-interface.d.ts +9 -0
- package/dist/integrations/ruvector/feature-flags.js +1 -1
- package/dist/mcp/bundle.js +2 -2
- package/package.json +1 -1
- package/dist/cli/chunks/adapter-WKI55MLS.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-QQHHH3ZL.js +0 -2
- package/dist/cli/chunks/base-3ENVJTIL.js +0 -2
- package/dist/cli/chunks/browser-workflow-QVT343YP.js +0 -2
- package/dist/cli/chunks/chunk-FONTSK2O.js +0 -2
- package/dist/cli/chunks/client-VUKA3X4R.js +0 -2
- package/dist/cli/chunks/cross-domain-router-5SUV5AP6.js +0 -2
- package/dist/cli/chunks/dream-2UNEPNI2.js +0 -2
- package/dist/cli/chunks/esm-node-TPR2KU6L.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-BLMGBVDE.js +0 -2
- package/dist/cli/chunks/hnsw-index-UWMXU7RN.js +0 -2
- package/dist/cli/chunks/impact-analyzer-RK2VPRRL.js +0 -2
- package/dist/cli/chunks/init-handler-RK256F2M.js +0 -68
- package/dist/cli/chunks/init-wizard-HA2VADPV.js +0 -2
- package/dist/cli/chunks/kernel-QMZBPOWP.js +0 -2
- package/dist/cli/chunks/knowledge-graph-INYQCVMS.js +0 -2
- package/dist/cli/chunks/load-test-YSEU2TUL.js +0 -2
- package/dist/cli/chunks/memory-backend-MNSPY44E.js +0 -2
- package/dist/cli/chunks/protocol-executor-CBKER6RL.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-C3J4RA2M.js +0 -2
- package/dist/cli/chunks/queen-coordinator-ZXTNAEYV.js +0 -2
- package/dist/cli/chunks/router-YMQF6M2D.js +0 -2
- package/dist/cli/chunks/routing-feedback-MM7LNDS7.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-3EEWPK4C.js +0 -2
- package/dist/cli/chunks/safe-db-5P6ABYNG.js +0 -2
- package/dist/cli/chunks/schedule-ZGESH3FK.js +0 -2
- package/dist/cli/chunks/scheduler-AC4AA2BD.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-UQQUEC52.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-KXDW2Q66.js +0 -2
- package/dist/cli/chunks/unified-memory-MNW25PVU.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-4RZRP37O.js +0 -2
- package/dist/cli/chunks/unified-persistence-6UBNXF25.js +0 -2
- package/dist/cli/chunks/visual-security-7742DBSK.js +0 -2
- package/dist/cli/chunks/witness-chain-QVPNOHDC.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-K3Q2GOEG.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{c as a,d as b,e as c,f as d}from"./chunk-55EAFHVH.js";import"./chunk-XG2JAIQT.js";import"./chunk-ZP237D7K.js";import"./chunk-4EOSDCDM.js";import"./chunk-KQ7VBUO4.js";import"./chunk-ZWS7J73Q.js";import"./chunk-BNYHBEDE.js";import"./chunk-T4KMG3GJ.js";import"./chunk-3KYKE7B6.js";import"./chunk-4FPCCKNQ.js";import"./chunk-HT5EZYPZ.js";import"./chunk-I4HGIQC2.js";import"./chunk-DSOEKRQL.js";import"./chunk-Z2GK7COI.js";import"./chunk-OQCEI7Q4.js";import"./chunk-CNGRXBKO.js";import"./chunk-DFOANC7Z.js";import"./chunk-MYIDAWGQ.js";import"./chunk-TRO45ZLC.js";import"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-WIZOYPFT.js";import"./chunk-TSA5MUTQ.js";import"./chunk-4QGNSNQL.js";import"./chunk-UPFCV7MX.js";import"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import"./chunk-2XJRSIM5.js";import"./chunk-GHFXURNS.js";export{a as DOMAIN_GROUPS,c as QueenCoordinator,b as TASK_DOMAIN_MAP,d as createQueenCoordinator};
|
|
@@ -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 b,b as c,c as d,d as e,e as f,f as g,g as h,h as i}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.5");process.exit(0)}
|
|
2
|
+
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i}from"./chunk-LPVQ6QCW.js";import"./chunk-MYIDAWGQ.js";import{a}from"./chunk-UPFCV7MX.js";import"./chunk-GHFXURNS.js";export{b as DEFAULT_EMBEDDING_CONFIG,e as clearEmbeddingCache,d as computeBatchEmbeddings,c as computeRealEmbedding,a as cosineSimilarity,f as getCacheStats,h as getEmbeddingDimension,g as isTransformerAvailable,i as resetInitialization};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b 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.5");process.exit(0)}
|
|
2
|
+
import{b as p}from"./chunk-IMGRYCAT.js";import{a as f,c as v}from"./chunk-MYIDAWGQ.js";import"./chunk-GHFXURNS.js";v();import{existsSync as n,mkdirSync as m,readFileSync as u,writeFileSync as a}from"fs";import{join as d,dirname as h}from"path";var l=class{projectRoot;overwrite;generator;constructor(r){this.projectRoot=r.projectRoot,this.overwrite=r.overwrite??!1,this.generator=p()}async install(){let r={success:!0,mcpConfigured:!1,modeInstalled:!1,errors:[],configPath:"",modePath:""};try{let t=this.generator.generateMcpConfig("roocode"),e=d(this.projectRoot,t.path);if(r.configPath=e,!n(e)||this.overwrite){let i=h(e);if(n(i)||m(i,{recursive:!0}),n(e)&&this.overwrite){let c=this.mergeExistingConfig(e,t.content);a(e,c)}else a(e,t.content);r.mcpConfigured=!0}let s=this.generator.generateBehavioralRules("roocode"),o=d(this.projectRoot,s.path);if(r.modePath=o,!n(o)||this.overwrite){let i=h(o);if(n(i)||m(i,{recursive:!0}),n(o)&&this.overwrite){let c=this.mergeExistingModes(o,s.content);a(o,c)}else a(o,s.content);r.modeInstalled=!0}}catch(t){r.success=!1,r.errors.push(`Roo Code installation failed: ${f(t)}`)}return r}mergeExistingConfig(r,t){try{let e=JSON.parse(u(r,"utf-8")),s=JSON.parse(t);return e.mcpServers||(e.mcpServers={}),Object.assign(e.mcpServers,s.mcpServers),JSON.stringify(e,null,2)+`
|
|
3
3
|
`}catch{return t}}mergeExistingModes(r,t){try{let e=JSON.parse(u(r,"utf-8")),s=JSON.parse(t);if(!Array.isArray(e))return t;let o=e.filter(i=>i.slug!=="qe-engineer");return o.push(...s),JSON.stringify(o,null,2)+`
|
|
4
4
|
`}catch{return t}}};function P(g){return new l(g)}export{l as RooCodeInstaller,P as createRooCodeInstaller};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b,c}from"./chunk-JYJXVTUP.js";import"./chunk-GSTDQLXR.js";import"./chunk-ITIYGUIL.js";import"./chunk-PTAUZ3XL.js";import"./chunk-JUBICWL2.js";import"./chunk-CNGRXBKO.js";import"./chunk-MYIDAWGQ.js";import"./chunk-GHFXURNS.js";export{a as ModelRouter,b as createModelRouter,c as createModelRouterWithAgentBooster};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b}from"./chunk-ERV3OVUG.js";import"./chunk-673PL3DG.js";import"./chunk-KCQ2GFRN.js";import"./chunk-YHKJYBWK.js";import"./chunk-HT5EZYPZ.js";import"./chunk-I4HGIQC2.js";import"./chunk-Z2GK7COI.js";import"./chunk-OQCEI7Q4.js";import"./chunk-CNGRXBKO.js";import"./chunk-MYIDAWGQ.js";import"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-WIZOYPFT.js";import"./chunk-TSA5MUTQ.js";import"./chunk-4QGNSNQL.js";import"./chunk-UPFCV7MX.js";import"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import"./chunk-2XJRSIM5.js";import"./chunk-GHFXURNS.js";export{a as RoutingFeedbackCollector,b as createRoutingFeedbackCollector};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as u}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.5");process.exit(0)}
|
|
2
|
+
import{b as u}from"./chunk-ERV3OVUG.js";import{c as m}from"./chunk-673PL3DG.js";import"./chunk-KCQ2GFRN.js";import"./chunk-YHKJYBWK.js";import"./chunk-HT5EZYPZ.js";import"./chunk-I4HGIQC2.js";import"./chunk-Z2GK7COI.js";import"./chunk-OQCEI7Q4.js";import"./chunk-CNGRXBKO.js";import{a as l,c as f}from"./chunk-MYIDAWGQ.js";import"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-WIZOYPFT.js";import"./chunk-TSA5MUTQ.js";import"./chunk-4QGNSNQL.js";import"./chunk-UPFCV7MX.js";import"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import"./chunk-2XJRSIM5.js";import"./chunk-GHFXURNS.js";f();import o from"chalk";var d=class{name="routing";description="View routing performance, economics, and accuracy";cleanupAndExit;constructor(n){this.cleanupAndExit=n}getHelp(){return["aqe routing economics [--complexity <0-1>] [--json] Show tier efficiency & budget","aqe routing accuracy [--json] Show routing accuracy analysis","aqe routing metrics [--json] Show per-agent performance"].join(`
|
|
3
3
|
`)}register(n,r){let t=n.command("routing").description(this.description);t.command("economics").description("Show economic routing report: tier efficiency, budget, savings").option("-c, --complexity <value>","Task complexity for scoring (0-1)","0.5").option("--json","Output as JSON").action(async e=>{await this.executeEconomics(parseFloat(e.complexity)||.5,!!e.json)}),t.command("accuracy").description("Show routing accuracy analysis").option("--json","Output as JSON").action(async e=>{await this.executeAccuracy(!!e.json)}),t.command("metrics").description("Show per-agent performance metrics").option("--json","Output as JSON").action(async e=>{await this.executeMetrics(!!e.json)})}async executeEconomics(n,r){try{let t=u(100);await t.initialize(),t.enableEconomicRouting({},m());let e=t.getEconomicReport();if(!e){console.error(o.red(`
|
|
4
4
|
Economic routing is not available.
|
|
5
5
|
`)),await this.cleanupAndExit(1);return}if(r){console.log(JSON.stringify(e,(a,s)=>s===1/0?"Infinity":s,2)),await this.cleanupAndExit(0);return}console.log(o.blue(`
|
|
@@ -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 p,c as S}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a as p,c as S}from"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import{S as A,a as u,b as f,c as d}from"./chunk-2XJRSIM5.js";import{a as y}from"./chunk-GHFXURNS.js";A();S();import{Command as h}from"commander";import e from"chalk";var F=[{name:"@ruvector/router",flag:"useNativeHNSW",fallback:"ProgressiveHnswBackend"},{name:"prime-radiant-advanced-wasm",flag:"useCoherenceGate",fallback:"Word-frequency heuristics"},{name:"@ruvector/sona",flag:"useSONAThreeLoop",fallback:"TypeScript MicroLoRA/EWC++"}],D={useQESONA:"Self-Optimizing Neural Architecture",useQEFlashAttention:"SIMD-accelerated attention computation",useQEGNNIndex:"Differentiable search and HNSW indexing",logMigrationMetrics:"Log migration metrics during rollout",useNativeHNSW:"Rust-based HNSW backend (@ruvector/router VectorDb)",useTemporalCompression:"Temporal tensor compression (ADR-085)",useMetadataFiltering:"SIMD-accelerated metadata filtering",useDeterministicDither:"Cross-platform deterministic dithering",useNeuralRouting:"Neural model routing via FastGRNN (ADR-082)",useSONAThreeLoop:"SONA Three-Loop Engine (Task 2.2)",useCrossDomainTransfer:"Cross-domain transfer learning (ADR-084)",useHnswHealthMonitor:"HNSW health monitor (Task 3.4)",useRegretTracking:"Regret tracking & learning health (Task 2.4)",useCoherenceGate:"Sheaf-gated coherence validation (ADR-083, Task 3.1)",useWitnessChain:"SHA-256 hash-chained witness records (Task 3.1)",useCNNVisualRegression:"CNN visual regression testing (Task 4.3)",useDAGAttention:"DAG attention for test scheduling (Task 4.2)",useCoherenceActionGate:"Coherence-gated agent actions (ADR-083, Task 3.2)",useReasoningQEC:"Reasoning QEC error correction (Task 4.5)",useRVFPatternStore:"RVF-backed PatternStore with persistent HNSW (ADR-066)",useAgentMemoryBranching:"Agent memory branching via RVF COW (ADR-067)",useUnifiedHnsw:"Unified HNSW provider replacing 3 legacy impls (ADR-071)",rvfMigrationStage:"RVF migration stage 0-4: sqlite\u2192hybrid\u2192dual\u2192rvf-primary (ADR-072)",useHDCFingerprinting:"HDC pattern fingerprinting (R1, ADR-087)",useCusumDriftDetection:"CUSUM drift detection (R2, ADR-087)",useDeltaEventSourcing:"Delta event sourcing (R3, ADR-087)",useEwcPlusPlusRegularization:"EWC++ regularization (ADR-087)",useGraphMAEEmbeddings:"GraphMAE self-supervised embeddings (R4, ADR-087)",useHopfieldMemory:"Modern Hopfield memory (R5, ADR-087)",useColdTierGNN:"Cold-tier GNN training (R6, ADR-087)",useMetaLearningEnhancements:"Meta-learning enhancements (R7, ADR-087)",useSublinearSolver:"Sublinear PageRank solver (R8, ADR-087)",useSpectralSparsification:"Spectral graph sparsification (R9, ADR-087)",useReservoirReplay:"Reservoir replay with coherence gating (R10, ADR-087)",useEpropOnlineLearning:"E-prop online learning, RL algorithm #10 (R11, ADR-087)",useGrangerCausality:"Granger causality for test failure prediction (R12, ADR-087)",useCognitiveRouting:"Cognitive routing with predictive delta compression (R13, ADR-087)",useHyperbolicHnsw:"Hyperbolic HNSW with Poincare ball embeddings (R14, ADR-087)"},m={performance:{useNativeHNSW:!0,useTemporalCompression:!0,useDeterministicDither:!0},experimental:{useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0},safe:{useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!1,useTemporalCompression:!1,useMetadataFiltering:!1,useDeterministicDither:!1,useNeuralRouting:!1}},g=Object.keys(u);function b(o){try{return y.resolve(o),!0}catch{return!1}}function v(o,s){return u[o]===s}function i(o,s){return o.padEnd(s)}function N(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:o<1024*1024*1024?`${(o/(1024*1024)).toFixed(1)}MB`:`${(o/(1024*1024*1024)).toFixed(2)}GB`}function k(o){return g.includes(o)}function C(o){return o in m}function T(){let o=f();console.log(""),console.log(e.bold.blue("RuVector Integration Status:")),console.log(e.cyan(" Native Packages:"));for(let t of F){let a=b(t.name)?e.green("installed"):e.gray(`not installed (fallback: ${t.fallback})`);console.log(` ${i(t.name+":",30)} ${a}`)}console.log(""),console.log(e.cyan(" Feature Flags:"));for(let t of g){let r=o[t],a=v(t,r),n=typeof r=="number"?e.cyan(String(r)):r?e.green("true"):e.gray("false"),l=a?e.gray(" (default)"):e.yellow(" (modified)");console.log(` ${i(t+":",30)} ${n}${l}`)}let s=p.listIndexes();if(s.length>0){console.log(""),console.log(e.cyan(" HNSW Memory Usage:"));let t=0,r=0;for(let a of s){let n=p.get(a);if(n){let l=n.size(),c=n.dimensions(),R=l*c*4*3;t+=l,r+=R,console.log(` ${i(a+":",20)} ${e.white(String(l))} vectors, ${e.white(c)}d, ~${e.white(N(R))}`)}}console.log(e.gray(` ${"\u2500".repeat(50)}`)),console.log(` ${i("Total:",20)} ${e.bold.white(String(t))} vectors, ~${e.bold.white(N(r))}`)}else console.log(""),console.log(e.cyan(" HNSW Memory Usage:")),console.log(e.gray(" No active indexes (indexes are created on first use)"));o.useTemporalCompression&&(console.log(""),console.log(e.cyan(" Temporal Compression:")),console.log(e.gray(" Hot tier: 8-bit quantization (frequently accessed patterns)")),console.log(e.gray(" Warm tier: 5-bit quantization (moderately accessed patterns)")),console.log(e.gray(" Cold tier: 3-bit quantization (rarely accessed patterns)")),console.log(e.gray(" Estimated memory savings: 40-60% for cold patterns"))),console.log("")}function x(o){if(o.profile){if(!C(o.profile)){console.log(""),console.log(e.red(` Unknown profile: ${o.profile}`)),console.log(e.gray(` Valid profiles: ${Object.keys(m).join(", ")}`)),console.log(""),process.exit(1);return}let t=m[o.profile];d(t),console.log(""),console.log(e.bold.blue(`Setting ${o.profile} profile:`));for(let[r,a]of Object.entries(t)){let n=a?e.green("true"):e.gray("false");console.log(` ${i(r+":",30)} ${n}`)}console.log("");return}if(o.set){let t=o.set.indexOf("=");if(t<=0){console.log(""),console.log(e.red(" Invalid format. Use: --set flagName=true|false")),console.log(""),process.exit(1);return}let r=o.set.substring(0,t),a=o.set.substring(t+1);if(!k(r)){console.log(""),console.log(e.red(` Unknown flag: ${r}`)),console.log(e.gray(` Valid flags: ${g.join(", ")}`)),console.log(""),process.exit(1);return}if(a!=="true"&&a!=="false"){console.log(""),console.log(e.red(` Invalid value: ${a}. Use true or false.`)),console.log(""),process.exit(1);return}let n=a==="true";d({[r]:n});let l=n?e.green("true"):e.gray("false");console.log(""),console.log(e.green(` Set ${r} = ${l}`)),console.log("");return}let s=f();console.log(""),console.log(e.bold.blue("RuVector Feature Flags:")),console.log(""),console.log(e.bold(" "+i("Flag",28)+i("Value",10)+"Description")),console.log(e.gray(" "+"-".repeat(78)));for(let t of g){let r=s[t],a=v(t,r),n=typeof r=="number"?e.cyan(String(r)):r?e.green("true"):e.gray("false"),l=a?"":e.yellow(" *"),c=D[t];console.log(" "+i(t,28)+i(String(r),10)+e.gray(c)+l)}console.log(""),console.log(e.gray(" * = modified from default")),console.log(""),console.log(e.gray(" Profiles: performance, experimental, safe")),console.log(e.gray(" Usage:")),console.log(e.gray(" aqe ruvector flags --set useNativeHNSW=true")),console.log(e.gray(" aqe ruvector flags --profile=performance")),console.log("")}function E(){let o=new h("ruvector").description("RuVector integration management").addHelpText("after",`
|
|
3
3
|
Examples:
|
|
4
4
|
$ aqe ruvector status Show native packages and flags
|
|
5
5
|
$ aqe ruvector flags List all feature flags
|
|
@@ -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,b}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.5");process.exit(0)}
|
|
2
|
+
import{a,b}from"./chunk-6QR7GSNJ.js";import"./chunk-GHFXURNS.js";export{a as RvfDualWriter,b as createDualWriter};
|
package/dist/cli/chunks/{rvf-migration-adapter-ESLGEE5X.js → rvf-migration-adapter-DZMYVJJY.js}
RENAMED
|
@@ -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,b}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.5");process.exit(0)}
|
|
2
|
+
import{a,b}from"./chunk-CGYOMD6X.js";import"./chunk-GHFXURNS.js";export{b as RvfMigrationAdapter,a as STAGE_NAMES};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{a as m,b 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.5");process.exit(0)}
|
|
2
|
+
import{a as m,b as p}from"./chunk-CGYOMD6X.js";import"./chunk-GHFXURNS.js";var v={sampleSize:50,windowDurationMs:6048e5,compactionThreshold:.3,scoreTolerance:.05},l=class{config;db=null;rvfStore=null;history=[];constructor(t){this.config={...v,...t}}setSqliteDb(t){this.db=t}setRvfStore(t){this.rvfStore=t}runCheck(){let t={timestamp:Date.now(),samplesChecked:0,divergences:0,divergenceRate:0,details:[],deadSpaceRatio:null,compactionTriggered:!1};if(!this.db||!this.rvfStore)return this.history.push(t),t;let e=this.getSampleIds(this.config.sampleSize);if(t.samplesChecked=e.length,e.length===0)return this.history.push(t),t;for(let a of e){let n=this.getSqliteEmbedding(a);if(!n){t.divergences++,t.details.push({patternId:a,issue:"missing-in-sqlite"});continue}try{let i=this.rvfStore.search(n,1);i.length===0?(t.divergences++,t.details.push({patternId:a,issue:"missing-in-rvf"})):i[0].id!==a&&i[0].score<.99&&(t.divergences++,t.details.push({patternId:a,issue:"score-mismatch",rvfScore:i[0].score}))}catch{t.divergences++,t.details.push({patternId:a,issue:"missing-in-rvf"})}}t.divergenceRate=t.samplesChecked>0?t.divergences/t.samplesChecked:0;try{let n=this.rvfStore.status().deadSpaceRatio;t.deadSpaceRatio=n??null,n!=null&&n>this.config.compactionThreshold&&(this.triggerCompaction(),t.compactionTriggered=!0)}catch{}return this.history.push(t),this.pruneHistory(),t}getRollingDivergenceRate(){let t=Date.now()-this.config.windowDurationMs,e=this.history.filter(i=>i.timestamp>=t);if(e.length===0)return 0;let a=e.reduce((i,r)=>i+r.samplesChecked,0),n=e.reduce((i,r)=>i+r.divergences,0);return a>0?n/a:0}getCheckCount(){let t=Date.now()-this.config.windowDurationMs;return this.history.filter(e=>e.timestamp>=t).length}getHistory(){let t=Date.now()-this.config.windowDurationMs;return this.history.filter(e=>e.timestamp>=t)}getSampleIds(t){if(!this.db)return[];try{return this.db.prepare("SELECT pattern_id FROM qe_pattern_embeddings ORDER BY RANDOM() LIMIT ?").all(t).map(a=>a.pattern_id)}catch{return[]}}getSqliteEmbedding(t){if(!this.db)return null;try{let e=this.db.prepare("SELECT embedding, dimension FROM qe_pattern_embeddings WHERE pattern_id = ?").get(t);return e?new Float32Array(e.embedding.buffer,e.embedding.byteOffset,e.dimension):null}catch{return null}}triggerCompaction(){try{this.rvfStore.compact?.()}catch{}}pruneHistory(){let t=Date.now()-this.config.windowDurationMs;this.history=this.history.filter(e=>e.timestamp>=t)}};var S={maxDivergenceRate2to3:1e-4,maxReadLatencyRatio2to3:2,maxFallbacks3to4:0,maxWriteLatencyRatio3to4:1.5,minChecksRequired:10},g=class{config;witnessChain=null;constructor(t){this.config={...S,...t}}setWitnessChain(t){this.witnessChain=t}evaluate(t,e,a){let n=Math.min(t+1,4);if(t>=4)return{canPromote:!1,currentStage:t,targetStage:4,checks:[],summary:"Already at maximum stage (4: RVF primary)"};if(t<2)return{canPromote:!0,currentStage:t,targetStage:n,checks:[],summary:`Stage ${t}\u2192${n} has no automated gates \u2014 manual promotion allowed`};let i=[];if(t===2){let s=e.getRollingDivergenceRate(),o=e.getCheckCount();i.push({name:"consistency-checks-count",passed:o>=this.config.minChecksRequired,actual:`${o} checks`,threshold:`>= ${this.config.minChecksRequired} checks`}),i.push({name:"divergence-rate",passed:s<=this.config.maxDivergenceRate2to3,actual:`${(s*100).toFixed(4)}%`,threshold:`<= ${(this.config.maxDivergenceRate2to3*100).toFixed(4)}%`});let c=a.sqliteReadLatencyAvgMs>0?a.rvfReadLatencyAvgMs/a.sqliteReadLatencyAvgMs:0;i.push({name:"read-latency-ratio",passed:c<=this.config.maxReadLatencyRatio2to3||a.rvfReadLatencyAvgMs===0,actual:`${c.toFixed(2)}x`,threshold:`<= ${this.config.maxReadLatencyRatio2to3}x`})}if(t===3){i.push({name:"fallback-count",passed:a.fallbacksUsed<=this.config.maxFallbacks3to4,actual:`${a.fallbacksUsed} fallbacks`,threshold:`<= ${this.config.maxFallbacks3to4} fallbacks`});let s=a.sqliteWriteLatencyAvgMs??a.sqliteReadLatencyAvgMs,o=a.rvfWriteLatencyAvgMs??a.rvfReadLatencyAvgMs,c=s>0?o/s:0;i.push({name:"write-latency-ratio",passed:c<=this.config.maxWriteLatencyRatio3to4||o===0,actual:`${c.toFixed(2)}x`,threshold:`<= ${this.config.maxWriteLatencyRatio3to4}x`})}let r=i.length>0&&i.every(s=>s.passed),u=i.filter(s=>!s.passed).map(s=>s.name);return{canPromote:r,currentStage:t,targetStage:n,checks:i,summary:r?`All gates passed \u2014 safe to promote to stage ${n}`:`Blocked: ${u.join(", ")} failed`}}promote(t,e,a,n=!1){let i=this.evaluate(t,e,a);if(!i.canPromote&&!n)return this.recordWitness("QUALITY_GATE_FAIL",{action:"stage-promotion-blocked",from:t,to:i.targetStage,failedChecks:i.checks.filter(u=>!u.passed),summary:i.summary}),{promoted:!1,newStage:t,result:i};let r=i.targetStage;return this.recordWitness("QUALITY_GATE_PASS",{action:n?"stage-promotion-forced":"stage-promotion-approved",from:t,to:r,checks:i.checks,forced:n,summary:i.summary}),{promoted:!0,newStage:r,result:i}}recordWitness(t,e){try{this.witnessChain?.append(t,e,"rvf-stage-gate")}catch{}}};var d=null,f=class h{adapter;validator;gate;currentStage;initialized=!1;constructor(t){this.currentStage=t?.stage??1,this.adapter=new p({stage:this.currentStage,rvfPath:t?.rvfPath??".agentic-qe/patterns.rvf",dimensions:t?.dimensions??384,enableFallback:!0}),this.validator=new l({sampleSize:50,windowDurationMs:10080*60*1e3,compactionThreshold:.3,scoreTolerance:.05}),this.gate=new g({minChecksRequired:10})}attachSqliteDb(t){this.adapter.setSqliteDb(t),this.validator.setSqliteDb(t)}attachRvfStore(t){this.adapter.setRvfStore(t),this.validator.setRvfStore(t)}attachWitnessChain(t){this.gate.setWitnessChain(t)}async initialize(){if(!this.initialized){if(this.currentStage===1)try{let{getRvfMigrationStage:t}=await import("./feature-flags-WBF5B6WE.js"),e=t();this.currentStage=e,this.adapter.setStage(e)}catch{}try{let{UnifiedMemoryManager:t}=await import("./unified-memory-3D4VDY4G.js"),e=t.getInstance();await e.initialize();let a=e.getDatabase();a&&this.attachSqliteDb(a)}catch{}try{let{getSharedRvfAdapter:t}=await import("./shared-rvf-adapter-PLZVKKW7.js"),e=t();e&&this.attachRvfStore(e)}catch{}try{let{WitnessChain:t}=await import("./witness-chain-CS76OJFL.js"),e=new t;await e.initialize(),this.attachWitnessChain(e)}catch{}this.initialized=!0}}getStatus(){let t=this.adapter.getMetrics(),e=this.adapter.status(),a=this.validator.getHistory(),n=this.gate.evaluate(this.currentStage,this.validator,t);return{stage:this.currentStage,stageName:m[this.currentStage],metrics:t,consistencyHistory:{totalChecks:this.validator.getCheckCount(),rollingDivergenceRate:this.validator.getRollingDivergenceRate(),lastCheck:a.length>0?a[a.length-1]:null},gateEvaluation:n,engineStatus:{sqliteVectorCount:e.sqlite.vectorCount,rvfAvailable:e.rvf!==null,rvfVectorCount:e.rvf?.totalVectors??null,rvfDeadSpaceRatio:e.rvf?.deadSpaceRatio??null}}}runConsistencyCheck(){return this.validator.runCheck()}evaluateGate(){return this.gate.evaluate(this.currentStage,this.validator,this.adapter.getMetrics())}promote(t=!1){let e=this.currentStage,{promoted:a,newStage:n,result:i}=this.gate.promote(this.currentStage,this.validator,this.adapter.getMetrics(),t);return a&&(this.currentStage=n,this.adapter.setStage(n)),{promoted:a,previousStage:e,newStage:n,result:i}}write(t,e){return this.adapter.write(t,e)}search(t,e){return this.adapter.search(t,e)}getAdapter(){return this.adapter}static getInstance(t){return d||(d=new h(t)),d}static resetInstance(){d=null}};export{f as RvfMigrationCoordinator};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b,c,d,f as e}from"./chunk-HA4COQ66.js";import"./chunk-GHFXURNS.js";e();export{a as createRvfStore,d as isRvfNativeAvailable,b as openRvfStore,c as openRvfStoreReadonly};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b}from"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-GHFXURNS.js";b();export{a as openDatabase};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a}from"./chunk-35DP6LX6.js";import"./chunk-YZ3WB4TN.js";import"./chunk-6VB4VZCR.js";import"./chunk-HT5EZYPZ.js";import"./chunk-I4HGIQC2.js";import"./chunk-Z2GK7COI.js";import"./chunk-OQCEI7Q4.js";import"./chunk-CNGRXBKO.js";import"./chunk-MYIDAWGQ.js";import"./chunk-TRO45ZLC.js";import"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-WIZOYPFT.js";import"./chunk-TSA5MUTQ.js";import"./chunk-4QGNSNQL.js";import"./chunk-UPFCV7MX.js";import"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import"./chunk-2XJRSIM5.js";import"./chunk-GHFXURNS.js";export{a as TestScheduleTool};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b,c,d}from"./chunk-MRTDOSHR.js";import"./chunk-45WEXMKC.js";import"./chunk-CNGRXBKO.js";import"./chunk-DFOANC7Z.js";import"./chunk-MYIDAWGQ.js";import"./chunk-GHFXURNS.js";export{a as PersistentScheduler,b as createPersistentScheduler,d as createScheduleEntry,c as generateScheduleId};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{b as h}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.5");process.exit(0)}
|
|
2
|
+
import{b as h}from"./chunk-MO3IIM7L.js";import{c as g,d as f,e as S,i as w}from"./chunk-QHMDETCU.js";import"./chunk-GHFXURNS.js";import{Command as b}from"commander";import e from"chalk";function P(v,a,k){return new b("security").description("Security scanning and URL validation").option("--sast","Run SAST scan").option("--dast","Run DAST scan").option("--compliance <frameworks>","Check compliance (gdpr,hipaa,soc2)","").option("--url-validate <url>","Validate a URL for security threats and PII exposure").option("--no-pii","Disable PII scanning when using --url-validate").option("-t, --target <path>","Target directory to scan",".").option("-F, --format <format>","Output format (text|json|sarif|markdown)","text").option("-o, --output <path>","Write output to file").action(async r=>{if(await k()){if(r.urlValidate){try{let o=r.format,u=r.urlValidate;o==="text"&&console.log(e.blue(`
|
|
3
3
|
Validating URL: ${u}
|
|
4
|
-
`));let{VisualSecurityTool:y}=await import("./visual-security-
|
|
4
|
+
`));let{VisualSecurityTool:y}=await import("./visual-security-ZBNB7LEG.js"),c=await new y().invoke({url:u,enablePII:r.pii!==!1});if(c.success&&c.data){let t=c.data;if(o==="json")g(f(t),r.output);else{if(t.urlSecurity.valid)console.log(e.green(" URL Security: CLEAN"));else{console.log(e.red(` URL Security: ${t.urlSecurity.issues.length} issue(s) (risk: ${t.urlSecurity.riskLevel})`));for(let s of t.urlSecurity.issues){let i=s.severity==="critical"?e.red:s.severity==="high"?e.yellow:e.gray;console.log(i(` [${s.severity}] ${s.type}: ${s.description}`))}}if(t.piiExposure.scanned)if(t.piiExposure.found){console.log(e.red(`
|
|
5
5
|
PII Exposure: ${t.piiExposure.types.length} type(s) found in URL`));for(let s of t.piiExposure.details)console.log(e.yellow(` [${s.type}] in ${s.location}: ${s.masked}`))}else console.log(e.green(`
|
|
6
6
|
PII Exposure: none detected`));console.log(`
|
|
7
7
|
${t.summary}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b,d as c}from"./chunk-WV7K5A7J.js";import"./chunk-HA4COQ66.js";import"./chunk-GHFXURNS.js";c();export{a as getSharedRvfAdapter,b as resetSharedRvfAdapter};
|
package/dist/cli/chunks/{shared-rvf-dual-writer-ZFNW4C3N.js → shared-rvf-dual-writer-2PUFIGX5.js}
RENAMED
|
@@ -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,b,c,d}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.5");process.exit(0)}
|
|
2
|
+
import{a,b,c,d}from"./chunk-BYD54ZUF.js";import"./chunk-GHFXURNS.js";export{c as getSharedMigrationAdapter,a as getSharedRvfDualWriter,b as getSharedRvfDualWriterSync,d as resetSharedRvfDualWriter};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a,b,c,d}from"./chunk-3UE5GART.js";import"./chunk-LPVQ6QCW.js";import"./chunk-HT5EZYPZ.js";import"./chunk-I4HGIQC2.js";import"./chunk-Z2GK7COI.js";import"./chunk-OQCEI7Q4.js";import"./chunk-CNGRXBKO.js";import"./chunk-MYIDAWGQ.js";import"./chunk-TRO45ZLC.js";import"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-WIZOYPFT.js";import"./chunk-TSA5MUTQ.js";import"./chunk-4QGNSNQL.js";import"./chunk-UPFCV7MX.js";import"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import"./chunk-2XJRSIM5.js";import"./chunk-GHFXURNS.js";export{a as DEFAULT_SQLITE_CONFIG,c as SQLitePatternStore,d as createSQLitePatternStore,b as hashEmbedding};
|
|
@@ -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 m,c as y}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.5");process.exit(0)}
|
|
2
|
+
import{a as m,c as y}from"./chunk-3DGO7NJK.js";import{c as g,d as h}from"./chunk-QHMDETCU.js";import"./chunk-GHFXURNS.js";import t from"chalk";var p=class{name="status";description="Show system status";cleanupAndExit;ensureInitialized;constructor(o,n){this.cleanupAndExit=o,this.ensureInitialized=n}register(o,n){o.command("status").description(this.description).option("-v, --verbose","Show detailed status").option("-F, --format <format>","Output format (text|json)","text").option("-o, --output <path>","Write output to file").action(async a=>{await this.executeStatus(a,n)})}async executeStatus(o,n){if(await this.ensureInitialized())try{let a=n.queen.getHealth(),e=n.queen.getMetrics();if((o.format||"text")==="json"){let s={};if(o.verbose)for(let[i,l]of a.domainHealth)s[i]={status:l.status,agents:l.agents,errors:l.errors.length};g(h({status:a.status,uptime:e.uptime,workStealing:a.workStealingActive,agents:{total:a.totalAgents,active:a.activeAgents,utilization:e.agentUtilization},tasks:{received:e.tasksReceived,completed:e.tasksCompleted,failed:e.tasksFailed,pending:a.pendingTasks,running:a.runningTasks,stolen:e.tasksStolen},coordination:{protocols:e.protocolsExecuted,workflows:e.workflowsExecuted},...o.verbose?{domains:s}:{},issues:a.issues}),o.output),await this.cleanupAndExit(0);return}if(console.log(t.blue(`
|
|
3
3
|
AQE v3 Status
|
|
4
4
|
`)),console.log(` Status: ${m(a.status)}`),console.log(` Uptime: ${t.cyan(y(e.uptime))}`),console.log(` Work Stealing: ${a.workStealingActive?t.green("active"):t.gray("inactive")}`),console.log(t.blue(`
|
|
5
5
|
Agents:`)),console.log(` Total: ${t.cyan(a.totalAgents)}`),console.log(` Active: ${t.yellow(a.activeAgents)}`),console.log(` Utilization: ${t.cyan((e.agentUtilization*100).toFixed(1))}%`),console.log(t.blue(`
|
|
@@ -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 l}from"./chunk-
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.5");process.exit(0)}
|
|
2
|
+
import{a as l}from"./chunk-CQT3IEEX.js";import"./chunk-TRRJP27A.js";import"./chunk-ZWS7J73Q.js";import"./chunk-2XJRSIM5.js";import"./chunk-GHFXURNS.js";var s={healthyThreshold:.4,warningThreshold:.2,maxHistoryEntries:100,enableLogging:!1},n=class{config;minCutService;history=[];constructor(t){this.config={...s,...t},this.minCutService=l()}computeFleetHealth(t){if(t.length===0)return this.emptyFleetResult();let r=this.minCutService.buildTaskGraphFromTopology(t);return this.computeFleetHealthFromGraph(r,t.length)}computeFleetHealthFromGraph(t,r){if(t.nodes.length===0)return this.emptyFleetResult();let e=this.minCutService.getStructuralHealth(t),o=this.determineStatus(e.normalizedLambda),a={lambda:e.lambda,healthy:e.healthy,weakPoints:e.weakPoints,normalizedLambda:e.normalizedLambda,riskScore:e.riskScore,status:o,suggestions:e.suggestions,measuredAt:new Date};return this.addHistoryEntry({lambda:e.lambda,healthy:e.healthy,weakPointCount:e.weakPoints.length,agentCount:r??t.nodes.length,timestamp:a.measuredAt}),this.config.enableLogging&&this.logHealth(a),a}getTrend(){if(this.history.length<2)return"stable";let t=Math.min(5,this.history.length),r=this.history.slice(-t),e=r[0].lambda,a=r[r.length-1].lambda-e;return Math.abs(a)<.05?"stable":a>0?"improving":"degrading"}getHistory(t){let r=[...this.history];return t!==void 0&&t<r.length?r.slice(-t):r}clearHistory(){this.history.length=0}getMinCutService(){return this.minCutService}determineStatus(t){return t>=this.config.healthyThreshold?"healthy":t>=this.config.warningThreshold?"warning":"critical"}addHistoryEntry(t){this.history.push(t),this.history.length>this.config.maxHistoryEntries&&this.history.splice(0,this.history.length-this.config.maxHistoryEntries)}emptyFleetResult(){return{lambda:0,healthy:!1,weakPoints:[],normalizedLambda:0,riskScore:1,status:"empty",suggestions:["No agents in fleet. Spawn agents to build a topology."],measuredAt:new Date}}logHealth(t){console.error(`[StructuralHealth] Status: ${t.status} | Lambda: ${t.normalizedLambda.toFixed(3)} | Weak points: ${t.weakPoints.length} | Risk: ${(t.riskScore*100).toFixed(0)}%`)}};function d(i){return new n(i)}export{s as DEFAULT_STRUCTURAL_HEALTH_CONFIG,n as StructuralHealthMonitor,d as createStructuralHealthMonitor};
|
|
@@ -1,23 +1,23 @@
|
|
|
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"./chunk-ZTIPMKUS.js";import{b as R,c as w,d as x,f as te,o as pe}from"./chunk-LQDAH47F.js";import"./chunk-RRELDHZY.js";import{a as P}from"./chunk-FONTSK2O.js";import{c as h}from"./chunk-6N26CWST.js";import{a as Re,b as j,d as ee}from"./chunk-CU36MONI.js";import{a as l,b as q,c as v}from"./chunk-OXR2FPHK.js";import{f as z}from"./chunk-EVIXQR4O.js";import{a as $,b as F}from"./chunk-DBEU5ISS.js";import"./chunk-GGKV5IQR.js";import"./chunk-ZMUVSL5Q.js";import"./chunk-WSVWVIVR.js";import"./chunk-TPFE3BAI.js";import{d as Ce}from"./chunk-OV6H3TRU.js";import"./chunk-M7PGW5Z5.js";import"./chunk-UC3RA5LW.js";import"./chunk-OJKGRB6D.js";import{f as Ee}from"./chunk-7ASGPJWU.js";import{Command as Ie}from"commander";import a from"chalk";import O from"ora";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]};var m={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};F();x();ee();v();P();import*as ne from"fs";import*as fe from"path";var W=h.create("sqlite-reader"),U=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=fe.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!ne.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=$(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${l(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${R(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${l(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),o=`SELECT * FROM ${R(n)} WHERE ${t} > ?`;try{return this.db.prepare(o).all(r).map(d=>this.transformRecord(d))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${R(e)}`).get().count}catch(t){return W.debug("Record count query failed",{table:e,error:l(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return W.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let o=this.db.prepare(`PRAGMA table_info(${R(e)})`).all().map(s=>s.name.toLowerCase());for(let s of t)if(o.includes(s))return s}catch(n){return W.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=j(r)}catch(o){W.debug("JSON parse failed for record field",{key:n,error:o instanceof Error?o.message:String(o)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let o=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,o))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=ne.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(i){return new U(i)}var ye=Ee(Re(),1);v();import{randomUUID as Te}from"crypto";import*as T from"fs";import*as he from"path";var B=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=he.resolve(e.baseDir,e.source.path)}async initialize(){if(!T.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=T.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!T.existsSync(this.filePath))return[];try{let e=T.readFileSync(this.filePath,"utf-8"),t=ye.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${l(e)}`),[]}}async readChanged(e){return T.existsSync(this.filePath)?T.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([o,s])=>({state:o,...typeof s=="object"?s:{value:s}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,o]of Object.entries(n)){if(r.startsWith("_"))continue;let s="general";r.includes("adr")?s="adr-analysis":r.includes("agent")?s="agent-patterns":r.includes("pattern")?s="patterns":r.includes("metric")&&(s="metrics"),t.push({key:r,value:typeof o=="object"?o:{data:o},category:s})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[o,s]of Object.entries(r))if(typeof s=="object"&&s!==null)for(let[c,d]of Object.entries(s)){let u=typeof d=="object"?d:{value:d};t.push({state:o,action:c,q_value:u.value||u.q_value||0,visits:u.visits||0,last_update:u.lastUpdate||u.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let o=r;t.push({id:o.id||`mem_${Date.now()}_${Te().slice(0,12)}`,memory_type:o.type||"file_access",content:o.content||o.path,embedding:o.embedding,metadata:o.metadata,timestamp:o.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[o,s]of Object.entries(r))if(typeof s=="object"&&s!==null){let c=s;t.push({worker_type:o,run_count:c.runCount||c.runs||0,success_count:c.successCount||c.successes||0,failure_count:c.failureCount||c.failures||0,avg_duration_ms:c.avgDuration||c.averageDurationMs,last_run:c.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=T.existsSync(this.filePath),t=0,n=null;if(e){let r=T.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function oe(i){return new B(i)}P();import{spawn as ve}from"child_process";import{createConnection as Pe}from"net";var _e=h.create("tunnel-manager");function be(i){try{let e=new URL(i);return e.password&&(e.password="***"),e.toString()}catch(e){return _e.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),i.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var J=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let o=Pe({host:e,port:t}),s=setTimeout(()=>{o.destroy(),r(!1)},n);o.on("connect",()=>{clearTimeout(s),o.destroy(),r(!0)}),o.on("error",()=>{clearTimeout(s),o.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=ve("gcloud",r,{stdio:["ignore","pipe","pipe"]});let o=!1,s="",c=!1;this.process.stderr?.on("data",d=>{let u=d.toString();console.log(`[TunnelManager] ${u.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(y=>u.includes(y))&&!o&&!c&&(c=!0,setTimeout(async()=>{for(let p=0;p<10;p++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${p+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){o=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(S=>setTimeout(S,1e3))}c=!1},2e3)),s+=u}),this.process.stdout?.on("data",d=>{let u=d.toString();console.log(`[TunnelManager] ${u.trim()}`)}),this.process.on("error",d=>{console.error(`[TunnelManager] Process error: ${d.message}`),o||n(new Error(`Failed to start tunnel: ${d.message}`))}),this.process.on("close",d=>{console.log(`[TunnelManager] Process closed with code ${d}`),this.process=null,this.connection=null,o||n(new Error(`Tunnel process exited with code ${d}: ${s}`))}),setTimeout(()=>{o||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,o=this.connection.port;return`postgresql://${t}:${n}@${r}:${o}/${e}`}getRedactedConnectionString(){return be(this.getConnectionString())}};var Q=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return be(this.connectionString)}};function M(i){return i.connectionString?new Q(i.connectionString):new J(i)}x();v();P();import{createRequire as $e}from"module";var D=h.create("postgres-writer"),xe=$e(import.meta.url),G=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=xe("pg")}catch(s){D.debug("pg module not installed, using mock mode",{error:s instanceof Error?s.message:String(s)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let o={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(o),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],o=Object.keys(r),s=n?.conflictColumns||this.inferConflictColumns(e,o),c=n?.updateColumns||o.filter(g=>!s.includes(g)),d=0,u=100;for(let g=0;g<t.length;g+=u){let E=t.slice(g,g+u);try{let y=await this.upsertBatch(e,E,o,s,c,n?.skipIfExists);d+=y}catch(y){let p=Math.floor(g/u)+1,b=Math.ceil(t.length/u);D.debug(`Batch ${p}/${b} failed for ${e}, retrying individually`,{error:l(y)});let S=0;for(let f of E)try{let C=await this.upsertBatch(e,[f],o,s,c,n?.skipIfExists);S+=C}catch(C){let L=f.id||f.key||"?";D.debug(`Skipped record ${String(L).slice(0,50)} in ${e}`,{error:l(C)})}d+=S,S<E.length&&console.warn(`[PostgresWriter] Batch ${p}/${b} for ${e}: ${S}/${E.length} recovered (${E.length-S} skipped)`)}}return d}async upsertBatch(e,t,n,r,o,s){if(!this.client)return 0;let c=[],d=[],u=1;for(let f of t){let C=[];for(let L of n){let we=f[L];C.push(`$${u++}`),d.push(this.serializeValue(we,L))}c.push(`(${C.join(", ")})`)}let g=w(e),E=n.map(w),y=r.map(w),p=o.map(w),b="";if(y.length>0){if(s)b=`ON CONFLICT (${y.join(", ")}) DO NOTHING`;else if(p.length>0){let f=p.map(C=>`${C} = EXCLUDED.${C}`).join(", ");b=`ON CONFLICT (${y.join(", ")}) DO UPDATE SET ${f}`}}let S=`
|
|
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.5");process.exit(0)}
|
|
2
|
+
import{a as fe}from"./chunk-IHXDXFUX.js";import"./chunk-GFZRXQWH.js";import{b as R,c as w,d as x,f as ne,o as pe}from"./chunk-HT5EZYPZ.js";import"./chunk-I4HGIQC2.js";import{a as P}from"./chunk-Z2GK7COI.js";import{c as h}from"./chunk-OQCEI7Q4.js";import{a as Te,b as F,d as te}from"./chunk-CNGRXBKO.js";import{a as l,b as q,c as v}from"./chunk-MYIDAWGQ.js";import{f as z}from"./chunk-TRO45ZLC.js";import{a as $,b as j}from"./chunk-YDBMYTOV.js";import"./chunk-ALX5RJSR.js";import"./chunk-WIZOYPFT.js";import"./chunk-TSA5MUTQ.js";import"./chunk-4QGNSNQL.js";import{d as Re}from"./chunk-UPFCV7MX.js";import"./chunk-PMFZHFCB.js";import"./chunk-3QH67ZYC.js";import"./chunk-2XJRSIM5.js";import{f as Ce}from"./chunk-GHFXURNS.js";import{Command as Le}from"commander";import a from"chalk";import O from"ora";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]};var m={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};j();x();te();v();P();import*as re from"fs";import*as he from"path";var W=h.create("sqlite-reader"),U=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=he.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!re.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=$(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${l(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${R(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${l(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),o=`SELECT * FROM ${R(n)} WHERE ${t} > ?`;try{return this.db.prepare(o).all(r).map(d=>this.transformRecord(d))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${R(e)}`).get().count}catch(t){return W.debug("Record count query failed",{table:e,error:l(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return W.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let o=this.db.prepare(`PRAGMA table_info(${R(e)})`).all().map(s=>s.name.toLowerCase());for(let s of t)if(o.includes(s))return s}catch(n){return W.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=F(r)}catch(o){W.debug("JSON parse failed for record field",{key:n,error:o instanceof Error?o.message:String(o)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let o=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,o))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=re.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function oe(i){return new U(i)}var be=Ce(Te(),1);v();import{randomUUID as ve}from"crypto";import*as T from"fs";import*as ye from"path";var B=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=ye.resolve(e.baseDir,e.source.path)}async initialize(){if(!T.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=T.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!T.existsSync(this.filePath))return[];try{let e=T.readFileSync(this.filePath,"utf-8"),t=be.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${l(e)}`),[]}}async readChanged(e){return T.existsSync(this.filePath)?T.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let o of n)if(r&&typeof r=="object"&&o in r)r=r[o];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([o,s])=>({state:o,...typeof s=="object"?s:{value:s}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,o]of Object.entries(n)){if(r.startsWith("_"))continue;let s="general";r.includes("adr")?s="adr-analysis":r.includes("agent")?s="agent-patterns":r.includes("pattern")?s="patterns":r.includes("metric")&&(s="metrics"),t.push({key:r,value:typeof o=="object"?o:{data:o},category:s})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[o,s]of Object.entries(r))if(typeof s=="object"&&s!==null)for(let[c,d]of Object.entries(s)){let u=typeof d=="object"?d:{value:d};t.push({state:o,action:c,q_value:u.value||u.q_value||0,visits:u.visits||0,last_update:u.lastUpdate||u.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let o=r;t.push({id:o.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:o.type||"file_access",content:o.content||o.path,embedding:o.embedding,metadata:o.metadata,timestamp:o.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[o,s]of Object.entries(r))if(typeof s=="object"&&s!==null){let c=s;t.push({worker_type:o,run_count:c.runCount||c.runs||0,success_count:c.successCount||c.successes||0,failure_count:c.failureCount||c.failures||0,avg_duration_ms:c.avgDuration||c.averageDurationMs,last_run:c.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=T.existsSync(this.filePath),t=0,n=null;if(e){let r=T.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function se(i){return new B(i)}P();import{spawn as Pe}from"child_process";import{createConnection as _e}from"net";var $e=h.create("tunnel-manager");function Se(i){try{let e=new URL(i);return e.password&&(e.password="***"),e.toString()}catch(e){return $e.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),i.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var J=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let o=_e({host:e,port:t}),s=setTimeout(()=>{o.destroy(),r(!1)},n);o.on("connect",()=>{clearTimeout(s),o.destroy(),r(!0)}),o.on("error",()=>{clearTimeout(s),o.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=Pe("gcloud",r,{stdio:["ignore","pipe","pipe"]});let o=!1,s="",c=!1;this.process.stderr?.on("data",d=>{let u=d.toString();console.log(`[TunnelManager] ${u.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(y=>u.includes(y))&&!o&&!c&&(c=!0,setTimeout(async()=>{for(let p=0;p<10;p++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${p+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){o=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(S=>setTimeout(S,1e3))}c=!1},2e3)),s+=u}),this.process.stdout?.on("data",d=>{let u=d.toString();console.log(`[TunnelManager] ${u.trim()}`)}),this.process.on("error",d=>{console.error(`[TunnelManager] Process error: ${d.message}`),o||n(new Error(`Failed to start tunnel: ${d.message}`))}),this.process.on("close",d=>{console.log(`[TunnelManager] Process closed with code ${d}`),this.process=null,this.connection=null,o||n(new Error(`Tunnel process exited with code ${d}: ${s}`))}),setTimeout(()=>{o||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,o=this.connection.port;return`postgresql://${t}:${n}@${r}:${o}/${e}`}getRedactedConnectionString(){return Se(this.getConnectionString())}};var Q=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return Se(this.connectionString)}};function k(i){return i.connectionString?new Q(i.connectionString):new J(i)}x();v();P();import{createRequire as xe}from"module";var M=h.create("postgres-writer"),Ae=xe(import.meta.url),G=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=Ae("pg")}catch(s){M.debug("pg module not installed, using mock mode",{error:s instanceof Error?s.message:String(s)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let o={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(o),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],o=Object.keys(r),s=n?.conflictColumns||this.inferConflictColumns(e,o),c=n?.updateColumns||o.filter(g=>!s.includes(g)),d=0,u=100;for(let g=0;g<t.length;g+=u){let E=t.slice(g,g+u);try{let y=await this.upsertBatch(e,E,o,s,c,n?.skipIfExists);d+=y}catch(y){let p=Math.floor(g/u)+1,b=Math.ceil(t.length/u);M.debug(`Batch ${p}/${b} failed for ${e}, retrying individually`,{error:l(y)});let S=0;for(let f of E)try{let C=await this.upsertBatch(e,[f],o,s,c,n?.skipIfExists);S+=C}catch(C){let L=f.id||f.key||"?";M.debug(`Skipped record ${String(L).slice(0,50)} in ${e}`,{error:l(C)})}d+=S,S<E.length&&console.warn(`[PostgresWriter] Batch ${p}/${b} for ${e}: ${S}/${E.length} recovered (${E.length-S} skipped)`)}}return d}async upsertBatch(e,t,n,r,o,s){if(!this.client)return 0;let c=[],d=[],u=1;for(let f of t){let C=[];for(let L of n){let Ee=f[L];C.push(`$${u++}`),d.push(this.serializeValue(Ee,L))}c.push(`(${C.join(", ")})`)}let g=w(e),E=n.map(w),y=r.map(w),p=o.map(w),b="";if(y.length>0){if(s)b=`ON CONFLICT (${y.join(", ")}) DO NOTHING`;else if(p.length>0){let f=p.map(C=>`${C} = EXCLUDED.${C}`).join(", ");b=`ON CONFLICT (${y.join(", ")}) DO UPDATE SET ${f}`}}let S=`
|
|
3
3
|
INSERT INTO ${g} (${E.join(", ")})
|
|
4
4
|
VALUES ${c.join(", ")}
|
|
5
5
|
${b}
|
|
6
|
-
`;try{return(await this.client.query(S,d)).rowCount||0}catch(f){throw
|
|
6
|
+
`;try{return(await this.client.query(S,d)).rowCount||0}catch(f){throw M.debug(`Upsert failed for ${e}`,{error:l(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){M.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function D(i){return new G(i)}x();v();P();var V=h.create("postgres-reader"),H=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${w(n)}.${w(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let o=await this.writer.query(n,r);return V.debug(`Read ${o.length} records from ${e.cloudTable}`,{env:this.environment}),o.map(s=>this.transformRecord(s,e))}catch(o){throw new Error(`Failed to read from ${e.cloudTable}: ${l(o)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return V.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let o,s;this.environment!=="all"?(o=`SELECT * FROM ${n} WHERE ${w(r)} > $1 AND source_env = $2`,s=[t.toISOString(),this.environment]):(o=`SELECT * FROM ${n} WHERE ${w(r)} > $1`,s=[t.toISOString()]);try{return(await this.writer.query(o,s)).map(d=>this.transformRecord(d,e))}catch(c){return V.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:l(c)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(n,r);return await this.writer.commit(),typeof o[0]?.count=="string"?parseInt(o[0].count,10):o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}return V.debug(`Count query failed for ${e.cloudTable}`,{error:l(o)}),-1}}transformRecord(e,t){let n={};for(let[r,o]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let s=t.columnMap?.[r]||r;n[s]=this.transformValue(o,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],s=(await this.writer.query(`SELECT column_name FROM information_schema.columns
|
|
7
7
|
WHERE table_schema = $1 AND table_name = $2
|
|
8
|
-
AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(c=>c.column_name);for(let c of t)if(s.includes(c))return c;return s[0]||null}catch{return null}}};function se(i){return new H(i)}F();x();v();P();import*as Se from"fs";var N=h.create("sqlite-writer"),X=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!Se.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=$(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),N.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${l(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=R(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return N.debug(`No columns found for table ${e}`),0;let o=new Set(r),s=0;for(let c=0;c<t.length;c+=this.batchSize){let d=t.slice(c,c+this.batchSize);try{let u=this.upsertBatch(n,d,o);s+=u}catch(u){let g=Math.floor(c/this.batchSize)+1;N.debug(`Batch ${g} failed for ${e}, retrying individually`,{error:l(u)});let E=0;for(let y of d)try{E+=this.upsertBatch(n,[y],o)}catch(p){let b=y.id||y.key||"?";N.debug(`Skipped record ${String(b).slice(0,50)} in ${e}`,{error:l(p)})}s+=E}}return s}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=R(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,N.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=R(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=R(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(o=>o.pk>0).sort((o,s)=>o.pk-s.pk).map(o=>o.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],o=Object.keys(r).filter(p=>n.has(p));if(o.length===0)return 0;let s=o.map(w),c=o.map(()=>"?").join(", "),d=e.replace(/"/g,""),u=this.getPrimaryKeyColumns(d),g;if(u.length>0){let p=u.map(w),b=o.filter(S=>!u.includes(S));if(b.length>0){let S=b.map(f=>`${w(f)} = excluded.${w(f)}`).join(", ");g=`INSERT INTO ${e} (${s.join(", ")}) VALUES (${c}) ON CONFLICT(${p.join(", ")}) DO UPDATE SET ${S}`}else g=`INSERT OR IGNORE INTO ${e} (${s.join(", ")}) VALUES (${c})`}else g=`INSERT OR IGNORE INTO ${e} (${s.join(", ")}) VALUES (${c})`;let E=this.db.prepare(g);return this.db.transaction(p=>{let b=0;for(let S of p){let f=o.map(C=>this.serializeValue(S[C]));E.run(...f),b++}return b})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function ie(i){return new X(i)}P();v();var Ae=h.create("sync-agent"),Y=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...m,...e,local:{...m.local,...e.local},cloud:{...m.cloud,...e.cloud},sync:{...m.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,o)=>{let s={high:0,medium:1,low:2};return s[r.priority]-s[o.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let o=await this.syncSource(r);this.report.results.push(o),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(l(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,o)=>{let s={high:0,medium:1,low:2};return s[r.priority]-s[o.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let o=await this.syncSourceIncremental(r,t);this.report.results.push(o)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(l(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let o=await r.readAll();if(this.log(`Read ${o.length} records from ${e.name}`),o.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o,{skipIfExists:e.mode==="append"});n.recordsSynced=s}else n.recordsSynced=o.length,this.log(`[DRY RUN] Would sync ${o.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=l(r),this.config.onError?.(q(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let o=this.readers.get(e.name);if(!o)throw new Error(`Reader not found: ${e.name}`);let s=await o.readChanged(t);if(this.log(`Read ${s.length} changed records from ${e.name} (since ${t.toISOString()})`),s.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let c=await this.writer.upsert(e.targetTable,s);r.recordsSynced=c}else r.recordsSynced=s.length;r.success=!0}catch(o){r.error=l(o)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),o=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let s=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),o=s[0]?.count||0}catch(s){try{await this.writer.rollback()}catch{}Ae.debug("Cloud count query failed",{source:t.name,error:s instanceof Error?s.message:String(s)}),o=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:o,match:r===o,diff:r-o})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?oe({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=M(this.config.cloud);this.writer=k({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:z(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function _(i){return new Y(i)}async function ae(i){let e=_({...i,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function ce(i,e){let t=_({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(i)}finally{await t.close()}}import*as Z from"fs";import*as le from"path";pe();v();P();var Nt=h.create("pull-agent"),K=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...A,...e,cloud:{...A.cloud,...e.cloud},sources:e.sources||A.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=M(this.config.cloud);this.cloudWriter=k({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=se({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=ie({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(l(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let o=await this.pullTableIncremental(r,t);this.report.results.push(o)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(l(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let o=await this.writer.upsert(e.localTable,r);n.recordsSynced=o,n.recordsSkipped=r.length-o}n.success=!0}catch(r){n.error=l(r),this.config.onError?.(q(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let o=await this.reader.readChanged(e,t);if(this.log(`Read ${o.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=o.length;else{let s=await this.writer.upsert(e.localTable,o);r.recordsSynced=s}r.success=!0}catch(o){r.error=l(o)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?le.resolve(this.config.targetDb):le.resolve(te(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Z.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Z.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${l(r)}`,"warn")}}createReport(e){return{syncId:z(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function de(i){return new K(i)}async function ue(i){let e=de({...i,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function me(i,e){let t=de({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(i)}finally{await t.close()}}F();pe();ee();Ce();F();x();v();ee();P();import{resolve as Yt,dirname as Me}from"path";import{fileURLToPath as De}from"url";var on=h.create("sync-embedding-generator"),ke=De(import.meta.url),sn=Me(ke);v();import*as I from"fs";import*as ge from"path";function Le(){let i=new Ie("sync").description("Sync local learning data to cloud PostgreSQL");return i.option("--full","Run full sync instead of incremental").option("-e, --env <environment>","Environment identifier",process.env.AQE_ENV||"devpod").option("--dry-run","Preview sync without making changes").option("-v, --verbose","Enable verbose output").option("--since <date>","Sync changes since date (ISO 8601)").option("--sources <sources>","Comma-separated list of sources to sync").action(async e=>{let t={environment:e.env,verbose:e.verbose,sync:{...m.sync,dryRun:e.dryRun}};if(e.sources){let r=e.sources.split(",").map(o=>o.trim());t.sync.sources=m.sync.sources.filter(o=>r.includes(o.name))}let n=O("Initializing sync agent...").start();try{let r;if(e.full)n.text="Running full sync...",r=await ae(t);else{let o=e.since?new Date(e.since):void 0;n.text="Running incremental sync...",r=await ce(o,t)}n.stop(),qe(r)}catch(r){n.fail(`Sync failed: ${l(r)}`),process.exit(1)}}),i.command("pull").description("Pull cloud learning data into local SQLite database").option("-f, --full","Full pull (all cloud data)").option("-e, --env <environment>","Pull only data from specific environment","all").option("--tables <tables>","Comma-separated list of tables to pull").option("--dry-run","Preview pull without writing to local DB").option("--target <path>","Custom target SQLite database path").option("--since <date>","Pull changes since date (ISO 8601)").option("-v, --verbose","Enable verbose output").action(async e=>{let t={environment:e.env,verbose:e.verbose,dryRun:e.dryRun,targetDb:e.target};e.tables&&(t.tables=e.tables.split(",").map(r=>r.trim()));let n=O("Initializing pull sync agent...").start();try{let r;if(e.full)n.text="Pulling all data from cloud...",r=await ue(t);else{let o=e.since?new Date(e.since):void 0;n.text=`Pulling ${o?"changes since "+o.toISOString():"incremental changes (last 24h)"}...`,r=await me(o,t)}n.stop(),je(r)}catch(r){n.fail(`Pull failed: ${l(r)}`),process.exit(1)}}),i.command("status").description("Show sync status and data source information").option("-e, --env <environment>","Environment identifier",process.env.AQE_ENV||"devpod").action(async e=>{let t=O("Checking sync status...").start();try{let n=_({environment:e.env,verbose:!1});await n.initialize();let r=await n.getStatus();await n.close(),t.stop(),ze(r)}catch(n){t.fail(`Failed to get status: ${l(n)}`),process.exit(1)}}),i.command("verify").description("Verify sync integrity between local and cloud").option("-e, --env <environment>","Environment identifier",process.env.AQE_ENV||"devpod").action(async e=>{let t=O("Verifying sync integrity...").start();try{let n=_({environment:e.env,verbose:!1});await n.initialize(),t.text="Connecting to cloud...";let r=await n.verify();await n.close(),t.stop(),Fe(r)}catch(n){t.fail(`Verification failed: ${l(n)}`),process.exit(1)}}),i.command("init").description("Initialize cloud schema (requires GCP credentials)").option("--dry-run","Print schema without executing").option("-o, --output <file>","Save schema to file").action(async e=>{let t=ge.join(__dirname,"../../sync/schema/cloud-schema.sql"),n;try{n=I.readFileSync(t,"utf-8")}catch{let o=ge.join(process.cwd(),"src/sync/schema/cloud-schema.sql");n=I.readFileSync(o,"utf-8")}if(e.output){I.writeFileSync(e.output,n),console.log(a.green(`Schema saved to ${e.output}`));return}if(e.dryRun){console.log(a.cyan(`
|
|
8
|
+
AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(c=>c.column_name);for(let c of t)if(s.includes(c))return c;return s[0]||null}catch{return null}}};function ie(i){return new H(i)}j();x();v();P();import*as we from"fs";var N=h.create("sqlite-writer"),X=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!we.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=$(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),N.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${l(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=R(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return N.debug(`No columns found for table ${e}`),0;let o=new Set(r),s=0;for(let c=0;c<t.length;c+=this.batchSize){let d=t.slice(c,c+this.batchSize);try{let u=this.upsertBatch(n,d,o);s+=u}catch(u){let g=Math.floor(c/this.batchSize)+1;N.debug(`Batch ${g} failed for ${e}, retrying individually`,{error:l(u)});let E=0;for(let y of d)try{E+=this.upsertBatch(n,[y],o)}catch(p){let b=y.id||y.key||"?";N.debug(`Skipped record ${String(b).slice(0,50)} in ${e}`,{error:l(p)})}s+=E}}return s}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=R(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,N.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=R(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=R(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(o=>o.pk>0).sort((o,s)=>o.pk-s.pk).map(o=>o.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],o=Object.keys(r).filter(p=>n.has(p));if(o.length===0)return 0;let s=o.map(w),c=o.map(()=>"?").join(", "),d=e.replace(/"/g,""),u=this.getPrimaryKeyColumns(d),g;if(u.length>0){let p=u.map(w),b=o.filter(S=>!u.includes(S));if(b.length>0){let S=b.map(f=>`${w(f)} = excluded.${w(f)}`).join(", ");g=`INSERT INTO ${e} (${s.join(", ")}) VALUES (${c}) ON CONFLICT(${p.join(", ")}) DO UPDATE SET ${S}`}else g=`INSERT OR IGNORE INTO ${e} (${s.join(", ")}) VALUES (${c})`}else g=`INSERT OR IGNORE INTO ${e} (${s.join(", ")}) VALUES (${c})`;let E=this.db.prepare(g);return this.db.transaction(p=>{let b=0;for(let S of p){let f=o.map(C=>this.serializeValue(S[C]));E.run(...f),b++}return b})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function ae(i){return new X(i)}P();v();var ke=h.create("sync-agent"),Y=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...m,...e,local:{...m.local,...e.local},cloud:{...m.cloud,...e.cloud},sync:{...m.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,o)=>{let s={high:0,medium:1,low:2};return s[r.priority]-s[o.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let o=await this.syncSource(r);this.report.results.push(o),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(l(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,o)=>{let s={high:0,medium:1,low:2};return s[r.priority]-s[o.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let o=await this.syncSourceIncremental(r,t);this.report.results.push(o)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(l(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let o=await r.readAll();if(this.log(`Read ${o.length} records from ${e.name}`),o.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o,{skipIfExists:e.mode==="append"});n.recordsSynced=s}else n.recordsSynced=o.length,this.log(`[DRY RUN] Would sync ${o.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=l(r),this.config.onError?.(q(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let o=this.readers.get(e.name);if(!o)throw new Error(`Reader not found: ${e.name}`);let s=await o.readChanged(t);if(this.log(`Read ${s.length} changed records from ${e.name} (since ${t.toISOString()})`),s.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let c=await this.writer.upsert(e.targetTable,s);r.recordsSynced=c}else r.recordsSynced=s.length;r.success=!0}catch(o){r.error=l(o)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),o=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let s=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),o=s[0]?.count||0}catch(s){try{await this.writer.rollback()}catch{}ke.debug("Cloud count query failed",{source:t.name,error:s instanceof Error?s.message:String(s)}),o=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:o,match:r===o,diff:r-o})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?oe({source:e,baseDir:t,environment:n}):e.type==="json"?se({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=k(this.config.cloud);this.writer=D({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:z(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function _(i){return new Y(i)}async function ce(i){let e=_({...i,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function le(i,e){let t=_({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(i)}finally{await t.close()}}import*as Z from"fs";import*as de from"path";pe();v();P();var Ot=h.create("pull-agent"),K=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...A,...e,cloud:{...A.cloud,...e.cloud},sources:e.sources||A.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=k(this.config.cloud);this.cloudWriter=D({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=ae({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(l(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let o=await this.pullTableIncremental(r,t);this.report.results.push(o)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(l(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let o=await this.writer.upsert(e.localTable,r);n.recordsSynced=o,n.recordsSkipped=r.length-o}n.success=!0}catch(r){n.error=l(r),this.config.onError?.(q(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let o=await this.reader.readChanged(e,t);if(this.log(`Read ${o.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=o.length;else{let s=await this.writer.upsert(e.localTable,o);r.recordsSynced=s}r.success=!0}catch(o){r.error=l(o)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?de.resolve(this.config.targetDb):de.resolve(ne(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Z.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Z.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${l(r)}`,"warn")}}createReport(e){return{syncId:z(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ue(i){return new K(i)}async function me(i){let e=ue({...i,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function ge(i,e){let t=ue({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(i)}finally{await t.close()}}j();pe();te();Re();j();x();v();te();P();import{resolve as Kt,dirname as Me}from"path";import{fileURLToPath as De}from"url";var sn=h.create("sync-embedding-generator"),Ne=De(import.meta.url),an=Me(Ne);v();import*as ee from"fs";import*as I from"path";function qe(){let i=new Le("sync").description("Sync local learning data to cloud PostgreSQL");return i.option("--full","Run full sync instead of incremental").option("-e, --env <environment>","Environment identifier",process.env.AQE_ENV||"devpod").option("--dry-run","Preview sync without making changes").option("-v, --verbose","Enable verbose output").option("--since <date>","Sync changes since date (ISO 8601)").option("--sources <sources>","Comma-separated list of sources to sync").action(async e=>{let t={environment:e.env,verbose:e.verbose,sync:{...m.sync,dryRun:e.dryRun}};if(e.sources){let r=e.sources.split(",").map(o=>o.trim());t.sync.sources=m.sync.sources.filter(o=>r.includes(o.name))}let n=O("Initializing sync agent...").start();try{let r;if(e.full)n.text="Running full sync...",r=await ce(t);else{let o=e.since?new Date(e.since):void 0;n.text="Running incremental sync...",r=await le(o,t)}n.stop(),ze(r)}catch(r){n.fail(`Sync failed: ${l(r)}`),process.exit(1)}}),i.command("pull").description("Pull cloud learning data into local SQLite database").option("-f, --full","Full pull (all cloud data)").option("-e, --env <environment>","Pull only data from specific environment","all").option("--tables <tables>","Comma-separated list of tables to pull").option("--dry-run","Preview pull without writing to local DB").option("--target <path>","Custom target SQLite database path").option("--since <date>","Pull changes since date (ISO 8601)").option("-v, --verbose","Enable verbose output").action(async e=>{let t={environment:e.env,verbose:e.verbose,dryRun:e.dryRun,targetDb:e.target};e.tables&&(t.tables=e.tables.split(",").map(r=>r.trim()));let n=O("Initializing pull sync agent...").start();try{let r;if(e.full)n.text="Pulling all data from cloud...",r=await me(t);else{let o=e.since?new Date(e.since):void 0;n.text=`Pulling ${o?"changes since "+o.toISOString():"incremental changes (last 24h)"}...`,r=await ge(o,t)}n.stop(),We(r)}catch(r){n.fail(`Pull failed: ${l(r)}`),process.exit(1)}}),i.command("status").description("Show sync status and data source information").option("-e, --env <environment>","Environment identifier",process.env.AQE_ENV||"devpod").action(async e=>{let t=O("Checking sync status...").start();try{let n=_({environment:e.env,verbose:!1});await n.initialize();let r=await n.getStatus();await n.close(),t.stop(),je(r)}catch(n){t.fail(`Failed to get status: ${l(n)}`),process.exit(1)}}),i.command("verify").description("Verify sync integrity between local and cloud").option("-e, --env <environment>","Environment identifier",process.env.AQE_ENV||"devpod").action(async e=>{let t=O("Verifying sync integrity...").start();try{let n=_({environment:e.env,verbose:!1});await n.initialize(),t.text="Connecting to cloud...";let r=await n.verify();await n.close(),t.stop(),Fe(r)}catch(n){t.fail(`Verification failed: ${l(n)}`),process.exit(1)}}),i.command("init").description("Initialize cloud schema (requires GCP credentials)").option("--dry-run","Print schema without executing").option("-o, --output <file>","Save schema to file").action(async e=>{let t=[I.join(__dirname,"../../sync/schema/cloud-schema.sql")],n=fe(import.meta.url);n&&(t.push(I.join(n,"src/sync/schema/cloud-schema.sql")),t.push(I.join(n,"dist/sync/schema/cloud-schema.sql"))),t.push(I.join(process.cwd(),"src/sync/schema/cloud-schema.sql"));let r;for(let s of t)try{r=ee.readFileSync(s,"utf-8");break}catch{}if(!r)throw new Error(`Could not locate cloud-schema.sql. Searched: ${t.join(", ")}`);if(e.output){ee.writeFileSync(e.output,r),console.log(a.green(`Schema saved to ${e.output}`));return}if(e.dryRun){console.log(a.cyan(`
|
|
9
9
|
=== Cloud Schema ===
|
|
10
|
-
`)),console.log(
|
|
11
|
-
Dry run - no changes made`));return}let
|
|
10
|
+
`)),console.log(r),console.log(a.yellow(`
|
|
11
|
+
Dry run - no changes made`));return}let o=O("Initializing cloud schema...").start();try{let s=_({verbose:!0});o.info("Schema initialization requires cloud connection"),o.info("Run with --output to save schema, then apply manually"),await s.close()}catch(s){o.fail(`Init failed: ${l(s)}`),process.exit(1)}}),i.command("config").description("Show or modify sync configuration").option("--show","Show current configuration").option("--sources","List configured data sources").action(async e=>{if(e.sources){console.log(a.cyan(`
|
|
12
12
|
=== Configured Data Sources ===
|
|
13
13
|
`));for(let t of m.sync.sources){let n=t.enabled!==!1?a.green("\u2713"):a.gray("\u25CB");console.log(`${n} ${a.bold(t.name)}`),console.log(` Type: ${t.type}`),console.log(` Path: ${t.path}`),console.log(` Target: ${t.targetTable}`),console.log(` Priority: ${t.priority}`),console.log(` Mode: ${t.mode}`),console.log()}return}console.log(a.cyan(`
|
|
14
14
|
=== Sync Configuration ===
|
|
15
|
-
`)),console.log(a.bold("Environment:"),process.env.AQE_ENV||"devpod"),console.log(a.bold("Sync Mode:"),m.sync.mode),console.log(a.bold("Batch Size:"),m.sync.batchSize),console.log(a.bold("Conflict Resolution:"),m.sync.conflictResolution),console.log(),console.log(a.bold("Cloud Configuration:")),console.log(` Project: ${m.cloud.project||"(not set)"}`),console.log(` Zone: ${m.cloud.zone}`),console.log(` Instance: ${m.cloud.instance}`),console.log(` Database: ${m.cloud.database}`),console.log(` Tunnel Port: ${m.cloud.tunnelPort}`),console.log(),console.log(a.gray("Use --sources to list data sources"))}),i}function
|
|
15
|
+
`)),console.log(a.bold("Environment:"),process.env.AQE_ENV||"devpod"),console.log(a.bold("Sync Mode:"),m.sync.mode),console.log(a.bold("Batch Size:"),m.sync.batchSize),console.log(a.bold("Conflict Resolution:"),m.sync.conflictResolution),console.log(),console.log(a.bold("Cloud Configuration:")),console.log(` Project: ${m.cloud.project||"(not set)"}`),console.log(` Zone: ${m.cloud.zone}`),console.log(` Instance: ${m.cloud.instance}`),console.log(` Database: ${m.cloud.database}`),console.log(` Tunnel Port: ${m.cloud.tunnelPort}`),console.log(),console.log(a.gray("Use --sources to list data sources"))}),i}function ze(i){let e=i.status==="completed"?a.green:i.status==="partial"?a.yellow:a.red;if(console.log(a.cyan(`
|
|
16
16
|
=== Sync Report ===
|
|
17
|
-
`)),console.log(a.bold("Sync ID:"),i.syncId),console.log(a.bold("Status:"),e(i.status.toUpperCase())),console.log(a.bold("Environment:"),i.environment),console.log(a.bold("Mode:"),i.mode),console.log(a.bold("Duration:"),`${i.totalDurationMs}ms`),console.log(),console.log(a.bold("Summary:")),console.log(` Records Synced: ${a.green(i.totalRecordsSynced)}`),console.log(` Conflicts Resolved: ${a.yellow(i.totalConflictsResolved)}`),console.log(),i.results.length>0){console.log(a.bold("Results by Source:"));for(let t of i.results){let n=t.success?a.green("\u2713"):a.red("\u2717");console.log(` ${n} ${t.source}`),console.log(` Table: ${t.table}`),console.log(` Records: ${t.recordsSynced}`),console.log(` Duration: ${t.durationMs}ms`),t.error&&console.log(` Error: ${a.red(t.error)}`)}console.log()}if(i.errors.length>0){console.log(a.red("Errors:"));for(let t of i.errors)console.log(` - ${t}`)}}function
|
|
17
|
+
`)),console.log(a.bold("Sync ID:"),i.syncId),console.log(a.bold("Status:"),e(i.status.toUpperCase())),console.log(a.bold("Environment:"),i.environment),console.log(a.bold("Mode:"),i.mode),console.log(a.bold("Duration:"),`${i.totalDurationMs}ms`),console.log(),console.log(a.bold("Summary:")),console.log(` Records Synced: ${a.green(i.totalRecordsSynced)}`),console.log(` Conflicts Resolved: ${a.yellow(i.totalConflictsResolved)}`),console.log(),i.results.length>0){console.log(a.bold("Results by Source:"));for(let t of i.results){let n=t.success?a.green("\u2713"):a.red("\u2717");console.log(` ${n} ${t.source}`),console.log(` Table: ${t.table}`),console.log(` Records: ${t.recordsSynced}`),console.log(` Duration: ${t.durationMs}ms`),t.error&&console.log(` Error: ${a.red(t.error)}`)}console.log()}if(i.errors.length>0){console.log(a.red("Errors:"));for(let t of i.errors)console.log(` - ${t}`)}}function je(i){console.log(a.cyan(`
|
|
18
18
|
=== Sync Status ===
|
|
19
19
|
`)),i.lastSync&&(console.log(a.bold("Last Sync:"),i.lastSync.toISOString()),console.log()),console.log(a.bold("Data Sources:")),console.log();let e=0;for(let t of i.sources){let n=t.enabled?a.green("\u2713"):a.gray("\u25CB"),r=t.priority==="high"?a.red:t.priority==="medium"?a.yellow:a.gray;console.log(`${n} ${a.bold(t.name)}`),console.log(` Type: ${t.type}`),console.log(` Target: ${t.targetTable}`),console.log(` Records: ${a.cyan(t.recordCount)}`),console.log(` Priority: ${r(t.priority)}`),t.error&&console.log(` Error: ${a.red(t.error)}`),console.log(),e+=t.recordCount}console.log(a.bold("Total Records:"),a.cyan(e))}function Fe(i){let e=i.verified?a.green:a.red;console.log(a.cyan(`
|
|
20
20
|
=== Verification Result ===
|
|
21
|
-
`)),console.log(a.bold("Status:"),e(i.verified?"VERIFIED":"MISMATCH")),console.log(),console.log(a.bold("Table Comparison:"));for(let t of i.results){let n=t.match?a.green("\u2713"):t.cloudCount===-1?a.yellow("?"):a.red("\u2717");if(console.log(`${n} ${t.source}`),console.log(` Local: ${t.localCount}`),console.log(` Cloud: ${t.cloudCount===-1?"N/A":t.cloudCount}`),!t.match&&t.cloudCount!==-1){let r=t.diff>0?a.green:a.red;console.log(` Diff: ${r(t.diff>0?"+"+t.diff:t.diff)}`)}console.log()}}function
|
|
21
|
+
`)),console.log(a.bold("Status:"),e(i.verified?"VERIFIED":"MISMATCH")),console.log(),console.log(a.bold("Table Comparison:"));for(let t of i.results){let n=t.match?a.green("\u2713"):t.cloudCount===-1?a.yellow("?"):a.red("\u2717");if(console.log(`${n} ${t.source}`),console.log(` Local: ${t.localCount}`),console.log(` Cloud: ${t.cloudCount===-1?"N/A":t.cloudCount}`),!t.match&&t.cloudCount!==-1){let r=t.diff>0?a.green:a.red;console.log(` Diff: ${r(t.diff>0?"+"+t.diff:t.diff)}`)}console.log()}}function We(i){let e=i.status==="completed"?a.green:i.status==="partial"?a.yellow:a.red;if(console.log(a.cyan(`
|
|
22
22
|
=== Pull Sync Report (Cloud \u2192 Local) ===
|
|
23
|
-
`)),console.log(a.bold("Sync ID:"),i.syncId),console.log(a.bold("Status:"),e(i.status.toUpperCase())),console.log(a.bold("Environment:"),i.environment),console.log(a.bold("Mode:"),i.mode),console.log(a.bold("Duration:"),`${i.totalDurationMs}ms`),console.log(),console.log(a.bold("Summary:")),console.log(` Records Pulled: ${a.green(i.totalRecordsSynced)}`),console.log(),i.results.length>0){console.log(a.bold("Results by Table:"));for(let t of i.results){let n=t.success?a.green("\u2713"):a.red("\u2717");console.log(` ${n} ${t.source} \u2192 ${t.table}`),console.log(` Records: ${t.recordsSynced}`),console.log(` Duration: ${t.durationMs}ms`),t.recordsSkipped>0&&console.log(` Skipped: ${a.yellow(t.recordsSkipped)}`),t.error&&console.log(` Error: ${a.red(t.error)}`)}console.log()}if(i.errors.length>0){console.log(a.red("Errors:"));for(let t of i.errors)console.log(` - ${t}`)}}var
|
|
23
|
+
`)),console.log(a.bold("Sync ID:"),i.syncId),console.log(a.bold("Status:"),e(i.status.toUpperCase())),console.log(a.bold("Environment:"),i.environment),console.log(a.bold("Mode:"),i.mode),console.log(a.bold("Duration:"),`${i.totalDurationMs}ms`),console.log(),console.log(a.bold("Summary:")),console.log(` Records Pulled: ${a.green(i.totalRecordsSynced)}`),console.log(),i.results.length>0){console.log(a.bold("Results by Table:"));for(let t of i.results){let n=t.success?a.green("\u2713"):a.red("\u2717");console.log(` ${n} ${t.source} \u2192 ${t.table}`),console.log(` Records: ${t.recordsSynced}`),console.log(` Duration: ${t.durationMs}ms`),t.recordsSkipped>0&&console.log(` Skipped: ${a.yellow(t.recordsSkipped)}`),t.error&&console.log(` Error: ${a.red(t.error)}`)}console.log()}if(i.errors.length>0){console.log(a.red("Errors:"));for(let t of i.errors)console.log(` - ${t}`)}}var An=qe;export{qe as createSyncCommands,An as default};
|