soma-core 2.0.1

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
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
use crate::edit_control::ModifiableEdit;
use crate::classification::{ClassifiedEdit, EditCategory};


/// Git Integration System for SOMA-CORE
/// Provides comprehensive Git workflow management with intelligent branching,
/// automated commits, conflict resolution, and backup strategies
#[derive(Debug, Clone)]
pub struct GitIntegrationSystem {
    /// Repository root path
    pub repository_path: PathBuf,
    /// Current Git configuration
    pub config: GitConfig,
    /// Branch management system
    pub branch_manager: BranchManager,
    /// Commit management system
    pub commit_manager: CommitManager,
    /// Conflict resolution system
    pub conflict_resolver: ConflictResolver,
    /// Backup management system
    pub backup_manager: BackupManager,
    /// Current session state
    pub session_state: GitSessionState,
}

/// Git configuration for SOMA-CORE integration
#[derive(Debug, Clone)]
pub struct GitConfig {
    /// Automatic commit on successful edits
    pub auto_commit: bool,
    /// Create session branches automatically
    pub session_branches: bool,
    /// Backup frequency in minutes
    pub backup_frequency_minutes: u32,
    /// Maximum backup retention days
    pub max_backup_days: u32,
    /// Integration with CI/CD pipelines
    pub cicd_integration: bool,
    /// Conflict resolution strategy
    pub conflict_strategy: ConflictStrategy,
}

/// Git session state tracking
#[derive(Debug, Clone)]
pub struct GitSessionState {
    /// Unique session identifier
    pub session_id: String,
    /// Session start timestamp
    pub start_time: SystemTime,
    /// Current branch name
    pub current_branch: String,
    /// Original branch name
    pub original_branch: String,
    /// Session edits applied
    pub edits_applied: Vec<String>,
    /// Session commit history
    pub commit_history: Vec<GitCommit>,
    /// Session backup points
    pub backup_points: Vec<BackupPoint>,
}

/// Branch management system
#[derive(Debug, Clone)]
pub struct BranchManager {
    /// Current repository path
    pub repo_path: PathBuf,
    /// Branch naming strategy
    pub naming_strategy: BranchNamingStrategy,
    /// Automatic cleanup of session branches
    pub auto_cleanup: bool,
    /// Maximum branch lifetime in days
    pub max_branch_lifetime_days: u32,
}

/// Commit management system
#[derive(Debug, Clone)]
pub struct CommitManager {
    /// Repository path
    pub repo_path: PathBuf,
    /// Commit message templates
    pub message_templates: HashMap<String, String>,
    /// Automatic staging of changes
    pub auto_stage: bool,
    /// Sign commits with GPG
    pub sign_commits: bool,
}

/// Conflict resolution system
#[derive(Debug, Clone)]
pub struct ConflictResolver {
    /// Repository path
    pub repo_path: PathBuf,
    /// Resolution strategies
    pub strategies: Vec<ConflictStrategy>,
    /// Integration with classification system
    pub use_classification: bool,
    /// Cognitive operator integration
    pub cognitive_resolution: bool,
}

/// Backup management system
#[derive(Debug, Clone)]
pub struct BackupManager {
    /// Repository path
    pub repo_path: PathBuf,
    /// Backup storage directory
    pub backup_dir: PathBuf,
    /// Compression enabled
    pub compress_backups: bool,
    /// Incremental backup strategy
    pub incremental: bool,
}

/// Git commit representation
#[derive(Debug, Clone)]
pub struct GitCommit {
    /// Commit hash
    pub hash: String,
    /// Commit message
    pub message: String,
    /// Commit timestamp
    pub timestamp: SystemTime,
    /// Files changed
    pub files_changed: Vec<String>,
    /// Associated SOMA edit IDs
    pub soma_edit_ids: Vec<String>,
}

/// Backup point for rollback capabilities
#[derive(Debug, Clone)]
pub struct BackupPoint {
    /// Backup identifier
    pub id: String,
    /// Backup timestamp
    pub timestamp: SystemTime,
    /// Repository state hash
    pub state_hash: String,
    /// Backup file path
    pub backup_path: PathBuf,
    /// Description of backup point
    pub description: String,
}

