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
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
// Custom Agent Configuration System for SOMA-CORE
// Issue #30: User-defined agent personalities, custom prompting, and behavior modification
// All comments in English (US) per coding_guidelines.md

#![allow(dead_code)] // Keep API for future expansion

use crate::agents::gpt4_agent::{CognitiveAgent, ProposedEdit, Insight, ExecutionTrace};
use crate::memory::SymbolicContext;
use crate::dag::Node;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use anyhow::{anyhow, Result};

/// Configuration for a custom agent personality
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentPersonality {
    pub name: String,
    pub description: String,
    pub focus_areas: Vec<String>,
    pub coding_style: CodingStyle,
    pub risk_tolerance: RiskTolerance,
    pub communication_style: CommunicationStyle,
    pub priority_weights: PriorityWeights,
}

/// Coding style preferences for the agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodingStyle {
    pub prefers_verbose_comments: bool,
    pub prefers_short_functions: bool,
    pub prefers_explicit_types: bool,
    pub prefers_error_handling: ErrorHandlingStyle,
    pub formatting_preferences: FormattingPreferences,
}

/// Error handling style preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ErrorHandlingStyle {
    Explicit,    // Always use Result<T, E>
    Panic,       // Use unwrap() and expect()
    Optional,    // Use Option<T> where possible
    Hybrid,      // Mix based on context
}

/// Code formatting preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormattingPreferences {
    pub max_line_length: usize,
    pub prefer_single_line_blocks: bool,
    pub indent_style: IndentStyle,
    pub brace_style: BraceStyle,
}

/// Indentation style
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IndentStyle {
    Spaces(usize),
    Tabs,
}

/// Brace placement style
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BraceStyle {
    SameLine,    // K&R style
    NextLine,    // Allman style
    Mixed,       // Context-dependent
}

/// Risk tolerance for suggesting changes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RiskTolerance {
    Conservative,  // Only suggest safe, well-tested changes
    Moderate,      // Balance between safety and innovation
    Aggressive,    // Suggest bold improvements even if risky
    Adaptive,      // Adjust based on project context
}

/// Communication style for explanations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CommunicationStyle {
    Concise,      // Brief, to-the-point explanations
    Detailed,     // Comprehensive explanations with examples
    Tutorial,     // Educational style with learning focus
    Professional, // Formal, business-oriented tone
    Friendly,     // Casual, approachable tone
}

/// Priority weights for different improvement aspects
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PriorityWeights {
    pub performance: f64,
    pub readability: f64,
    pub maintainability: f64,
    pub security: f64,
    pub testing: f64,
    pub documentation: f64,
}

/// Custom prompting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomPromptConfig {
    pub base_prompt: String,
    pub context_templates: HashMap<String, String>,
    pub response_format_preferences: ResponseFormatPreferences,
    pub custom_instructions: Vec<String>,
}

/// Response format preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResponseFormatPreferences {
    pub include_confidence_scores: bool,
    pub include_reasoning_steps: bool,
    pub include_alternative_options: bool,
    pub preferred_explanation_length: ExplanationLength,
}

/// Preferred explanation length
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExplanationLength {
    Minimal,     // One-line explanations
    Brief,       // 1-2 sentences
    Standard,    // 2-3 sentences
    Detailed,    // Paragraph-length
    Comprehensive, // Multiple paragraphs
}

/// User preference learning and adaptation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreferenceLearning {
    pub accepted_suggestions: Vec<SuggestionRecord>,
    pub rejected_suggestions: Vec<SuggestionRecord>,
    pub modification_patterns: Vec<ModificationPattern>,
    pub learned_preferences: LearnedPreferences,
}

/// Record of a suggestion and user action
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestionRecord {
    pub suggestion_type: String,
    pub context: String,
    pub confidence: f64,
    pub user_action: UserAction,
    pub timestamp: String,
    pub project_context: String,
}

/// User action on a suggestion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum UserAction {
    Accepted,
    Rejected,
    Modified,
    Deferred,
}

/// Pattern in how user modifies suggestions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModificationPattern {
    pub pattern_type: String,
    pub frequency: usize,
    pub description: String,
    pub confidence: f64,
}

/// Learned preferences from user interactions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LearnedPreferences {
    pub preferred_suggestion_types: HashMap<String, f64>,
    pub disliked_patterns: Vec<String>,
    pub context_specific_preferences: HashMap<String, ContextualPreference>,
    pub optimal_confidence_thresholds: HashMap<String, f64>,
}

