Skip to main content

soma_core/cli/
cognitive_workflow.rs

1// Cognitive-assisted edit workflow interface
2// Integrates cognitive operators into the CLI edit decision process
3
4use crate::edit_control::ApprovalState;
5use crate::memory::SymbolicContext;
6use crate::ops::{default_operator_registry, SomaOperator};
7use anyhow::Result;
8
9
10/// Cognitive-assisted edit workflow that uses operators to guide decisions
11pub struct CognitiveWorkflow {
12    registry: std::collections::HashMap<String, Box<dyn SomaOperator>>,
13    confidence_threshold: f64,
14}
15
16impl Default for CognitiveWorkflow {
17    fn default() -> Self {
18        Self::new()
19    }
20}
21
22impl CognitiveWorkflow {
23    pub fn new() -> Self {
24        Self {
25            registry: default_operator_registry(),
26            confidence_threshold: 0.8,
27        }
28    }
29
30    /// Main cognitive workflow entry point for simple edit analysis
31    pub fn analyze_edit_context(&self, file_path: &str, reasoning: &str, confidence: f64) -> Result<CognitiveAnalysis> {
32        println!("\n🧠 Cognitive-Assisted Edit Analysis");
33        println!("====================================");
34
35        // Step 1: Build context for cognitive analysis
36        let edit_context = self.build_edit_context(file_path, reasoning, confidence)?;
37
38        // Step 2: Run cognitive analysis
39        let cognitive_analysis = self.run_cognitive_analysis(&edit_context)?;
40
41        // Step 3: Display analysis
42        self.display_cognitive_insights(&cognitive_analysis)?;
43
44        Ok(cognitive_analysis)
45    }
46
47    /// Build context for cognitive operators from edit information
48    fn build_edit_context(&self, file_path: &str, reasoning: &str, confidence: f64) -> Result<SymbolicContext> {
49        let mut ctx = SymbolicContext::new();
50
51        // Edit characteristics
52        ctx.set("edit_file", file_path);
53        ctx.set("edit_confidence", &confidence.to_string());
54        ctx.set("edit_reasoning", reasoning);
55
56        // System context
57        ctx.set("system_performance", "optimal");
58        ctx.set("operator_count", "15");
59        ctx.set("errors_count", "0");
60
61        // File type analysis
62        if file_path.ends_with(".rs") {
63            ctx.set("file_type", "rust");
64            ctx.set("security_sensitive", "true");
65        } else if file_path.ends_with(".md") {
66            ctx.set("file_type", "documentation");
67            ctx.set("security_sensitive", "false");
68        } else {
69            ctx.set("file_type", "generic");
70            ctx.set("security_sensitive", "unknown");
71        }
72
73        // Risk assessment context
74        let risk_level = if confidence < 0.7 {
75            "high"
76        } else if confidence < 0.9 {
77            "medium"
78        } else {
79            "low"
80        };
81        ctx.set("risk_level", risk_level);
82
83        Ok(ctx)
84    }
85
86    /// Run cognitive analysis using multiple operators
87    fn run_cognitive_analysis(&self, context: &SymbolicContext) -> Result<CognitiveAnalysis> {
88        let mut analysis = CognitiveAnalysis::new();
89
90        // 1. Introspection Analysis
91        if let Some(introspect_op) = self.registry.get("introspect") {
92            if let Ok(introspect_result) = introspect_op.execute(context) {
93                analysis.introspection = Some(introspect_result);
94            }
95        }
96
97        // 2. Cognitive Load Assessment
98        if let Some(load_op) = self.registry.get("cognitive_load") {
99            if let Ok(load_result) = load_op.execute(context) {
100                analysis.cognitive_load = Some(load_result);
101            }
102        }
103
104        // 3. Attention Focus Analysis
105        if let Some(attention_op) = self.registry.get("attention_focus") {
106            if let Ok(attention_result) = attention_op.execute(context) {
107                analysis.attention_focus = Some(attention_result);
108            }
109        }
110
111        // 4. Doubt/Uncertainty Analysis
112        if let Some(doubt_op) = self.registry.get("doubt") {
113            if let Ok(doubt_result) = doubt_op.execute(context) {
114                analysis.doubt_analysis = Some(doubt_result);
115            }
116        }
117
118        // 5. Meta-Reflective Analysis
119        if let Some(meta_op) = self.registry.get("meta_reflective") {
120            if let Ok(meta_result) = meta_op.execute(context) {
121                analysis.meta_reflection = Some(meta_result);
122            }
123        }
124
125        Ok(analysis)
126    }
127
128    /// Display cognitive insights to the user
129    fn display_cognitive_insights(&self, analysis: &CognitiveAnalysis) -> Result<()> {
130        // Introspection insights
131        if let Some(ref introspect) = analysis.introspection {
132            println!("\n🔍 Cognitive Introspection:");
133            if let Some(complexity) = introspect.get("complexity_score") {
134                println!("   • Complexity score: {}", complexity);
135            }
136            if let Some(bottleneck) = introspect.get("bottleneck_detected") {
137                println!("   • Bottleneck detected: {}", bottleneck);
138            }
139        }
140
141        // Cognitive load insights
142        if let Some(ref load) = analysis.cognitive_load {
143            println!("\n⚡ Cognitive Load Assessment:");
144            if let Some(level) = load.get("load_level") {
145                println!("   • Load level: {}", level);
146            }
147            if let Some(optimization) = load.get("optimization_needed") {
148                println!("   • Optimization needed: {}", optimization);
149            }
150        }
151
152        // Attention focus insights
153        if let Some(ref attention) = analysis.attention_focus {
154            println!("\n🎯 Attention Focus Analysis:");
155            if let Some(target) = attention.get("focus_target_0") {
156                println!("   • Primary focus: {}", target);
157            }
158            if let Some(weight) = attention.get("focus_weight_0") {
159                println!("   • Focus strength: {}", weight);
160            }
161        }
162
163        // Doubt/uncertainty insights
164        if let Some(ref doubt) = analysis.doubt_analysis {
165            println!("\n❓ Uncertainty Assessment:");
166            if let Some(confidence) = doubt.get("confidence") {
167                println!("   • Confidence level: {}", confidence);
168            }
169            if let Some(flagged) = doubt.get("flagged") {
170                println!("   • Flagged for review: {}", flagged);
171                if flagged == "true" {
172                    println!("   ⚠️  RECOMMENDATION: Extra review recommended");
173                }
174            }
175        }
176
177        // Meta-reflection insights
178        if let Some(ref meta) = analysis.meta_reflection {
179            println!("\n🌟 Meta-Cognitive Analysis:");
180            if let Some(performance) = meta.get("system_performance_score") {
181                println!("   • System performance: {}", performance);
182            }
183            if let Some(state) = meta.get("meta_cognitive_state") {
184                println!("   • Cognitive state: {}", state);
185            }
186            if let Some(optimization) = meta.get("optimization_Θ_0") {
187                println!("   • Suggested optimization: {}", optimization);
188            }
189        }
190
191        Ok(())
192    }
193
194    /// Calculate cognitive recommendation from analysis
195    pub fn calculate_cognitive_recommendation(&self, analysis: &CognitiveAnalysis) -> CognitiveRecommendation {
196        let mut confidence_score = 0.5; // Base confidence
197        let mut reasons = Vec::new();
198
199        // Factor in doubt analysis
200        if let Some(ref doubt) = analysis.doubt_analysis {
201            if let Some(confidence_str) = doubt.get("confidence") {
202                if let Ok(confidence) = confidence_str.parse::<f64>() {
203                    confidence_score = confidence;
204                }
205            }
206            if let Some(flagged) = doubt.get("flagged") {
207                if flagged == "true" {
208                    reasons.push("Low confidence detected".to_string());
209                }
210            }
211        }
212
213        // Factor in cognitive load
214        if let Some(ref load) = analysis.cognitive_load {
215            if let Some(level) = load.get("load_level") {
216                if level == "high" {
217                    confidence_score *= 0.9; // Reduce confidence for high cognitive load
218                    reasons.push("High cognitive load detected".to_string());
219                }
220            }
221        }
222
223        // Factor in meta-cognitive state
224        if let Some(ref meta) = analysis.meta_reflection {
225            if let Some(state) = meta.get("meta_cognitive_state") {
226                if state == "optimal" {
227                    confidence_score *= 1.1; // Boost confidence for optimal state
228                    reasons.push("System in optimal cognitive state".to_string());
229                }
230            }
231        }
232
233        // Determine recommendation
234        let (action, description) = if confidence_score > 0.8 {
235            ("APPROVE", "High confidence - recommended to accept")
236        } else if confidence_score > 0.6 {
237            ("REVIEW", "Moderate confidence - careful review recommended")
238        } else {
239            ("CAUTION", "Low confidence - detailed analysis recommended")
240        };
241
242        CognitiveRecommendation {
243            action: action.to_string(),
244            description: description.to_string(),
245            confidence: confidence_score.min(1.0),
246            reasons,
247        }
248    }
249
250    /// Interactive decision with cognitive guidance
251    pub fn get_cognitive_decision(&self, analysis: &CognitiveAnalysis) -> Result<ApprovalState> {
252        let recommendation = self.calculate_cognitive_recommendation(analysis);
253
254        println!("\n🤖 Cognitive Recommendation: {}", recommendation.description);
255        println!("   Confidence: {}%", (recommendation.confidence * 100.0) as i32);
256        println!("   Action: {}", recommendation.action);
257
258        if !recommendation.reasons.is_empty() {
259            println!("   Reasons:");
260            for reason in &recommendation.reasons {
261                println!("     • {}", reason);
262            }
263        }
264
265        // Simple decision based on confidence
266        if recommendation.confidence > self.confidence_threshold {
267            println!("✅ High confidence - recommending approval");
268            Ok(ApprovalState::Approved)
269        } else {
270            println!("⚠️  Low confidence - recommending review");
271            Ok(ApprovalState::Pending)
272        }
273    }
274}
275
276/// Container for cognitive analysis results
277#[derive(Debug)]
278pub struct CognitiveAnalysis {
279    pub introspection: Option<SymbolicContext>,
280    pub cognitive_load: Option<SymbolicContext>,
281    pub attention_focus: Option<SymbolicContext>,
282    pub doubt_analysis: Option<SymbolicContext>,
283    pub meta_reflection: Option<SymbolicContext>,
284}
285
286impl CognitiveAnalysis {
287    pub fn new() -> Self {
288        Self {
289            introspection: None,
290            cognitive_load: None,
291            attention_focus: None,
292            doubt_analysis: None,
293            meta_reflection: None,
294        }
295    }
296}
297
298/// Cognitive recommendation from analysis
299#[derive(Debug)]
300pub struct CognitiveRecommendation {
301    pub action: String,
302    pub description: String,
303    pub confidence: f64,
304    pub reasons: Vec<String>,
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    #[test]
312    fn test_cognitive_workflow_creation() {
313        let workflow = CognitiveWorkflow::new();
314        assert!(workflow.registry.contains_key("introspect"));
315        assert!(workflow.registry.contains_key("cognitive_load"));
316        assert!(workflow.registry.contains_key("attention_focus"));
317        assert!(workflow.registry.contains_key("doubt"));
318        assert!(workflow.registry.contains_key("meta_reflective"));
319    }
320
321    #[test]
322    fn test_cognitive_analysis_structure() {
323        let analysis = CognitiveAnalysis::new();
324        assert!(analysis.introspection.is_none());
325        assert!(analysis.cognitive_load.is_none());
326        assert!(analysis.attention_focus.is_none());
327        assert!(analysis.doubt_analysis.is_none());
328        assert!(analysis.meta_reflection.is_none());
329    }
330
331    #[test]
332    fn test_edit_context_building() {
333        let workflow = CognitiveWorkflow::new();
334        let context = workflow.build_edit_context("src/test.rs", "test edit", 0.85).unwrap();
335        assert_eq!(context.get("edit_file").unwrap(), "src/test.rs");
336        assert_eq!(context.get("edit_confidence").unwrap(), "0.85");
337        assert_eq!(context.get("file_type").unwrap(), "rust");
338    }
339}