/// Branch naming strategies
#[derive(Debug, Clone)]
pub enum BranchNamingStrategy {
    /// soma-session-{timestamp}
    SessionTimestamp,
    /// soma-session-{session_id}
    SessionId,
    /// soma-{user}-{timestamp}
    UserTimestamp,
    /// Custom naming pattern
    Custom(String),
}

/// Conflict resolution strategies
#[derive(Debug, Clone)]
pub enum ConflictStrategy {
    /// Prefer local changes
    PreferLocal,
    /// Prefer remote changes
    PreferRemote,
    /// Interactive resolution
    Interactive,
    /// Classification-based resolution
    ClassificationBased,
    /// Cognitive operator resolution
    CognitiveResolution,
}

/// Git operation results
#[derive(Debug, Clone)]
pub enum GitOperationResult {
    /// Operation succeeded
    Success(String),
    /// Operation failed with error
    Error(String),
    /// Operation requires user intervention
    RequiresIntervention(String),
    /// Conflict detected
    Conflict(ConflictInfo),
}

/// Conflict information
#[derive(Debug, Clone)]
pub struct ConflictInfo {
    /// Conflicted files
    pub files: Vec<String>,
    /// Conflict descriptions
    pub descriptions: Vec<String>,
    /// Suggested resolution strategy
    pub suggested_strategy: ConflictStrategy,
    /// Classification results for conflicted edits
    pub classification_results: Vec<ClassifiedEdit>,
}

impl Default for GitConfig {
    fn default() -> Self {
        GitConfig {
            auto_commit: true,
            session_branches: true,
            backup_frequency_minutes: 30,
            max_backup_days: 7,
            cicd_integration: false,
            conflict_strategy: ConflictStrategy::Interactive,
        }
    }
}

impl Default for BranchNamingStrategy {
    fn default() -> Self {
        BranchNamingStrategy::SessionTimestamp
    }
}

impl GitIntegrationSystem {
    /// Create a new Git integration system
    pub fn new(repository_path: PathBuf) -> Result<Self, String> {
        // Validate repository
        if !Self::is_git_repository(&repository_path) {
            return Err(format!("Path {:?} is not a Git repository", repository_path));
        }

        let config = GitConfig::default();
        let branch_manager = BranchManager::new(repository_path.clone())?;
        let commit_manager = CommitManager::new(repository_path.clone())?;
        let conflict_resolver = ConflictResolver::new(repository_path.clone())?;
        let backup_manager = BackupManager::new(repository_path.clone())?;
        
        let session_id = Self::generate_session_id();
        let current_branch = Self::get_current_branch(&repository_path)?;
        
        let session_state = GitSessionState {
            session_id,
            start_time: SystemTime::now(),
            current_branch: current_branch.clone(),
            original_branch: current_branch,
            edits_applied: Vec::new(),
            commit_history: Vec::new(),
            backup_points: Vec::new(),
        };

        Ok(GitIntegrationSystem {
            repository_path,
            config,
            branch_manager,
            commit_manager,
            conflict_resolver,
            backup_manager,
            session_state,
        })
    }

    /// Initialize a new SOMA editing session with Git integration
    pub fn start_session(&mut self, session_name: Option<String>) -> Result<String, String> {
        // Create session branch if enabled
        if self.config.session_branches {
            let branch_name = self.branch_manager.create_session_branch(
                session_name.clone()
            )?;
            self.session_state.current_branch = branch_name.clone();
            
            // Switch to session branch
            self.switch_branch(&branch_name)?;
        }

        // Create initial backup point
        let backup_point = self.backup_manager.create_backup_point(
            "Session start".to_string()
        )?;
        self.session_state.backup_points.push(backup_point);

        // Initialize commit manager for session
        self.commit_manager.initialize_session(&self.session_state.session_id)?;

        Ok(format!("Started SOMA Git session: {}", self.session_state.session_id))
    }

