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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
// src/cli/mod.rs
// Interactive CLI for multi-agent code editing collaboration

use crate::agents::claude_agent::ClaudeAgent;
use crate::agents::gemini_agent::GeminiAgent;
use crate::agents::gpt4_agent::{CognitiveAgent, GPT4Agent, ProposedEdit};
use crate::feedback_loop::{apply_consensus_edits, restore_file, show_file_diff};
use crate::memory::SymbolicContext;
use std::fs;
use std::io::{self, Write};

pub mod editor;
pub mod preview;
pub mod advanced_preview;
// Issue #19: Granular Approval Levels
pub mod granular_approval;
// Issue #20: Staged Application System
pub mod staged_application;
// Cognitive-assisted workflow
pub mod cognitive_workflow;
// Issue #25: Edit Classification System
pub mod edit_classification;
// Issue #26: Git Integration System
pub mod git_integration;
// Issue #27: Time Travel CLI
pub mod time_travel;
// Issue #30: Custom Agent Configuration CLI
pub mod custom_agent_config;
// Issue #31: Visual Reasoning CLI
pub mod visual_reasoning;
// Issue #32: Meta-Reflective CLI
pub mod meta_reflective;

// Re-export for external use
pub use advanced_preview::AdvancedPreviewSystem;
// Issue #20: Re-export StagedApplicationInterface
pub use staged_application::StagedApplicationInterface;

use crate::edit_control::{validation::EditValidator, ModifiableEdit};
use editor::InlineEditor;
use preview::EditPreviewBuilder;
// Issue #19: Granular Approval System imports
use crate::cli::granular_approval::process_edit_with_granular_approval;
use crate::edit_control::ApprovalRole;
// Issue #20: Staged Application System imports
use crate::cli::staged_application::process_edit_with_staged_application;
// Cognitive workflow imports
use crate::cli::cognitive_workflow::CognitiveWorkflow;
// Issue #25: Edit Classification imports
use crate::cli::edit_classification::EditClassificationCLI;

pub struct AgentCollaboration {
    agents: Vec<(String, Box<dyn CognitiveAgent>)>,
}

impl AgentCollaboration {
    pub fn new() -> Self {
        Self {
            agents: vec![
                ("GPT-4".to_string(), Box::new(GPT4Agent)),
                ("Claude".to_string(), Box::new(ClaudeAgent)),
                ("Gemini".to_string(), Box::new(GeminiAgent)),
            ],
        }
    }

    pub fn run_interactive_session(&self) -> Result<(), Box<dyn std::error::Error>> {
        self.print_welcome();

        loop {
            match self.main_menu()? {
                MenuChoice::AnalyzeFile => self.analyze_file_workflow()?,
                MenuChoice::CustomTask => self.custom_task_workflow()?,
                MenuChoice::ViewAgentCapabilities => self.show_agent_capabilities(),
                MenuChoice::Exit => {
                    println!("\n👋 Thanks for collaborating with the SOMA agents!");
                    break;
                }
            }
        }

        Ok(())
    }

    fn print_welcome(&self) {
        println!("{}", "=".repeat(60));
        println!("🤝 SOMA CORE - Interactive Agent Collaboration");
        println!("{}", "=".repeat(60));
        println!("Welcome! You can collaborate with our AI agents to improve your code.");
        println!("Each agent has different expertise:");
        println!("  🚀 GPT-4:  Performance & Best Practices");
        println!("  📚 Claude: Readability & Architecture");
        println!("  🧪 Gemini: Testing & Validation");
        println!("\n💡 Your vote is decisive - you choose which suggestions to apply!\n");
    }

    fn main_menu(&self) -> Result<MenuChoice, Box<dyn std::error::Error>> {
        loop {
            println!("\n📋 What would you like to do?");
            println!("  1. 📄 Analyze & improve a specific file");
            println!("  2. 🎯 Set custom improvement task");
            println!("  3. 🤖 View agent capabilities");
            println!("  4. 🚪 Exit");

            print!("\nChoose an option (1-4): ");
            io::stdout().flush()?;

            let mut input = String::new();
            io::stdin().read_line(&mut input)?;

            match input.trim() {
                "1" => return Ok(MenuChoice::AnalyzeFile),
                "2" => return Ok(MenuChoice::CustomTask),
                "3" => return Ok(MenuChoice::ViewAgentCapabilities),
                "4" => return Ok(MenuChoice::Exit),
                _ => {
                    println!("❌ Invalid choice. Please try again.");
                    continue;
                }
            }
        }
    }

    fn analyze_file_workflow(&self) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n📂 File Analysis Mode");
        println!("{}", "=".repeat(30));

