aimds_analysis/
lib.rs

1//! # AIMDS Analysis Layer
2//!
3//! High-level behavioral analysis and policy verification for AIMDS using
4//! temporal-attractor-studio and temporal-neural-solver.
5//!
6//! ## Components
7//!
8//! - **Behavioral Analyzer**: Attractor-based anomaly detection (target: <100ms p99)
9//! - **Policy Verifier**: LTL-based policy verification (target: <500ms p99)
10//! - **LTL Checker**: Linear Temporal Logic verification engine
11//!
12//! ## Performance
13//!
14//! - Behavioral analysis: 87ms baseline + overhead → <100ms p99
15//! - Policy verification: 423ms baseline + overhead → <500ms p99
16//! - Combined deep path: <520ms total
17
18pub mod behavioral;
19pub mod policy_verifier;
20pub mod ltl_checker;
21pub mod errors;
22
23pub use behavioral::{BehavioralAnalyzer, BehaviorProfile, AnomalyScore};
24pub use policy_verifier::{PolicyVerifier, SecurityPolicy, VerificationResult};
25pub use ltl_checker::{LTLChecker, LTLFormula, Trace};
26pub use errors::{AnalysisError, AnalysisResult};
27
28use std::sync::Arc;
29use tokio::sync::RwLock;
30use aimds_core::types::PromptInput;
31
32/// Combined analysis engine integrating behavioral and policy verification
33pub struct AnalysisEngine {
34    behavioral: Arc<BehavioralAnalyzer>,
35    policy: Arc<RwLock<PolicyVerifier>>,
36    ltl: Arc<LTLChecker>,
37}
38
39impl AnalysisEngine {
40    /// Create new analysis engine with default configuration
41    pub fn new(dimensions: usize) -> AnalysisResult<Self> {
42        Ok(Self {
43            behavioral: Arc::new(BehavioralAnalyzer::new(dimensions)?),
44            policy: Arc::new(RwLock::new(PolicyVerifier::new()?)),
45            ltl: Arc::new(LTLChecker::new()),
46        })
47    }
48
49    /// Analyze behavior and verify policies
50    pub async fn analyze_full(
51        &self,
52        sequence: &[f64],
53        input: &PromptInput,
54    ) -> AnalysisResult<FullAnalysis> {
55        let start = std::time::Instant::now();
56
57        // Parallel behavioral analysis and policy verification
58        let behavior_future = self.behavioral.analyze_behavior(sequence);
59        let policy_guard = self.policy.read().await;
60        let policy_future = policy_guard.verify_policy(input);
61
62        let (behavior_result, policy_result) = tokio::join!(
63            behavior_future,
64            policy_future
65        );
66
67        let behavior = behavior_result?;
68        let policy = policy_result?;
69
70        let duration = start.elapsed();
71
72        Ok(FullAnalysis {
73            behavior,
74            policy,
75            duration,
76        })
77    }
78
79    /// Get behavioral analyzer reference
80    pub fn behavioral(&self) -> &BehavioralAnalyzer {
81        &self.behavioral
82    }
83
84    /// Get policy verifier reference
85    pub fn policy(&self) -> Arc<RwLock<PolicyVerifier>> {
86        Arc::clone(&self.policy)
87    }
88
89    /// Get LTL checker reference
90    pub fn ltl(&self) -> &LTLChecker {
91        &self.ltl
92    }
93}
94
95/// Combined analysis result
96#[derive(Debug, Clone)]
97pub struct FullAnalysis {
98    pub behavior: AnomalyScore,
99    pub policy: VerificationResult,
100    pub duration: std::time::Duration,
101}
102
103impl FullAnalysis {
104    /// Check if analysis indicates a threat
105    pub fn is_threat(&self) -> bool {
106        self.behavior.is_anomalous || !self.policy.verified
107    }
108
109    /// Get threat severity (0.0 = safe, 1.0 = critical)
110    pub fn threat_level(&self) -> f64 {
111        if !self.is_threat() {
112            return 0.0;
113        }
114
115        // Combine behavioral score and policy verification
116        let behavioral_weight = 0.6;
117        let policy_weight = 0.4;
118
119        let behavioral_score = self.behavior.score;
120        let policy_score = if self.policy.verified { 0.0 } else { 1.0 };
121
122        behavioral_score * behavioral_weight + policy_score * policy_weight
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[tokio::test]
131    async fn test_engine_creation() {
132        let engine = AnalysisEngine::new(10).unwrap();
133        assert!(Arc::strong_count(&engine.behavioral) >= 1);
134    }
135
136    #[tokio::test]
137    async fn test_threat_level() {
138        let analysis = FullAnalysis {
139            behavior: AnomalyScore {
140                score: 0.8,
141                is_anomalous: true,
142                confidence: 0.95,
143            },
144            policy: VerificationResult {
145                verified: false,
146                confidence: 0.9,
147                violations: vec!["unauthorized_access".to_string()],
148                proof: None,
149            },
150            duration: std::time::Duration::from_millis(150),
151        };
152
153        assert!(analysis.is_threat());
154        let level = analysis.threat_level();
155        assert!(level > 0.6 && level < 1.0);
156    }
157}