/// Context-specific preferences
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextualPreference {
    pub context: String,
    pub preference_adjustments: PriorityWeights,
    pub specific_instructions: Vec<String>,
}

/// Project-specific context configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectContext {
    pub project_name: String,
    pub project_type: ProjectType,
    pub languages: Vec<String>,
    pub frameworks: Vec<String>,
    pub coding_standards: Vec<String>,
    pub specific_constraints: Vec<String>,
    pub team_preferences: Option<TeamPreferences>,
}

/// Type of software project
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ProjectType {
    WebApplication,
    Library,
    SystemTool,
    Game,
    Mobile,
    DataScience,
    MachineLearning,
    Embedded,
    Other(String),
}

/// Team-wide preferences and standards
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TeamPreferences {
    pub shared_coding_style: CodingStyle,
    pub review_requirements: ReviewRequirements,
    pub testing_standards: TestingStandards,
    pub documentation_requirements: DocumentationRequirements,
}

/// Code review requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewRequirements {
    pub require_peer_review: bool,
    pub minimum_reviewers: usize,
    pub require_security_review: bool,
    pub require_performance_review: bool,
}

/// Testing standards and requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestingStandards {
    pub minimum_coverage: f64,
    pub require_unit_tests: bool,
    pub require_integration_tests: bool,
    pub test_naming_convention: String,
}

/// Documentation requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentationRequirements {
    pub require_function_docs: bool,
    pub require_module_docs: bool,
    pub require_examples: bool,
    pub documentation_style: DocumentationStyle,
}

/// Style of documentation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DocumentationStyle {
    Minimal,      // Basic function signatures
    Standard,     // Function descriptions and parameters
    Comprehensive, // Full examples and edge cases
    Tutorial,     // Learning-focused documentation
}

/// Main custom agent configuration system
pub struct CustomAgentConfigurationSystem {
    personalities: HashMap<String, AgentPersonality>,
    prompt_configs: HashMap<String, CustomPromptConfig>,
    preference_learning: PreferenceLearning,
    project_contexts: HashMap<String, ProjectContext>,
    active_configuration: Option<String>,
    config_file_path: String,
}

impl CustomAgentConfigurationSystem {
    /// Create a new configuration system
    pub fn new(config_dir: &str) -> Self {
        let config_file_path = format!("{}/agent_configurations.json", config_dir);
        
        Self {
            personalities: HashMap::new(),
            prompt_configs: HashMap::new(),
            preference_learning: PreferenceLearning::new(),
            project_contexts: HashMap::new(),
            active_configuration: None,
            config_file_path,
        }
    }

    /// Load configuration from file
    pub fn load_from_file(&mut self) -> Result<()> {
        if Path::new(&self.config_file_path).exists() {
            let content = fs::read_to_string(&self.config_file_path)?;
            let config: SavedConfiguration = serde_json::from_str(&content)?;
            
            self.personalities = config.personalities;
            self.prompt_configs = config.prompt_configs;
            self.preference_learning = config.preference_learning;
            self.project_contexts = config.project_contexts;
            self.active_configuration = config.active_configuration;
        } else {
            // Create default configuration
            self.create_default_personalities();
            self.create_default_prompt_configs();
            self.save_to_file()?;
        }
        
        Ok(())
    }

    /// Save configuration to file
    pub fn save_to_file(&self) -> Result<()> {
        let config = SavedConfiguration {
            personalities: self.personalities.clone(),
            prompt_configs: self.prompt_configs.clone(),
            preference_learning: self.preference_learning.clone(),
            project_contexts: self.project_contexts.clone(),
            active_configuration: self.active_configuration.clone(),
        };
        
        let content = serde_json::to_string_pretty(&config)?;
        
        // Ensure directory exists
        if let Some(parent) = Path::new(&self.config_file_path).parent() {
            fs::create_dir_all(parent)?;
        }
        
        fs::write(&self.config_file_path, content)?;
        Ok(())
    }