        // Get file path from user
        print!("Enter the file path to analyze: ");
        io::stdout().flush()?;
        let mut file_path = String::new();
        io::stdin().read_line(&mut file_path)?;
        let file_path = file_path.trim();

        if !std::path::Path::new(file_path).exists() {
            println!("❌ File '{}' not found. Please check the path.", file_path);
            return Ok(());
        }

        // Show current file content
        self.show_file_content(file_path)?;

        // Get improvement focus from user
        let task_context = self.get_improvement_focus()?;

        // Get agent proposals
        let proposals = self.collect_agent_proposals(&task_context, Some(file_path));

        // Show proposals and get user decision
        let selected_proposals = self.interactive_proposal_review(proposals)?;

        if !selected_proposals.is_empty() {
            self.apply_selected_edits(file_path, selected_proposals)?;
        } else {
            println!("\n📝 No edits selected. File remains unchanged.");
        }

        Ok(())
    }

    fn custom_task_workflow(&self) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n🎯 Custom Task Mode");
        println!("{}", "=".repeat(25));

        print!("Describe what you want to improve (e.g., 'add error handling', 'optimize performance'): ");
        io::stdout().flush()?;
        let mut task_description = String::new();
        io::stdin().read_line(&mut task_description)?;
        let task_description = task_description.trim();

        // Get target file
        print!("Which file should the agents work on? ");
        io::stdout().flush()?;
        let mut file_path = String::new();
        io::stdin().read_line(&mut file_path)?;
        let file_path = file_path.trim();

        if !std::path::Path::new(file_path).exists() {
            println!("❌ File '{}' not found. Please check the path.", file_path);
            return Ok(());
        }

        // Show current file
        self.show_file_content(file_path)?;

        // Create context
        let mut ctx = SymbolicContext::new();
        ctx.set("current_task", task_description);
        ctx.set("target_file", file_path);

        // Get proposals
        let proposals = self.collect_agent_proposals(&ctx, Some(file_path));

        // Interactive review
        let selected_proposals = self.interactive_proposal_review(proposals)?;

        if !selected_proposals.is_empty() {
            self.apply_selected_edits(file_path, selected_proposals)?;
        } else {
            println!("\n📝 No edits selected. File remains unchanged.");
        }

        Ok(())
    }

    fn get_improvement_focus(&self) -> Result<SymbolicContext, Box<dyn std::error::Error>> {
        println!("\n🎯 What kind of improvements are you looking for?");
        println!("  1. 🚀 Performance optimization");
        println!("  2. 🛡️  Safety & error handling");
        println!("  3. 📖 Readability & documentation");
        println!("  4. 🏗️  Architecture & design");
        println!("  5. 🧪 Testing & validation");
        println!("  6. 🎛️  General improvements");

        print!("\nChoose focus area (1-6): ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;

        let mut ctx = SymbolicContext::new();
        let task = match input.trim() {
            "1" => "performance",
            "2" => "safety",
            "3" => "readability",
            "4" => "architecture",
            "5" => "testing",
            "6" => "general improvement",
            _ => {
                println!("❌ Invalid choice, defaulting to general improvements.");
                "general improvement"
            }
        };

        ctx.set("current_task", task);
        Ok(ctx)
    }

    fn show_file_content(&self, file_path: &str) -> Result<(), Box<dyn std::error::Error>> {
        println!("\n📄 Current file content: {}", file_path);
        println!("{}", "=".repeat(50));

        let content = fs::read_to_string(file_path)?;
        for (i, line) in content.lines().enumerate() {
            println!("{:3}: {}", i + 1, line);
        }

        Ok(())
    }

    fn collect_agent_proposals(
        &self,
        ctx: &SymbolicContext,
        _file_path: Option<&str>,
    ) -> Vec<(String, ProposedEdit)> {
        println!("\n🤖 Agents are analyzing and proposing improvements...");
        println!("{}", "=".repeat(50));

        let mut proposals = Vec::new();

        for (agent_name, agent) in &self.agents {
            println!("🔍 {} is thinking...", agent_name);
            let proposal = agent.propose_edit(ctx);
            proposals.push((agent_name.clone(), proposal));
        }

        proposals
    }

    fn interactive_proposal_review(
        &self,
        proposals: Vec<(String, ProposedEdit)>,
    ) -> Result<Vec<ProposedEdit>, Box<dyn std::error::Error>> {
        println!("\n📋 Agent Proposals - Your Review Required");
        println!("{}", "=".repeat(50));

        let mut selected_proposals = Vec::new();

        for (i, (agent_name, proposal)) in proposals.iter().enumerate() {
            println!("\n{}. 🤖 {} proposes:", i + 1, agent_name);
            println!("   📁 File: {}", proposal.file);
            println!("   📍 Lines: {:?}", proposal.line_range);
            println!("   💡 Reason: {}", proposal.reason);
            println!("   📊 Confidence: {:.1}%", proposal.confidence * 100.0);
            println!("   📝 Proposed code:");
            for (line_num, line) in proposal.new_code.lines().enumerate() {
                println!("      {}: {}", line_num + 1, line);
            }

            // Get user decision
            loop {
                print!("\n   ❓ Do you want to apply this edit? (y/n/s=skip to next): ");
                io::stdout().flush()?;

                let mut decision = String::new();
                io::stdin().read_line(&mut decision)?;

                match decision.trim().to_lowercase().as_str() {
                    "y" | "yes" => {
                        println!("   ✅ Edit approved!");
                        selected_proposals.push(proposal.clone());
                        break;
                    }
                    "n" | "no" => {
                        println!("   ❌ Edit rejected.");
                        break;
                    }
                    "s" | "skip" => {
                        println!("   ⏭️  Skipped for now.");
                        break;
                    }
                    _ => {
                        println!("   ⚠️  Please enter 'y' for yes, 'n' for no, or 's' to skip.");
                        continue;
                    }
                }
            }
        }

        Ok(selected_proposals)
    }

    fn apply_selected_edits(
        &self,
        file_path: &str,
        edits: Vec<ProposedEdit>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        if edits.is_empty() {
            return Ok(());
        }

        println!("\n🔧 Applying {} selected edit(s)...", edits.len());
        println!("{}", "=".repeat(40));

        // Create references for the function
        let edit_refs: Vec<&ProposedEdit> = edits.iter().collect();

        // Apply edits with backup
        let backup_paths = apply_consensus_edits(&edit_refs)?;

        // Show the changes
        if let Some(backup_path) = backup_paths.first() {
            println!("\n📊 Changes Applied - Before vs After:");
            show_file_diff(file_path, backup_path)?;

            // Show final result
            println!("\n📄 Updated file content:");
            println!("{}", "=".repeat(50));
            let final_content = fs::read_to_string(file_path)?;
            for (i, line) in final_content.lines().enumerate() {
                println!("{:3}: {}", i + 1, line);
            }

            // Ask user if they want to keep changes
            print!("\n💾 Keep these changes? (y/n): ");
            io::stdout().flush()?;

            let mut decision = String::new();
            io::stdin().read_line(&mut decision)?;

            match decision.trim().to_lowercase().as_str() {
                "y" | "yes" => {
                    println!("✅ Changes saved! Backup removed.");
                    fs::remove_file(backup_path)?;
                }
                _ => {
                    println!("🔄 Restoring original file...");
                    restore_file(file_path, backup_path)?;
                    println!("✅ Original file restored.");
                }
            }
        }

        Ok(())
    }

    fn show_agent_capabilities(&self) {
        println!("\n🤖 Agent Capabilities & Specializations");
        println!("{}", "=".repeat(50));

        println!("\n🚀 GPT-4 Agent:");
        println!("   • Performance optimization & efficient algorithms");
        println!("   • Memory safety & bounds checking");
        println!("   • Error handling & best practices");
        println!("   • Code optimization for runtime efficiency");

        println!("\n📚 Claude Agent:");
        println!("   • Code readability & clear documentation");
        println!("   • Architectural improvements & design patterns");
        println!("   • Code organization & separation of concerns");
        println!("   • Modular design & maintainability");

        println!("\n🧪 Gemini Agent:");
        println!("   • Comprehensive testing & edge case coverage");
        println!("   • Input validation & robustness");
        println!("   • Debugging capabilities & assertions");
        println!("   • Quality assurance & reliability");

        println!("\n💡 All agents work together to provide comprehensive code analysis!");
    }
}

