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
// examples/git_integration_demo.rs
// Issue #26: GitIntegration - Comprehensive demonstration
// Showcases Git workflow integration with SOMA-CORE

use soma_core::git_integration::{
    GitIntegrationSystem, GitConfig, BranchNamingStrategy, ConflictStrategy
};
use soma_core::edit_control::ModifiableEdit;
use soma_core::classification::{EditClassificationSystem, ClassifiedEdit};
use soma_core::agents::gpt4_agent::ProposedEdit;
use std::path::PathBuf;
use std::fs;
use tempfile::TempDir;
use std::process::Command;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🔧 SOMA-CORE Git Integration Demo");
    println!("═══════════════════════════════════");
    
    // Create a temporary Git repository for demonstration
    let temp_dir = create_test_git_repo()?;
    let repo_path = temp_dir.path().to_path_buf();
    
    println!("📁 Created test repository at: {:?}", repo_path);
    
    // Demo 1: Basic Git Integration System
    demo_git_integration_system(&repo_path)?;
    
    // Demo 2: Session Management
    demo_session_management(&repo_path)?;
    
    // Demo 3: Branch Management
    demo_branch_management(&repo_path)?;
    
    // Demo 4: Commit Strategies
    demo_commit_strategies(&repo_path)?;
    
    // Demo 5: Backup and Restore
    demo_backup_restore(&repo_path)?;
    
    // Demo 6: Classification Integration
    demo_classification_integration(&repo_path)?;
    
    // Demo 7: Conflict Resolution
    demo_conflict_resolution(&repo_path)?;
    
    // Demo 8: Configuration Options
    demo_configuration_options(&repo_path)?;
    
    println!("\n🎉 Git Integration Demo Complete!");
    println!("All features demonstrated successfully.");
    
    Ok(())
}

/// Demo 1: Basic Git Integration System
fn demo_git_integration_system(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🚀 Demo 1: Basic Git Integration System");
    println!("─────────────────────────────────────────");
    
    // Create Git integration system
    let git_system = GitIntegrationSystem::new(repo_path.clone())?;
    
    println!("✅ Git integration system created successfully");
    println!("   Repository: {:?}", git_system.repository_path);
    println!("   Session ID: {}", git_system.session_state.session_id);
    println!("   Current Branch: {}", git_system.session_state.current_branch);
    println!("   Configuration: {:?}", git_system.config);
    
    Ok(())
}

/// Demo 2: Session Management
fn demo_session_management(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n📋 Demo 2: Session Management");
    println!("─────────────────────────────");
    
    let mut git_system = GitIntegrationSystem::new(repo_path.clone())?;
    
    // Start a new session
    let session_result = git_system.start_session(Some("demo-session".to_string()))?;
    println!("{}", session_result);
    
    // Show session state
    println!("📊 Session State:");
    println!("   Session ID: {}", git_system.session_state.session_id);
    println!("   Start Time: {:?}", git_system.session_state.start_time);
    println!("   Current Branch: {}", git_system.session_state.current_branch);
    println!("   Original Branch: {}", git_system.session_state.original_branch);
    println!("   Edits Applied: {}", git_system.session_state.edits_applied.len());
    println!("   Backup Points: {}", git_system.session_state.backup_points.len());
    
    // End the session
    let end_result = git_system.end_session(false)?;
    println!("{}", end_result);
    
    Ok(())
}

/// Demo 3: Branch Management
fn demo_branch_management(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🌿 Demo 3: Branch Management");
    println!("───────────────────────────");
    
    let git_system = GitIntegrationSystem::new(repo_path.clone())?;
    
    // Test different branch naming strategies
    let strategies = vec![
        BranchNamingStrategy::SessionTimestamp,
        BranchNamingStrategy::SessionId,
        BranchNamingStrategy::UserTimestamp,
        BranchNamingStrategy::Custom("soma-custom-branch".to_string()),
    ];
    
    for strategy in strategies {
        let mut branch_manager = git_system.branch_manager.clone();
        branch_manager.naming_strategy = strategy.clone();
        
        match branch_manager.create_session_branch(Some("test".to_string())) {
            Ok(branch_name) => {
                println!("✅ Created branch with {:?} strategy: {}", strategy, branch_name);
            }
            Err(e) => {
                println!("❌ Failed to create branch with {:?} strategy: {}", strategy, e);
            }
        }
    }
    
    Ok(())
}

