caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
//! WASM Module Validator
//!
//! Provides comprehensive validation of WASM modules before deployment,
//! including security policy enforcement, structural validation, and metadata extraction.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::RwLock;
use tracing::{debug, info, warn};

use crate::agent_lifecycle_manager::WasmModuleValidator;
#[cfg(test)]
use crate::domain::ValidationRuleType;
use crate::domain::{
    AgentVersion, CustomValidationRule, ValidationFailure, ValidationResult, ValidationWarning,
    VersionNumber, WasmModule, WasmSecurityPolicy, WasmValidationError, millis_to_f64_for_stats,
    u64_to_f64_for_stats,
};
use crate::domain_types::AgentName;

/// Validation modes for different validation types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationMode {
    /// Validation is enabled
    Enabled,
    /// Validation is disabled
    Disabled,
}

/// Strictness level for validation
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StrictnessLevel {
    /// Strict validation with all checks enabled
    Strict,
    /// Relaxed validation with some checks bypassed
    Relaxed,
}

/// Validation configuration for different environments
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Security policy to apply during validation
    pub security_policy: WasmSecurityPolicy,
    /// Whether to perform structural validation
    pub structural_validation: ValidationMode,
    /// Whether to perform security validation
    pub security_validation: ValidationMode,
    /// Whether to perform performance analysis
    pub performance_analysis: ValidationMode,
    /// Strictness level for validation
    pub strictness: StrictnessLevel,
    /// Maximum time allowed for validation in milliseconds
    pub max_validation_time_ms: u64,
}

impl ValidationConfig {
    /// Creates a strict validation configuration
    pub fn strict() -> Self {
        Self {
            security_policy: WasmSecurityPolicy::strict(),
            structural_validation: ValidationMode::Enabled,
            security_validation: ValidationMode::Enabled,
            performance_analysis: ValidationMode::Enabled,
            strictness: StrictnessLevel::Strict,
            max_validation_time_ms: 30_000, // 30 seconds
        }
    }

    /// Creates a permissive validation configuration
    pub fn permissive() -> Self {
        Self {
            security_policy: WasmSecurityPolicy::permissive(),
            structural_validation: ValidationMode::Enabled,
            security_validation: ValidationMode::Disabled,
            performance_analysis: ValidationMode::Disabled,
            strictness: StrictnessLevel::Relaxed,
            max_validation_time_ms: 10_000, // 10 seconds
        }
    }

    /// Creates a testing validation configuration
    pub fn testing() -> Self {
        Self {
            security_policy: WasmSecurityPolicy::testing(),
            structural_validation: ValidationMode::Enabled,
            security_validation: ValidationMode::Enabled,
            performance_analysis: ValidationMode::Enabled, // Enable for comprehensive testing
            strictness: StrictnessLevel::Relaxed,
            max_validation_time_ms: 5_000, // 5 seconds
        }
    }
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self::strict()
    }
}

/// Structural analysis results
#[derive(Debug, Clone)]
struct StructuralAnalysis {
    pub function_count: usize,
    pub import_count: usize,
    pub export_count: usize,
    pub memory_pages: u32,
    pub table_elements: u32,
    pub complexity_score: f64,
}

/// Security analysis results
#[derive(Debug, Clone)]
struct SecurityAnalysis {
    pub unauthorized_imports: Vec<String>,
    pub missing_exports: Vec<String>,
    pub policy_violations: Vec<String>,
    pub security_score: f64,
}

/// Performance analysis results
#[derive(Debug, Clone)]
struct PerformanceAnalysis {
    pub estimated_memory_usage: usize,
    pub estimated_execution_cost: u64,
    pub potential_bottlenecks: Vec<String>,
    pub optimization_suggestions: Vec<String>,
}

/// Validation statistics
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct ValidationStatistics {
    pub modules_validated: u64,
    pub modules_passed: u64,
    pub modules_failed: u64,
    pub average_validation_time_ms: f64,
    pub common_failures: HashMap<String, u32>,
}

impl Default for ValidationStatistics {
    fn default() -> Self {
        Self::new()
    }
}

impl ValidationStatistics {
    /// Create new validation statistics
    pub fn new() -> Self {
        Self {
            modules_validated: 0,
            modules_passed: 0,
            modules_failed: 0,
            average_validation_time_ms: 0.0,
            common_failures: HashMap::new(),
        }
    }