#[derive(Debug)]
enum MenuChoice {
    AnalyzeFile,
    CustomTask,
    ViewAgentCapabilities,
    Exit,
}

pub fn start_interactive_cli() -> Result<(), Box<dyn std::error::Error>> {
    let collaboration = AgentCollaboration::new();
    collaboration.run_interactive_session()
}

/// Enhanced edit processing with modification interface
pub fn process_edits_with_modifications(
    edits: Vec<ModifiableEdit>,
) -> Result<(), Box<dyn std::error::Error>> {
    let validator = EditValidator::new();
    let preview = EditPreviewBuilder::new().build();

    println!(
        "🔧 Enhanced Edit Processing - {} edits to review",
        edits.len()
    );
    println!("═══════════════════════════════════════════════════");

    let total_edits = edits.len();
    for (index, mut edit) in edits.into_iter().enumerate() {
        println!("\n📝 Edit {} of {}", index + 1, total_edits);

        // Generate preview
        let preview_output = preview.render_to_string(&edit);
        println!("{}", preview_output);

        // Validate edit
        let validation_summary = validator.validate_edit(&mut edit);
        display_validation_summary(&validation_summary);

        // User decision
        match get_user_decision(&edit)? {
            EditDecision::Accept => {
                println!("✅ Edit approved and applied.");
                // Apply edit logic here
            }
            EditDecision::Modify => {
                if let Some(_modified_edit) = modify_edit_interactive(edit)? {
                    println!("✅ Modified edit applied.");
                    // Apply modified edit logic here
                } else {
                    println!("❌ Edit modification cancelled.");
                }
            }
            EditDecision::AdvancedEdit => {
                if let Some(_modified_edit) = modify_edit_advanced_preview(edit)? {
                    println!("✅ Advanced edit session completed.");
                    // Apply modified edit logic here
                } else {
                    println!("❌ Advanced edit session cancelled.");
                }
            }
            EditDecision::GranularApproval => {
                if let Err(e) = process_granular_approval(edit)? {
                    println!("❌ Granular approval process failed: {}", e);
                } else {
                    println!("✅ Granular approval process completed.");
                }
            }
            EditDecision::StagedApplication => {
                if let Err(e) = process_staged_application(edit)? {
                    println!("❌ Staged application process failed: {}", e);
                } else {
                    println!("✅ Staged application process completed.");
                }
            }
            EditDecision::CognitiveAssisted => {
                if let Err(e) = process_cognitive_assisted(edit)? {
                    println!("❌ Cognitive assisted process failed: {}", e);
                } else {
                    println!("✅ Cognitive assisted process completed.");
                }
            }
            EditDecision::SmartClassification => {
                if let Err(e) = process_smart_classification(edit)? {
                    println!("❌ Smart classification process failed: {}", e);
                } else {
                    println!("✅ Smart classification process completed.");
                }
            }
            EditDecision::GitIntegration => {
                if let Err(e) = process_git_integration(edit)? {
                    println!("❌ Git integration process failed: {}", e);
                } else {
                    println!("✅ Git integration process completed.");
                }
            }
            EditDecision::TimeTravel => {
                if let Err(e) = process_time_travel(edit)? {
                    println!("❌ Time travel process failed: {}", e);
                } else {
                    println!("✅ Time travel process completed.");
                }
            }
            EditDecision::CustomAgentConfig => {
                if let Err(e) = process_custom_agent_config(edit)? {
                    println!("❌ Custom agent configuration process failed: {}", e);
                } else {
                    println!("✅ Custom agent configuration process completed.");
                }
            }
            EditDecision::VisualReasoning => {
                if let Err(e) = process_visual_reasoning(edit)? {
                    println!("❌ Visual reasoning process failed: {}", e);
                } else {
                    println!("✅ Visual reasoning process completed.");
                }
            }
            EditDecision::MetaReflective => {
                if let Err(e) = process_meta_reflective(edit)? {
                    println!("❌ Meta-reflective analysis process failed: {}", e);
                } else {
                    println!("✅ Meta-reflective analysis process completed.");
                }
            }
            EditDecision::Preview => {
                println!("🔍 Previewing edit...");
                // Preview logic here
            }
            EditDecision::AdvancedPreview => {
                if let Some(_modified_edit) = modify_edit_advanced_preview(edit)? {
                    println!("✅ Advanced preview session completed.");
                } else {
                    println!("❌ Advanced preview session cancelled.");
                }
            }
            EditDecision::Skip => {
                println!("⏭️ Edit skipped.");
            }
            EditDecision::Reject => {
                println!("❌ Edit rejected.");
            }
        }
    }

    Ok(())
}

