soma-core 2.0.2

World's first production-ready self-aware development system with meta-cognitive capabilities and cognitive reasoning engine for intelligent development platforms
Documentation
// Cognitive-assisted edit workflow interface
// Integrates cognitive operators into the CLI edit decision process

use crate::edit_control::ApprovalState;
use crate::memory::SymbolicContext;
use crate::ops::{default_operator_registry, SomaOperator};
use anyhow::Result;


/// Cognitive-assisted edit workflow that uses operators to guide decisions
pub struct CognitiveWorkflow {
    registry: std::collections::HashMap<String, Box<dyn SomaOperator>>,
    confidence_threshold: f64,
}

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

impl CognitiveWorkflow {
    pub fn new() -> Self {
        Self {
            registry: default_operator_registry(),
            confidence_threshold: 0.8,
        }
    }

    /// Main cognitive workflow entry point for simple edit analysis
    pub fn analyze_edit_context(&self, file_path: &str, reasoning: &str, confidence: f64) -> Result<CognitiveAnalysis> {
        println!("\n🧠 Cognitive-Assisted Edit Analysis");
        println!("====================================");

        // Step 1: Build context for cognitive analysis
        let edit_context = self.build_edit_context(file_path, reasoning, confidence)?;

        // Step 2: Run cognitive analysis
        let cognitive_analysis = self.run_cognitive_analysis(&edit_context)?;

        // Step 3: Display analysis
        self.display_cognitive_insights(&cognitive_analysis)?;

        Ok(cognitive_analysis)
    }

    /// Build context for cognitive operators from edit information
    fn build_edit_context(&self, file_path: &str, reasoning: &str, confidence: f64) -> Result<SymbolicContext> {
        let mut ctx = SymbolicContext::new();

        // Edit characteristics
        ctx.set("edit_file", file_path);
        ctx.set("edit_confidence", &confidence.to_string());
        ctx.set("edit_reasoning", reasoning);

        // System context
        ctx.set("system_performance", "optimal");
        ctx.set("operator_count", "15");
        ctx.set("errors_count", "0");

        // File type analysis
        if file_path.ends_with(".rs") {
            ctx.set("file_type", "rust");
            ctx.set("security_sensitive", "true");
        } else if file_path.ends_with(".md") {
            ctx.set("file_type", "documentation");
            ctx.set("security_sensitive", "false");
        } else {
            ctx.set("file_type", "generic");
            ctx.set("security_sensitive", "unknown");
        }

        // Risk assessment context
        let risk_level = if confidence < 0.7 {
            "high"
        } else if confidence < 0.9 {
            "medium"
        } else {
            "low"
        };
        ctx.set("risk_level", risk_level);

        Ok(ctx)
    }

    /// Run cognitive analysis using multiple operators
    fn run_cognitive_analysis(&self, context: &SymbolicContext) -> Result<CognitiveAnalysis> {
        let mut analysis = CognitiveAnalysis::new();

        // 1. Introspection Analysis
        if let Some(introspect_op) = self.registry.get("introspect") {
            if let Ok(introspect_result) = introspect_op.execute(context) {
                analysis.introspection = Some(introspect_result);
            }
        }

        // 2. Cognitive Load Assessment
        if let Some(load_op) = self.registry.get("cognitive_load") {
            if let Ok(load_result) = load_op.execute(context) {
                analysis.cognitive_load = Some(load_result);
            }
        }

        // 3. Attention Focus Analysis
        if let Some(attention_op) = self.registry.get("attention_focus") {
            if let Ok(attention_result) = attention_op.execute(context) {
                analysis.attention_focus = Some(attention_result);
            }
        }

        // 4. Doubt/Uncertainty Analysis
        if let Some(doubt_op) = self.registry.get("doubt") {
            if let Ok(doubt_result) = doubt_op.execute(context) {
                analysis.doubt_analysis = Some(doubt_result);
            }
        }

        // 5. Meta-Reflective Analysis
        if let Some(meta_op) = self.registry.get("meta_reflective") {
            if let Ok(meta_result) = meta_op.execute(context) {
                analysis.meta_reflection = Some(meta_result);
            }
        }

        Ok(analysis)
    }

    /// Display cognitive insights to the user
    fn display_cognitive_insights(&self, analysis: &CognitiveAnalysis) -> Result<()> {
        // Introspection insights
        if let Some(ref introspect) = analysis.introspection {
            println!("\n🔍 Cognitive Introspection:");
            if let Some(complexity) = introspect.get("complexity_score") {
                println!("   • Complexity score: {}", complexity);
            }
            if let Some(bottleneck) = introspect.get("bottleneck_detected") {
                println!("   • Bottleneck detected: {}", bottleneck);
            }
        }

        // Cognitive load insights
        if let Some(ref load) = analysis.cognitive_load {
            println!("\n⚡ Cognitive Load Assessment:");
            if let Some(level) = load.get("load_level") {
                println!("   • Load level: {}", level);
            }
            if let Some(optimization) = load.get("optimization_needed") {
                println!("   • Optimization needed: {}", optimization);
            }
        }

        // Attention focus insights
        if let Some(ref attention) = analysis.attention_focus {
            println!("\n🎯 Attention Focus Analysis:");
            if let Some(target) = attention.get("focus_target_0") {
                println!("   • Primary focus: {}", target);
            }
            if let Some(weight) = attention.get("focus_weight_0") {
                println!("   • Focus strength: {}", weight);
            }
        }

        // Doubt/uncertainty insights
        if let Some(ref doubt) = analysis.doubt_analysis {
            println!("\n❓ Uncertainty Assessment:");
            if let Some(confidence) = doubt.get("confidence") {
                println!("   • Confidence level: {}", confidence);
            }
            if let Some(flagged) = doubt.get("flagged") {
                println!("   • Flagged for review: {}", flagged);
                if flagged == "true" {
                    println!("   ⚠️  RECOMMENDATION: Extra review recommended");
                }
            }
        }

        // Meta-reflection insights
        if let Some(ref meta) = analysis.meta_reflection {
            println!("\n🌟 Meta-Cognitive Analysis:");
            if let Some(performance) = meta.get("system_performance_score") {
                println!("   • System performance: {}", performance);
            }
            if let Some(state) = meta.get("meta_cognitive_state") {
                println!("   • Cognitive state: {}", state);
            }
            if let Some(optimization) = meta.get("optimization_Θ_0") {
                println!("   • Suggested optimization: {}", optimization);
            }
        }

        Ok(())
    }