    /// Create default agent personalities
    fn create_default_personalities(&mut self) {
        // Performance-focused agent
        let performance_agent = AgentPersonality {
            name: "PerformanceOptimizer".to_string(),
            description: "Focuses on code performance, efficiency, and optimization".to_string(),
            focus_areas: vec![
                "algorithm_optimization".to_string(),
                "memory_usage".to_string(),
                "cpu_efficiency".to_string(),
                "caching_strategies".to_string(),
            ],
            coding_style: CodingStyle {
                prefers_verbose_comments: false,
                prefers_short_functions: true,
                prefers_explicit_types: true,
                prefers_error_handling: ErrorHandlingStyle::Explicit,
                formatting_preferences: FormattingPreferences {
                    max_line_length: 100,
                    prefer_single_line_blocks: true,
                    indent_style: IndentStyle::Spaces(4),
                    brace_style: BraceStyle::SameLine,
                },
            },
            risk_tolerance: RiskTolerance::Moderate,
            communication_style: CommunicationStyle::Professional,
            priority_weights: PriorityWeights {
                performance: 0.4,
                readability: 0.15,
                maintainability: 0.2,
                security: 0.1,
                testing: 0.1,
                documentation: 0.05,
            },
        };

        // Readability-focused agent
        let readability_agent = AgentPersonality {
            name: "ReadabilityExpert".to_string(),
            description: "Emphasizes code clarity, readability, and maintainability".to_string(),
            focus_areas: vec![
                "code_clarity".to_string(),
                "naming_conventions".to_string(),
                "code_structure".to_string(),
                "documentation".to_string(),
            ],
            coding_style: CodingStyle {
                prefers_verbose_comments: true,
                prefers_short_functions: true,
                prefers_explicit_types: true,
                prefers_error_handling: ErrorHandlingStyle::Explicit,
                formatting_preferences: FormattingPreferences {
                    max_line_length: 80,
                    prefer_single_line_blocks: false,
                    indent_style: IndentStyle::Spaces(4),
                    brace_style: BraceStyle::NextLine,
                },
            },
            risk_tolerance: RiskTolerance::Conservative,
            communication_style: CommunicationStyle::Tutorial,
            priority_weights: PriorityWeights {
                performance: 0.1,
                readability: 0.4,
                maintainability: 0.3,
                security: 0.05,
                testing: 0.1,
                documentation: 0.05,
            },
        };

        // Security-focused agent
        let security_agent = AgentPersonality {
            name: "SecuritySpecialist".to_string(),
            description: "Prioritizes security, safety, and robust error handling".to_string(),
            focus_areas: vec![
                "input_validation".to_string(),
                "memory_safety".to_string(),
                "secure_coding".to_string(),
                "error_handling".to_string(),
            ],
            coding_style: CodingStyle {
                prefers_verbose_comments: true,
                prefers_short_functions: true,
                prefers_explicit_types: true,
                prefers_error_handling: ErrorHandlingStyle::Explicit,
                formatting_preferences: FormattingPreferences {
                    max_line_length: 100,
                    prefer_single_line_blocks: false,
                    indent_style: IndentStyle::Spaces(4),
                    brace_style: BraceStyle::SameLine,
                },
            },
            risk_tolerance: RiskTolerance::Conservative,
            communication_style: CommunicationStyle::Detailed,
            priority_weights: PriorityWeights {
                performance: 0.1,
                readability: 0.2,
                maintainability: 0.2,
                security: 0.4,
                testing: 0.05,
                documentation: 0.05,
            },
        };

        self.personalities.insert("performance_optimizer".to_string(), performance_agent);
        self.personalities.insert("readability_expert".to_string(), readability_agent);
        self.personalities.insert("security_specialist".to_string(), security_agent);
    }

    /// Create default prompt configurations
    fn create_default_prompt_configs(&mut self) {
        let performance_prompt = CustomPromptConfig {
            base_prompt: "You are a performance optimization expert. Focus on improving code efficiency, reducing memory usage, and optimizing algorithms. Always consider the performance implications of your suggestions.".to_string(),
            context_templates: {
                let mut templates = HashMap::new();
                templates.insert("file_analysis".to_string(), 
                    "Analyze the following code for performance optimization opportunities: {code}".to_string());
                templates.insert("function_optimization".to_string(), 
                    "Optimize this function for better performance: {function}".to_string());
                templates
            },
            response_format_preferences: ResponseFormatPreferences {
                include_confidence_scores: true,
                include_reasoning_steps: true,
                include_alternative_options: true,
                preferred_explanation_length: ExplanationLength::Standard,
            },
            custom_instructions: vec![
                "Always measure before optimizing".to_string(),
                "Consider algorithmic complexity first".to_string(),
                "Profile memory usage patterns".to_string(),
            ],
        };

        let readability_prompt = CustomPromptConfig {
            base_prompt: "You are a code readability expert. Focus on making code clear, well-documented, and easy to understand. Prioritize maintainability and developer experience.".to_string(),
            context_templates: {
                let mut templates = HashMap::new();
                templates.insert("file_analysis".to_string(), 
                    "Review the following code for readability improvements: {code}".to_string());
                templates.insert("naming_review".to_string(), 
                    "Suggest better naming for variables and functions in: {code}".to_string());
                templates
            },
            response_format_preferences: ResponseFormatPreferences {
                include_confidence_scores: false,
                include_reasoning_steps: true,
                include_alternative_options: true,
                preferred_explanation_length: ExplanationLength::Detailed,
            },
            custom_instructions: vec![
                "Prefer descriptive names over short ones".to_string(),
                "Add comments for complex logic".to_string(),
                "Break down large functions".to_string(),
            ],
        };

        self.prompt_configs.insert("performance_optimizer".to_string(), performance_prompt);
        self.prompt_configs.insert("readability_expert".to_string(), readability_prompt);
    }

