Skip to main content

soma_core/cli/
mod.rs

1// src/cli/mod.rs
2// Interactive CLI for multi-agent code editing collaboration
3
4use crate::agents::claude_agent::ClaudeAgent;
5use crate::agents::gemini_agent::GeminiAgent;
6use crate::agents::gpt4_agent::{CognitiveAgent, GPT4Agent, ProposedEdit};
7use crate::feedback_loop::{apply_consensus_edits, restore_file, show_file_diff};
8use crate::memory::SymbolicContext;
9use std::fs;
10use std::io::{self, Write};
11
12pub mod editor;
13pub mod preview;
14pub mod advanced_preview;
15// Issue #19: Granular Approval Levels
16pub mod granular_approval;
17// Issue #20: Staged Application System
18pub mod staged_application;
19// Cognitive-assisted workflow
20pub mod cognitive_workflow;
21// Issue #25: Edit Classification System
22pub mod edit_classification;
23// Issue #26: Git Integration System
24pub mod git_integration;
25// Issue #27: Time Travel CLI
26pub mod time_travel;
27// Issue #30: Custom Agent Configuration CLI
28pub mod custom_agent_config;
29// Issue #31: Visual Reasoning CLI
30pub mod visual_reasoning;
31// Issue #32: Meta-Reflective CLI
32pub mod meta_reflective;
33
34// Re-export for external use
35pub use advanced_preview::AdvancedPreviewSystem;
36// Issue #20: Re-export StagedApplicationInterface
37pub use staged_application::StagedApplicationInterface;
38
39use crate::edit_control::{validation::EditValidator, ModifiableEdit};
40use editor::InlineEditor;
41use preview::EditPreviewBuilder;
42// Issue #19: Granular Approval System imports
43use crate::cli::granular_approval::process_edit_with_granular_approval;
44use crate::edit_control::ApprovalRole;
45// Issue #20: Staged Application System imports
46use crate::cli::staged_application::process_edit_with_staged_application;
47// Cognitive workflow imports
48use crate::cli::cognitive_workflow::CognitiveWorkflow;
49// Issue #25: Edit Classification imports
50use crate::cli::edit_classification::EditClassificationCLI;
51
52pub struct AgentCollaboration {
53    agents: Vec<(String, Box<dyn CognitiveAgent>)>,
54}
55
56impl AgentCollaboration {
57    pub fn new() -> Self {
58        Self {
59            agents: vec![
60                ("GPT-4".to_string(), Box::new(GPT4Agent)),
61                ("Claude".to_string(), Box::new(ClaudeAgent)),
62                ("Gemini".to_string(), Box::new(GeminiAgent)),
63            ],
64        }
65    }
66
67    pub fn run_interactive_session(&self) -> Result<(), Box<dyn std::error::Error>> {
68        self.print_welcome();
69
70        loop {
71            match self.main_menu()? {
72                MenuChoice::AnalyzeFile => self.analyze_file_workflow()?,
73                MenuChoice::CustomTask => self.custom_task_workflow()?,
74                MenuChoice::ViewAgentCapabilities => self.show_agent_capabilities(),
75                MenuChoice::Exit => {
76                    println!("\n๐Ÿ‘‹ Thanks for collaborating with the SOMA agents!");
77                    break;
78                }
79            }
80        }
81
82        Ok(())
83    }
84
85    fn print_welcome(&self) {
86        println!("{}", "=".repeat(60));
87        println!("๐Ÿค SOMA CORE - Interactive Agent Collaboration");
88        println!("{}", "=".repeat(60));
89        println!("Welcome! You can collaborate with our AI agents to improve your code.");
90        println!("Each agent has different expertise:");
91        println!("  ๐Ÿš€ GPT-4:  Performance & Best Practices");
92        println!("  ๐Ÿ“š Claude: Readability & Architecture");
93        println!("  ๐Ÿงช Gemini: Testing & Validation");
94        println!("\n๐Ÿ’ก Your vote is decisive - you choose which suggestions to apply!\n");
95    }
96
97    fn main_menu(&self) -> Result<MenuChoice, Box<dyn std::error::Error>> {
98        loop {
99            println!("\n๐Ÿ“‹ What would you like to do?");
100            println!("  1. ๐Ÿ“„ Analyze & improve a specific file");
101            println!("  2. ๐ŸŽฏ Set custom improvement task");
102            println!("  3. ๐Ÿค– View agent capabilities");
103            println!("  4. ๐Ÿšช Exit");
104
105            print!("\nChoose an option (1-4): ");
106            io::stdout().flush()?;
107
108            let mut input = String::new();
109            io::stdin().read_line(&mut input)?;
110
111            match input.trim() {
112                "1" => return Ok(MenuChoice::AnalyzeFile),
113                "2" => return Ok(MenuChoice::CustomTask),
114                "3" => return Ok(MenuChoice::ViewAgentCapabilities),
115                "4" => return Ok(MenuChoice::Exit),
116                _ => {
117                    println!("โŒ Invalid choice. Please try again.");
118                    continue;
119                }
120            }
121        }
122    }
123
124    fn analyze_file_workflow(&self) -> Result<(), Box<dyn std::error::Error>> {
125        println!("\n๐Ÿ“‚ File Analysis Mode");
126        println!("{}", "=".repeat(30));
127
128        // Get file path from user
129        print!("Enter the file path to analyze: ");
130        io::stdout().flush()?;
131        let mut file_path = String::new();
132        io::stdin().read_line(&mut file_path)?;
133        let file_path = file_path.trim();
134
135        if !std::path::Path::new(file_path).exists() {
136            println!("โŒ File '{}' not found. Please check the path.", file_path);
137            return Ok(());
138        }
139
140        // Show current file content
141        self.show_file_content(file_path)?;
142
143        // Get improvement focus from user
144        let task_context = self.get_improvement_focus()?;
145
146        // Get agent proposals
147        let proposals = self.collect_agent_proposals(&task_context, Some(file_path));
148
149        // Show proposals and get user decision
150        let selected_proposals = self.interactive_proposal_review(proposals)?;
151
152        if !selected_proposals.is_empty() {
153            self.apply_selected_edits(file_path, selected_proposals)?;
154        } else {
155            println!("\n๐Ÿ“ No edits selected. File remains unchanged.");
156        }
157
158        Ok(())
159    }
160
161    fn custom_task_workflow(&self) -> Result<(), Box<dyn std::error::Error>> {
162        println!("\n๐ŸŽฏ Custom Task Mode");
163        println!("{}", "=".repeat(25));
164
165        print!("Describe what you want to improve (e.g., 'add error handling', 'optimize performance'): ");
166        io::stdout().flush()?;
167        let mut task_description = String::new();
168        io::stdin().read_line(&mut task_description)?;
169        let task_description = task_description.trim();
170
171        // Get target file
172        print!("Which file should the agents work on? ");
173        io::stdout().flush()?;
174        let mut file_path = String::new();
175        io::stdin().read_line(&mut file_path)?;
176        let file_path = file_path.trim();
177
178        if !std::path::Path::new(file_path).exists() {
179            println!("โŒ File '{}' not found. Please check the path.", file_path);
180            return Ok(());
181        }
182
183        // Show current file
184        self.show_file_content(file_path)?;
185
186        // Create context
187        let mut ctx = SymbolicContext::new();
188        ctx.set("current_task", task_description);
189        ctx.set("target_file", file_path);
190
191        // Get proposals
192        let proposals = self.collect_agent_proposals(&ctx, Some(file_path));
193
194        // Interactive review
195        let selected_proposals = self.interactive_proposal_review(proposals)?;
196
197        if !selected_proposals.is_empty() {
198            self.apply_selected_edits(file_path, selected_proposals)?;
199        } else {
200            println!("\n๐Ÿ“ No edits selected. File remains unchanged.");
201        }
202
203        Ok(())
204    }
205
206    fn get_improvement_focus(&self) -> Result<SymbolicContext, Box<dyn std::error::Error>> {
207        println!("\n๐ŸŽฏ What kind of improvements are you looking for?");
208        println!("  1. ๐Ÿš€ Performance optimization");
209        println!("  2. ๐Ÿ›ก๏ธ  Safety & error handling");
210        println!("  3. ๐Ÿ“– Readability & documentation");
211        println!("  4. ๐Ÿ—๏ธ  Architecture & design");
212        println!("  5. ๐Ÿงช Testing & validation");
213        println!("  6. ๐ŸŽ›๏ธ  General improvements");
214
215        print!("\nChoose focus area (1-6): ");
216        io::stdout().flush()?;
217
218        let mut input = String::new();
219        io::stdin().read_line(&mut input)?;
220
221        let mut ctx = SymbolicContext::new();
222        let task = match input.trim() {
223            "1" => "performance",
224            "2" => "safety",
225            "3" => "readability",
226            "4" => "architecture",
227            "5" => "testing",
228            "6" => "general improvement",
229            _ => {
230                println!("โŒ Invalid choice, defaulting to general improvements.");
231                "general improvement"
232            }
233        };
234
235        ctx.set("current_task", task);
236        Ok(ctx)
237    }
238
239    fn show_file_content(&self, file_path: &str) -> Result<(), Box<dyn std::error::Error>> {
240        println!("\n๐Ÿ“„ Current file content: {}", file_path);
241        println!("{}", "=".repeat(50));
242
243        let content = fs::read_to_string(file_path)?;
244        for (i, line) in content.lines().enumerate() {
245            println!("{:3}: {}", i + 1, line);
246        }
247
248        Ok(())
249    }
250
251    fn collect_agent_proposals(
252        &self,
253        ctx: &SymbolicContext,
254        _file_path: Option<&str>,
255    ) -> Vec<(String, ProposedEdit)> {
256        println!("\n๐Ÿค– Agents are analyzing and proposing improvements...");
257        println!("{}", "=".repeat(50));
258
259        let mut proposals = Vec::new();
260
261        for (agent_name, agent) in &self.agents {
262            println!("๐Ÿ” {} is thinking...", agent_name);
263            let proposal = agent.propose_edit(ctx);
264            proposals.push((agent_name.clone(), proposal));
265        }
266
267        proposals
268    }
269
270    fn interactive_proposal_review(
271        &self,
272        proposals: Vec<(String, ProposedEdit)>,
273    ) -> Result<Vec<ProposedEdit>, Box<dyn std::error::Error>> {
274        println!("\n๐Ÿ“‹ Agent Proposals - Your Review Required");
275        println!("{}", "=".repeat(50));
276
277        let mut selected_proposals = Vec::new();
278
279        for (i, (agent_name, proposal)) in proposals.iter().enumerate() {
280            println!("\n{}. ๐Ÿค– {} proposes:", i + 1, agent_name);
281            println!("   ๐Ÿ“ File: {}", proposal.file);
282            println!("   ๐Ÿ“ Lines: {:?}", proposal.line_range);
283            println!("   ๐Ÿ’ก Reason: {}", proposal.reason);
284            println!("   ๐Ÿ“Š Confidence: {:.1}%", proposal.confidence * 100.0);
285            println!("   ๐Ÿ“ Proposed code:");
286            for (line_num, line) in proposal.new_code.lines().enumerate() {
287                println!("      {}: {}", line_num + 1, line);
288            }
289
290            // Get user decision
291            loop {
292                print!("\n   โ“ Do you want to apply this edit? (y/n/s=skip to next): ");
293                io::stdout().flush()?;
294
295                let mut decision = String::new();
296                io::stdin().read_line(&mut decision)?;
297
298                match decision.trim().to_lowercase().as_str() {
299                    "y" | "yes" => {
300                        println!("   โœ… Edit approved!");
301                        selected_proposals.push(proposal.clone());
302                        break;
303                    }
304                    "n" | "no" => {
305                        println!("   โŒ Edit rejected.");
306                        break;
307                    }
308                    "s" | "skip" => {
309                        println!("   โญ๏ธ  Skipped for now.");
310                        break;
311                    }
312                    _ => {
313                        println!("   โš ๏ธ  Please enter 'y' for yes, 'n' for no, or 's' to skip.");
314                        continue;
315                    }
316                }
317            }
318        }
319
320        Ok(selected_proposals)
321    }
322
323    fn apply_selected_edits(
324        &self,
325        file_path: &str,
326        edits: Vec<ProposedEdit>,
327    ) -> Result<(), Box<dyn std::error::Error>> {
328        if edits.is_empty() {
329            return Ok(());
330        }
331
332        println!("\n๐Ÿ”ง Applying {} selected edit(s)...", edits.len());
333        println!("{}", "=".repeat(40));
334
335        // Create references for the function
336        let edit_refs: Vec<&ProposedEdit> = edits.iter().collect();
337
338        // Apply edits with backup
339        let backup_paths = apply_consensus_edits(&edit_refs)?;
340
341        // Show the changes
342        if let Some(backup_path) = backup_paths.first() {
343            println!("\n๐Ÿ“Š Changes Applied - Before vs After:");
344            show_file_diff(file_path, backup_path)?;
345
346            // Show final result
347            println!("\n๐Ÿ“„ Updated file content:");
348            println!("{}", "=".repeat(50));
349            let final_content = fs::read_to_string(file_path)?;
350            for (i, line) in final_content.lines().enumerate() {
351                println!("{:3}: {}", i + 1, line);
352            }
353
354            // Ask user if they want to keep changes
355            print!("\n๐Ÿ’พ Keep these changes? (y/n): ");
356            io::stdout().flush()?;
357
358            let mut decision = String::new();
359            io::stdin().read_line(&mut decision)?;
360
361            match decision.trim().to_lowercase().as_str() {
362                "y" | "yes" => {
363                    println!("โœ… Changes saved! Backup removed.");
364                    fs::remove_file(backup_path)?;
365                }
366                _ => {
367                    println!("๐Ÿ”„ Restoring original file...");
368                    restore_file(file_path, backup_path)?;
369                    println!("โœ… Original file restored.");
370                }
371            }
372        }
373
374        Ok(())
375    }
376
377    fn show_agent_capabilities(&self) {
378        println!("\n๐Ÿค– Agent Capabilities & Specializations");
379        println!("{}", "=".repeat(50));
380
381        println!("\n๐Ÿš€ GPT-4 Agent:");
382        println!("   โ€ข Performance optimization & efficient algorithms");
383        println!("   โ€ข Memory safety & bounds checking");
384        println!("   โ€ข Error handling & best practices");
385        println!("   โ€ข Code optimization for runtime efficiency");
386
387        println!("\n๐Ÿ“š Claude Agent:");
388        println!("   โ€ข Code readability & clear documentation");
389        println!("   โ€ข Architectural improvements & design patterns");
390        println!("   โ€ข Code organization & separation of concerns");
391        println!("   โ€ข Modular design & maintainability");
392
393        println!("\n๐Ÿงช Gemini Agent:");
394        println!("   โ€ข Comprehensive testing & edge case coverage");
395        println!("   โ€ข Input validation & robustness");
396        println!("   โ€ข Debugging capabilities & assertions");
397        println!("   โ€ข Quality assurance & reliability");
398
399        println!("\n๐Ÿ’ก All agents work together to provide comprehensive code analysis!");
400    }
401}
402
403#[derive(Debug)]
404enum MenuChoice {
405    AnalyzeFile,
406    CustomTask,
407    ViewAgentCapabilities,
408    Exit,
409}
410
411pub fn start_interactive_cli() -> Result<(), Box<dyn std::error::Error>> {
412    let collaboration = AgentCollaboration::new();
413    collaboration.run_interactive_session()
414}
415
416/// Enhanced edit processing with modification interface
417pub fn process_edits_with_modifications(
418    edits: Vec<ModifiableEdit>,
419) -> Result<(), Box<dyn std::error::Error>> {
420    let validator = EditValidator::new();
421    let preview = EditPreviewBuilder::new().build();
422
423    println!(
424        "๐Ÿ”ง Enhanced Edit Processing - {} edits to review",
425        edits.len()
426    );
427    println!("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
428
429    let total_edits = edits.len();
430    for (index, mut edit) in edits.into_iter().enumerate() {
431        println!("\n๐Ÿ“ Edit {} of {}", index + 1, total_edits);
432
433        // Generate preview
434        let preview_output = preview.render_to_string(&edit);
435        println!("{}", preview_output);
436
437        // Validate edit
438        let validation_summary = validator.validate_edit(&mut edit);
439        display_validation_summary(&validation_summary);
440
441        // User decision
442        match get_user_decision(&edit)? {
443            EditDecision::Accept => {
444                println!("โœ… Edit approved and applied.");
445                // Apply edit logic here
446            }
447            EditDecision::Modify => {
448                if let Some(_modified_edit) = modify_edit_interactive(edit)? {
449                    println!("โœ… Modified edit applied.");
450                    // Apply modified edit logic here
451                } else {
452                    println!("โŒ Edit modification cancelled.");
453                }
454            }
455            EditDecision::AdvancedEdit => {
456                if let Some(_modified_edit) = modify_edit_advanced_preview(edit)? {
457                    println!("โœ… Advanced edit session completed.");
458                    // Apply modified edit logic here
459                } else {
460                    println!("โŒ Advanced edit session cancelled.");
461                }
462            }
463            EditDecision::GranularApproval => {
464                if let Err(e) = process_granular_approval(edit)? {
465                    println!("โŒ Granular approval process failed: {}", e);
466                } else {
467                    println!("โœ… Granular approval process completed.");
468                }
469            }
470            EditDecision::StagedApplication => {
471                if let Err(e) = process_staged_application(edit)? {
472                    println!("โŒ Staged application process failed: {}", e);
473                } else {
474                    println!("โœ… Staged application process completed.");
475                }
476            }
477            EditDecision::CognitiveAssisted => {
478                if let Err(e) = process_cognitive_assisted(edit)? {
479                    println!("โŒ Cognitive assisted process failed: {}", e);
480                } else {
481                    println!("โœ… Cognitive assisted process completed.");
482                }
483            }
484            EditDecision::SmartClassification => {
485                if let Err(e) = process_smart_classification(edit)? {
486                    println!("โŒ Smart classification process failed: {}", e);
487                } else {
488                    println!("โœ… Smart classification process completed.");
489                }
490            }
491            EditDecision::GitIntegration => {
492                if let Err(e) = process_git_integration(edit)? {
493                    println!("โŒ Git integration process failed: {}", e);
494                } else {
495                    println!("โœ… Git integration process completed.");
496                }
497            }
498            EditDecision::TimeTravel => {
499                if let Err(e) = process_time_travel(edit)? {
500                    println!("โŒ Time travel process failed: {}", e);
501                } else {
502                    println!("โœ… Time travel process completed.");
503                }
504            }
505            EditDecision::CustomAgentConfig => {
506                if let Err(e) = process_custom_agent_config(edit)? {
507                    println!("โŒ Custom agent configuration process failed: {}", e);
508                } else {
509                    println!("โœ… Custom agent configuration process completed.");
510                }
511            }
512            EditDecision::VisualReasoning => {
513                if let Err(e) = process_visual_reasoning(edit)? {
514                    println!("โŒ Visual reasoning process failed: {}", e);
515                } else {
516                    println!("โœ… Visual reasoning process completed.");
517                }
518            }
519            EditDecision::MetaReflective => {
520                if let Err(e) = process_meta_reflective(edit)? {
521                    println!("โŒ Meta-reflective analysis process failed: {}", e);
522                } else {
523                    println!("โœ… Meta-reflective analysis process completed.");
524                }
525            }
526            EditDecision::Preview => {
527                println!("๐Ÿ” Previewing edit...");
528                // Preview logic here
529            }
530            EditDecision::AdvancedPreview => {
531                if let Some(_modified_edit) = modify_edit_advanced_preview(edit)? {
532                    println!("โœ… Advanced preview session completed.");
533                } else {
534                    println!("โŒ Advanced preview session cancelled.");
535                }
536            }
537            EditDecision::Skip => {
538                println!("โญ๏ธ Edit skipped.");
539            }
540            EditDecision::Reject => {
541                println!("โŒ Edit rejected.");
542            }
543        }
544    }
545
546    Ok(())
547}
548
549fn modify_edit_interactive(
550    edit: ModifiableEdit,
551) -> Result<Option<ModifiableEdit>, Box<dyn std::error::Error>> {
552    println!("\n๐Ÿ–Š๏ธ Opening interactive editor...");
553
554    let mut editor = InlineEditor::new(edit);
555    match editor.edit()? {
556        Some(modified_interface) => {
557            println!("โœ… Edit modified successfully!");
558            Ok(Some(modified_interface.modifiable_edit))
559        }
560        None => {
561            println!("โŒ Edit modification cancelled.");
562            Ok(None)
563        }
564    }
565}
566
567/// Enhanced modification with AdvancedPreviewSystem (Issue #18)
568fn modify_edit_advanced_preview(
569    edit: ModifiableEdit,
570) -> Result<Option<ModifiableEdit>, Box<dyn std::error::Error>> {
571    println!("\n๐Ÿ”„ Opening AdvancedPreviewSystem - Split-pane Live Editor...");
572    println!("Features available:");
573    println!("  โ€ข Split-pane editing with live preview");
574    println!("  โ€ข Multiple layout modes (Horizontal/Vertical/Full)");
575    println!("  โ€ข Real-time syntax validation");
576    println!("  โ€ข Enhanced diff visualization");
577    println!("  โ€ข Tab to switch between editor and preview");
578    println!("  โ€ข Ctrl+L to cycle layouts");
579
580    let interface = crate::edit_control::EditModificationInterface::new(edit);
581    let mut advanced_editor = AdvancedPreviewSystem::new(interface);
582    
583    match advanced_editor.edit_with_live_preview()? {
584        Some(modified_interface) => {
585            println!("โœ… Advanced edit session completed!");
586            Ok(Some(modified_interface.modifiable_edit))
587        }
588        None => {
589            println!("โŒ Advanced edit session cancelled.");
590            Ok(None)
591        }
592    }
593}
594
595fn get_user_decision(_edit: &ModifiableEdit) -> Result<EditDecision, Box<dyn std::error::Error>> {
596    println!("\n๐Ÿค” What would you like to do with this edit?");
597    println!("  [a] Approve  [m] Modify  [e] Advanced Edit  [g] Granular Approval  [st] Staged Application  [c] Cognitive Assisted  [cl] Smart Classification  [git] Git Integration  [ca] Custom Agent  [vr] Visual Reasoning  [mr] Meta-Reflective  [s] Skip  [r] Reject");
598    print!("Your choice: ");
599    io::stdout().flush()?;
600
601    let mut input = String::new();
602    io::stdin().read_line(&mut input)?;
603
604    match input.trim().to_lowercase().as_str() {
605        "a" | "approve" => Ok(EditDecision::Accept),
606        "m" | "modify" => Ok(EditDecision::Modify),
607        "e" | "advanced" => Ok(EditDecision::AdvancedEdit),
608        "g" | "granular" => Ok(EditDecision::GranularApproval),
609        "st" | "staged" => Ok(EditDecision::StagedApplication),
610        "c" | "cognitive" => Ok(EditDecision::CognitiveAssisted),
611        "cl" | "classify" => Ok(EditDecision::SmartClassification),
612        "git" | "gitintegration" => Ok(EditDecision::GitIntegration),
613        "tt" | "timetravel" => Ok(EditDecision::TimeTravel),
614        "ca" | "customagent" => Ok(EditDecision::CustomAgentConfig),
615        "vr" | "visualreasoning" => Ok(EditDecision::VisualReasoning),
616        "mr" | "metareflective" => Ok(EditDecision::MetaReflective),
617        "p" | "preview" => Ok(EditDecision::Preview),
618        "ap" | "advancedpreview" => Ok(EditDecision::AdvancedPreview),
619        "s" | "skip" => Ok(EditDecision::Skip),
620        "r" | "reject" => Ok(EditDecision::Reject),
621        _ => {
622            println!("Invalid choice, skipping edit.");
623            Ok(EditDecision::Skip)
624        }
625    }
626}
627
628/// Issue #19: Granular approval processing function
629fn process_granular_approval(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
630    println!("\n๐Ÿ”’ Initiating Granular Approval Process...");
631    println!("Features available:");
632    println!("  โ€ข Multi-level approval system (Auto/Low/Medium/High/Critical)");
633    println!("  โ€ข Role-based approval workflow (Junior/Senior/Lead/Architect/Security)");
634    println!("  โ€ข Risk assessment and automatic level determination");
635    println!("  โ€ข Escalation and delegation capabilities");
636    println!("  โ€ข Approval history tracking with comments");
637    
638    // For demo purposes, we'll simulate different user roles
639    // In a real system, this would come from authentication
640    let user_role = get_user_role()?;
641    let user_id = get_user_id()?;
642    
643    let mut mutable_edit = edit;
644    match process_edit_with_granular_approval(&mut mutable_edit, user_role, user_id) {
645        Ok(_) => {
646            println!("โœ… Granular approval completed successfully!");
647            println!("Final approval state: {:?}", mutable_edit.approval_state);
648            Ok(Ok(()))
649        }
650        Err(e) => {
651            println!("โŒ Granular approval failed: {}", e);
652            Ok(Err(e.to_string()))
653        }
654    }
655}
656
657/// Get user role for approval system (demo implementation)
658fn get_user_role() -> Result<ApprovalRole, Box<dyn std::error::Error>> {
659    println!("\n๐Ÿ‘ค Select your role for approval:");
660    println!("   [1] Junior Developer");
661    println!("   [2] Senior Developer");
662    println!("   [3] Team Lead");
663    println!("   [4] Architect");
664    println!("   [5] Security Reviewer");
665    print!("Your role (1-5): ");
666    io::stdout().flush()?;
667    
668    let mut input = String::new();
669    io::stdin().read_line(&mut input)?;
670    
671    match input.trim() {
672        "1" => Ok(ApprovalRole::Junior),
673        "2" => Ok(ApprovalRole::Senior),
674        "3" => Ok(ApprovalRole::Lead),
675        "4" => Ok(ApprovalRole::Architect),
676        "5" => Ok(ApprovalRole::Security),
677        _ => {
678            println!("Invalid selection, defaulting to Senior Developer");
679            Ok(ApprovalRole::Senior)
680        }
681    }
682}
683
684/// Get user ID for approval system (demo implementation)
685fn get_user_id() -> Result<String, Box<dyn std::error::Error>> {
686    print!("Enter your user ID (or press Enter for 'demo_user'): ");
687    io::stdout().flush()?;
688    
689    let mut input = String::new();
690    io::stdin().read_line(&mut input)?;
691    
692    let user_id = input.trim();
693    if user_id.is_empty() {
694        Ok("demo_user".to_string())
695    } else {
696        Ok(user_id.to_string())
697    }
698}
699
700fn display_validation_summary(summary: &crate::edit_control::validation::ValidationSummary) {
701    println!("\n๐Ÿ” Validation Summary:");
702    println!("  Total checks: {}", summary.total_validations);
703    println!("  โœ… Passed: {}", summary.passed);
704    println!("  โš ๏ธ Warnings: {}", summary.warnings);
705    println!("  โŒ Errors: {}", summary.errors);
706    println!("  ๐Ÿšจ Critical: {}", summary.critical);
707
708    if !summary.conflicts.is_empty() {
709        println!("  ๐Ÿ”ฅ Conflicts: {}", summary.conflicts.len());
710    }
711
712    println!("  ๐Ÿ“Š Status: {:?}", summary.overall_status);
713}
714
715#[derive(Debug, Clone, PartialEq)]
716pub enum EditDecision {
717    Preview,
718    Accept,
719    Reject,
720    Modify,
721    // Issue #17: Enhanced Edit Modification Interface
722    AdvancedEdit,
723    // Issue #18: Advanced Preview System  
724    AdvancedPreview,
725    // Issue #19: Granular Approval Levels
726    GranularApproval,
727    // Issue #20: Staged Application System
728    StagedApplication,
729    // Issue #25: Edit Classification System
730    SmartClassification,
731    // Issue #26: Git Integration System
732    GitIntegration,
733    // Issue #27: Edit History Time Travel
734    TimeTravel,
735    // Issue #30: Custom Agent Configuration
736    CustomAgentConfig,
737    // Issue #31: Visual Reasoning
738    VisualReasoning,
739    // Issue #32: Meta-Reflective Analysis
740    MetaReflective,
741    // Additional options for compatibility
742    CognitiveAssisted,
743    Skip,
744}
745
746/// Issue #20: Staged application processing function
747fn process_staged_application(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
748    println!("\n๐Ÿš€ Initiating Staged Application System...");
749    println!("Features available:");
750    println!("  โ€ข Phased edit application with rollback capabilities");
751    println!("  โ€ข Multiple stages with dependency management");
752    println!("  โ€ข Checkpoint creation and restoration");
753    println!("  โ€ข Comprehensive validation at each stage");
754    println!("  โ€ข Timeline view and execution progress tracking");
755    
756    // Create a single edit as a stage for demonstration
757    let edits = vec![edit];
758    match process_edit_with_staged_application(edits, Some("Demo Stage".to_string())) {
759        Ok(_) => {
760            println!("โœ… Staged application completed successfully!");
761            Ok(Ok(()))
762        }
763        Err(e) => {
764            println!("โŒ Staged application failed: {}", e);
765            Ok(Err(e.to_string()))
766        }
767    }
768}
769
770/// Cognitive-assisted processing function
771fn process_cognitive_assisted(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
772    println!("\n๐Ÿง  Initiating Cognitive-Assisted Analysis...");
773    println!("Features available:");
774    println!("  โ€ข AI-powered edit analysis and insights");
775    println!("  โ€ข Introspection and complexity assessment");
776    println!("  โ€ข Cognitive load and attention focus analysis");
777    println!("  โ€ข Uncertainty and confidence evaluation");
778    println!("  โ€ข Meta-cognitive recommendations");
779    
780    let cognitive_workflow = CognitiveWorkflow::new();
781    
782    // Analyze the edit using cognitive operators
783    match cognitive_workflow.analyze_edit_context(
784        &edit.base_edit.file,
785        &edit.base_edit.reason,
786        edit.base_edit.confidence
787    ) {
788        Ok(analysis) => {
789            // Get cognitive recommendation
790            let decision = cognitive_workflow.get_cognitive_decision(&analysis)?;
791            println!("โœ… Cognitive analysis completed!");
792            println!("Final decision: {:?}", decision);
793            Ok(Ok(()))
794        }
795        Err(e) => {
796            println!("โŒ Cognitive analysis failed: {}", e);
797            Ok(Err(e.to_string()))
798        }
799    }
800}
801
802/// Issue #25: Smart classification processing function
803fn process_smart_classification(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
804    println!("\n๐Ÿ” Initiating Smart Edit Classification...");
805    println!("Features available:");
806    println!("  โ€ข Intelligent edit categorization (Critical/Experimental/Safe/Cosmetic)");
807    println!("  โ€ข Risk assessment with pattern detection");
808    println!("  โ€ข Priority scoring and confidence evaluation");
809    println!("  โ€ข Cognitive operator integration for enhanced analysis");
810    println!("  โ€ข Automatic recommendation generation");
811    
812    // Create classification CLI instance
813    let mut classifier = EditClassificationCLI::new()?;
814    
815    // Classify the edit
816    match classifier.classify_single_edit(&edit) {
817        Ok(classified_edit) => {
818            println!("\n๐Ÿ“Š Classification Analysis Complete!");
819            
820            println!("\n๐ŸŽฏ Smart Recommendation:");
821            match &classified_edit.recommendation {
822                crate::classification::edit_classifier_working::ClassificationRecommendation::AutoApprove { confidence } => {
823                    println!("   โœ… Auto-approve recommended ({:.1}% confidence)", confidence * 100.0);
824                    println!("   This edit is classified as safe and can be automatically approved.");
825                }
826                crate::classification::edit_classifier_working::ClassificationRecommendation::RequireReview { concerns } => {
827                    println!("   ๐Ÿ” Manual review required");
828                    println!("   Concerns identified:");
829                    for concern in concerns {
830                        println!("      โ€ข {}", concern);
831                    }
832                }
833                crate::classification::edit_classifier_working::ClassificationRecommendation::Escalate { target_level, reason } => {
834                    println!("   โฌ†๏ธ  Escalation recommended to: {}", target_level);
835                    println!("   Reason: {}", reason);
836                }
837                crate::classification::edit_classifier_working::ClassificationRecommendation::Reject { reason } => {
838                    println!("   โŒ Rejection recommended");
839                    println!("   Reason: {}", reason);
840                }
841                crate::classification::edit_classifier_working::ClassificationRecommendation::RequestInfo { questions } => {
842                    println!("   โ“ Additional information needed");
843                    for question in questions {
844                        println!("      โ€ข {}", question);
845                    }
846                }
847            }
848            
849            println!("\n๐Ÿ“ˆ Classification Summary:");
850            println!("   Category: {:?}", classified_edit.category);
851            println!("   Priority Score: {:.3}", classified_edit.priority_score);
852            println!("   Risk Score: {:.3}", classified_edit.risk_assessment.overall_score);
853            println!("   Classification Confidence: {:.3}", classified_edit.classification_confidence);
854            
855            Ok(Ok(()))
856        }
857        Err(e) => {
858            println!("โŒ Smart classification failed: {}", e);
859            Ok(Err(e.to_string()))
860        }
861    }
862}
863
864/// Issue #26: Git integration processing function
865fn process_git_integration(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
866    println!("\n๐Ÿ”ง Initiating Git Integration Workflow...");
867    println!("Features available:");
868    println!("  โ€ข Automatic session branching with intelligent naming");
869    println!("  โ€ข Classification-based commit strategies");
870    println!("  โ€ข Conflict resolution with cognitive operators");
871    println!("  โ€ข Automated backup points and rollback capabilities");
872    println!("  โ€ข CI/CD pipeline integration hooks");
873    
874    // Get the current repository path
875    let current_dir = std::env::current_dir()
876        .map_err(|e| format!("Failed to get current directory: {}", e))?;
877    
878    // Use the git_integration module's interactive workflow
879
880    
881    // Create a simple classification for this edit (in real usage, this would come from the classification system)
882    use crate::classification::EditClassificationSystem;
883    
884    // Classify the edit using the classification system
885    let classifier = EditClassificationSystem::new();
886    let classified_edit = classifier.classify_edit(&edit)
887        .map_err(|e| format!("Failed to classify edit: {}", e))?;
888    
889    // For the Git integration, we need to convert to the expected format
890    // This is a simplified approach - in practice, the Git integration would work directly with ClassifiedEdit
891    println!("๐Ÿ“Š Edit Classification:");
892    println!("   Category: {:?}", classified_edit.category);
893    println!("   Risk Score: {:.3}", classified_edit.risk_assessment.overall_score);
894    println!("   Priority: {:.3}", classified_edit.priority_score);
895    println!("   Confidence: {:.3}", classified_edit.classification_confidence);
896    
897    // For now, we'll use a simplified Git workflow without the full classification integration
898    // In a complete implementation, the Git integration would be updated to work with ClassifiedEdit
899    println!("\n๐Ÿ”ง Proceeding with Git workflow...");
900    
901    match crate::cli::git_integration::GitIntegrationCLI::new(current_dir.clone()) {
902        Ok(mut git_cli) => {
903            match git_cli.start_interactive_session() {
904                Ok(_) => {
905                    println!("โœ… Git integration session completed!");
906                    Ok(Ok(()))
907                }
908                Err(e) => {
909                    println!("โŒ Git integration session failed: {}", e);
910                    Ok(Err(e))
911                }
912            }
913        }
914                 Err(e) => {
915             println!("โŒ Failed to initialize Git integration: {}", e);
916             Ok(Err(e))
917         }
918     }
919}
920
921/// Issue #27: Time travel processing function
922fn process_time_travel(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
923    println!("\n๐Ÿ•ฐ๏ธ  Initiating Time Travel System...");
924    println!("Features available:");
925    println!("  โ€ข Complete edit history with timeline branching");
926    println!("  โ€ข Navigate through different edit paths and timelines");
927    println!("  โ€ข Create and restore stable checkpoints");
928    println!("  โ€ข Search through historical changes and patterns");
929    println!("  โ€ข Merge and compare different edit timelines");
930    println!("  โ€ข Git integration for persistent history tracking");
931    
932    // Use the time_travel module's interactive workflow
933    use crate::cli::time_travel::interactive_time_travel_decision;
934    
935    // Create a dummy classification for this edit (in real usage, this would come from the classification system)
936    use crate::classification::EditClassificationSystem;
937    
938    let classifier = EditClassificationSystem::new();
939    let classified_edit = classifier.classify_edit(&edit)
940        .map_err(|e| format!("Failed to classify edit for time travel: {}", e))?;
941    
942    println!("๐Ÿ“Š Edit Classification for Time Travel:");
943    println!("   Category: {:?}", classified_edit.category);
944    println!("   Risk Score: {:.3}", classified_edit.risk_assessment.overall_score);
945    println!("   Priority: {:.3}", classified_edit.priority_score);
946    println!("   Reasoning: {}", classified_edit.reasoning);
947    
948    // Launch interactive time travel workflow
949    match interactive_time_travel_decision(vec![edit], vec![classified_edit]) {
950        Ok(used_time_travel) => {
951            if used_time_travel {
952                println!("โœ… Time travel session completed successfully");
953                Ok(Ok(()))
954            } else {
955                println!("โ„น๏ธ  Time travel was not used");
956                Ok(Ok(()))
957            }
958        }
959        Err(e) => {
960            println!("โŒ Time travel error: {}", e);
961            Ok(Err(e.to_string()))
962        }
963    }
964}
965
966/// Issue #30: Custom agent configuration processing function
967fn process_custom_agent_config(_edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
968    println!("\n๐Ÿค– Initiating Custom Agent Configuration...");
969    println!("Features available:");
970    println!("  โ€ข User-defined agent personalities and behavior modification");
971    println!("  โ€ข Custom prompting and context templates");
972    println!("  โ€ข Preference learning and adaptation");
973    println!("  โ€ข Project-specific context configuration");
974    println!("  โ€ข Agent performance tracking and optimization");
975    
976    // Use the comprehensive custom agent configuration CLI
977    use crate::cli::custom_agent_config::CustomAgentConfigCLI;
978    
979    match CustomAgentConfigCLI::new() {
980        Ok(mut config_cli) => {
981            match config_cli.start_interactive_session() {
982                Ok(_) => {
983                    println!("โœ… Custom agent configuration completed successfully!");
984                    Ok(Ok(()))
985                }
986                Err(e) => {
987                    println!("โŒ Custom agent configuration failed: {}", e);
988                    Ok(Err(e.to_string()))
989                }
990            }
991        }
992        Err(e) => {
993            println!("โŒ Failed to initialize custom agent configuration: {}", e);
994            Ok(Err(e.to_string()))
995        }
996    }
997}
998
999/// Issue #31: Visual reasoning processing function
1000fn process_visual_reasoning(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
1001    println!("\n๐Ÿ”ฌ Initiating Visual Reasoning Analysis...");
1002    println!("Features available:");
1003    println!("  โ€ข Code structure analysis with AST visualization");
1004    println!("  โ€ข Pattern recognition and code smell detection");
1005    println!("  โ€ข Dependency mapping with visual graph representation");
1006    println!("  โ€ข Visual diff analysis with change impact assessment");
1007    println!("  โ€ข Interactive session with analysis history tracking");
1008    println!("  โ€ข Export capabilities for analysis results");
1009    
1010    // Launch the visual reasoning CLI
1011    match crate::cli::visual_reasoning::process_visual_reasoning(edit) {
1012        Ok(Ok(())) => {
1013            println!("โœ… Visual reasoning analysis completed successfully!");
1014            Ok(Ok(()))
1015        }
1016        Ok(Err(e)) => {
1017            println!("โŒ Visual reasoning analysis failed: {}", e);
1018            Ok(Err(e))
1019        }
1020        Err(e) => {
1021            println!("โŒ Visual reasoning system error: {}", e);
1022            Ok(Err(format!("System error: {}", e)))
1023        }
1024    }
1025}
1026
1027/// Issue #32: Meta-reflective analysis processing function
1028fn process_meta_reflective(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
1029    println!("\n๐Ÿง  Initiating Meta-Reflective Analysis...");
1030    println!("Features available:");
1031    println!("  โ€ข System introspection and cognitive bottleneck detection");
1032    println!("  โ€ข Performance analysis with trend monitoring");
1033    println!("  โ€ข Cognitive assessment with meta-cognitive state evaluation");
1034    println!("  โ€ข Optimization recommendations with priority scoring");
1035    println!("  โ€ข Session history tracking with performance metrics");
1036    println!("  โ€ข Real-time system monitoring and health indicators");
1037    println!("  โ€ข Analysis data export in multiple formats");
1038    
1039    // Create context from edit and system state
1040    let mut context = crate::memory::SymbolicContext::new();
1041    context.set("file_path", &edit.base_edit.file);
1042    context.set("edit_content", &edit.base_edit.new_code);
1043    context.set("analysis_mode", "meta_reflective");
1044    context.set("cognitive_focus", "system_optimization");
1045    
1046    // Add system metrics to context
1047    context.set("operator_count", "15"); // Current operator count
1048    context.set("system_uptime", &std::time::SystemTime::now()
1049        .duration_since(std::time::UNIX_EPOCH)
1050        .unwrap()
1051        .as_secs()
1052        .to_string());
1053    context.set("errors_count", "0"); // Assume clean state
1054    
1055    // Process meta-reflective workflow
1056    match crate::cli::meta_reflective::process_meta_reflective_workflow(&context) {
1057        Ok(analysis_result) => {
1058            println!("โœ… Meta-reflective analysis completed successfully!");
1059            
1060            // Display key insights
1061            if let Some(performance_score) = analysis_result.get("system_performance_score") {
1062                println!("๐ŸŽฏ System Performance Score: {}", performance_score);
1063            }
1064            if let Some(cognitive_state) = analysis_result.get("meta_cognitive_state") {
1065                println!("๐Ÿง  Meta-Cognitive State: {}", cognitive_state);
1066            }
1067            if let Some(reasoning_patterns) = analysis_result.get("reasoning_patterns_detected") {
1068                println!("๐Ÿงฉ Reasoning Patterns: {}", reasoning_patterns);
1069            }
1070            if let Some(emergence_level) = analysis_result.get("emergence_level") {
1071                println!("๐ŸŒŸ Emergence Level: {}", emergence_level);
1072            }
1073            
1074            // Display optimization suggestions
1075            for i in 0..3 {
1076                if let Some(optimization) = analysis_result.get(&format!("optimization_ฮ˜_{}", i)) {
1077                    println!("๐Ÿ’ก Optimization {}: {}", i + 1, optimization);
1078                }
1079            }
1080            
1081            Ok(Ok(()))
1082        }
1083        Err(e) => {
1084            println!("โŒ Meta-reflective analysis failed: {}", e);
1085            Ok(Err(format!("Meta-reflective analysis error: {}", e)))
1086        }
1087    }
1088}