soma-core 2.0.0

World's first production-ready self-aware development system with meta-cognitive capabilities and cognitive reasoning engine for intelligent development platforms
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
// Issue #29: File Protection & Constraints System
// Simplified implementation focusing on core functionality

use crate::edit_control::{ModifiableEdit, ValidationResult, ValidationSeverity, ApprovalLevel};
use crate::classification::edit_classifier_working::{EditClassificationSystem, ClassificationRecommendation};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use anyhow::{Result, anyhow};

/// File protection and constraints system
#[derive(Debug)]
pub struct FileProtectionSystem {
    /// Protection rules organized by file patterns
    protection_rules: HashMap<String, FileProtectionRule>,
    
    /// Function-level protection constraints
    function_constraints: HashMap<String, FunctionConstraint>,
    
    /// Global protection configuration
    config: ProtectionConfig,
    
    /// Integration with classification system
    classification_system: EditClassificationSystem,
}

/// Configuration for protection system behavior
#[derive(Debug, Clone)]
pub struct ProtectionConfig {
    /// Enable strict mode (reject all protected modifications)
    pub strict_mode: bool,
    
    /// Allow emergency bypass with elevated approval
    pub emergency_bypass_enabled: bool,
    
    /// Required approval level for emergency bypass
    pub emergency_bypass_level: ApprovalLevel,
    
    /// Enable audit logging for all protection decisions
    pub audit_logging: bool,
    
    /// Default protection level for unspecified files
    pub default_protection_level: ProtectionLevel,
}

impl Default for ProtectionConfig {
    fn default() -> Self {
        Self {
            strict_mode: false,
            emergency_bypass_enabled: true,
            emergency_bypass_level: ApprovalLevel::Critical,
            audit_logging: true,
            default_protection_level: ProtectionLevel::Standard,
        }
    }
}

/// File-level protection rule
#[derive(Debug, Clone)]
pub struct FileProtectionRule {
    /// Pattern to match files (simple glob-style)
    pub pattern: String,
    
    /// Protection level
    pub protection_level: ProtectionLevel,
    
    /// Allowed edit types
    pub allowed_edit_types: HashSet<EditType>,
    
    /// Forbidden patterns in content
    pub forbidden_patterns: Vec<String>,
    
    /// Required patterns that must remain
    pub required_patterns: Vec<String>,
    
    /// Maximum lines that can be modified
    pub max_lines_modified: Option<usize>,
    
    /// Justification for protection
    pub reason: String,
}

/// Function-level constraint
#[derive(Debug, Clone)]
pub struct FunctionConstraint {
    /// File pattern where function is located
    pub file_pattern: String,
    
    /// Function name or pattern
    pub function_pattern: String,
    
    /// Protection level for this function
    pub protection_level: ProtectionLevel,
    
    /// Documentation requirements
    pub documentation_required: bool,
}

/// Protection levels with increasing restrictiveness
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum ProtectionLevel {
    /// No protection - all edits allowed
    None,
    
    /// Standard protection - basic constraints
    Standard,
    
    /// High protection - strict constraints
    High,
    
    /// Critical protection - minimal allowed changes
    Critical,
    
    /// Read-only - no modifications allowed
    ReadOnly,
}

/// Types of edits that can be controlled
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EditType {
    ContentModification,
    FileRename,
    FileDeletion,
    CommentModification,
    DocumentationUpdate,
}

/// Protection validation result
#[derive(Debug, Clone)]
pub struct ProtectionResult {
    /// Whether the edit is allowed
    pub allowed: bool,
    
    /// Protection level that was applied
    pub applied_protection: ProtectionLevel,
    
    /// Validation results from all checks
    pub validation_results: Vec<ValidationResult>,
    
    /// Required approval level if elevated approval needed
    pub required_approval_level: Option<ApprovalLevel>,
    
    /// Applied constraints
    pub applied_constraints: Vec<String>,
    
    /// Recommendations for compliance
    pub recommendations: Vec<String>,
}

impl FileProtectionSystem {
    /// Create new protection system with default configuration
    pub fn new() -> Self {
        Self::with_config(ProtectionConfig::default())
    }
    
    /// Create protection system with custom configuration
    pub fn with_config(config: ProtectionConfig) -> Self {
        Self {
            protection_rules: Self::default_protection_rules(),
            function_constraints: Self::default_function_constraints(),
            config,
            classification_system: EditClassificationSystem::new(),
        }
    }
    