    /// Create a custom agent with the specified personality
    pub fn create_custom_agent(&self, personality_name: &str) -> Result<CustomAgent> {
        let personality = self.personalities.get(personality_name)
            .ok_or_else(|| anyhow!("Personality '{}' not found", personality_name))?;
        
        let prompt_config = self.prompt_configs.get(personality_name);
        
        Ok(CustomAgent {
            personality: personality.clone(),
            prompt_config: prompt_config.cloned(),
            learned_preferences: self.preference_learning.learned_preferences.clone(),
        })
    }

    /// Add a new custom personality
    pub fn add_personality(&mut self, name: String, personality: AgentPersonality) {
        self.personalities.insert(name, personality);
    }

    /// Update preference learning based on user interaction
    pub fn record_user_interaction(&mut self, suggestion_type: String, context: String, 
                                 confidence: f64, action: UserAction, project_context: String) {
        let record = SuggestionRecord {
            suggestion_type: suggestion_type.clone(),
            context,
            confidence,
            user_action: action.clone(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            project_context,
        };

        match action {
            UserAction::Accepted => self.preference_learning.accepted_suggestions.push(record),
            UserAction::Rejected => self.preference_learning.rejected_suggestions.push(record),
            _ => {} // Handle other actions as needed
        }

        // Update learned preferences
        self.update_learned_preferences(&suggestion_type, &action);
    }

    /// Update learned preferences based on user actions
    fn update_learned_preferences(&mut self, suggestion_type: &str, action: &UserAction) {
        let current_score = self.preference_learning.learned_preferences
            .preferred_suggestion_types
            .get(suggestion_type)
            .unwrap_or(&0.5);

        let adjustment = match action {
            UserAction::Accepted => 0.1,
            UserAction::Rejected => -0.1,
            UserAction::Modified => 0.05,
            UserAction::Deferred => -0.02,
        };

        let new_score = (current_score + adjustment).clamp(0.0, 1.0);
        self.preference_learning.learned_preferences
            .preferred_suggestion_types
            .insert(suggestion_type.to_string(), new_score);
    }

    /// Get available personalities
    pub fn get_personalities(&self) -> &HashMap<String, AgentPersonality> {
        &self.personalities
    }

    /// Set active configuration
    pub fn set_active_configuration(&mut self, personality_name: String) {
        self.active_configuration = Some(personality_name);
    }

    /// Get active configuration
    pub fn get_active_configuration(&self) -> Option<&String> {
        self.active_configuration.as_ref()
    }
}

/// Serializable configuration for saving/loading
#[derive(Debug, Serialize, Deserialize)]
struct SavedConfiguration {
    personalities: HashMap<String, AgentPersonality>,
    prompt_configs: HashMap<String, CustomPromptConfig>,
    preference_learning: PreferenceLearning,
    project_contexts: HashMap<String, ProjectContext>,
    active_configuration: Option<String>,
}

/// Custom agent implementation with configurable personality
pub struct CustomAgent {
    personality: AgentPersonality,
    prompt_config: Option<CustomPromptConfig>,
    learned_preferences: LearnedPreferences,
}

impl CognitiveAgent for CustomAgent {
    fn propose_edit(&self, ctx: &SymbolicContext) -> ProposedEdit {
        let task = ctx.resolve_or_default("current_task", "general improvement");
        let file = ctx.resolve_or_default("target_file", "src/main.rs");

        // Apply personality-driven logic
        let confidence_modifier = match self.personality.risk_tolerance {
            RiskTolerance::Conservative => -0.1,
            RiskTolerance::Moderate => 0.0,
            RiskTolerance::Aggressive => 0.1,
            RiskTolerance::Adaptive => self.calculate_adaptive_modifier(ctx),
        };

        // Generate edit based on personality focus areas
        let edit = if self.personality.focus_areas.contains(&"performance".to_string()) {
            self.generate_performance_edit(&task, &file)
        } else if self.personality.focus_areas.contains(&"code_clarity".to_string()) {
            self.generate_readability_edit(&task, &file)
        } else if self.personality.focus_areas.contains(&"input_validation".to_string()) {
            self.generate_security_edit(&task, &file)
        } else {
            self.generate_general_edit(&task, &file)
        };

        // Adjust confidence based on personality and learned preferences
        let mut adjusted_edit = edit;
        adjusted_edit.confidence = (adjusted_edit.confidence + confidence_modifier).clamp(0.0, 1.0);

        // Apply learned preferences
        if let Some(preference_score) = self.learned_preferences.preferred_suggestion_types.get(&adjusted_edit.reason) {
            adjusted_edit.confidence = (adjusted_edit.confidence * preference_score).clamp(0.0, 1.0);
        }

        adjusted_edit
    }