/// Demo 4: Commit Strategies
fn demo_commit_strategies(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n📝 Demo 4: Commit Strategies");
    println!("───────────────────────────");
    
    let git_system = GitIntegrationSystem::new(repo_path.clone())?;
    
    // Create test edits with different classifications
    let test_edits = create_test_edits();
    let classifier = EditClassificationSystem::new();
    
    for edit in test_edits {
        let classified = classifier.classify_edit(&edit)?;
        let commit_message = git_system.commit_manager.generate_commit_message(&edit, &classified);
        
        println!("📝 Edit: {}", edit.base_edit.file);
        println!("   Category: {:?}", classified.category);
        println!("   Commit Message: {}", commit_message);
        println!("   Risk Score: {:.3}", classified.risk_assessment.overall_score);
        println!();
    }
    
    Ok(())
}

/// Demo 5: Backup and Restore
fn demo_backup_restore(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n💾 Demo 5: Backup and Restore");
    println!("─────────────────────────────");
    
    let git_system = GitIntegrationSystem::new(repo_path.clone())?;
    
    // Create multiple backup points
    let backup_descriptions = vec![
        "Initial state",
        "After first edit",
        "Before experimental changes",
        "Critical checkpoint",
    ];
    
    for description in backup_descriptions {
        match git_system.backup_manager.create_backup_point(description.to_string()) {
            Ok(backup) => {
                println!("✅ Created backup: {}", backup.id);
                println!("   Description: {}", backup.description);
                println!("   State Hash: {}", &backup.state_hash[..8]);
                println!("   Timestamp: {:?}", backup.timestamp);
                println!();
            }
            Err(e) => {
                println!("❌ Failed to create backup '{}': {}", description, e);
            }
        }
    }
    
    Ok(())
}

/// Demo 6: Classification Integration
fn demo_classification_integration(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n🧠 Demo 6: Classification Integration");
    println!("────────────────────────────────────");
    
    let _git_system = GitIntegrationSystem::new(repo_path.clone())?;
    let classifier = EditClassificationSystem::new();
    
    // Create test edits
    let test_edits = create_test_edits();
    
    // Classify edits
    let mut classified_edits = Vec::new();
    for edit in test_edits {
        let classified = classifier.classify_edit(&edit)?;
        classified_edits.push(classified);
    }
    
    // Show how Git integration uses classification results
    println!("📊 Classification Results for Git Integration:");
    for classified in &classified_edits {
        println!("   File: {}", classified.edit.base_edit.file);
        println!("   Category: {:?}", classified.category);
        println!("   Risk: {:.3}", classified.risk_assessment.overall_score);
        println!("   Priority: {:.3}", classified.priority_score);
        println!("   Recommendation: {:?}", classified.recommendation);
        
        // Show Git strategy based on classification
        let git_strategy = determine_git_strategy(&classified);
        println!("   Git Strategy: {}", git_strategy);
        println!();
    }
    
    Ok(())
}

/// Demo 7: Conflict Resolution
fn demo_conflict_resolution(repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n⚠️  Demo 7: Conflict Resolution");
    println!("─────────────────────────────");
    
    let git_system = GitIntegrationSystem::new(repo_path.clone())?;
    
    // Create a file with conflict markers for testing
    let conflict_file = repo_path.join("conflict_test.txt");
    let conflict_content = r#"line1
<<<<<<< HEAD
local change
=======
remote change
>>>>>>> feature-branch
line3"#;
    
    fs::write(&conflict_file, conflict_content)?;
    
    // Test conflict detection
    match git_system.check_for_conflicts(&conflict_file.to_string_lossy()) {
        Ok(Some(conflict_info)) => {
            println!("🔍 Conflict detected!");
            println!("   Files: {:?}", conflict_info.files);
            println!("   Descriptions: {:?}", conflict_info.descriptions);
            println!("   Suggested Strategy: {:?}", conflict_info.suggested_strategy);
        }
        Ok(None) => {
            println!("✅ No conflicts detected");
        }
        Err(e) => {
            println!("❌ Error checking for conflicts: {}", e);
        }
    }
    
    // Show available conflict resolution strategies
    println!("\n🛠️  Available Conflict Resolution Strategies:");
    let strategies = vec![
        ConflictStrategy::PreferLocal,
        ConflictStrategy::PreferRemote,
        ConflictStrategy::Interactive,
        ConflictStrategy::ClassificationBased,
        ConflictStrategy::CognitiveResolution,
    ];
    
    for strategy in strategies {
        println!("{:?}", strategy);
    }
    
    Ok(())
}