    /// Validate edit against all protection constraints
    pub fn validate_edit(&self, edit: &ModifiableEdit) -> Result<ProtectionResult> {
        let file_path = Path::new(&edit.base_edit.file);
        
        // Step 1: Determine applicable protection rules
        let applicable_rules = self.find_applicable_rules(file_path);
        
        // Step 2: Check file-level constraints
        let file_results = self.validate_file_constraints(edit, &applicable_rules)?;
        
        // Step 3: Check function-level constraints if applicable
        let function_results = self.validate_function_constraints(edit)?;
        
        // Step 4: Integrate with classification system
        let classification_results = self.validate_classification_constraints(edit)?;
        
        // Step 5: Combine all results
        let all_results = [file_results, function_results, classification_results].concat();
        
        // Step 6: Determine overall protection result
        self.determine_protection_result(edit, &applicable_rules, all_results)
    }
    
    /// Add new file protection rule
    pub fn add_protection_rule(&mut self, pattern: String, rule: FileProtectionRule) {
        self.protection_rules.insert(pattern, rule);
    }
    
    /// Add function-level constraint
    pub fn add_function_constraint(&mut self, name: String, constraint: FunctionConstraint) {
        self.function_constraints.insert(name, constraint);
    }
    
    /// Get configuration for display purposes
    pub fn config(&self) -> &ProtectionConfig {
        &self.config
    }
    
    /// Find protection rules applicable to a file
    fn find_applicable_rules(&self, file_path: &Path) -> Vec<&FileProtectionRule> {
        let mut applicable = Vec::new();
        
        for (pattern, rule) in &self.protection_rules {
            if self.matches_pattern(file_path, pattern) {
                applicable.push(rule);
            }
        }
        
        // Sort by protection level (most restrictive first)
        applicable.sort_by(|a, b| b.protection_level.cmp(&a.protection_level));
        
        applicable
    }
    
    /// Check if file path matches protection pattern (simple glob matching)
    fn matches_pattern(&self, file_path: &Path, pattern: &str) -> bool {
        let path_str = file_path.to_string_lossy();
        
        // Simple pattern matching
        if pattern.contains("*") {
            let prefix = pattern.split("*").next().unwrap_or("");
            let suffix = pattern.split("*").last().unwrap_or("");
            path_str.starts_with(prefix) && path_str.ends_with(suffix)
        } else {
            path_str == pattern
        }
    }
    
    /// Validate file-level constraints
    fn validate_file_constraints(
        &self, 
        edit: &ModifiableEdit, 
        rules: &[&FileProtectionRule]
    ) -> Result<Vec<ValidationResult>> {
        let mut results = Vec::new();
        
        for rule in rules {
            // Check if edit type is allowed
            let edit_type = self.determine_edit_type(edit);
            if !rule.allowed_edit_types.contains(&edit_type) {
                results.push(ValidationResult {
                    validator_name: "file_protection".to_string(),
                    passed: false,
                    message: format!("Edit type {:?} not allowed for file {}", edit_type, edit.base_edit.file),
                    severity: ValidationSeverity::Error,
                });
            }
            
            // Check forbidden patterns
            for forbidden in &rule.forbidden_patterns {
                if edit.base_edit.new_code.contains(forbidden) {
                    results.push(ValidationResult {
                        validator_name: "forbidden_pattern".to_string(),
                        passed: false,
                        message: format!("Forbidden pattern '{}' found in edit", forbidden),
                        severity: ValidationSeverity::Critical,
                    });
                }
            }
            
            // Check required patterns
            for required in &rule.required_patterns {
                if !edit.compute_final_code().contains(required) {
                    results.push(ValidationResult {
                        validator_name: "required_pattern".to_string(),
                        passed: false,
                        message: format!("Required pattern '{}' missing after edit", required),
                        severity: ValidationSeverity::Error,
                    });
                }
            }
            
            // Check line count limits
            if let Some(max_lines) = rule.max_lines_modified {
                let lines_modified = edit.base_edit.new_code.lines().count();
                if lines_modified > max_lines {
                    results.push(ValidationResult {
                        validator_name: "line_count_limit".to_string(),
                        passed: false,
                        message: format!("Edit modifies {} lines, maximum allowed is {}", lines_modified, max_lines),
                        severity: ValidationSeverity::Warning,
                    });
                }
            }
        }
        
        Ok(results)
    }
    