fn modify_edit_interactive(
    edit: ModifiableEdit,
) -> Result<Option<ModifiableEdit>, Box<dyn std::error::Error>> {
    println!("\n🖊️ Opening interactive editor...");

    let mut editor = InlineEditor::new(edit);
    match editor.edit()? {
        Some(modified_interface) => {
            println!("✅ Edit modified successfully!");
            Ok(Some(modified_interface.modifiable_edit))
        }
        None => {
            println!("❌ Edit modification cancelled.");
            Ok(None)
        }
    }
}

/// Enhanced modification with AdvancedPreviewSystem (Issue #18)
fn modify_edit_advanced_preview(
    edit: ModifiableEdit,
) -> Result<Option<ModifiableEdit>, Box<dyn std::error::Error>> {
    println!("\n🔄 Opening AdvancedPreviewSystem - Split-pane Live Editor...");
    println!("Features available:");
    println!("  • Split-pane editing with live preview");
    println!("  • Multiple layout modes (Horizontal/Vertical/Full)");
    println!("  • Real-time syntax validation");
    println!("  • Enhanced diff visualization");
    println!("  • Tab to switch between editor and preview");
    println!("  • Ctrl+L to cycle layouts");

    let interface = crate::edit_control::EditModificationInterface::new(edit);
    let mut advanced_editor = AdvancedPreviewSystem::new(interface);
    
    match advanced_editor.edit_with_live_preview()? {
        Some(modified_interface) => {
            println!("✅ Advanced edit session completed!");
            Ok(Some(modified_interface.modifiable_edit))
        }
        None => {
            println!("❌ Advanced edit session cancelled.");
            Ok(None)
        }
    }
}