    /// Apply edits with Git integration
    pub fn apply_edits_with_git(
        &mut self, 
        edits: Vec<ModifiableEdit>,
        classifications: Vec<ClassifiedEdit>
    ) -> Result<Vec<GitOperationResult>, String> {
        let mut results = Vec::new();

        // Group edits by risk level from classification
        let mut critical_edits = Vec::new();
        let mut safe_edits = Vec::new();
        let mut experimental_edits = Vec::new();

        for (edit, classification) in edits.iter().zip(classifications.iter()) {
            match &classification.category {
                EditCategory::Critical { .. } => {
                    critical_edits.push((edit, classification));
                }
                EditCategory::Safe { .. } => {
                    safe_edits.push((edit, classification));
                }
                EditCategory::Experimental { .. } => {
                    experimental_edits.push((edit, classification));
                }
                EditCategory::Cosmetic { .. } => {
                    safe_edits.push((edit, classification));
                }
            }
        }

        // Apply safe edits first
        for (edit, classification) in safe_edits {
            let result = self.apply_single_edit_with_git(edit, classification)?;
            results.push(result);
        }

        // Apply experimental edits with additional backup
        if !experimental_edits.is_empty() {
            let backup_point = self.backup_manager.create_backup_point(
                "Before experimental edits".to_string()
            )?;
            self.session_state.backup_points.push(backup_point);

            for (edit, classification) in experimental_edits {
                let result = self.apply_single_edit_with_git(edit, classification)?;
                results.push(result);
            }
        }

        // Apply critical edits with maximum safeguards
        if !critical_edits.is_empty() {
            let backup_point = self.backup_manager.create_backup_point(
                "Before critical edits".to_string()
            )?;
            self.session_state.backup_points.push(backup_point);

            for (edit, classification) in critical_edits {
                let result = self.apply_single_edit_with_git(edit, classification)?;
                results.push(result.clone());
                
                // Immediate commit for critical edits
                if matches!(result, GitOperationResult::Success(_)) {
                    self.commit_current_changes(&format!(
                        "SOMA Critical Edit: {}", 
                        classification.reasoning
                    ))?;
                }
            }
        }

        Ok(results)
    }

    /// Apply a single edit with Git integration
    fn apply_single_edit_with_git(
        &mut self,
        edit: &ModifiableEdit,
        classification: &ClassifiedEdit
    ) -> Result<GitOperationResult, String> {
        // Check for conflicts before applying
        if let Some(conflicts) = self.check_for_conflicts(&edit.base_edit.file)? {
            return Ok(GitOperationResult::Conflict(conflicts));
        }

        // Apply the edit (this would integrate with your existing edit application logic)
        // For now, we'll simulate the edit application
        let file_path = &edit.base_edit.file;
        
        // Record the edit in session state
        self.session_state.edits_applied.push(format!("{:?}", edit.base_edit));

        // Auto-commit if enabled and edit is not critical
        if self.config.auto_commit && !matches!(classification.category, EditCategory::Critical { .. }) {
            let commit_message = self.commit_manager.generate_commit_message(edit, classification);
            match self.commit_current_changes(&commit_message) {
                Ok(commit_hash) => {
                    let commit = GitCommit {
                        hash: commit_hash.clone(),
                        message: commit_message,
                        timestamp: SystemTime::now(),
                        files_changed: vec![file_path.clone()],
                        soma_edit_ids: vec![format!("{:?}", edit)],
                    };
                    self.session_state.commit_history.push(commit);
                    Ok(GitOperationResult::Success(commit_hash))
                }
                Err(e) => Ok(GitOperationResult::Error(e)),
            }
        } else {
            Ok(GitOperationResult::Success("Edit applied successfully".to_string()))
        }
    }

    /// End the current SOMA editing session
    pub fn end_session(&mut self, merge_to_main: bool) -> Result<String, String> {
        // Create final backup
        let final_backup = self.backup_manager.create_backup_point(
            "Session end".to_string()
        )?;
        self.session_state.backup_points.push(final_backup);

        // Commit any pending changes
        if self.has_uncommitted_changes()? {
            self.commit_current_changes("SOMA Session final commit")?;
        }

        let session_summary = format!(
            "Session {} completed:\n- Edits applied: {}\n- Commits: {}\n- Backups: {}",
            self.session_state.session_id,
            self.session_state.edits_applied.len(),
            self.session_state.commit_history.len(),
            self.session_state.backup_points.len()
        );

        // Merge to main branch if requested
        if merge_to_main && self.config.session_branches {
            self.merge_session_to_main()?;
        }

        // Switch back to original branch
        if self.config.session_branches {
            self.switch_branch(&self.session_state.original_branch)?;
        }

        Ok(session_summary)
    }

