Skip to main content

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