fn get_user_decision(_edit: &ModifiableEdit) -> Result<EditDecision, Box<dyn std::error::Error>> {
    println!("\n🤔 What would you like to do with this edit?");
    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");
    print!("Your choice: ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    match input.trim().to_lowercase().as_str() {
        "a" | "approve" => Ok(EditDecision::Accept),
        "m" | "modify" => Ok(EditDecision::Modify),
        "e" | "advanced" => Ok(EditDecision::AdvancedEdit),
        "g" | "granular" => Ok(EditDecision::GranularApproval),
        "st" | "staged" => Ok(EditDecision::StagedApplication),
        "c" | "cognitive" => Ok(EditDecision::CognitiveAssisted),
        "cl" | "classify" => Ok(EditDecision::SmartClassification),
        "git" | "gitintegration" => Ok(EditDecision::GitIntegration),
        "tt" | "timetravel" => Ok(EditDecision::TimeTravel),
        "ca" | "customagent" => Ok(EditDecision::CustomAgentConfig),
        "vr" | "visualreasoning" => Ok(EditDecision::VisualReasoning),
        "mr" | "metareflective" => Ok(EditDecision::MetaReflective),
        "p" | "preview" => Ok(EditDecision::Preview),
        "ap" | "advancedpreview" => Ok(EditDecision::AdvancedPreview),
        "s" | "skip" => Ok(EditDecision::Skip),
        "r" | "reject" => Ok(EditDecision::Reject),
        _ => {
            println!("Invalid choice, skipping edit.");
            Ok(EditDecision::Skip)
        }
    }
}

/// Issue #19: Granular approval processing function
fn process_granular_approval(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🔒 Initiating Granular Approval Process...");
    println!("Features available:");
    println!("  • Multi-level approval system (Auto/Low/Medium/High/Critical)");
    println!("  • Role-based approval workflow (Junior/Senior/Lead/Architect/Security)");
    println!("  • Risk assessment and automatic level determination");
    println!("  • Escalation and delegation capabilities");
    println!("  • Approval history tracking with comments");
    
    // For demo purposes, we'll simulate different user roles
    // In a real system, this would come from authentication
    let user_role = get_user_role()?;
    let user_id = get_user_id()?;
    
    let mut mutable_edit = edit;
    match process_edit_with_granular_approval(&mut mutable_edit, user_role, user_id) {
        Ok(_) => {
            println!("✅ Granular approval completed successfully!");
            println!("Final approval state: {:?}", mutable_edit.approval_state);
            Ok(Ok(()))
        }
        Err(e) => {
            println!("❌ Granular approval failed: {}", e);
            Ok(Err(e.to_string()))
        }
    }
}

/// Get user role for approval system (demo implementation)
fn get_user_role() -> Result<ApprovalRole, Box<dyn std::error::Error>> {
    println!("\n👤 Select your role for approval:");
    println!("   [1] Junior Developer");
    println!("   [2] Senior Developer");
    println!("   [3] Team Lead");
    println!("   [4] Architect");
    println!("   [5] Security Reviewer");
    print!("Your role (1-5): ");
    io::stdout().flush()?;
    
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    
    match input.trim() {
        "1" => Ok(ApprovalRole::Junior),
        "2" => Ok(ApprovalRole::Senior),
        "3" => Ok(ApprovalRole::Lead),
        "4" => Ok(ApprovalRole::Architect),
        "5" => Ok(ApprovalRole::Security),
        _ => {
            println!("Invalid selection, defaulting to Senior Developer");
            Ok(ApprovalRole::Senior)
        }
    }
}

/// Get user ID for approval system (demo implementation)
fn get_user_id() -> Result<String, Box<dyn std::error::Error>> {
    print!("Enter your user ID (or press Enter for 'demo_user'): ");
    io::stdout().flush()?;
    
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    
    let user_id = input.trim();
    if user_id.is_empty() {
        Ok("demo_user".to_string())
    } else {
        Ok(user_id.to_string())
    }
}

fn display_validation_summary(summary: &crate::edit_control::validation::ValidationSummary) {
    println!("\n🔍 Validation Summary:");
    println!("  Total checks: {}", summary.total_validations);
    println!("  ✅ Passed: {}", summary.passed);
    println!("  ⚠️ Warnings: {}", summary.warnings);
    println!("  ❌ Errors: {}", summary.errors);
    println!("  🚨 Critical: {}", summary.critical);

    if !summary.conflicts.is_empty() {
        println!("  🔥 Conflicts: {}", summary.conflicts.len());
    }

    println!("  📊 Status: {:?}", summary.overall_status);
}