    fn reason_about_code(&self, file: &str, lines: &[String]) -> Insight {
        let analysis = self.analyze_code_with_personality(lines);
        
        Insight {
            summary: format!("{} analysis of {} ({} lines)", 
                self.personality.name, file, lines.len()),
            details: analysis,
            confidence: self.calculate_reasoning_confidence(lines),
        }
    }

    fn simulate(&self, phase: &str, dag: &[Node]) -> Vec<ExecutionTrace> {
        dag.iter()
            .map(|node| ExecutionTrace {
                phase: phase.to_string(),
                node_id: node.id.clone(),
                result: format!("{} simulation result", self.personality.name),
            })
            .collect()
    }
}

impl CustomAgent {
    fn calculate_adaptive_modifier(&self, _ctx: &SymbolicContext) -> f64 {
        // Implement adaptive risk calculation based on context
        0.0
    }

    fn generate_performance_edit(&self, task: &str, file: &str) -> ProposedEdit {
        ProposedEdit {
            file: file.to_string(),
            line_range: (10, 15),
            new_code: format!("// {}: Performance optimization\n// {}\npub fn optimized_implementation() {{\n    // More efficient approach\n}}", 
                self.personality.name, task),
            reason: "performance_optimization".to_string(),
            confidence: 0.85,
        }
    }

    fn generate_readability_edit(&self, task: &str, file: &str) -> ProposedEdit {
        ProposedEdit {
            file: file.to_string(),
            line_range: (20, 25),
            new_code: format!("// {}: Readability improvement\n// {}\n/// Clear documentation for better understanding\npub fn well_documented_function() {{\n    // Self-explanatory implementation\n}}", 
                self.personality.name, task),
            reason: "readability_improvement".to_string(),
            confidence: 0.90,
        }
    }

    fn generate_security_edit(&self, task: &str, file: &str) -> ProposedEdit {
        ProposedEdit {
            file: file.to_string(),
            line_range: (30, 35),
            new_code: format!("// {}: Security enhancement\n// {}\npub fn secure_function(input: &str) -> Result<String, SecurityError> {{\n    validate_input(input)?;\n    // Secure processing\n    Ok(processed_result)\n}}", 
                self.personality.name, task),
            reason: "security_enhancement".to_string(),
            confidence: 0.88,
        }
    }

    fn generate_general_edit(&self, task: &str, file: &str) -> ProposedEdit {
        ProposedEdit {
            file: file.to_string(),
            line_range: (40, 45),
            new_code: format!("// {}: General improvement\n// {}\npub fn improved_function() {{\n    // Enhanced implementation\n}}", 
                self.personality.name, task),
            reason: "general_improvement".to_string(),
            confidence: 0.75,
        }
    }