    /// Record a validation result
    pub fn record_validation(
        &mut self,
        passed: bool,
        validation_time_ms: f64,
        failure_reason: Option<&str>,
    ) {
        self.modules_validated += 1;
        if passed {
            self.modules_passed += 1;
        } else {
            self.modules_failed += 1;
            if let Some(reason) = failure_reason {
                *self.common_failures.entry(reason.to_string()).or_insert(0) += 1;
            }
        }

        // Update average validation time with safe conversions
        let validated_f64 = u64_to_f64_for_stats(self.modules_validated);
        self.average_validation_time_ms =
            ((self.average_validation_time_ms * (validated_f64 - 1.0)) + validation_time_ms)
                / validated_f64;
    }

    /// Calculate success rate percentage
    pub fn success_rate(&self) -> f64 {
        if self.modules_validated == 0 {
            return 0.0;
        }
        let passed_f64 = u64_to_f64_for_stats(self.modules_passed);
        let validated_f64 = u64_to_f64_for_stats(self.modules_validated);
        (passed_f64 / validated_f64) * 100.0
    }
}

/// Core WASM module validator implementation
pub struct CaxtonWasmModuleValidator {
    /// Validation configuration
    config: Arc<RwLock<ValidationConfig>>,
    /// Validation statistics
    statistics: Arc<RwLock<ValidationStatistics>>,
    /// Custom validation rules
    custom_rules: Arc<RwLock<Vec<CustomValidationRule>>>,
}