#[derive(Debug, Clone, PartialEq)]
pub enum EditDecision {
    Preview,
    Accept,
    Reject,
    Modify,
    // Issue #17: Enhanced Edit Modification Interface
    AdvancedEdit,
    // Issue #18: Advanced Preview System  
    AdvancedPreview,
    // Issue #19: Granular Approval Levels
    GranularApproval,
    // Issue #20: Staged Application System
    StagedApplication,
    // Issue #25: Edit Classification System
    SmartClassification,
    // Issue #26: Git Integration System
    GitIntegration,
    // Issue #27: Edit History Time Travel
    TimeTravel,
    // Issue #30: Custom Agent Configuration
    CustomAgentConfig,
    // Issue #31: Visual Reasoning
    VisualReasoning,
    // Issue #32: Meta-Reflective Analysis
    MetaReflective,
    // Additional options for compatibility
    CognitiveAssisted,
    Skip,
}

/// Issue #20: Staged application processing function
fn process_staged_application(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🚀 Initiating Staged Application System...");
    println!("Features available:");
    println!("  • Phased edit application with rollback capabilities");
    println!("  • Multiple stages with dependency management");
    println!("  • Checkpoint creation and restoration");
    println!("  • Comprehensive validation at each stage");
    println!("  • Timeline view and execution progress tracking");
    
    // Create a single edit as a stage for demonstration
    let edits = vec![edit];
    match process_edit_with_staged_application(edits, Some("Demo Stage".to_string())) {
        Ok(_) => {
            println!("✅ Staged application completed successfully!");
            Ok(Ok(()))
        }
        Err(e) => {
            println!("❌ Staged application failed: {}", e);
            Ok(Err(e.to_string()))
        }
    }
}

/// Cognitive-assisted processing function
fn process_cognitive_assisted(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🧠 Initiating Cognitive-Assisted Analysis...");
    println!("Features available:");
    println!("  • AI-powered edit analysis and insights");
    println!("  • Introspection and complexity assessment");
    println!("  • Cognitive load and attention focus analysis");
    println!("  • Uncertainty and confidence evaluation");
    println!("  • Meta-cognitive recommendations");
    
    let cognitive_workflow = CognitiveWorkflow::new();
    
    // Analyze the edit using cognitive operators
    match cognitive_workflow.analyze_edit_context(
        &edit.base_edit.file,
        &edit.base_edit.reason,
        edit.base_edit.confidence
    ) {
        Ok(analysis) => {
            // Get cognitive recommendation
            let decision = cognitive_workflow.get_cognitive_decision(&analysis)?;
            println!("✅ Cognitive analysis completed!");
            println!("Final decision: {:?}", decision);
            Ok(Ok(()))
        }
        Err(e) => {
            println!("❌ Cognitive analysis failed: {}", e);
            Ok(Err(e.to_string()))
        }
    }
}

/// Issue #25: Smart classification processing function
fn process_smart_classification(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🔍 Initiating Smart Edit Classification...");
    println!("Features available:");
    println!("  • Intelligent edit categorization (Critical/Experimental/Safe/Cosmetic)");
    println!("  • Risk assessment with pattern detection");
    println!("  • Priority scoring and confidence evaluation");
    println!("  • Cognitive operator integration for enhanced analysis");
    println!("  • Automatic recommendation generation");
    
    // Create classification CLI instance
    let mut classifier = EditClassificationCLI::new()?;
    
    // Classify the edit
    match classifier.classify_single_edit(&edit) {
        Ok(classified_edit) => {
            println!("\n📊 Classification Analysis Complete!");
            
            println!("\n🎯 Smart Recommendation:");
            match &classified_edit.recommendation {
                crate::classification::edit_classifier_working::ClassificationRecommendation::AutoApprove { confidence } => {
                    println!("   ✅ Auto-approve recommended ({:.1}% confidence)", confidence * 100.0);
                    println!("   This edit is classified as safe and can be automatically approved.");
                }
                crate::classification::edit_classifier_working::ClassificationRecommendation::RequireReview { concerns } => {
                    println!("   🔍 Manual review required");
                    println!("   Concerns identified:");
                    for concern in concerns {
                        println!("{}", concern);
                    }
                }
                crate::classification::edit_classifier_working::ClassificationRecommendation::Escalate { target_level, reason } => {
                    println!("   ⬆️  Escalation recommended to: {}", target_level);
                    println!("   Reason: {}", reason);
                }
                crate::classification::edit_classifier_working::ClassificationRecommendation::Reject { reason } => {
                    println!("   ❌ Rejection recommended");
                    println!("   Reason: {}", reason);
                }
                crate::classification::edit_classifier_working::ClassificationRecommendation::RequestInfo { questions } => {
                    println!("   ❓ Additional information needed");
                    for question in questions {
                        println!("{}", question);
                    }
                }
            }
            
            println!("\n📈 Classification Summary:");
            println!("   Category: {:?}", classified_edit.category);
            println!("   Priority Score: {:.3}", classified_edit.priority_score);
            println!("   Risk Score: {:.3}", classified_edit.risk_assessment.overall_score);
            println!("   Classification Confidence: {:.3}", classified_edit.classification_confidence);
            
            Ok(Ok(()))
        }
        Err(e) => {
            println!("❌ Smart classification failed: {}", e);
            Ok(Err(e.to_string()))
        }
    }
}