    /// Check if path is a Git repository
    fn is_git_repository(path: &Path) -> bool {
        path.join(".git").exists()
    }

    /// Generate unique session ID
    fn generate_session_id() -> String {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        format!("soma-{}", timestamp)
    }

    /// Get current Git branch
    fn get_current_branch(repo_path: &Path) -> Result<String, String> {
        let output = Command::new("git")
            .arg("branch")
            .arg("--show-current")
            .current_dir(repo_path)
            .output()
            .map_err(|e| format!("Failed to get current branch: {}", e))?;

        if output.status.success() {
            let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
            Ok(branch)
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            Err(format!("Git error: {}", error))
        }
    }

    /// Switch to specified branch
    fn switch_branch(&self, branch_name: &str) -> Result<(), String> {
        let output = Command::new("git")
            .arg("checkout")
            .arg(branch_name)
            .current_dir(&self.repository_path)
            .output()
            .map_err(|e| format!("Failed to switch branch: {}", e))?;

        if output.status.success() {
            Ok(())
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            Err(format!("Failed to switch to branch {}: {}", branch_name, error))
        }
    }

    /// Check for conflicts in specified file
    pub fn check_for_conflicts(&self, file_path: &str) -> Result<Option<ConflictInfo>, String> {
        // Check if file has merge conflicts
        let file_content = fs::read_to_string(file_path)
            .map_err(|e| format!("Failed to read file {}: {}", file_path, e))?;

        if file_content.contains("<<<<<<< HEAD") || 
           file_content.contains("=======") || 
           file_content.contains(">>>>>>> ") {
            
            let conflict_info = ConflictInfo {
                files: vec![file_path.to_string()],
                descriptions: vec!["Merge conflict detected".to_string()],
                suggested_strategy: ConflictStrategy::Interactive,
                classification_results: Vec::new(),
            };
            
            Ok(Some(conflict_info))
        } else {
            Ok(None)
        }
    }

    /// Commit current changes
    pub fn commit_current_changes(&self, message: &str) -> Result<String, String> {
        // Stage all changes
        let stage_output = Command::new("git")
            .arg("add")
            .arg(".")
            .current_dir(&self.repository_path)
            .output()
            .map_err(|e| format!("Failed to stage changes: {}", e))?;

        if !stage_output.status.success() {
            let error = String::from_utf8_lossy(&stage_output.stderr);
            return Err(format!("Failed to stage changes: {}", error));
        }

        // Commit changes
        let commit_output = Command::new("git")
            .arg("commit")
            .arg("-m")
            .arg(message)
            .current_dir(&self.repository_path)
            .output()
            .map_err(|e| format!("Failed to commit: {}", e))?;

        if commit_output.status.success() {
            // Get commit hash
            let hash_output = Command::new("git")
                .arg("rev-parse")
                .arg("HEAD")
                .current_dir(&self.repository_path)
                .output()
                .map_err(|e| format!("Failed to get commit hash: {}", e))?;

            if hash_output.status.success() {
                let hash = String::from_utf8_lossy(&hash_output.stdout).trim().to_string();
                Ok(hash)
            } else {
                Ok("unknown".to_string())
            }
        } else {
            let error = String::from_utf8_lossy(&commit_output.stderr);
            Err(format!("Failed to commit: {}", error))
        }
    }

    /// Check if there are uncommitted changes
    fn has_uncommitted_changes(&self) -> Result<bool, String> {
        let output = Command::new("git")
            .arg("status")
            .arg("--porcelain")
            .current_dir(&self.repository_path)
            .output()
            .map_err(|e| format!("Failed to check git status: {}", e))?;

        if output.status.success() {
            let status = String::from_utf8_lossy(&output.stdout);
            Ok(!status.trim().is_empty())
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            Err(format!("Git status error: {}", error))
        }
    }

