anya_core/core/
mod.rs

1use std::sync::Arc;
2
3// Modules
4pub mod metrics;
5pub mod performance_optimization;
6pub mod reliability;
7
8// Re-exports
9pub use metrics::PrometheusMetrics;
10pub use performance_optimization::{OptimizationStatus, PerformanceOptimizer, ResourceType};
11pub use reliability::{
12    execute_with_monitoring, execute_with_recovery, AiVerification, ProgressTracker, Watchdog,
13};
14
15
16/// Core functionality with auto-save capabilities.
17/// Provides performance optimization and input processing for the Anya system.
18pub struct CoreSystem {
19    performance_optimizer: PerformanceOptimizer,
20}
21
22impl CoreSystem {
23    /// Creates a new core system with the specified auto-save frequency for each component.
24    pub fn new(auto_save_frequency: usize) -> Self {
25        Self {
26            performance_optimizer: PerformanceOptimizer::new(auto_save_frequency),
27        }
28    }
29
30    /// Returns a reference to the performance optimizer.
31    pub fn performance_optimizer(&self) -> &PerformanceOptimizer {
32        &self.performance_optimizer
33    }
34
35    /// Processes input across all components. Returns Ok if successful.
36    pub fn process_input(&self, _input: &str) -> Result<(), String> {
37        Ok(())
38    }
39
40    /// Gets stats about the auto-save state of all components.
41    /// Returns a tuple of (agent_inputs, hardening_changes, performance_changes).
42    pub fn get_auto_save_stats(&self) -> (usize, usize, usize) {
43        let (performance_changes, _, _) = self.performance_optimizer.get_stats();
44        (0, 0, performance_changes)
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51    use crate::core::ResourceType;
52    use std::collections::HashMap;
53    use std::time::Duration;
54
55    /// Integration test for CoreSystem performance optimizer and input processing.
56    #[test]
57    fn test_core_system_integration() -> Result<(), Box<dyn std::error::Error>> {
58        let core = CoreSystem::new(20);
59
60        for i in 0..25 {
61            let input = if i % 5 == 0 {
62                format!("success message {i}")
63            } else {
64                format!("normal message {i}")
65            };
66            core.process_input(&input)?;
67        }
68
69        let mut settings = HashMap::new();
70        settings.insert("cache_size".to_string(), "1024".to_string());
71
72        core.performance_optimizer().configure_resource(
73            "database",
74            ResourceType::Database,
75            settings,
76            0.8,
77            500.0,
78            Duration::from_millis(50),
79        )?;
80
81        let (agent_inputs, hardening_changes, performance_changes) = core.get_auto_save_stats();
82
83        assert_eq!(agent_inputs, 0);
84        assert_eq!(hardening_changes, 0);
85        assert_eq!(performance_changes, 1);
86
87        Ok(())
88    }
89}
90
91// Core module
92pub mod performance;
93pub use performance::Metrics;
94
95/// Core hexagonal architecture port definitions
96pub mod ports {
97    pub mod node_communication {}
98    pub mod wallet_interface {}
99    pub mod smart_contract {}
100    pub mod taproot_assets {}
101    pub mod dlc_oracle {}
102    pub mod metrics_port {}
103    pub mod audit_trail {}
104}
105
106use crate::ml::agent_system::MLAgentSystem;
107use crate::tokenomics::{engine::TokenomicsConfig, TokenomicsEngine};
108// use Web5Adapter HTTP client instead of direct web5 imports
109
110#[derive(Debug, Clone)]
111pub struct BitcoinConfig {
112    pub network: String,
113    pub rpc_url: Option<String>,
114}
115
116#[derive(Debug, Clone)]
117pub struct Web5Config {
118    pub endpoint: String,
119}
120
121#[derive(Debug, Clone)]
122pub struct MlConfig {
123    pub model_path: String,
124}
125
126pub struct Config {
127    pub bitcoin: BitcoinConfig,
128    pub web5: Web5Config,
129    pub ml: MlConfig,
130    pub tokenomics: TokenomicsConfig,
131}
132
133#[allow(dead_code)]
134pub struct AnyaCore {
135    #[cfg(feature = "rust-bitcoin")]
136    bitcoin_adapter: Arc<dyn crate::bitcoin::interface::BitcoinInterface>,
137    web5_adapter: Arc<crate::web::web5_adapter::Web5Adapter>,
138    ml_agent_system: Arc<MLAgentSystem>,
139    dao_governance: Arc<crate::dao::DaoGovernance>,
140    tokenomics: Arc<TokenomicsEngine>,
141}
142
143impl AnyaCore {
144    #[cfg(feature = "rust-bitcoin")]
145    pub async fn new(config: Config) -> Result<Self, Box<dyn std::error::Error>> {
146        let bitcoin_config = crate::bitcoin::config::BitcoinConfig {
147            enabled: true,
148            network: config.bitcoin.network.clone(),
149            rpc_url: config.bitcoin.rpc_url.clone(),
150            auth: None,
151            min_confirmations: 6,
152            default_fee_rate: 1,
153            wallet_path: Some("/tmp/bitcoin-wallet".to_string()),
154        };
155
156        let bitcoin_adapter = crate::bitcoin::BitcoinAdapter::new(bitcoin_config).await?;
157        let bitcoin: Arc<dyn crate::bitcoin::interface::BitcoinInterface + Send + Sync> =
158            Arc::new(bitcoin_adapter);
159
160        // Use HTTP-based Web5Adapter client
161        let web5 = Arc::new(crate::web::web5_adapter::Web5Adapter::new(&config.web5.endpoint));
162
163        let ml_config = crate::ml::MLConfig {
164            enabled: true,
165            model_path: Some(config.ml.model_path.clone()),
166            use_gpu: true,
167            federated_learning: true,
168            max_model_size: 100 * 1024 * 1024,
169        };
170        let agents = Arc::new(MLAgentSystem::init(ml_config).await?);
171
172        let dao = Arc::new(crate::dao::DaoGovernance::default());
173        let tokens = TokenomicsEngine::setup(config.tokenomics).await?;
174
175        Ok(Self {
176            bitcoin_adapter: bitcoin,
177            web5_adapter: web5,
178            ml_agent_system: agents,
179            dao_governance: dao,
180            tokenomics: tokens,
181        })
182    }
183
184    #[cfg(not(feature = "rust-bitcoin"))]
185    pub async fn new(config: Config) -> Result<Self, Box<dyn std::error::Error>> {
186        // Use HTTP-based Web5Adapter client
187        let web5 = Arc::new(crate::web::web5_adapter::Web5Adapter::new(&config.web5.endpoint));
188
189        let ml_config = crate::ml::MLConfig {
190            enabled: true,
191            model_path: Some(config.ml.model_path.clone()),
192            use_gpu: true,
193            federated_learning: true,
194            max_model_size: 100 * 1024 * 1024,
195        };
196        let agents = Arc::new(MLAgentSystem::init(ml_config).await?);
197
198        let dao = Arc::new(crate::dao::DaoGovernance::default());
199        let tokens = TokenomicsEngine::setup(config.tokenomics).await?;
200
201        Ok(Self {
202            web5_adapter: web5,
203            ml_agent_system: agents,
204            dao_governance: dao,
205            tokenomics: tokens,
206        })
207    }
208}
209
210pub mod rpc_ports {
211    use crate::core::metrics::PrometheusMetrics;
212    use async_trait::async_trait;
213    use serde_json::Value as JsonValue;
214    use std::sync::{Arc, Mutex};
215
216    #[async_trait]
217    pub trait BitcoinRpc {
218        async fn call_method(
219            &self,
220            method: &str,
221            params: JsonValue,
222        ) -> Result<JsonValue, Box<dyn std::error::Error + Send + Sync>>;
223        async fn validate_response(
224            &self,
225            response: JsonValue,
226        ) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
227    }
228
229    #[async_trait]
230    pub trait LightningRpc {
231        async fn create_invoice(
232            &self,
233            amount_msat: u64,
234            description: &str,
235        ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
236        async fn verify_payment(
237            &self,
238            payment_hash: &str,
239        ) -> Result<bool, Box<dyn std::error::Error + Send + Sync>>;
240    }
241
242    #[allow(dead_code)]
243    pub struct AnyaRpcAdapter {
244        bitcoin: Arc<dyn BitcoinRpc + Send + Sync>,
245        lightning: Arc<dyn LightningRpc + Send + Sync>,
246        metrics: Arc<Mutex<PrometheusMetrics>>,
247    }
248}