    /// Validate function-level constraints
    fn validate_function_constraints(&self, edit: &ModifiableEdit) -> Result<Vec<ValidationResult>> {
        let mut results = Vec::new();
        let file_path = Path::new(&edit.base_edit.file);
        
        for (_constraint_name, constraint) in &self.function_constraints {
            if self.matches_pattern(file_path, &constraint.file_pattern) {
                // Check if edit affects this function
                if self.edit_affects_function(edit, &constraint.function_pattern) {
                    let function_results = self.validate_function_constraint(edit, constraint)?;
                    results.extend(function_results);
                }
            }
        }
        
        Ok(results)
    }
    
    /// Integrate with classification system for additional validation
    fn validate_classification_constraints(&self, edit: &ModifiableEdit) -> Result<Vec<ValidationResult>> {
        let classified = self.classification_system.classify_edit(edit)
            .map_err(|e| anyhow!("Classification failed: {}", e))?;
        
        let mut results = Vec::new();
        
        // Check if classified risk requires additional protection
        if classified.risk_assessment.overall_score > 0.8 {
            match classified.recommendation {
                ClassificationRecommendation::RequireReview { concerns } => {
                    results.push(ValidationResult {
                        validator_name: "classification_protection".to_string(),
                        passed: false,
                        message: format!("High-risk edit requires review: {:?}", concerns),
                        severity: ValidationSeverity::Error,
                    });
                }
                ClassificationRecommendation::Escalate { target_level, reason } => {
                    results.push(ValidationResult {
                        validator_name: "classification_protection".to_string(),
                        passed: false,
                        message: format!("Edit requires escalation to {}: {}", target_level, reason),
                        severity: ValidationSeverity::Critical,
                    });
                }
                _ => {}
            }
        }
        
        Ok(results)
    }
    
    /// Determine final protection result
    fn determine_protection_result(
        &self,
        _edit: &ModifiableEdit,
        rules: &[&FileProtectionRule],
        validation_results: Vec<ValidationResult>
    ) -> Result<ProtectionResult> {
        let has_critical_failures = validation_results.iter()
            .any(|r| !r.passed && r.severity == ValidationSeverity::Critical);
        
        let has_errors = validation_results.iter()
            .any(|r| !r.passed && r.severity == ValidationSeverity::Error);
        
        let applied_protection = rules.first()
            .map(|r| r.protection_level.clone())
            .unwrap_or(self.config.default_protection_level.clone());
        
        let allowed = if self.config.strict_mode {
            !has_critical_failures && !has_errors
        } else {
            !has_critical_failures
        };
        
        let required_approval_level = if has_critical_failures {
            Some(ApprovalLevel::Critical)
        } else if has_errors {
            Some(ApprovalLevel::High)
        } else {
            None
        };
        
        Ok(ProtectionResult {
            allowed,
            applied_protection,
            validation_results,
            required_approval_level,
            applied_constraints: rules.iter().map(|r| r.reason.clone()).collect(),
            recommendations: self.generate_recommendations(rules),
        })
    }
    
    // Helper methods
    fn determine_edit_type(&self, edit: &ModifiableEdit) -> EditType {
        // Simplified edit type detection
        if edit.base_edit.new_code.contains("//") || edit.base_edit.new_code.contains("/*") {
            EditType::CommentModification
        } else if edit.base_edit.file.ends_with(".md") || edit.base_edit.file.ends_with(".txt") {
            EditType::DocumentationUpdate
        } else {
            EditType::ContentModification
        }
    }
    
    fn edit_affects_function(&self, edit: &ModifiableEdit, function_pattern: &str) -> bool {
        let simple_pattern = function_pattern.replace("*", "");
        edit.compute_final_code().contains(&format!("fn {}", simple_pattern))
    }
    
    fn validate_function_constraint(&self, edit: &ModifiableEdit, constraint: &FunctionConstraint) -> Result<Vec<ValidationResult>> {
        let mut results = Vec::new();
        
        // Check if documentation is required
        if constraint.documentation_required {
            let has_docs = edit.compute_final_code().contains("///") || edit.compute_final_code().contains("/**");
            results.push(ValidationResult {
                validator_name: "function_documentation".to_string(),
                passed: has_docs,
                message: if has_docs {
                    "Function documentation found".to_string()
                } else {
                    "Function documentation required".to_string()
                },
                severity: if has_docs { ValidationSeverity::Info } else { ValidationSeverity::Warning },
            });
        }
        
        Ok(results)
    }
    