impl CaxtonWasmModuleValidator {
    /// Creates a new WASM module validator
    pub fn new(config: ValidationConfig) -> Self {
        Self {
            config: Arc::new(RwLock::new(config)),
            statistics: Arc::new(RwLock::new(ValidationStatistics::new())),
            custom_rules: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Creates validator with default strict configuration
    pub fn strict() -> Self {
        Self::new(ValidationConfig::strict())
    }

    /// Creates validator with permissive configuration
    pub fn permissive() -> Self {
        Self::new(ValidationConfig::permissive())
    }

    /// Creates validator with testing configuration
    pub fn testing() -> Self {
        Self::new(ValidationConfig::testing())
    }

    /// Update validation configuration
    pub async fn update_config(&self, config: ValidationConfig) {
        let mut current_config = self.config.write().await;
        *current_config = config;
    }

    /// Add custom validation rule
    pub async fn add_custom_rule(&self, rule: CustomValidationRule) {
        let mut rules = self.custom_rules.write().await;
        rules.push(rule);
    }

    /// Get validation statistics
    pub async fn get_statistics(&self) -> ValidationStatistics {
        self.statistics.read().await.clone()
    }

    /// Perform basic WASM format validation
    fn validate_wasm_format(wasm_bytes: &[u8]) -> Result<(), ValidationFailure> {
        if wasm_bytes.is_empty() {
            return Err(ValidationFailure::InvalidWasmFormat);
        }

        // Check WASM magic number (0x00, 0x61, 0x73, 0x6D)
        if wasm_bytes.len() < 4 {
            return Err(ValidationFailure::InvalidWasmFormat);
        }

        let magic = &wasm_bytes[0..4];
        if magic != [0x00, 0x61, 0x73, 0x6D] {
            return Err(ValidationFailure::InvalidWasmFormat);
        }

        // Check version (1, 0, 0, 0)
        if wasm_bytes.len() < 8 {
            return Err(ValidationFailure::InvalidWasmFormat);
        }

        let version = &wasm_bytes[4..8];
        if version != [0x01, 0x00, 0x00, 0x00] {
            return Err(ValidationFailure::UnsupportedWasmVersion);
        }

        Ok(())
    }

    /// Perform structural analysis of WASM module
    fn analyze_structure(_wasm_bytes: &[u8]) -> StructuralAnalysis {
        // In a real implementation, this would use wasmparser to analyze the module structure
        // For now, we'll return mock analysis

        StructuralAnalysis {
            function_count: 10,
            import_count: 2,
            export_count: 3,
            memory_pages: 16,
            table_elements: 0,
            complexity_score: 0.3, // Low complexity
        }
    }

    /// Perform security analysis against policy
    fn analyze_security(
        _wasm_bytes: &[u8],
        policy: &WasmSecurityPolicy,
        _analysis: &StructuralAnalysis,
    ) -> SecurityAnalysis {
        // In a real implementation, this would analyze imports/exports against the policy
        // For now, we'll return mock analysis

        let mut security_analysis = SecurityAnalysis {
            unauthorized_imports: Vec::new(),
            missing_exports: Vec::new(),
            policy_violations: Vec::new(),
            security_score: 95.0, // High security score
        };

        // Check if policy is too strict for testing
        if policy.name == "strict" {
            security_analysis.security_score = 98.0;
        } else if policy.name == "permissive" {
            security_analysis.security_score = 75.0;
        }

        security_analysis
    }

    /// Perform performance analysis
    fn analyze_performance(
        _wasm_bytes: &[u8],
        analysis: &StructuralAnalysis,
    ) -> PerformanceAnalysis {
        let estimated_memory = (analysis.memory_pages as usize) * 65536; // 64KB per page
        let estimated_cost = (analysis.function_count as u64) * 1000; // 1000 fuel per function (estimate)

        let mut bottlenecks = Vec::new();
        let mut suggestions = Vec::new();

        if analysis.function_count > 100 {
            bottlenecks.push("High function count may impact load time".to_string());
            suggestions.push("Consider splitting module into smaller components".to_string());
        }

        if analysis.memory_pages > 64 {
            bottlenecks.push("High memory usage may impact performance".to_string());
            suggestions.push("Optimize memory layout and reduce allocations".to_string());
        }

        if analysis.complexity_score > 0.8 {
            bottlenecks.push("High complexity may impact execution performance".to_string());
            suggestions.push("Refactor complex functions for better performance".to_string());
        }

        PerformanceAnalysis {
            estimated_memory_usage: estimated_memory,
            estimated_execution_cost: estimated_cost,
            potential_bottlenecks: bottlenecks,
            optimization_suggestions: suggestions,
        }
    }

    /// Create comprehensive validation result
    fn create_validation_result(
        structural: &StructuralAnalysis,
        security: &SecurityAnalysis,
        performance: &PerformanceAnalysis,
        custom_warnings: Vec<ValidationWarning>,
        config: &ValidationConfig,
    ) -> ValidationResult {
        let mut failures = Vec::new();
        let mut warnings = custom_warnings;

        // Check structural limits
        if structural.function_count > 1000 {
            failures.push(ValidationFailure::TooManyFunctions {
                count: structural.function_count,
                limit: 1000,
            });
        }

        if structural.import_count > 100 {
            failures.push(ValidationFailure::TooManyImports {
                count: structural.import_count,
                limit: 100,
            });
        }

        if structural.export_count > 100 {
            failures.push(ValidationFailure::TooManyExports {
                count: structural.export_count,
                limit: 100,
            });
        }

        // Check security violations
        for import in &security.unauthorized_imports {
            failures.push(ValidationFailure::UnauthorizedImport {
                function_name: import.clone(),
            });
        }

        for export in &security.missing_exports {
            failures.push(ValidationFailure::MissingRequiredExport {
                function_name: export.clone(),
            });
        }

        for violation in &security.policy_violations {
            failures.push(ValidationFailure::SecurityViolation {
                policy: config.security_policy.name.clone(),
                violation: violation.clone(),
            });
        }

        // Add performance warnings if enabled
        if config.performance_analysis == ValidationMode::Enabled {
            for bottleneck in &performance.potential_bottlenecks {
                warnings.push(ValidationWarning::PerformanceWarning {
                    warning: bottleneck.clone(),
                });
            }
        }

        // Add structural warnings
        if structural.function_count > 500 {
            warnings.push(ValidationWarning::LargeFunctionCount {
                count: structural.function_count,
            });
        }

        // Determine final result
        if !failures.is_empty() {
            ValidationResult::Invalid { reasons: failures }
        } else if !warnings.is_empty() {
            ValidationResult::Warning { warnings }
        } else {
            ValidationResult::Valid
        }
    }

    /// Extract basic metadata from WASM bytes
    fn extract_basic_metadata(wasm_bytes: &[u8]) -> HashMap<String, String> {
        let mut metadata = HashMap::new();

        metadata.insert("size_bytes".to_string(), wasm_bytes.len().to_string());
        metadata.insert(
            "size_kb".to_string(),
            wasm_bytes.len().div_ceil(1024).to_string(),
        );

        // Extract format info
        if wasm_bytes.len() >= 8 {
            metadata.insert("wasm_version".to_string(), "1".to_string());
        }

        // In a real implementation, would extract more detailed metadata
        metadata.insert(
            "validation_timestamp".to_string(),
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
                .to_string(),
        );

        metadata
    }

    /// Comprehensive validation implementation
    async fn validate_module_comprehensive(
        &self,
        wasm_bytes: &[u8],
        agent_name: Option<AgentName>,
    ) -> Result<WasmModule, WasmValidationError> {
        let validation_start = SystemTime::now();
        self.perform_validation_steps(wasm_bytes, agent_name, validation_start)
            .await
    }

    /// Perform all validation steps
    async fn perform_validation_steps(
        &self,
        wasm_bytes: &[u8],
        agent_name: Option<AgentName>,
        validation_start: SystemTime,
    ) -> Result<WasmModule, WasmValidationError> {
        let config = self.config.read().await.clone();

        Self::validate_basic_format(wasm_bytes)?;

        let (structural, security, performance) = Self::perform_analysis_phase(wasm_bytes, &config);

        let custom_warnings =
            Self::apply_custom_validation_rules(wasm_bytes, agent_name.as_ref(), &config);

        let validation_result = Self::create_validation_result(
            &structural,
            &security,
            &performance,
            custom_warnings,
            &config,
        );

        self.finalize_validation(
            wasm_bytes,
            agent_name,
            validation_result,
            validation_start,
            (structural, security, performance),
        )
        .await
    }

    /// Validate basic WASM format
    fn validate_basic_format(wasm_bytes: &[u8]) -> Result<(), WasmValidationError> {
        info!(
            "Starting comprehensive WASM module validation (size: {} bytes)",
            wasm_bytes.len()
        );

        Self::validate_wasm_format(wasm_bytes).map_err(|failure| {
            WasmValidationError::InvalidFormat {
                reason: failure.to_string(),
            }
        })
    }

    /// Perform structural, security, and performance analysis
    fn perform_analysis_phase(
        wasm_bytes: &[u8],
        config: &ValidationConfig,
    ) -> (StructuralAnalysis, SecurityAnalysis, PerformanceAnalysis) {
        // Step 2: Structural analysis
        let structural = if config.structural_validation == ValidationMode::Enabled {
            Self::analyze_structure(wasm_bytes)
        } else {
            StructuralAnalysis {
                function_count: 0,
                import_count: 0,
                export_count: 0,
                memory_pages: 0,
                table_elements: 0,
                complexity_score: 0.0,
            }
        };

        debug!(
            "Structural analysis completed: {} functions, {} imports, {} exports",
            structural.function_count, structural.import_count, structural.export_count
        );

        // Step 3: Security analysis
        let security = if config.security_validation == ValidationMode::Enabled {
            Self::analyze_security(wasm_bytes, &config.security_policy, &structural)
        } else {
            SecurityAnalysis {
                unauthorized_imports: Vec::new(),
                missing_exports: Vec::new(),
                policy_violations: Vec::new(),
                security_score: 100.0,
            }
        };

        debug!(
            "Security analysis completed: score {}",
            security.security_score
        );

        // Step 4: Performance analysis
        let performance = if config.performance_analysis == ValidationMode::Enabled {
            Self::analyze_performance(wasm_bytes, &structural)
        } else {
            PerformanceAnalysis {
                estimated_memory_usage: 0,
                estimated_execution_cost: 0,
                potential_bottlenecks: Vec::new(),
                optimization_suggestions: Vec::new(),
            }
        };

        debug!(
            "Performance analysis completed: {} bytes memory, {} fuel cost",
            performance.estimated_memory_usage, performance.estimated_execution_cost
        );

        (structural, security, performance)
    }

    /// Apply custom validation rules
    fn apply_custom_validation_rules(
        _wasm_bytes: &[u8],
        _agent_name: Option<&AgentName>,
        _config: &ValidationConfig,
    ) -> Vec<ValidationWarning> {
        // For now, return empty warnings as we'd need a full WasmModule to apply custom rules
        // In a real implementation, this would be restructured to pass the necessary data
        Vec::new()
    }

    /// Finalize validation by creating the final module and updating statistics
    async fn finalize_validation(
        &self,
        wasm_bytes: &[u8],
        agent_name: Option<AgentName>,
        validation_result: ValidationResult,
        validation_start: SystemTime,
        analysis_results: (StructuralAnalysis, SecurityAnalysis, PerformanceAnalysis),
    ) -> Result<WasmModule, WasmValidationError> {
        let validation_millis = validation_start.elapsed().unwrap_or_default().as_millis();
        // Convert u128 to f64 with controlled precision loss for timing statistics
        let validation_duration = millis_to_f64_for_stats(validation_millis);

        // Note: Statistics are handled by the caller (validate_module trait implementation)

        let config = self.config.read().await;
        let mut final_module = WasmModule::from_bytes(
            AgentVersion::generate(),
            VersionNumber::first(),
            None, // WasmModuleName - we don't have one
            agent_name,
            wasm_bytes,
            &config.security_policy,
        )?;

        // Override validation result with comprehensive analysis
        final_module.validation_result = validation_result.clone();

        // Populate metadata with analysis results
        let (structural, security, performance) = analysis_results;
        final_module.metadata.insert(
            "estimated_memory_usage".to_string(),
            performance.estimated_memory_usage.to_string(),
        );
        final_module.metadata.insert(
            "estimated_execution_cost".to_string(),
            performance.estimated_execution_cost.to_string(),
        );
        final_module.metadata.insert(
            "security_score".to_string(),
            security.security_score.to_string(),
        );
        final_module.metadata.insert(
            "complexity_score".to_string(),
            structural.complexity_score.to_string(),
        );

        info!(
            "WASM module validation completed in {:.2}ms with result: {:?}",
            validation_duration, final_module.validation_result
        );

        Ok(final_module)
    }
}

#[async_trait::async_trait]
impl WasmModuleValidator for CaxtonWasmModuleValidator {
    /// Validate WASM module with comprehensive analysis
    async fn validate_module(
        &self,
        wasm_bytes: &[u8],
        agent_name: Option<AgentName>,
    ) -> Result<WasmModule, WasmValidationError> {
        let validation_start = SystemTime::now();

        // Check for early validation failures
        let early_error = if wasm_bytes.is_empty() {
            Some(WasmValidationError::EmptyModule)
        } else if wasm_bytes.len() > 100 * 1024 * 1024 {
            // 100MB limit
            Some(WasmValidationError::ModuleTooLarge {
                size: wasm_bytes.len(),
                limit: 100 * 1024 * 1024,
            })
        } else {
            None
        };

        // Update statistics for early failures
        if let Some(error) = early_error {
            let validation_millis = validation_start.elapsed().unwrap_or_default().as_millis();
            // Convert u128 to f64 with controlled precision loss for timing statistics
            let validation_time = millis_to_f64_for_stats(validation_millis);
            let validation_time = validation_time.max(0.1); // Minimum 0.1ms for statistics
            let mut stats = self.statistics.write().await;
            stats.record_validation(false, validation_time, Some(&error.to_string()));
            return Err(error);
        }

        let result = self
            .validate_module_comprehensive(wasm_bytes, agent_name)
            .await;

        // Always update statistics here (comprehensive function will also do it, but that's ok)
        let validation_millis = validation_start.elapsed().unwrap_or_default().as_millis();
        // Safe conversion from u128 to f64 with saturation for very large values
        let validation_time = millis_to_f64_for_stats(validation_millis);
        let validation_time = validation_time.max(0.1); // Minimum 0.1ms for statistics
        let passed = result.is_ok();
        let failure_reason = if let Err(ref error) = result {
            Some(error.to_string())
        } else {
            None
        };

        {
            let mut stats = self.statistics.write().await;
            stats.record_validation(passed, validation_time, failure_reason.as_deref());
        }

        result
    }

    /// Perform security-focused validation
    async fn validate_security(
        &self,
        module: &WasmModule,
    ) -> Result<ValidationResult, WasmValidationError> {
        info!(
            "Performing security validation for module {}",
            module
                .name
                .as_ref()
                .map_or_else(|| "unnamed".to_string(), std::string::ToString::to_string)
        );

        let config = self.config.read().await;

        if config.security_validation != ValidationMode::Enabled {
            debug!("Security validation disabled, returning valid");
            return Ok(ValidationResult::Valid);
        }

        // Use the module's security policy for validation
        let validation_result = module.security_policy.validate_module(module);

        // Log security validation result
        match &validation_result {
            ValidationResult::Valid => {
                debug!("Security validation passed");
            }
            ValidationResult::Invalid { reasons } => {
                warn!("Security validation failed: {} violations", reasons.len());
                for reason in reasons {
                    warn!("Security violation: {}", reason);
                }
            }
            ValidationResult::Warning { warnings } => {
                info!(
                    "Security validation passed with {} warnings",
                    warnings.len()
                );
                for warning in warnings {
                    info!("Security warning: {}", warning);
                }
            }
        }

        Ok(validation_result)
    }

    /// Extract metadata from WASM module
    async fn extract_metadata(
        &self,
        wasm_bytes: &[u8],
    ) -> Result<HashMap<String, String>, WasmValidationError> {
        debug!(
            "Extracting metadata from WASM module ({} bytes)",
            wasm_bytes.len()
        );

        if wasm_bytes.is_empty() {
            return Err(WasmValidationError::EmptyModule);
        }

        // Validate basic format first
        Self::validate_wasm_format(wasm_bytes).map_err(|e| WasmValidationError::InvalidFormat {
            reason: e.to_string(),
        })?;

        let mut metadata = Self::extract_basic_metadata(wasm_bytes);

        // Add structural analysis metadata if enabled
        let config = self.config.read().await;
        if config.structural_validation == ValidationMode::Enabled {
            let structural = Self::analyze_structure(wasm_bytes);
            metadata.insert(
                "function_count".to_string(),
                structural.function_count.to_string(),
            );
            metadata.insert(
                "import_count".to_string(),
                structural.import_count.to_string(),
            );
            metadata.insert(
                "export_count".to_string(),
                structural.export_count.to_string(),
            );
            metadata.insert(
                "memory_pages".to_string(),
                structural.memory_pages.to_string(),
            );
            metadata.insert(
                "table_elements".to_string(),
                structural.table_elements.to_string(),
            );
            metadata.insert(
                "complexity_score".to_string(),
                structural.complexity_score.to_string(),
            );
        }

        // Add performance metadata if enabled
        if config.performance_analysis == ValidationMode::Enabled {
            let structural = Self::analyze_structure(wasm_bytes);
            let performance = Self::analyze_performance(wasm_bytes, &structural);
            metadata.insert(
                "estimated_memory_usage".to_string(),
                performance.estimated_memory_usage.to_string(),
            );
            metadata.insert(
                "estimated_execution_cost".to_string(),
                performance.estimated_execution_cost.to_string(),
            );
            metadata.insert(
                "bottleneck_count".to_string(),
                performance.potential_bottlenecks.len().to_string(),
            );
            metadata.insert(
                "optimization_suggestions_count".to_string(),
                performance.optimization_suggestions.len().to_string(),
            );
        }

        debug!("Extracted {} metadata fields", metadata.len());
        Ok(metadata)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_valid_wasm_bytes() -> Vec<u8> {
        // WASM magic number + version
        vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00]
    }

    fn create_invalid_wasm_bytes() -> Vec<u8> {
        vec![0xFF, 0xFF, 0xFF, 0xFF] // Invalid magic number
    }

    #[tokio::test]
    async fn test_valid_wasm_module_validation() {
        let validator = CaxtonWasmModuleValidator::testing();
        let wasm_bytes = create_valid_wasm_bytes();

        let result = validator.validate_module(&wasm_bytes, None).await;
        assert!(result.is_ok());

        let module = result.unwrap();
        assert!(module.is_valid() || module.validation_result.has_warnings());
    }

    #[tokio::test]
    async fn test_invalid_wasm_module_validation() {
        let validator = CaxtonWasmModuleValidator::strict();
        let wasm_bytes = create_invalid_wasm_bytes();

        let result = validator.validate_module(&wasm_bytes, None).await;
        assert!(result.is_err());

        assert!(matches!(
            result.unwrap_err(),
            WasmValidationError::InvalidFormat { .. }
        ));
    }

    #[tokio::test]
    async fn test_empty_wasm_module_validation() {
        let validator = CaxtonWasmModuleValidator::testing();
        let empty_bytes = vec![];

        let result = validator.validate_module(&empty_bytes, None).await;
        assert!(result.is_err());

        assert!(matches!(
            result.unwrap_err(),
            WasmValidationError::EmptyModule
        ));
    }

    #[tokio::test]
    async fn test_security_validation() {
        // Use testing policy since our test WASM is minimal
        let validator = CaxtonWasmModuleValidator::testing();
        let wasm_bytes = create_valid_wasm_bytes();

        let module = validator.validate_module(&wasm_bytes, None).await.unwrap();
        let security_result = validator.validate_security(&module).await.unwrap();

        // Security validation should pass for valid WASM with testing policy
        assert!(
            security_result.is_valid(),
            "Security validation should pass for valid WASM module with testing policy"
        );
    }

    #[tokio::test]
    async fn test_metadata_extraction() {
        let validator = CaxtonWasmModuleValidator::testing();
        let wasm_bytes = create_valid_wasm_bytes();

        let result = validator.extract_metadata(&wasm_bytes).await;
        assert!(result.is_ok());

        let metadata = result.unwrap();
        assert!(metadata.contains_key("size_bytes"));
        assert!(metadata.contains_key("wasm_version"));
    }

    #[tokio::test]
    async fn test_custom_validation_rules() {
        let validator = CaxtonWasmModuleValidator::testing();

        // Add custom rule
        let custom_rule = CustomValidationRule {
            name: "test_rule".to_string(),
            description: "Test custom rule".to_string(),
            rule_type: ValidationRuleType::FunctionNamePattern,
            parameters: {
                let mut params = HashMap::new();
                params.insert("pattern".to_string(), "test_*".to_string());
                params
            },
        };

        validator.add_custom_rule(custom_rule).await;

        let wasm_bytes = create_valid_wasm_bytes();
        let result = validator.validate_module(&wasm_bytes, None).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_validation_statistics() {
        let validator = CaxtonWasmModuleValidator::testing();
        let wasm_bytes = create_valid_wasm_bytes();

        // Perform several validations
        for _ in 0..3 {
            let _ = validator.validate_module(&wasm_bytes, None).await;
        }

        let stats = validator.get_statistics().await;
        assert!(stats.modules_validated >= 3);
        assert!(stats.success_rate() > 0.0);
    }

    #[tokio::test]
    async fn test_configuration_update() {
        let validator = CaxtonWasmModuleValidator::strict();

        // Update to permissive configuration
        let new_config = ValidationConfig::permissive();
        validator.update_config(new_config).await;

        // Validation should now be more permissive
        let wasm_bytes = create_valid_wasm_bytes();
        let result = validator.validate_module(&wasm_bytes, None).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_validation_config_creation() {
        let strict_config = ValidationConfig::strict();
        assert!(strict_config.strictness == StrictnessLevel::Strict);
        assert!(strict_config.security_validation == ValidationMode::Enabled);

        let permissive_config = ValidationConfig::permissive();
        assert_eq!(permissive_config.strictness, StrictnessLevel::Relaxed);
        assert_eq!(
            permissive_config.security_validation,
            ValidationMode::Disabled
        );

        let testing_config = ValidationConfig::testing();
        assert_eq!(testing_config.strictness, StrictnessLevel::Relaxed);
        assert_eq!(testing_config.security_validation, ValidationMode::Enabled);
    }

    #[test]
    fn test_validation_statistics_tracking() {
        let mut stats = ValidationStatistics::new();

        stats.record_validation(true, 100.0, None);
        stats.record_validation(false, 150.0, Some("test_error"));
        stats.record_validation(true, 120.0, None);

        assert_eq!(stats.modules_validated, 3);
        assert_eq!(stats.modules_passed, 2);
        assert_eq!(stats.modules_failed, 1);
        assert!((stats.success_rate() - 66.666_666_666_666_66).abs() < f64::EPSILON);
        assert_eq!(stats.common_failures.get("test_error"), Some(&1));
    }
}