aimds_response/
lib.rs

1//! AIMDS Response Layer
2//!
3//! Adaptive response and mitigation system with meta-learning capabilities.
4//! Uses strange-loop recursive self-improvement for autonomous threat response.
5//!
6//! # Features
7//!
8//! - **Meta-Learning**: 25-level recursive optimization using strange-loop
9//! - **Adaptive Mitigation**: Self-improving threat response strategies
10//! - **Rollback Support**: Safe mitigation with automatic rollback
11//! - **Audit Logging**: Comprehensive tracking of all mitigation actions
12//!
13//! # Example
14//!
15//! ```rust,no_run
16//! use aimds_response::{ResponseSystem, MitigationStrategy};
17//! use aimds_core::ThreatIncident;
18//!
19//! #[tokio::main]
20//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
21//!     let response_system = ResponseSystem::new().await?;
22//!
23//!     // Apply adaptive mitigation
24//!     let result = response_system.mitigate(&threat).await?;
25//!
26//!     // Learn from outcome
27//!     response_system.learn_from_result(&result).await?;
28//!
29//!     Ok(())
30//! }
31//! ```
32
33pub mod meta_learning;
34pub mod adaptive;
35pub mod mitigations;
36pub mod audit;
37pub mod rollback;
38pub mod error;
39
40use std::sync::Arc;
41use tokio::sync::RwLock;
42use crate::meta_learning::ThreatIncident;
43
44pub use meta_learning::MetaLearningEngine;
45pub use adaptive::{AdaptiveMitigator, MitigationStrategy};
46pub use mitigations::{MitigationAction, MitigationOutcome, ThreatContext};
47pub use audit::AuditLogger;
48pub use rollback::RollbackManager;
49pub use error::{ResponseError, Result};
50
51/// Main response system coordinating meta-learning and adaptive mitigation
52#[derive(Clone)]
53pub struct ResponseSystem {
54    meta_learner: Arc<RwLock<MetaLearningEngine>>,
55    mitigator: Arc<RwLock<AdaptiveMitigator>>,
56    audit_logger: Arc<AuditLogger>,
57    rollback_manager: Arc<RollbackManager>,
58}
59
60impl ResponseSystem {
61    /// Create new response system with default configuration
62    pub async fn new() -> Result<Self> {
63        Ok(Self {
64            meta_learner: Arc::new(RwLock::new(MetaLearningEngine::new())),
65            mitigator: Arc::new(RwLock::new(AdaptiveMitigator::new())),
66            audit_logger: Arc::new(AuditLogger::new()),
67            rollback_manager: Arc::new(RollbackManager::new()),
68        })
69    }
70
71    /// Apply mitigation to detected threat
72    pub async fn mitigate(&self, threat: &ThreatIncident) -> Result<MitigationOutcome> {
73        let context = ThreatContext::from_incident(threat);
74
75        // Record mitigation attempt
76        self.audit_logger.log_mitigation_start(&context).await;
77
78        // Apply mitigation with rollback support
79        let mitigator = self.mitigator.read().await;
80        let result = mitigator.apply_mitigation(threat).await;
81
82        match &result {
83            Ok(outcome) => {
84                self.audit_logger.log_mitigation_success(&context, outcome).await;
85
86                // Update effectiveness tracking
87                drop(mitigator);
88                let mut mitigator = self.mitigator.write().await;
89                mitigator.update_effectiveness(&outcome.strategy_id, true);
90            }
91            Err(e) => {
92                self.audit_logger.log_mitigation_failure(&context, e).await;
93
94                // Attempt rollback
95                self.rollback_manager.rollback_last().await?;
96            }
97        }
98
99        result
100    }
101
102    /// Learn from mitigation outcome to improve future responses
103    pub async fn learn_from_result(&self, outcome: &MitigationOutcome) -> Result<()> {
104        let mut meta_learner = self.meta_learner.write().await;
105        meta_learner.learn_from_outcome(outcome).await;
106        Ok(())
107    }
108
109    /// Optimize strategies based on feedback signals
110    pub async fn optimize(&self, feedback: &[FeedbackSignal]) -> Result<()> {
111        let mut meta_learner = self.meta_learner.write().await;
112        meta_learner.optimize_strategy(feedback);
113        Ok(())
114    }
115
116    /// Get current system metrics
117    pub async fn metrics(&self) -> ResponseMetrics {
118        let meta_learner = self.meta_learner.read().await;
119        let mitigator = self.mitigator.read().await;
120
121        ResponseMetrics {
122            learned_patterns: meta_learner.learned_patterns_count(),
123            active_strategies: mitigator.active_strategies_count(),
124            total_mitigations: self.audit_logger.total_mitigations(),
125            successful_mitigations: self.audit_logger.successful_mitigations(),
126            optimization_level: meta_learner.current_optimization_level(),
127        }
128    }
129}
130
131/// Feedback signal for meta-learning optimization
132#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
133pub struct FeedbackSignal {
134    pub strategy_id: String,
135    pub success: bool,
136    pub effectiveness_score: f64,
137    pub timestamp: chrono::DateTime<chrono::Utc>,
138    pub context: Option<String>,
139}
140
141/// Response system performance metrics
142#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
143pub struct ResponseMetrics {
144    pub learned_patterns: usize,
145    pub active_strategies: usize,
146    pub total_mitigations: u64,
147    pub successful_mitigations: u64,
148    pub optimization_level: usize,
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[tokio::test]
156    async fn test_response_system_creation() {
157        let system = ResponseSystem::new().await;
158        assert!(system.is_ok());
159    }
160
161    #[tokio::test]
162    async fn test_metrics_collection() {
163        let system = ResponseSystem::new().await.unwrap();
164        let metrics = system.metrics().await;
165
166        assert_eq!(metrics.learned_patterns, 0);
167        assert_eq!(metrics.total_mitigations, 0);
168    }
169}