sekuire 0.1.0

The official SDK for the Sekuire Agent Identity Protocol
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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
/*!
🛡️ Sekuire Compliance Enforcement System for Rust

Runtime compliance enforcement that blocks all unauthorized behavior.
Everything blocked unless explicitly allowed in sekuire.yaml.
*/

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use regex::Regex;
use thiserror::Error;
use anyhow::{Result, Context};

// ==================== TYPES ====================

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceConfig {
    pub agent: AgentConfig,
    pub permissions: PermissionsConfig,
    pub logging: Option<LoggingConfig>,
    pub alerts: Option<AlertsConfig>,
    pub enterprise: Option<EnterpriseConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    pub name: String,
    pub version: String,
    pub tenant: Option<String>,
    pub compliance_level: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionsConfig {
    pub network: NetworkConfig,
    pub filesystem: FilesystemConfig,
    pub env: EnvConfig,
    pub tools: ToolsConfig,
    pub model: ModelConfig,
    pub content: ContentConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkConfig {
    #[serde(default)]
    pub default_deny: bool,
    pub allow: Vec<String>,
    pub block: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilesystemConfig {
    #[serde(default)]
    pub default_deny: bool,
    pub allow_read: Vec<String>,
    pub allow_write: Vec<String>,
    pub block_all: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvConfig {
    #[serde(default)]
    pub default_deny: bool,
    pub allow: Vec<String>,
    pub block: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolsConfig {
    pub enforce_whitelist: bool,
    #[serde(default)]
    pub audit_all_calls: bool,
    pub blocked_patterns: Vec<String>,
    pub timeout_seconds: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
    pub allowed_models: Vec<String>,
    pub max_temperature: f64,
    pub max_tokens: u32,
    #[serde(default)]
    pub audit_api_calls: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContentConfig {
    pub blocked_input_patterns: Vec<String>,
    pub blocked_output_patterns: Vec<String>,
    pub max_response_length: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    pub level: String,
    #[serde(default)]
    pub audit_all_requests: bool,
    #[serde(default)]
    pub audit_all_tool_calls: bool,
    #[serde(default)]
    pub log_network_requests: bool,
    #[serde(default)]
    pub log_file_access: bool,
    pub retention_days: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertsConfig {
    #[serde(default)]
    pub real_time_monitoring: bool,
    #[serde(default)]
    pub security_violation_alerts: bool,
    #[serde(default)]
    pub compliance_breach_alerts: bool,
    #[serde(default)]
    pub performance_anomaly_alerts: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnterpriseConfig {
    pub tenant_id: Option<String>,
    pub department: Option<String>,
    pub cost_center: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceViolation {
    pub timestamp: u64,
    pub category: String,
    pub message: String,
    pub details: serde_json::Value,
    pub agent_id: String,
}

#[derive(Error, Debug)]
pub enum ComplianceError {
    #[error("Network compliance violation: {0}")]
    Network(String),

    #[error("Filesystem compliance violation: {0}")]
    Filesystem(String),

    #[error("Environment variable compliance violation: {0}")]
    Environment(String),

    #[error("Tool usage compliance violation: {0}")]
    Tool(String),

    #[error("Content policy compliance violation: {0}")]
    Content(String),

    #[error("Model usage compliance violation: {0}")]
    Model(String),

    #[error("Integrity compliance violation: {0}")]
    Integrity(String),

    #[error("Configuration error: {0}")]
    Configuration(String),

    #[error("Compliance check failed: {0}")]
    CheckFailed(String),
}

// ==================== MAIN COMPLIANCE MONITOR ====================

/// 🔒 Runtime compliance enforcement system
///
/// Enforces all rules defined in sekuire.yaml:
/// - Network access control
/// - File system restrictions
/// - Tool usage limits
/// - Content filtering
/// - Environment variable access
#[derive(Debug, Clone)]
pub struct ComplianceMonitor {
    config: ComplianceConfig,
    logger: Option<Arc<crate::logger::SekuireLogger>>,

    // Pre-computed fast lookup structures
    network_allow_set: Arc<HashSet<String>>,
    network_block_set: Arc<HashSet<String>>,
    files_read_set: Arc<HashSet<String>>,
    files_write_set: Arc<HashSet<String>>,
    files_block_patterns: Arc<Vec<String>>,
    env_allow_set: Arc<HashSet<String>>,
    env_block_set: Arc<HashSet<String>>,
    allowed_tools_set: Arc<HashSet<String>>,
    tool_block_patterns: Arc<Vec<Regex>>,
    input_block_patterns: Arc<Vec<Regex>>,
    output_block_patterns: Arc<Vec<Regex>>,
    allowed_models_set: Arc<HashSet<String>>,

    // Violation tracking
    violations: Arc<Mutex<Vec<ComplianceViolation>>>,

    // Performance cache
    network_cache: Arc<RwLock<std::collections::HashMap<String, bool>>>,
    content_cache: Arc<RwLock<std::collections::HashMap<String, bool>>>,
    max_cache_size: usize,
}

impl ComplianceMonitor {
    /// Create a new compliance monitor from a config file
    pub fn new<P: AsRef<Path>>(config_path: P) -> Result<Self> {
        let config = Self::load_config(&config_path)
            .context("Failed to load compliance configuration")?;

        Self::from_config(config)
    }

    /// Create a new compliance monitor with logger integration
    pub fn new_with_logger<P: AsRef<Path>>(
        config_path: P,
        logger: Arc<crate::logger::SekuireLogger>,
    ) -> Result<Self> {
        let config = Self::load_config(&config_path)
            .context("Failed to load compliance configuration")?;

        let mut monitor = Self::from_config(config)?;
        monitor.logger = Some(logger);
        Ok(monitor)
    }

    /// Create a new compliance monitor from config
    pub fn from_config(config: ComplianceConfig) -> Result<Self> {
        // Compile regex patterns
        let mut tool_patterns = Vec::new();
        for pattern in &config.permissions.tools.blocked_patterns {
            let regex = Regex::new(&format!("(?i){}", regex::escape(pattern)))
                .context("Failed to compile tool block pattern")?;
            tool_patterns.push(regex);
        }

        let mut input_patterns = Vec::new();
        for pattern in &config.permissions.content.blocked_input_patterns {
            let regex = Regex::new(&format!("(?i){}", pattern))
                .context("Failed to compile input block pattern")?;
            input_patterns.push(regex);
        }

        let mut output_patterns = Vec::new();
        for pattern in &config.permissions.content.blocked_output_patterns {
            let regex = Regex::new(&format!("(?i){}", pattern))
                .context("Failed to compile output block pattern")?;
            output_patterns.push(regex);
        }

        // Load allowed tools (if tools.json exists)
        let allowed_tools = if Path::new("tools.json").exists() {
            let content = fs::read_to_string("tools.json")
                .context("Failed to read tools.json")?;
            let tools: Vec<serde_json::Value> = serde_json::from_str(&content)
                .context("Failed to parse tools.json")?;
            tools
                .iter()
                .filter_map(|tool| tool.get("name"))
                .filter_map(|name| name.as_str())
                .map(|name| name.to_string())
                .collect()
        } else {
            HashSet::new()
        };

        let monitor = Self {
            config: config.clone(),
            logger: None,
            network_allow_set: Arc::new(config.permissions.network.allow.into_iter().collect()),
            network_block_set: Arc::new(config.permissions.network.block.unwrap_or_default().into_iter().collect()),
            files_read_set: Arc::new(config.permissions.filesystem.allow_read.into_iter().collect()),
            files_write_set: Arc::new(config.permissions.filesystem.allow_write.into_iter().collect()),
            files_block_patterns: Arc::new(config.permissions.filesystem.block_all.unwrap_or_default()),
            env_allow_set: Arc::new(config.permissions.env.allow.into_iter().collect()),
            env_block_set: Arc::new(config.permissions.env.block.unwrap_or_default().into_iter().collect()),
            allowed_tools_set: Arc::new(allowed_tools),
            tool_block_patterns: Arc::new(tool_patterns),
            input_block_patterns: Arc::new(input_patterns),
            output_block_patterns: Arc::new(output_patterns),
            allowed_models_set: Arc::new(config.permissions.model.allowed_models.into_iter().collect()),
            violations: Arc::new(Mutex::new(Vec::new())),
            network_cache: Arc::new(RwLock::new(std::collections::HashMap::new())),
            content_cache: Arc::new(RwLock::new(std::collections::HashMap::new())),
            max_cache_size: 10000,
        };

        Ok(monitor)
    }

    fn load_config<P: AsRef<Path>>(config_path: P) -> Result<ComplianceConfig> {
        let content = fs::read_to_string(&config_path)
            .context("Failed to read configuration file")?;

        serde_yaml::from_str(&content)
            .context("Failed to parse YAML configuration")
    }

    // Note: This method is intentionally left as a no-op stub
    // Regex patterns are now initialized directly in from_config()
    fn initialize_regex_patterns(&self) -> Result<()> {
        Ok(())
    }

    // Note: This method is intentionally left as a no-op stub  
    // Tools are loaded directly in from_config()
    fn load_allowed_tools(&self) -> Result<()> {
        Ok(())
    }

    // ==================== NETWORK COMPLIANCE ====================

    /// 🌐 Check if network access is allowed
    ///
    /// # Arguments
    /// * `url` - Target URL
    /// * `method` - HTTP method (GET, POST, etc.)
    ///
    /// # Errors
    /// Returns `ComplianceError::Network` if access is blocked
    pub fn check_network_access(&self, url: &str, method: &str) -> Result<()> {
        // Check cache first
        {
            let cache = self.network_cache.read().unwrap();
            if let Some(allowed) = cache.get(url) {
                return if *allowed { Ok(()) } else {
                    Err(ComplianceError::Network(format!("Access to {} is blocked", url)))
                };
            }
        }

        // Check blocklist first
        for blocked in self.network_block_set.iter() {
            if url.starts_with(blocked) {
                let violation = self.create_violation(
                    "network",
                    format!("Network access to {} blocked by blocklist rule: {}", url, blocked),
                    serde_json::json!({
                        "url": url,
                        "method": method,
                        "rule": blocked
                    }),
                );
                self.log_violation(violation);

                // Cache result
                {
                    let mut cache = self.network_cache.write().unwrap();
                    self.set_cache_value(&mut *cache, url.to_string(), false);
                }

                return Err(ComplianceError::Network(violation.message));
            }
        }

        // Check allowlist
        if !self.network_allow_set.is_empty() {
            let allowed = self.network_allow_set.iter().any(|allowed| url.starts_with(allowed));
            if !allowed {
                let violation = self.create_violation(
                    "network",
                    format!("Network access to {} not in allowlist", url),
                    serde_json::json!({
                        "url": url,
                        "method": method
                    }),
                );
                self.log_violation(violation);

                // Cache result
                {
                    let mut cache = self.network_cache.write().unwrap();
                    self.set_cache_value(&mut *cache, url.to_string(), false);
                }

                return Err(ComplianceError::Network(violation.message));
            }
        }

        // Cache result
        {
            let mut cache = self.network_cache.write().unwrap();
            self.set_cache_value(&mut *cache, url.to_string(), true);
        }

        // Log successful access if enabled
        if self.config.permissions.network.log_network_requests {
            if let Some(logger) = &self.logger {
                logger.log_event(
                    crate::logger::EventType::NetworkAccess,
                    crate::logger::Severity::Info,
                    serde_json::json!({
                        "url": url,
                        "method": method,
                        "status": "allowed",
                    }),
                );
            }
        }

        Ok(())
    }

    // ==================== FILE SYSTEM COMPLIANCE ====================

    /// 📁 Check if file access is allowed
    ///
    /// # Arguments
    /// * `file_path` - File path
    /// * `mode` - 'read', 'write', 'execute'
    ///
    /// # Errors
    /// Returns `ComplianceError::Filesystem` if access is blocked
    pub fn check_file_access(&self, file_path: &str, mode: &str) -> Result<()> {
        // Normalize path
        let resolved_path = fs::canonicalize(file_path)
            .unwrap_or_else(|_| PathBuf::from(file_path));
        let path_str = resolved_path.to_string_lossy();

        // Check block patterns
        for blocked_pattern in self.files_block_patterns.iter() {
            if path_str.contains(blocked_pattern) || path_str.starts_with(blocked_pattern) {
                let violation = self.create_violation(
                    "filesystem",
                    format!("File access blocked by pattern: {}", blocked_pattern),
                    serde_json::json!({
                        "path": path_str,
                        "mode": mode,
                        "pattern": blocked_pattern
                    }),
                );
                self.log_violation(violation);
                return Err(ComplianceError::Filesystem(violation.message));
            }
        }

        // Check allowlists
        match mode {
            "read" => {
                if !self.files_read_set.is_empty() {
                    let allowed = self.files_read_set.iter().any(|allowed| {
                        path_str.ends_with(allowed) || path_str == *allowed
                    });
                    if !allowed {
                        let violation = self.create_violation(
                            "filesystem",
                            format!("File read access not allowed: {}", path_str),
                            serde_json::json!({
                                "path": path_str,
                                "mode": mode
                            }),
                        );
                        self.log_violation(violation);
                        return Err(ComplianceError::Filesystem(violation.message));
                    }
                }
            }
            "write" => {
                if !self.files_write_set.is_empty() {
                    let allowed = self.files_write_set.iter().any(|allowed| path_str.starts_with(allowed));
                    if !allowed {
                        let violation = self.create_violation(
                            "filesystem",
                            format!("File write access not allowed: {}", path_str),
                            serde_json::json!({
                                "path": path_str,
                                "mode": mode
                            }),
                        );
                        self.log_violation(violation);
                        return Err(ComplianceError::Filesystem(violation.message));
                    }
                }
            }
            _ => {
                return Err(ComplianceError::Filesystem(format!("Unsupported access mode: {}", mode)));
            }
        }

        // Log successful access if enabled (we'll use log_network_requests flag for file access too)
        if self.config.permissions.network.log_network_requests {
            if let Some(logger) = &self.logger {
                logger.log_event(
                    crate::logger::EventType::FileAccess,
                    crate::logger::Severity::Info,
                    serde_json::json!({
                        "path": path_str,
                        "mode": mode,
                        "status": "allowed",
                    }),
                );
            }
        }

        Ok(())
    }

    /// Safe file reading with compliance check
    pub fn safe_read_file<P: AsRef<Path>>(&self, path: P) -> Result<String> {
        let path_str = path.as_ref().to_string_lossy();
        self.check_file_access(&path_str, "read")?;

        fs::read_to_string(path)
            .context("Failed to read file")
    }

    /// Safe file writing with compliance check
    pub fn safe_write_file<P: AsRef<Path>, C: AsRef<[u8]>>(&self, path: P, contents: C) -> Result<()> {
        let path_str = path.as_ref().to_string_lossy();
        self.check_file_access(&path_str, "write")?;

        fs::write(path, contents)
            .context("Failed to write file")
    }

    // ==================== ENVIRONMENT VARIABLE COMPLIANCE ====================

    /// 🔐 Check if environment variable access is allowed
    ///
    /// # Arguments
    /// * `var_name` - Environment variable name
    ///
    /// # Errors
    /// Returns `ComplianceError::Environment` if access is blocked
    pub fn check_env_access(&self, var_name: &str) -> Result<()> {
        let var_lower = var_name.to_lowercase();

        // Check blocklist
        for blocked in self.env_block_set.iter() {
            if var_lower.contains(&blocked.to_lowercase()) {
                let violation = self.create_violation(
                    "env",
                    format!("Environment variable access blocked: {}", var_name),
                    serde_json::json!({
                        "var_name": var_name
                    }),
                );
                self.log_violation(violation);
                return Err(ComplianceError::Environment(violation.message));
            }
        }

        // Check allowlist
        if !self.env_allow_set.is_empty() && !self.env_allow_set.contains(var_name) {
            let violation = self.create_violation(
                "env",
                format!("Environment variable {} not in allowlist", var_name),
                serde_json::json!({
                    "var_name": var_name
                }),
            );
            self.log_violation(violation);
            return Err(ComplianceError::Environment(violation.message));
        }

        Ok(())
    }

    /// Safe environment variable access
    pub fn safe_get_env(&self, var_name: &str) -> Option<String> {
        self.check_env_access(var_name).ok()?;
        std::env::var(var_name).ok()
    }

    // ==================== TOOL USAGE COMPLIANCE ====================

    /// 🛠️ Check if tool usage is allowed
    ///
    /// # Arguments
    /// * `tool_name` - Name of the tool
    /// * `code_snippet` - Code snippet for pattern checking
    ///
    /// # Errors
    /// Returns `ComplianceError::Tool` if tool usage is blocked
    pub fn check_tool_usage(&self, tool_name: &str, code_snippet: Option<&str>) -> Result<()> {
        // Check blocked patterns in code
        if let Some(code) = code_snippet {
            for pattern in self.tool_block_patterns.iter() {
                if pattern.is_match(code) {
                    let violation = self.create_violation(
                        "tools",
                        format!("Tool usage contains blocked pattern: {}", pattern.as_str()),
                        serde_json::json!({
                            "tool": tool_name,
                            "pattern": pattern.as_str()
                        }),
                    );
                    self.log_violation(violation);
                    return Err(ComplianceError::Tool(violation.message));
                }
            }
        }

        // Check tool whitelist
        if self.config.permissions.tools.enforce_whitelist && !self.allowed_tools_set.contains(tool_name) {
            let violation = self.create_violation(
                "tools",
                format!("Tool {} not in approved tools.json whitelist", tool_name),
                serde_json::json!({
                    "tool": tool_name,
                    "allowed_tools": self.allowed_tools_set.iter().cloned().collect::<Vec<_>>()
                }),
            );
            self.log_violation(violation);
            return Err(ComplianceError::Tool(violation.message));
        }

        // Log successful tool usage if enabled
        if self.config.permissions.tools.audit_all_tool_calls {
            if let Some(logger) = &self.logger {
                logger.log_event(
                    crate::logger::EventType::ToolExecution,
                    crate::logger::Severity::Info,
                    serde_json::json!({
                        "tool": tool_name,
                        "status": "allowed",
                        "has_code_snippet": code_snippet.is_some(),
                    }),
                );
            }
        }

        Ok(())
    }

    // ==================== CONTENT POLICY COMPLIANCE ====================

    /// 💬 Check input content for policy violations
    ///
    /// # Arguments
    /// * `content` - Input content to check
    ///
    /// # Errors
    /// Returns `ComplianceError::Content` if content violates policy
    pub fn check_input_content(&self, content: &str) -> Result<()> {
        self.check_content(content, &self.input_block_patterns, "input")
    }

    /// 📤 Check output content for policy violations
    ///
    /// # Arguments
    /// * `content` - Output content to check
    ///
    /// # Errors
    /// Returns `ComplianceError::Content` if content violates policy
    pub fn check_output_content(&self, content: &str) -> Result<()> {
        self.check_content(content, &self.output_block_patterns, "output")
    }

    fn check_content(&self, content: &str, patterns: &[Regex], content_type: &str) -> Result<()> {
        // Check cache first
        let cache_key = format!("{}:{}", content_type, &content[..content.len().min(100)]);
        {
            let cache = self.content_cache.read().unwrap();
            if let Some(allowed) = cache.get(&cache_key) {
                return if *allowed { Ok(()) } else {
                    Err(ComplianceError::Content(format!("Content check failed for {}", content_type)))
                };
            }
        }

        // Check blocked patterns
        for pattern in patterns {
            if pattern.is_match(content) {
                let violation = self.create_violation(
                    "content",
                    format!("{} contains blocked pattern: {}", content_type, pattern.as_str()),
                    serde_json::json!({
                        "pattern": pattern.as_str(),
                        "content_length": content.len(),
                        "content_type": content_type
                    }),
                );
                self.log_violation(violation);

                // Cache result
                {
                    let mut cache = self.content_cache.write().unwrap();
                    self.set_cache_value(&mut *cache, cache_key, false);
                }

                return Err(ComplianceError::Content(violation.message));
            }
        }

        // Check response length limit
        if content_type == "output" {
            if let Some(max_length) = self.config.permissions.content.max_response_length {
                if content.len() > max_length {
                    let violation = self.create_violation(
                        "content",
                        format!("{} length {} exceeds maximum {}", content_type, content.len(), max_length),
                        serde_json::json!({
                            "content_length": content.len(),
                            "max_length": max_length,
                            "content_type": content_type
                        }),
                    );
                    self.log_violation(violation);
                    return Err(ComplianceError::Content(violation.message));
                }
            }
        }

        // Cache result
        {
            let mut cache = self.content_cache.write().unwrap();
            self.set_cache_value(&mut *cache, cache_key, true);
        }

        Ok(())
    }

    // ==================== AI MODEL COMPLIANCE ====================

    /// 🤖 Check AI model usage compliance
    ///
    /// # Arguments
    /// * `model` - Model name
    /// * `temperature` - Temperature setting
    /// * `max_tokens` - Max tokens setting
    ///
    /// # Errors
    /// Returns `ComplianceError::Model` if model usage violates rules
    pub fn check_model_usage(&self, model: &str, temperature: Option<f64>, max_tokens: Option<u32>) -> Result<()> {
        // Check allowed models
        if !self.allowed_models_set.is_empty() && !self.allowed_models_set.contains(model) {
            let violation = self.create_violation(
                "model",
                format!("Model {} not in allowlist", model),
                serde_json::json!({
                    "model": model,
                    "allowed_models": self.allowed_models_set.iter().cloned().collect::<Vec<_>>()
                }),
            );
            self.log_violation(violation);
            return Err(ComplianceError::Model(violation.message));
        }

        // Check temperature
        if let Some(temp) = temperature {
            if temp > self.config.permissions.model.max_temperature {
                let violation = self.create_violation(
                    "model",
                    format!("Temperature {} exceeds maximum {}", temp, self.config.permissions.model.max_temperature),
                    serde_json::json!({
                        "model": model,
                        "temperature": temp
                    }),
                );
                self.log_violation(violation);
                return Err(ComplianceError::Model(violation.message));
            }
        }

        // Check max tokens
        if let Some(tokens) = max_tokens {
            if tokens > self.config.permissions.model.max_tokens {
                let violation = self.create_violation(
                    "model",
                    format!("Max tokens {} exceeds maximum {}", tokens, self.config.permissions.model.max_tokens),
                    serde_json::json!({
                        "model": model,
                        "max_tokens": tokens
                    }),
                );
                self.log_violation(violation);
                return Err(ComplianceError::Model(violation.message));
            }
        }

        Ok(())
    }

    // ==================== INTEGRITY CHECKING ====================

    /// 🔢 Generate BLAKE3 hash for content integrity checking
    pub fn hash_content(&self, content: &str) -> Result<String> {
        use blake3::Hasher;

        let mut hasher = Hasher::new();
        hasher.update(content.as_bytes());
        Ok(format!("{:x}", hasher.finalize()))
    }

    /// Verify file hasn't been modified
    pub fn check_file_integrity(&self, file_path: &str, expected_hash: &str) -> Result<()> {
        let content = fs::read_to_string(file_path)
            .context("Failed to read file for integrity check")?;

        let actual_hash = self.hash_content(&content)?;

        if actual_hash != expected_hash {
            let violation = self.create_violation(
                "integrity",
                format!("File integrity check failed: {}", file_path),
                serde_json::json!({
                    "file": file_path,
                    "expected": expected_hash,
                    "actual": actual_hash
                }),
            );
            self.log_violation(violation);
            return Err(ComplianceError::Integrity(violation.message));
        }

        Ok(())
    }

    // ==================== MONITORING & LOGGING ====================

    fn create_violation(&self, category: &str, message: String, details: serde_json::Value) -> ComplianceViolation {
        ComplianceViolation {
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            category: category.to_string(),
            message,
            details,
            agent_id: self.config.agent.name.clone(),
        }
    }

    fn log_violation(&self, violation: ComplianceViolation) {
        // Add to violations list
        {
            let mut violations = self.violations.lock().unwrap();
            violations.push(violation.clone());

            // Keep list size manageable
            if violations.len() > 10000 {
                violations.drain(0..5000);
            }
        }

        // Console warning for development
        eprintln!("⚠️ Compliance Violation [{}]: {}", violation.category, violation.message);

        // Log to Sekuire API via logger
        if let Some(logger) = &self.logger {
            logger.log_event(
                crate::logger::EventType::PolicyViolation,
                crate::logger::Severity::Error,
                serde_json::json!({
                    "category": violation.category,
                    "message": violation.message.clone(),
                    "details": violation.details,
                    "agent_id": violation.agent_id,
                    "timestamp": violation.timestamp,
                }),
            );
        }

        // Send alerts if configured
        if let Some(alerts) = &self.config.alerts {
            match violation.category.as_str() {
                "network" if alerts.security_violation_alerts => self.send_security_alert(&violation),
                "filesystem" if alerts.security_violation_alerts => self.send_security_alert(&violation),
                "tools" if alerts.compliance_breach_alerts => self.send_security_alert(&violation),
                "content" if alerts.compliance_breach_alerts => self.send_security_alert(&violation),
                _ => {}
            }
        }
    }

    /// 🚨 Send security alert to monitoring systems
    fn send_security_alert(&self, violation: &ComplianceViolation) {
        // TODO: Integrate with enterprise monitoring systems
        // - Send to SIEM
        // - Send to security teams
        // - Create tickets
        // - Send to webhook endpoints

        println!("🚨 Security Alert: {} - {}", violation.category, violation.message);
    }

    /// 📊 Get current compliance status and statistics
    pub fn get_compliance_status(&self) -> serde_json::Value {
        let violations = self.violations.lock().unwrap();
        let network_cache = self.network_cache.read().unwrap();
        let content_cache = self.content_cache.read().unwrap();

        let last_violation = violations.last().cloned();

        serde_json::json!({
            "config_loaded": true,
            "violations_count": violations.len(),
            "last_violation": last_violation,
            "rules_enforced": [
                "network_access",
                "file_access",
                "tool_usage",
                "content_filtering",
                "env_var_access",
                "model_usage"
            ],
            "security_stats": {
                "network_rules": self.network_allow_set.len() + self.network_block_set.len(),
                "allowed_tools": self.allowed_tools_set.len(),
                "content_patterns": self.input_block_patterns.len() + self.output_block_patterns.len(),
                "cache_size": network_cache.len() + content_cache.len()
            }
        })
    }

    /// Get recent violations
    pub fn get_violations(&self, category: Option<&str>, limit: Option<usize>) -> Vec<ComplianceViolation> {
        let violations = self.violations.lock().unwrap();

        let filtered = if let Some(cat) = category {
            violations.iter().filter(|v| v.category == cat).cloned().collect()
        } else {
            violations.clone()
        };

        if let Some(limit) = limit {
            filtered.into_iter().rev().take(limit).collect()
        } else {
            filtered
        }
    }

    /// Clear violation log
    pub fn clear_violations(&self) {
        self.violations.lock().unwrap().clear();
        self.network_cache.write().unwrap().clear();
        self.content_cache.write().unwrap().clear();
    }

    // ==================== PERFORMANCE OPTIMIZATIONS ====================

    fn set_cache_value<K, V>(&self, cache: &mut std::collections::HashMap<K, V>, key: K, value: V) {
        if cache.len() >= self.max_cache_size {
            // Remove oldest entries (simple FIFO)
            let keys_to_delete: Vec<K> = cache.keys().take(self.max_cache_size / 5).cloned().collect();
            for key in keys_to_delete {
                cache.remove(&key);
            }
        }
        cache.insert(key, value);
    }

    /// Pre-warm caches with common operations
    pub fn pre_warm_caches(&self) {
        // Pre-warm network cache with common domains
        let common_domains = [
            "https://api.openai.com",
            "https://api.anthropic.com",
            "https://registry.sekuire.ai",
        ];

        for domain in &common_domains {
            let _ = self.check_network_access(domain, "GET");
        }
    }
}

// ==================== MACRO FOR COMPLIANCE ENFORCEMENT ====================

/// Macro to enforce compliance on a function call
#[macro_export]
macro_rules! enforce_compliance {
    ($monitor:expr, $check:expr, $error_type:ident, $message:expr) => {
        if let Err(e) = $check {
            return Err($crate::compliance::ComplianceError::$error_type(format!("{}: {}", $message, e)));
        }
    };
}

/// Macro to enforce network compliance
#[macro_export]
macro_rules! enforce_network {
    ($monitor:expr, $url:expr, $method:expr) => {
        $crate::enforce_compliance!($monitor, $monitor.check_network_access($url, $method), Network, "Network access denied")
    };
}

/// Macro to enforce file access compliance
#[macro_export]
macro_rules! enforce_file_access {
    ($monitor:expr, $path:expr, $mode:expr) => {
        $crate::enforce_compliance!($monitor, $monitor.check_file_access($path, $mode), Filesystem, "File access denied")
    };
}

/// Macro to enforce tool usage compliance
#[macro_export]
macro_rules! enforce_tool_usage {
    ($monitor:expr, $tool:expr, $code:expr) => {
        $crate::enforce_compliance!($monitor, $monitor.check_tool_usage($tool, $code), Tool, "Tool usage denied")
    };
}

/// Macro to enforce content compliance
#[macro_export]
macro_rules! enforce_content {
    ($monitor:expr, $content:expr, $direction:expr) => {
        let check_result = match $direction {
            "input" => $monitor.check_input_content($content),
            "output" => $monitor.check_output_content($content),
            _ => return Err($crate::compliance::ComplianceError::Content("Invalid content direction".to_string())),
        };
        $crate::enforce_compliance!($monitor, check_result, Content, "Content policy violation")
    };
}

// ==================== TESTS ====================

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;
    use std::io::Write;

    #[test]
    fn test_config_loading() {
        let config_content = r#"
agent:
  name: "test-agent"
  version: "1.0.0"

permissions:
  network:
    allow: ["api.openai.com"]
    block: ["github.com"]
  filesystem:
    allow_read: ["config/"]
    allow_write: ["logs/"]
  env:
    allow: ["OPENAI_API_KEY"]
  tools:
    enforce_whitelist: true
    blocked_patterns: ["os.system", "eval("]
  model:
    allowed_models: ["gpt-4"]
    max_temperature: 0.7
    max_tokens: 1000
  content:
    blocked_input_patterns: ["password"]
    blocked_output_patterns: ["sudo su"]
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(config_content.as_bytes()).unwrap();

        let monitor = ComplianceMonitor::new(temp_file.path()).unwrap();

        assert_eq!(monitor.config.agent.name, "test-agent");
        assert_eq!(monitor.network_allow_set.len(), 1);
        assert!(monitor.network_allow_set.contains("api.openai.com"));
    }

    #[test]
    fn test_network_compliance() {
        let config = ComplianceConfig {
            agent: AgentConfig {
                name: "test".to_string(),
                version: "1.0.0".to_string(),
                tenant: None,
                compliance_level: None,
            },
            permissions: PermissionsConfig {
                network: NetworkConfig {
                    default_deny: false,
                    allow: vec!["api.openai.com".to_string()],
                    block: Some(vec!["github.com".to_string()]),
                },
                filesystem: FilesystemConfig {
                    default_deny: false,
                    allow_read: vec![],
                    allow_write: vec![],
                    block_all: None,
                },
                env: EnvConfig {
                    default_deny: false,
                    allow: vec![],
                    block: None,
                },
                tools: ToolsConfig {
                    enforce_whitelist: true,
                    audit_all_calls: false,
                    blocked_patterns: vec![],
                    timeout_seconds: None,
                },
                model: ModelConfig {
                    allowed_models: vec![],
                    max_temperature: 1.0,
                    max_tokens: 1000,
                    audit_api_calls: false,
                },
                content: ContentConfig {
                    blocked_input_patterns: vec![],
                    blocked_output_patterns: vec![],
                    max_response_length: None,
                },
            },
            logging: None,
            alerts: None,
            enterprise: None,
        };

        let monitor = ComplianceMonitor::from_config(config).unwrap();

        // Should allow allowed domain
        assert!(monitor.check_network_access("https://api.openai.com/v1/chat", "POST").is_ok());

        // Should block blocked domain
        assert!(monitor.check_network_access("https://github.com/repo", "GET").is_err());

        // Should block non-allowed domain
        assert!(monitor.check_network_access("https://example.com", "GET").is_err());
    }

    #[test]
    fn test_content_compliance() {
        let config = ComplianceConfig {
            agent: AgentConfig {
                name: "test".to_string(),
                version: "1.0.0".to_string(),
                tenant: None,
                compliance_level: None,
            },
            permissions: PermissionsConfig {
                network: NetworkConfig {
                    default_deny: false,
                    allow: vec![],
                    block: None,
                },
                filesystem: FilesystemConfig {
                    default_deny: false,
                    allow_read: vec![],
                    allow_write: vec![],
                    block_all: None,
                },
                env: EnvConfig {
                    default_deny: false,
                    allow: vec![],
                    block: None,
                },
                tools: ToolsConfig {
                    enforce_whitelist: true,
                    audit_all_calls: false,
                    blocked_patterns: vec![],
                    timeout_seconds: None,
                },
                model: ModelConfig {
                    allowed_models: vec![],
                    max_temperature: 1.0,
                    max_tokens: 1000,
                    audit_api_calls: false,
                },
                content: ContentConfig {
                    blocked_input_patterns: vec!["password".to_string(), "secret".to_string()],
                    blocked_output_patterns: vec!["sudo su".to_string()],
                    max_response_length: None,
                },
            },
            logging: None,
            alerts: None,
            enterprise: None,
        };

        let monitor = ComplianceMonitor::from_config(config).unwrap();

        // Should block input with blocked pattern
        assert!(monitor.check_input_content("What's the admin password?").is_err());

        // Should allow clean input
        assert!(monitor.check_input_content("Hello, how can I help you?").is_ok());

        // Should block output with blocked pattern
        assert!(monitor.check_output_content("Run: sudo su to get root").is_err());

        // Should allow clean output
        assert!(monitor.check_output_content("Here's the information you requested").is_ok());
    }
}