    /// Calculate cognitive recommendation from analysis
    pub fn calculate_cognitive_recommendation(&self, analysis: &CognitiveAnalysis) -> CognitiveRecommendation {
        let mut confidence_score = 0.5; // Base confidence
        let mut reasons = Vec::new();

        // Factor in doubt analysis
        if let Some(ref doubt) = analysis.doubt_analysis {
            if let Some(confidence_str) = doubt.get("confidence") {
                if let Ok(confidence) = confidence_str.parse::<f64>() {
                    confidence_score = confidence;
                }
            }
            if let Some(flagged) = doubt.get("flagged") {
                if flagged == "true" {
                    reasons.push("Low confidence detected".to_string());
                }
            }
        }

        // Factor in cognitive load
        if let Some(ref load) = analysis.cognitive_load {
            if let Some(level) = load.get("load_level") {
                if level == "high" {
                    confidence_score *= 0.9; // Reduce confidence for high cognitive load
                    reasons.push("High cognitive load detected".to_string());
                }
            }
        }

        // Factor in meta-cognitive state
        if let Some(ref meta) = analysis.meta_reflection {
            if let Some(state) = meta.get("meta_cognitive_state") {
                if state == "optimal" {
                    confidence_score *= 1.1; // Boost confidence for optimal state
                    reasons.push("System in optimal cognitive state".to_string());
                }
            }
        }

        // Determine recommendation
        let (action, description) = if confidence_score > 0.8 {
            ("APPROVE", "High confidence - recommended to accept")
        } else if confidence_score > 0.6 {
            ("REVIEW", "Moderate confidence - careful review recommended")
        } else {
            ("CAUTION", "Low confidence - detailed analysis recommended")
        };

        CognitiveRecommendation {
            action: action.to_string(),
            description: description.to_string(),
            confidence: confidence_score.min(1.0),
            reasons,
        }
    }

    /// Interactive decision with cognitive guidance
    pub fn get_cognitive_decision(&self, analysis: &CognitiveAnalysis) -> Result<ApprovalState> {
        let recommendation = self.calculate_cognitive_recommendation(analysis);

        println!("\n🤖 Cognitive Recommendation: {}", recommendation.description);
        println!("   Confidence: {}%", (recommendation.confidence * 100.0) as i32);
        println!("   Action: {}", recommendation.action);

        if !recommendation.reasons.is_empty() {
            println!("   Reasons:");
            for reason in &recommendation.reasons {
                println!("{}", reason);
            }
        }

        // Simple decision based on confidence
        if recommendation.confidence > self.confidence_threshold {
            println!("✅ High confidence - recommending approval");
            Ok(ApprovalState::Approved)
        } else {
            println!("⚠️  Low confidence - recommending review");
            Ok(ApprovalState::Pending)
        }
    }
}

/// Container for cognitive analysis results
#[derive(Debug)]
pub struct CognitiveAnalysis {
    pub introspection: Option<SymbolicContext>,
    pub cognitive_load: Option<SymbolicContext>,
    pub attention_focus: Option<SymbolicContext>,
    pub doubt_analysis: Option<SymbolicContext>,
    pub meta_reflection: Option<SymbolicContext>,
}

impl CognitiveAnalysis {
    pub fn new() -> Self {
        Self {
            introspection: None,
            cognitive_load: None,
            attention_focus: None,
            doubt_analysis: None,
            meta_reflection: None,
        }
    }
}

/// Cognitive recommendation from analysis
#[derive(Debug)]
pub struct CognitiveRecommendation {
    pub action: String,
    pub description: String,
    pub confidence: f64,
    pub reasons: Vec<String>,
}

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

    #[test]
    fn test_cognitive_workflow_creation() {
        let workflow = CognitiveWorkflow::new();
        assert!(workflow.registry.contains_key("introspect"));
        assert!(workflow.registry.contains_key("cognitive_load"));
        assert!(workflow.registry.contains_key("attention_focus"));
        assert!(workflow.registry.contains_key("doubt"));
        assert!(workflow.registry.contains_key("meta_reflective"));
    }

    #[test]
    fn test_cognitive_analysis_structure() {
        let analysis = CognitiveAnalysis::new();
        assert!(analysis.introspection.is_none());
        assert!(analysis.cognitive_load.is_none());
        assert!(analysis.attention_focus.is_none());
        assert!(analysis.doubt_analysis.is_none());
        assert!(analysis.meta_reflection.is_none());
    }

    #[test]
    fn test_edit_context_building() {
        let workflow = CognitiveWorkflow::new();
        let context = workflow.build_edit_context("src/test.rs", "test edit", 0.85).unwrap();
        assert_eq!(context.get("edit_file").unwrap(), "src/test.rs");
        assert_eq!(context.get("edit_confidence").unwrap(), "0.85");
        assert_eq!(context.get("file_type").unwrap(), "rust");
    }
}