/// Issue #26: Git integration processing function
fn process_git_integration(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🔧 Initiating Git Integration Workflow...");
    println!("Features available:");
    println!("  • Automatic session branching with intelligent naming");
    println!("  • Classification-based commit strategies");
    println!("  • Conflict resolution with cognitive operators");
    println!("  • Automated backup points and rollback capabilities");
    println!("  • CI/CD pipeline integration hooks");
    
    // Get the current repository path
    let current_dir = std::env::current_dir()
        .map_err(|e| format!("Failed to get current directory: {}", e))?;
    
    // Use the git_integration module's interactive workflow

    
    // Create a simple classification for this edit (in real usage, this would come from the classification system)
    use crate::classification::EditClassificationSystem;
    
    // Classify the edit using the classification system
    let classifier = EditClassificationSystem::new();
    let classified_edit = classifier.classify_edit(&edit)
        .map_err(|e| format!("Failed to classify edit: {}", e))?;
    
    // For the Git integration, we need to convert to the expected format
    // This is a simplified approach - in practice, the Git integration would work directly with ClassifiedEdit
    println!("📊 Edit Classification:");
    println!("   Category: {:?}", classified_edit.category);
    println!("   Risk Score: {:.3}", classified_edit.risk_assessment.overall_score);
    println!("   Priority: {:.3}", classified_edit.priority_score);
    println!("   Confidence: {:.3}", classified_edit.classification_confidence);
    
    // For now, we'll use a simplified Git workflow without the full classification integration
    // In a complete implementation, the Git integration would be updated to work with ClassifiedEdit
    println!("\n🔧 Proceeding with Git workflow...");
    
    match crate::cli::git_integration::GitIntegrationCLI::new(current_dir.clone()) {
        Ok(mut git_cli) => {
            match git_cli.start_interactive_session() {
                Ok(_) => {
                    println!("✅ Git integration session completed!");
                    Ok(Ok(()))
                }
                Err(e) => {
                    println!("❌ Git integration session failed: {}", e);
                    Ok(Err(e))
                }
            }
        }
                 Err(e) => {
             println!("❌ Failed to initialize Git integration: {}", e);
             Ok(Err(e))
         }
     }
}

/// Issue #27: Time travel processing function
fn process_time_travel(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🕰️  Initiating Time Travel System...");
    println!("Features available:");
    println!("  • Complete edit history with timeline branching");
    println!("  • Navigate through different edit paths and timelines");
    println!("  • Create and restore stable checkpoints");
    println!("  • Search through historical changes and patterns");
    println!("  • Merge and compare different edit timelines");
    println!("  • Git integration for persistent history tracking");
    
    // Use the time_travel module's interactive workflow
    use crate::cli::time_travel::interactive_time_travel_decision;
    
    // Create a dummy classification for this edit (in real usage, this would come from the classification system)
    use crate::classification::EditClassificationSystem;
    
    let classifier = EditClassificationSystem::new();
    let classified_edit = classifier.classify_edit(&edit)
        .map_err(|e| format!("Failed to classify edit for time travel: {}", e))?;
    
    println!("📊 Edit Classification for Time Travel:");
    println!("   Category: {:?}", classified_edit.category);
    println!("   Risk Score: {:.3}", classified_edit.risk_assessment.overall_score);
    println!("   Priority: {:.3}", classified_edit.priority_score);
    println!("   Reasoning: {}", classified_edit.reasoning);
    
    // Launch interactive time travel workflow
    match interactive_time_travel_decision(vec![edit], vec![classified_edit]) {
        Ok(used_time_travel) => {
            if used_time_travel {
                println!("✅ Time travel session completed successfully");
                Ok(Ok(()))
            } else {
                println!("ℹ️  Time travel was not used");
                Ok(Ok(()))
            }
        }
        Err(e) => {
            println!("❌ Time travel error: {}", e);
            Ok(Err(e.to_string()))
        }
    }
}