    fn analyze_code_with_personality(&self, lines: &[String]) -> String {
        let focus = self.personality.focus_areas.join(", ");
        match self.personality.communication_style {
            CommunicationStyle::Concise => format!("Focused on: {}", focus),
            CommunicationStyle::Detailed => format!("Comprehensive analysis focusing on {}. Code structure appears well-organized with {} lines analyzed.", focus, lines.len()),
            CommunicationStyle::Tutorial => format!("Let's examine this code with focus on {}. We have {} lines to analyze, which allows us to understand the structure and identify improvement opportunities.", focus, lines.len()),
            CommunicationStyle::Professional => format!("Professional assessment: The code base consists of {} lines with analysis focus on {}. Initial review indicates standard implementation patterns.", lines.len(), focus),
            CommunicationStyle::Friendly => format!("Hey! Looking at this code with {} in mind. We've got {} lines here - let's see what we can improve together!", focus, lines.len()),
        }
    }

    fn calculate_reasoning_confidence(&self, lines: &[String]) -> f64 {
        let base_confidence = match self.personality.risk_tolerance {
            RiskTolerance::Conservative => 0.7,
            RiskTolerance::Moderate => 0.8,
            RiskTolerance::Aggressive => 0.9,
            RiskTolerance::Adaptive => 0.75,
        };

        // Adjust based on code complexity
        let complexity_factor: f64 = if lines.len() > 100 { -0.1 } else { 0.0 };
        
        (base_confidence + complexity_factor).clamp(0.0, 1.0)
    }
}

impl PreferenceLearning {
    pub fn new() -> Self {
        Self {
            accepted_suggestions: Vec::new(),
            rejected_suggestions: Vec::new(),
            modification_patterns: Vec::new(),
            learned_preferences: LearnedPreferences {
                preferred_suggestion_types: HashMap::new(),
                disliked_patterns: Vec::new(),
                context_specific_preferences: HashMap::new(),
                optimal_confidence_thresholds: HashMap::new(),
            },
        }
    }
}

impl Default for PriorityWeights {
    fn default() -> Self {
        Self {
            performance: 0.2,
            readability: 0.2,
            maintainability: 0.2,
            security: 0.15,
            testing: 0.15,
            documentation: 0.1,
        }
    }
}

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

    #[test]
    fn test_custom_agent_configuration_system_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().to_str().unwrap();
        
        let mut system = CustomAgentConfigurationSystem::new(config_dir);
        assert!(system.load_from_file().is_ok());
        assert_eq!(system.personalities.len(), 3); // Default personalities
        assert!(!system.personalities.is_empty());
    }

    #[test]
    fn test_personality_creation_and_retrieval() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().to_str().unwrap();
        
        let mut system = CustomAgentConfigurationSystem::new(config_dir);
        system.load_from_file().unwrap();
        
        // Test retrieving default personalities
        let personalities = system.get_personalities();
        assert!(personalities.contains_key("performance_optimizer"));
        assert!(personalities.contains_key("readability_expert"));
        assert!(personalities.contains_key("security_specialist"));
    }

    #[test]
    fn test_custom_agent_creation() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().to_str().unwrap();
        
        let mut system = CustomAgentConfigurationSystem::new(config_dir);
        system.load_from_file().unwrap();
        
        let agent = system.create_custom_agent("performance_optimizer").unwrap();
        assert_eq!(agent.personality.name, "PerformanceOptimizer");
        assert_eq!(agent.personality.priority_weights.performance, 0.4);
    }

    #[test]
    fn test_user_interaction_recording() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().to_str().unwrap();
        
        let mut system = CustomAgentConfigurationSystem::new(config_dir);
        system.load_from_file().unwrap();
        
        system.record_user_interaction(
            "performance_optimization".to_string(),
            "loop optimization".to_string(),
            0.9,
            UserAction::Accepted,
            "rust_project".to_string(),
        );
        
        assert_eq!(system.preference_learning.accepted_suggestions.len(), 1);
        let learned_score = system.preference_learning.learned_preferences
            .preferred_suggestion_types
            .get("performance_optimization")
            .unwrap();
        assert!(*learned_score > 0.5);
    }

    #[test]
    fn test_save_and_load_configuration() {
        let temp_dir = TempDir::new().unwrap();
        let config_dir = temp_dir.path().to_str().unwrap();
        
        let mut system = CustomAgentConfigurationSystem::new(config_dir);
        system.load_from_file().unwrap();
        system.set_active_configuration("performance_optimizer".to_string());
        
        // Save configuration
        assert!(system.save_to_file().is_ok());
        
        // Create new system and load
        let mut new_system = CustomAgentConfigurationSystem::new(config_dir);
        assert!(new_system.load_from_file().is_ok());
        assert_eq!(new_system.get_active_configuration(), Some(&"performance_optimizer".to_string()));
    }
}