    /// Merge session branch to main
    pub fn merge_session_to_main(&self) -> Result<(), String> {
        // Switch to main branch
        self.switch_branch("main")?;

        // Merge session branch
        let merge_output = Command::new("git")
            .arg("merge")
            .arg(&self.session_state.current_branch)
            .current_dir(&self.repository_path)
            .output()
            .map_err(|e| format!("Failed to merge: {}", e))?;

        if merge_output.status.success() {
            Ok(())
        } else {
            let error = String::from_utf8_lossy(&merge_output.stderr);
            Err(format!("Failed to merge session branch: {}", error))
        }
    }
}

// Implementation for sub-systems

impl BranchManager {
    pub fn new(repo_path: PathBuf) -> Result<Self, String> {
        Ok(BranchManager {
            repo_path,
            naming_strategy: BranchNamingStrategy::default(),
            auto_cleanup: true,
            max_branch_lifetime_days: 7,
        })
    }

    pub fn create_session_branch(&self, session_name: Option<String>) -> Result<String, String> {
        let branch_name = match &self.naming_strategy {
            BranchNamingStrategy::SessionTimestamp => {
                let timestamp = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();
                format!("soma-session-{}", timestamp)
            }
            BranchNamingStrategy::SessionId => {
                format!("soma-session-{}", 
                    session_name.unwrap_or_else(|| "default".to_string()))
            }
            BranchNamingStrategy::UserTimestamp => {
                let timestamp = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs();
                format!("soma-user-{}", timestamp)
            }
            BranchNamingStrategy::Custom(pattern) => {
                pattern.clone()
            }
        };

        // Create new branch
        let output = Command::new("git")
            .arg("checkout")
            .arg("-b")
            .arg(&branch_name)
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| format!("Failed to create branch: {}", e))?;

        if output.status.success() {
            Ok(branch_name)
        } else {
            let error = String::from_utf8_lossy(&output.stderr);
            Err(format!("Failed to create branch: {}", error))
        }
    }
}

impl CommitManager {
    pub fn new(repo_path: PathBuf) -> Result<Self, String> {
        let mut message_templates = HashMap::new();
        message_templates.insert("safe".to_string(), "SOMA Safe Edit: {}".to_string());
        message_templates.insert("critical".to_string(), "SOMA Critical Edit: {}".to_string());
        message_templates.insert("experimental".to_string(), "SOMA Experimental Edit: {}".to_string());
        message_templates.insert("cosmetic".to_string(), "SOMA Cosmetic Edit: {}".to_string());

        Ok(CommitManager {
            repo_path,
            message_templates,
            auto_stage: true,
            sign_commits: false,
        })
    }

    pub fn initialize_session(&self, _session_id: &str) -> Result<(), String> {
        // Initialize session-specific commit settings
        Ok(())
    }

    pub fn generate_commit_message(&self, edit: &ModifiableEdit, classification: &ClassifiedEdit) -> String {
        let edit_type = match &classification.category {
            EditCategory::Critical { .. } => "critical",
            EditCategory::Safe { .. } => "safe",
            EditCategory::Experimental { .. } => "experimental",
            EditCategory::Cosmetic { .. } => "cosmetic",
        };

        let default_template = "SOMA Edit: {}".to_string();
        let template = self.message_templates.get(edit_type)
            .unwrap_or(&default_template);

        let description = if !classification.reasoning.is_empty() {
            &classification.reasoning
        } else {
            &format!("Edit to {}", edit.base_edit.file)
        };

        template.replace("{}", description)
    }
}

impl ConflictResolver {
    pub fn new(repo_path: PathBuf) -> Result<Self, String> {
        Ok(ConflictResolver {
            repo_path,
            strategies: vec![ConflictStrategy::Interactive],
            use_classification: true,
            cognitive_resolution: true,
        })
    }
}

impl BackupManager {
    pub fn new(repo_path: PathBuf) -> Result<Self, String> {
        let backup_dir = repo_path.join(".soma-backups");
        
        // Create backup directory if it doesn't exist
        if !backup_dir.exists() {
            fs::create_dir_all(&backup_dir)
                .map_err(|e| format!("Failed to create backup directory: {}", e))?;
        }

        Ok(BackupManager {
            repo_path,
            backup_dir,
            compress_backups: true,
            incremental: true,
        })
    }

