use crate::edit_control::ApprovalState;
use crate::memory::SymbolicContext;
use crate::ops::{default_operator_registry, SomaOperator};
use anyhow::Result;
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,
}
}
pub fn analyze_edit_context(&self, file_path: &str, reasoning: &str, confidence: f64) -> Result<CognitiveAnalysis> {
println!("\n🧠 Cognitive-Assisted Edit Analysis");
println!("====================================");
let edit_context = self.build_edit_context(file_path, reasoning, confidence)?;
let cognitive_analysis = self.run_cognitive_analysis(&edit_context)?;
self.display_cognitive_insights(&cognitive_analysis)?;
Ok(cognitive_analysis)
}
fn build_edit_context(&self, file_path: &str, reasoning: &str, confidence: f64) -> Result<SymbolicContext> {
let mut ctx = SymbolicContext::new();
ctx.set("edit_file", file_path);
ctx.set("edit_confidence", &confidence.to_string());
ctx.set("edit_reasoning", reasoning);
ctx.set("system_performance", "optimal");
ctx.set("operator_count", "15");
ctx.set("errors_count", "0");
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");
}
let risk_level = if confidence < 0.7 {
"high"
} else if confidence < 0.9 {
"medium"
} else {
"low"
};
ctx.set("risk_level", risk_level);
Ok(ctx)
}
fn run_cognitive_analysis(&self, context: &SymbolicContext) -> Result<CognitiveAnalysis> {
let mut analysis = CognitiveAnalysis::new();
if let Some(introspect_op) = self.registry.get("introspect") {
if let Ok(introspect_result) = introspect_op.execute(context) {
analysis.introspection = Some(introspect_result);
}
}
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);
}
}
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);
}
}
if let Some(doubt_op) = self.registry.get("doubt") {
if let Ok(doubt_result) = doubt_op.execute(context) {
analysis.doubt_analysis = Some(doubt_result);
}
}
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)
}
fn display_cognitive_insights(&self, analysis: &CognitiveAnalysis) -> Result<()> {
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);
}
}
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);
}
}
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);
}
}
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");
}
}
}
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(())
}
pub fn calculate_cognitive_recommendation(&self, analysis: &CognitiveAnalysis) -> CognitiveRecommendation {
let mut confidence_score = 0.5; let mut reasons = Vec::new();
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());
}
}
}
if let Some(ref load) = analysis.cognitive_load {
if let Some(level) = load.get("load_level") {
if level == "high" {
confidence_score *= 0.9; reasons.push("High cognitive load detected".to_string());
}
}
}
if let Some(ref meta) = analysis.meta_reflection {
if let Some(state) = meta.get("meta_cognitive_state") {
if state == "optimal" {
confidence_score *= 1.1; reasons.push("System in optimal cognitive state".to_string());
}
}
}
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,
}
}
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);
}
}
if recommendation.confidence > self.confidence_threshold {
println!("✅ High confidence - recommending approval");
Ok(ApprovalState::Approved)
} else {
println!("⚠️ Low confidence - recommending review");
Ok(ApprovalState::Pending)
}
}
}
#[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,
}
}
}
#[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");
}
}