    fn generate_recommendations(&self, rules: &[&FileProtectionRule]) -> Vec<String> {
        let mut recommendations = Vec::new();
        
        for rule in rules {
            if rule.protection_level >= ProtectionLevel::High {
                recommendations.push(format!("Consider elevated approval for protected file: {}", rule.reason));
            }
        }
        
        if recommendations.is_empty() {
            recommendations.push("No specific recommendations for this edit".to_string());
        }
        
        recommendations
    }
    
    // Default configuration methods
    fn default_protection_rules() -> HashMap<String, FileProtectionRule> {
        let mut rules = HashMap::new();
        
        // Security-critical files
        rules.insert("src/security/*".to_string(), FileProtectionRule {
            pattern: "src/security/*".to_string(),
            protection_level: ProtectionLevel::Critical,
            allowed_edit_types: [EditType::DocumentationUpdate, EditType::CommentModification].iter().cloned().collect(),
            forbidden_patterns: vec!["password".to_string(), "hardcoded".to_string()],
            required_patterns: vec!["#[cfg(test)]".to_string()],
            max_lines_modified: Some(10),
            reason: "Security-critical code requires maximum protection".to_string(),
        });
        
        // Configuration files
        rules.insert("Cargo.toml".to_string(), FileProtectionRule {
            pattern: "Cargo.toml".to_string(),
            protection_level: ProtectionLevel::High,
            allowed_edit_types: [EditType::ContentModification, EditType::DocumentationUpdate].iter().cloned().collect(),
            forbidden_patterns: vec!["unsafe".to_string()],
            required_patterns: vec![],
            max_lines_modified: Some(5),
            reason: "Dependency changes require careful review".to_string(),
        });
        
        rules
    }
    
    fn default_function_constraints() -> HashMap<String, FunctionConstraint> {
        let mut constraints = HashMap::new();
        
        // Critical security functions
        constraints.insert("auth_*".to_string(), FunctionConstraint {
            file_pattern: "src/security/*".to_string(),
            function_pattern: "auth_*".to_string(),
            protection_level: ProtectionLevel::Critical,
            documentation_required: true,
        });
        
        constraints
    }
}

// Default implementations
impl Default for FileProtectionSystem {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agents::gpt4_agent::ProposedEdit;
    
    fn create_test_edit(file: &str, content: &str, reason: &str) -> ModifiableEdit {
        let proposed = ProposedEdit {
            file: file.to_string(),
            line_range: (1, 5),
            new_code: content.to_string(),
            reason: reason.to_string(),
            confidence: 0.8,
        };
        ModifiableEdit::from_proposed_edit(proposed)
    }
    
    #[test]
    fn test_protection_system_creation() {
        let system = FileProtectionSystem::new();
        assert_eq!(system.config.default_protection_level, ProtectionLevel::Standard);
        assert!(system.config.emergency_bypass_enabled);
    }
    
    #[test]
    fn test_file_pattern_matching() {
        let system = FileProtectionSystem::new();
        let path = Path::new("src/security/auth.rs");
        
        let matches = system.matches_pattern(path, "src/security/*");
        assert!(matches);
        
        let no_match = system.matches_pattern(path, "src/public/*");
        assert!(!no_match);
    }
    
    #[test]
    fn test_security_file_protection() {
        let system = FileProtectionSystem::new();
        let edit = create_test_edit(
            "src/security/auth.rs",
            "let password = \"hardcoded123\";",
            "Add authentication"
        );
        
        let result = system.validate_edit(&edit).unwrap();
        
        assert!(!result.allowed);
        assert_eq!(result.applied_protection, ProtectionLevel::Critical);
        assert!(result.validation_results.iter().any(|r| !r.passed));
    }
    
    #[test]
    fn test_documentation_edit_allowed() {
        let system = FileProtectionSystem::new();
        let edit = create_test_edit(
            "README.md",
            "# Updated Documentation\nThis is safe content.",
            "Update documentation"
        );
        
        let result = system.validate_edit(&edit).unwrap();
        
        assert!(result.allowed);
        assert_eq!(result.applied_protection, ProtectionLevel::Standard);
    }
}