/// Demo 8: Configuration Options
fn demo_configuration_options(_repo_path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    println!("\n⚙️  Demo 8: Configuration Options");
    println!("─────────────────────────────────");
    
    // Show default configuration
    let default_config = GitConfig::default();
    println!("📋 Default Configuration:");
    println!("   Auto Commit: {}", default_config.auto_commit);
    println!("   Session Branches: {}", default_config.session_branches);
    println!("   Backup Frequency: {} minutes", default_config.backup_frequency_minutes);
    println!("   Max Backup Days: {}", default_config.max_backup_days);
    println!("   CI/CD Integration: {}", default_config.cicd_integration);
    println!("   Conflict Strategy: {:?}", default_config.conflict_strategy);
    
    // Create custom configuration
    let custom_config = GitConfig {
        auto_commit: false,
        session_branches: true,
        backup_frequency_minutes: 15,
        max_backup_days: 14,
        cicd_integration: true,
        conflict_strategy: ConflictStrategy::ClassificationBased,
    };
    
    println!("\n🔧 Custom Configuration Example:");
    println!("   Auto Commit: {}", custom_config.auto_commit);
    println!("   Session Branches: {}", custom_config.session_branches);
    println!("   Backup Frequency: {} minutes", custom_config.backup_frequency_minutes);
    println!("   Max Backup Days: {}", custom_config.max_backup_days);
    println!("   CI/CD Integration: {}", custom_config.cicd_integration);
    println!("   Conflict Strategy: {:?}", custom_config.conflict_strategy);
    
    Ok(())
}

/// Helper function to create test Git repository
fn create_test_git_repo() -> Result<TempDir, Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let repo_path = temp_dir.path();
    
    // Initialize git repository
    Command::new("git")
        .arg("init")
        .current_dir(repo_path)
        .output()?;
    
    // Configure git user for tests
    Command::new("git")
        .args(&["config", "user.name", "SOMA Demo"])
        .current_dir(repo_path)
        .output()?;
    
    Command::new("git")
        .args(&["config", "user.email", "soma@demo.com"])
        .current_dir(repo_path)
        .output()?;
    
    // Create initial commit
    let readme_content = "# SOMA-CORE Git Integration Demo\n\nThis is a test repository for demonstrating Git integration features.";
    fs::write(repo_path.join("README.md"), readme_content)?;
    
    Command::new("git")
        .args(&["add", "README.md"])
        .current_dir(repo_path)
        .output()?;
    
    Command::new("git")
        .args(&["commit", "-m", "Initial commit"])
        .current_dir(repo_path)
        .output()?;
    
    Ok(temp_dir)
}

/// Helper function to create test edits
fn create_test_edits() -> Vec<ModifiableEdit> {
    vec![
        create_test_edit("src/main.rs", "fn main() { println!(\"Hello, world!\"); }", "Add main function"),
        create_test_edit("src/lib.rs", "pub mod utils;", "Add utils module"),
        create_test_edit("Cargo.toml", "[package]\nname = \"test\"", "Initialize Cargo.toml"),
        create_test_edit("src/security.rs", "use crypto::*;", "Add crypto imports"),
        create_test_edit("README.md", "# Updated README", "Update documentation"),
    ]
}

/// Helper function to create a test edit
fn create_test_edit(file: &str, content: &str, reason: &str) -> ModifiableEdit {
    let proposed_edit = ProposedEdit {
        file: file.to_string(),
        line_range: (1, 1),
        new_code: content.to_string(),
        reason: reason.to_string(),
        confidence: 0.8,
    };
    
    ModifiableEdit::from_proposed_edit(proposed_edit)
}

/// Helper function to determine Git strategy based on classification
fn determine_git_strategy(classified: &ClassifiedEdit) -> String {
    match classified.category {
        soma_core::classification::EditCategory::Critical { .. } => {
            "Immediate commit with backup, require review before merge".to_string()
        }
        soma_core::classification::EditCategory::Safe { .. } => {
            "Auto-commit, can be merged automatically".to_string()
        }
        soma_core::classification::EditCategory::Experimental { .. } => {
            "Create backup before commit, require testing before merge".to_string()
        }
        soma_core::classification::EditCategory::Cosmetic { .. } => {
            "Batch with other cosmetic changes, low priority merge".to_string()
        }
    }
}

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

    #[test]
    fn test_git_integration_demo() {
        // This test ensures the demo can be compiled and basic functions work
        let temp_dir = create_test_git_repo().unwrap();
        let repo_path = temp_dir.path().to_path_buf();
        
        // Test basic Git integration system creation
        let git_system = GitIntegrationSystem::new(repo_path);
        assert!(git_system.is_ok());
    }

    #[test]
    fn test_test_edit_creation() {
        let edit = create_test_edit("test.rs", "fn test() {}", "Test function");
        assert_eq!(edit.base_edit.file, "test.rs");
        assert_eq!(edit.base_edit.new_code, "fn test() {}");
        assert_eq!(edit.base_edit.reason, "Test function");
    }

    #[test]
    fn test_git_strategy_determination() {
        use soma_core::classification::{EditCategory, CriticalType, ImpactScope};
        
        let test_edit = create_test_edit("test.rs", "test", "test");
        let classifier = EditClassificationSystem::new();
        let classified = classifier.classify_edit(&test_edit).unwrap();
        
        let strategy = determine_git_strategy(&classified);
        assert!(!strategy.is_empty());
    }
}