/// Issue #30: Custom agent configuration processing function
fn process_custom_agent_config(_edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🤖 Initiating Custom Agent Configuration...");
    println!("Features available:");
    println!("  • User-defined agent personalities and behavior modification");
    println!("  • Custom prompting and context templates");
    println!("  • Preference learning and adaptation");
    println!("  • Project-specific context configuration");
    println!("  • Agent performance tracking and optimization");
    
    // Use the comprehensive custom agent configuration CLI
    use crate::cli::custom_agent_config::CustomAgentConfigCLI;
    
    match CustomAgentConfigCLI::new() {
        Ok(mut config_cli) => {
            match config_cli.start_interactive_session() {
                Ok(_) => {
                    println!("✅ Custom agent configuration completed successfully!");
                    Ok(Ok(()))
                }
                Err(e) => {
                    println!("❌ Custom agent configuration failed: {}", e);
                    Ok(Err(e.to_string()))
                }
            }
        }
        Err(e) => {
            println!("❌ Failed to initialize custom agent configuration: {}", e);
            Ok(Err(e.to_string()))
        }
    }
}

/// Issue #31: Visual reasoning processing function
fn process_visual_reasoning(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🔬 Initiating Visual Reasoning Analysis...");
    println!("Features available:");
    println!("  • Code structure analysis with AST visualization");
    println!("  • Pattern recognition and code smell detection");
    println!("  • Dependency mapping with visual graph representation");
    println!("  • Visual diff analysis with change impact assessment");
    println!("  • Interactive session with analysis history tracking");
    println!("  • Export capabilities for analysis results");
    
    // Launch the visual reasoning CLI
    match crate::cli::visual_reasoning::process_visual_reasoning(edit) {
        Ok(Ok(())) => {
            println!("✅ Visual reasoning analysis completed successfully!");
            Ok(Ok(()))
        }
        Ok(Err(e)) => {
            println!("❌ Visual reasoning analysis failed: {}", e);
            Ok(Err(e))
        }
        Err(e) => {
            println!("❌ Visual reasoning system error: {}", e);
            Ok(Err(format!("System error: {}", e)))
        }
    }
}

/// Issue #32: Meta-reflective analysis processing function
fn process_meta_reflective(edit: ModifiableEdit) -> Result<Result<(), String>, Box<dyn std::error::Error>> {
    println!("\n🧠 Initiating Meta-Reflective Analysis...");
    println!("Features available:");
    println!("  • System introspection and cognitive bottleneck detection");
    println!("  • Performance analysis with trend monitoring");
    println!("  • Cognitive assessment with meta-cognitive state evaluation");
    println!("  • Optimization recommendations with priority scoring");
    println!("  • Session history tracking with performance metrics");
    println!("  • Real-time system monitoring and health indicators");
    println!("  • Analysis data export in multiple formats");
    
    // Create context from edit and system state
    let mut context = crate::memory::SymbolicContext::new();
    context.set("file_path", &edit.base_edit.file);
    context.set("edit_content", &edit.base_edit.new_code);
    context.set("analysis_mode", "meta_reflective");
    context.set("cognitive_focus", "system_optimization");
    
    // Add system metrics to context
    context.set("operator_count", "15"); // Current operator count
    context.set("system_uptime", &std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        .to_string());
    context.set("errors_count", "0"); // Assume clean state
    
    // Process meta-reflective workflow
    match crate::cli::meta_reflective::process_meta_reflective_workflow(&context) {
        Ok(analysis_result) => {
            println!("✅ Meta-reflective analysis completed successfully!");
            
            // Display key insights
            if let Some(performance_score) = analysis_result.get("system_performance_score") {
                println!("🎯 System Performance Score: {}", performance_score);
            }
            if let Some(cognitive_state) = analysis_result.get("meta_cognitive_state") {
                println!("🧠 Meta-Cognitive State: {}", cognitive_state);
            }
            if let Some(reasoning_patterns) = analysis_result.get("reasoning_patterns_detected") {
                println!("🧩 Reasoning Patterns: {}", reasoning_patterns);
            }
            if let Some(emergence_level) = analysis_result.get("emergence_level") {
                println!("🌟 Emergence Level: {}", emergence_level);
            }
            
            // Display optimization suggestions
            for i in 0..3 {
                if let Some(optimization) = analysis_result.get(&format!("optimization_Θ_{}", i)) {
                    println!("💡 Optimization {}: {}", i + 1, optimization);
                }
            }
            
            Ok(Ok(()))
        }
        Err(e) => {
            println!("❌ Meta-reflective analysis failed: {}", e);
            Ok(Err(format!("Meta-reflective analysis error: {}", e)))
        }
    }
}