    pub fn create_backup_point(&self, description: String) -> Result<BackupPoint, String> {
        let timestamp = SystemTime::now();
        let id = format!("backup-{}", timestamp.duration_since(UNIX_EPOCH).unwrap().as_secs());
        
        // Get current commit hash as state hash
        let hash_output = Command::new("git")
            .arg("rev-parse")
            .arg("HEAD")
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| format!("Failed to get state hash: {}", e))?;

        let state_hash = if hash_output.status.success() {
            String::from_utf8_lossy(&hash_output.stdout).trim().to_string()
        } else {
            "unknown".to_string()
        };

        // Try to create Git stash as backup (only if there are changes)
        let _stash_output = Command::new("git")
            .arg("stash")
            .arg("push")
            .arg("-m")
            .arg(&format!("SOMA Backup: {}", description))
            .current_dir(&self.repo_path)
            .output()
            .map_err(|e| format!("Failed to create backup stash: {}", e))?;

        // Stash command succeeds even if there are no changes to stash
        // We'll create the backup point regardless
        Ok(BackupPoint {
            id,
            timestamp,
            state_hash,
            backup_path: self.backup_dir.clone(),
            description,
        })
    }
}

// Tests
#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_git_repo() -> (TempDir, PathBuf) {
        let temp_dir = TempDir::new().unwrap();
        let repo_path = temp_dir.path().to_path_buf();
        
        // Initialize git repository
        Command::new("git")
            .arg("init")
            .current_dir(&repo_path)
            .output()
            .unwrap();
            
        // Configure git user for tests
        Command::new("git")
            .args(&["config", "user.name", "SOMA Test"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
            
        Command::new("git")
            .args(&["config", "user.email", "soma@test.com"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        // Create an initial commit to have a valid Git history
        let initial_file = repo_path.join("README.md");
        fs::write(&initial_file, "# SOMA Test Repository\n").unwrap();
        
        Command::new("git")
            .args(&["add", "README.md"])
            .current_dir(&repo_path)
            .output()
            .unwrap();
            
        Command::new("git")
            .args(&["commit", "-m", "Initial commit"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        (temp_dir, repo_path)
    }

    #[test]
    fn test_git_integration_system_creation() {
        let (_temp_dir, repo_path) = create_test_git_repo();
        
        let git_system = GitIntegrationSystem::new(repo_path);
        assert!(git_system.is_ok());
    }

    #[test]
    fn test_session_start_and_end() {
        let (_temp_dir, repo_path) = create_test_git_repo();
        
        let mut git_system = GitIntegrationSystem::new(repo_path).unwrap();
        
        // Start session
        let session_result = git_system.start_session(Some("test-session".to_string()));
        assert!(session_result.is_ok());
        
        // End session
        let end_result = git_system.end_session(false);
        assert!(end_result.is_ok());
    }

    #[test]
    fn test_branch_manager() {
        let (_temp_dir, repo_path) = create_test_git_repo();
        
        let branch_manager = BranchManager::new(repo_path).unwrap();
        let branch_name = branch_manager.create_session_branch(Some("test".to_string()));
        assert!(branch_name.is_ok());
    }

    #[test]
    fn test_backup_manager() {
        let (_temp_dir, repo_path) = create_test_git_repo();
        
        let backup_manager = BackupManager::new(repo_path).unwrap();
        let backup_point = backup_manager.create_backup_point("Test backup".to_string());
        assert!(backup_point.is_ok());
    }

    #[test]
    fn test_conflict_detection() {
        let (_temp_dir, repo_path) = create_test_git_repo();
        
        // Create a file with conflict markers
        let test_file = repo_path.join("test_conflict.txt");
        fs::write(&test_file, "line1\n<<<<<<< HEAD\nlocal change\n=======\nremote change\n>>>>>>> branch\nline3").unwrap();
        
        let git_system = GitIntegrationSystem::new(repo_path).unwrap();
        let conflicts = git_system.check_for_conflicts(&test_file.to_string_lossy()).unwrap();
        assert!(conflicts.is_some());
    }

    #[test]
    fn test_git_config_default() {
        let config = GitConfig::default();
        assert!(config.auto_commit);
        assert!(config.session_branches);
        assert_eq!(config.backup_frequency_minutes, 30);
    }
}