cascade_cli/stack/
rebase.rs

1use crate::errors::{CascadeError, Result};
2use crate::git::{ConflictAnalyzer, GitRepository};
3use crate::stack::{Stack, StackManager};
4use chrono::Utc;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use tracing::{debug, info, warn};
8use uuid::Uuid;
9
10/// Conflict resolution result
11#[derive(Debug, Clone)]
12enum ConflictResolution {
13    /// Conflict was successfully resolved
14    Resolved,
15    /// Conflict is too complex for automatic resolution
16    TooComplex,
17}
18
19/// Represents a conflict region in a file
20#[derive(Debug, Clone)]
21#[allow(dead_code)]
22struct ConflictRegion {
23    /// Byte position where conflict starts
24    start: usize,
25    /// Byte position where conflict ends  
26    end: usize,
27    /// Line number where conflict starts
28    start_line: usize,
29    /// Line number where conflict ends
30    end_line: usize,
31    /// Content from "our" side (before separator)
32    our_content: String,
33    /// Content from "their" side (after separator)
34    their_content: String,
35}
36
37/// Strategy for rebasing stacks (force-push is the only valid approach for preserving PR history)
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
39pub enum RebaseStrategy {
40    /// Force-push rebased commits to original branches (preserves PR history)
41    /// This is the industry standard used by Graphite, Phabricator, spr, etc.
42    ForcePush,
43    /// Interactive rebase with conflict resolution
44    Interactive,
45}
46
47/// Options for rebase operations
48#[derive(Debug, Clone)]
49pub struct RebaseOptions {
50    /// The rebase strategy to use
51    pub strategy: RebaseStrategy,
52    /// Whether to run interactively (prompt for user input)
53    pub interactive: bool,
54    /// Target base branch to rebase onto
55    pub target_base: Option<String>,
56    /// Whether to preserve merge commits
57    pub preserve_merges: bool,
58    /// Whether to auto-resolve simple conflicts
59    pub auto_resolve: bool,
60    /// Maximum number of retries for conflict resolution
61    pub max_retries: usize,
62    /// Skip pulling latest changes (when already done by caller)
63    pub skip_pull: Option<bool>,
64}
65
66/// Result of a rebase operation
67#[derive(Debug)]
68pub struct RebaseResult {
69    /// Whether the rebase was successful
70    pub success: bool,
71    /// Old branch to new branch mapping
72    pub branch_mapping: HashMap<String, String>,
73    /// Commits that had conflicts
74    pub conflicts: Vec<String>,
75    /// New commit hashes
76    pub new_commits: Vec<String>,
77    /// Error message if rebase failed
78    pub error: Option<String>,
79    /// Summary of changes made
80    pub summary: String,
81}
82
83/// RAII guard to ensure temporary branches are cleaned up even on error/panic
84///
85/// This stores branch names and provides a cleanup method that can be called
86/// with a GitRepository reference. The Drop trait ensures cleanup happens
87/// even if the rebase function panics or returns early with an error.
88#[allow(dead_code)]
89struct TempBranchCleanupGuard {
90    branches: Vec<String>,
91    cleaned: bool,
92}
93
94#[allow(dead_code)]
95impl TempBranchCleanupGuard {
96    fn new() -> Self {
97        Self {
98            branches: Vec::new(),
99            cleaned: false,
100        }
101    }
102
103    fn add_branch(&mut self, branch: String) {
104        self.branches.push(branch);
105    }
106
107    /// Perform cleanup with provided git repository
108    fn cleanup(&mut self, git_repo: &GitRepository) {
109        if self.cleaned || self.branches.is_empty() {
110            return;
111        }
112
113        info!("๐Ÿงน Cleaning up {} temporary branches", self.branches.len());
114        for branch in &self.branches {
115            if let Err(e) = git_repo.delete_branch_unsafe(branch) {
116                warn!("Failed to delete temp branch {}: {}", branch, e);
117                // Continue with cleanup even if one fails
118            }
119        }
120        self.cleaned = true;
121    }
122}
123
124impl Drop for TempBranchCleanupGuard {
125    fn drop(&mut self) {
126        if !self.cleaned && !self.branches.is_empty() {
127            // This path is only hit on panic or unexpected early return
128            // We can't access git_repo here, so just log the branches that need manual cleanup
129            warn!(
130                "โš ๏ธ  {} temporary branches were not cleaned up: {}",
131                self.branches.len(),
132                self.branches.join(", ")
133            );
134            warn!("Run 'ca cleanup' to remove orphaned temporary branches");
135        }
136    }
137}
138
139/// Manages rebase operations for stacks
140pub struct RebaseManager {
141    stack_manager: StackManager,
142    git_repo: GitRepository,
143    options: RebaseOptions,
144    conflict_analyzer: ConflictAnalyzer,
145}
146
147impl Default for RebaseOptions {
148    fn default() -> Self {
149        Self {
150            strategy: RebaseStrategy::ForcePush,
151            interactive: false,
152            target_base: None,
153            preserve_merges: true,
154            auto_resolve: true,
155            max_retries: 3,
156            skip_pull: None,
157        }
158    }
159}
160
161impl RebaseManager {
162    /// Create a new rebase manager
163    pub fn new(
164        stack_manager: StackManager,
165        git_repo: GitRepository,
166        options: RebaseOptions,
167    ) -> Self {
168        Self {
169            stack_manager,
170            git_repo,
171            options,
172            conflict_analyzer: ConflictAnalyzer::new(),
173        }
174    }
175
176    /// Consume the rebase manager and return the updated stack manager
177    pub fn into_stack_manager(self) -> StackManager {
178        self.stack_manager
179    }
180
181    /// Rebase an entire stack onto a new base
182    pub fn rebase_stack(&mut self, stack_id: &Uuid) -> Result<RebaseResult> {
183        debug!("Starting rebase for stack {}", stack_id);
184
185        let stack = self
186            .stack_manager
187            .get_stack(stack_id)
188            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?
189            .clone();
190
191        match self.options.strategy {
192            RebaseStrategy::ForcePush => self.rebase_with_force_push(&stack),
193            RebaseStrategy::Interactive => self.rebase_interactive(&stack),
194        }
195    }
196
197    /// Rebase using force-push strategy (industry standard for stacked diffs)
198    /// This updates local branches in-place, then force-pushes ONLY branches with existing PRs
199    /// to preserve PR history - the approach used by Graphite, Phabricator, spr, etc.
200    fn rebase_with_force_push(&mut self, stack: &Stack) -> Result<RebaseResult> {
201        use crate::cli::output::Output;
202
203        // Check if there's an in-progress cherry-pick from a previous failed sync
204        if self.has_in_progress_cherry_pick()? {
205            return self.handle_in_progress_cherry_pick(stack);
206        }
207
208        Output::section(format!("Rebasing stack: {}", stack.name));
209
210        let mut result = RebaseResult {
211            success: true,
212            branch_mapping: HashMap::new(),
213            conflicts: Vec::new(),
214            new_commits: Vec::new(),
215            error: None,
216            summary: String::new(),
217        };
218
219        let target_base = self
220            .options
221            .target_base
222            .as_ref()
223            .unwrap_or(&stack.base_branch)
224            .clone(); // Clone to avoid borrow issues
225
226        // Save original working branch to restore later
227        let original_branch = self.git_repo.get_current_branch().ok();
228
229        // Note: Caller (sync_stack) has already checked out base branch when skip_pull=true
230        // Only pull if not already done by caller (like sync command)
231        if !self.options.skip_pull.unwrap_or(false) {
232            if let Err(e) = self.pull_latest_changes(&target_base) {
233                Output::warning(format!("Could not pull latest changes: {}", e));
234            }
235        }
236
237        // Reset working directory to clean state before rebase
238        if let Err(e) = self.git_repo.reset_to_head() {
239            Output::warning(format!("Could not reset working directory: {}", e));
240        }
241
242        let mut current_base = target_base.clone();
243        let entry_count = stack.entries.len();
244        let mut temp_branches: Vec<String> = Vec::new(); // Track temp branches for cleanup
245        let mut branches_to_push: Vec<(String, String)> = Vec::new(); // (branch_name, pr_number)
246
247        println!(); // Spacing before tree
248        let plural = if entry_count == 1 { "entry" } else { "entries" };
249        println!("Rebasing {} {}...", entry_count, plural);
250
251        // Phase 1: Rebase all entries locally (libgit2 only - no CLI commands)
252        for (index, entry) in stack.entries.iter().enumerate() {
253            let original_branch = &entry.branch;
254
255            // Create a temporary branch from the current base
256            // This avoids committing directly to protected branches like develop/main
257            let temp_branch = format!("{}-temp-{}", original_branch, Utc::now().timestamp());
258            temp_branches.push(temp_branch.clone()); // Track for cleanup
259            self.git_repo
260                .create_branch(&temp_branch, Some(&current_base))?;
261            self.git_repo.checkout_branch(&temp_branch)?;
262
263            // Cherry-pick the commit onto the temp branch (NOT the protected base!)
264            match self.cherry_pick_commit(&entry.commit_hash) {
265                Ok(new_commit_hash) => {
266                    result.new_commits.push(new_commit_hash.clone());
267
268                    // Get the commit that's now at HEAD (the cherry-picked commit)
269                    let rebased_commit_id = self.git_repo.get_head_commit()?.id().to_string();
270
271                    // Update the original branch to point to this rebased commit
272                    // This is LOCAL ONLY - moves refs/heads/<branch> to the commit on temp branch
273                    self.git_repo
274                        .update_branch_to_commit(original_branch, &rebased_commit_id)?;
275
276                    // Track which branches need to be pushed (only those with PRs)
277                    let tree_char = if index + 1 == entry_count {
278                        "โ””โ”€"
279                    } else {
280                        "โ”œโ”€"
281                    };
282
283                    if let Some(pr_num) = &entry.pull_request_id {
284                        println!("   {} {} (PR #{})", tree_char, original_branch, pr_num);
285                        branches_to_push.push((original_branch.clone(), pr_num.clone()));
286                    } else {
287                        println!("   {} {} (not submitted)", tree_char, original_branch);
288                    }
289
290                    result
291                        .branch_mapping
292                        .insert(original_branch.clone(), original_branch.clone());
293
294                    // Update stack entry with new commit hash
295                    self.update_stack_entry(
296                        stack.id,
297                        &entry.id,
298                        original_branch,
299                        &rebased_commit_id,
300                    )?;
301
302                    // This branch becomes the base for the next entry
303                    current_base = original_branch.clone();
304                }
305                Err(e) => {
306                    println!(); // Spacing before error
307                    Output::error(format!("Conflict in {}: {}", &entry.commit_hash[..8], e));
308                    result.conflicts.push(entry.commit_hash.clone());
309
310                    if !self.options.auto_resolve {
311                        result.success = false;
312                        result.error = Some(format!(
313                            "Conflict in {}: {}\n\n\
314                            MANUAL CONFLICT RESOLUTION REQUIRED\n\
315                            =====================================\n\n\
316                            Step 1: Analyze conflicts\n\
317                            โ†’ Run: ca conflicts\n\
318                            โ†’ This shows which conflicts are in which files\n\n\
319                            Step 2: Resolve conflicts in your editor\n\
320                            โ†’ Open conflicted files and edit them\n\
321                            โ†’ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
322                            โ†’ Keep the code you want\n\
323                            โ†’ Save the files\n\n\
324                            Step 3: Mark conflicts as resolved\n\
325                            โ†’ Run: git add <resolved-files>\n\
326                            โ†’ Or: git add -A (to stage all resolved files)\n\n\
327                            Step 4: Complete the sync\n\
328                            โ†’ Run: ca sync\n\
329                            โ†’ Cascade will detect resolved conflicts and continue\n\n\
330                            Alternative: Abort and start over\n\
331                            โ†’ Run: git cherry-pick --abort\n\
332                            โ†’ Then: ca sync (starts fresh)\n\n\
333                            TIP: Enable auto-resolution for simple conflicts:\n\
334                            โ†’ Run: ca sync --auto-resolve\n\
335                            โ†’ Only complex conflicts will require manual resolution",
336                            entry.commit_hash, e
337                        ));
338                        break;
339                    }
340
341                    // Try to resolve automatically
342                    match self.auto_resolve_conflicts(&entry.commit_hash) {
343                        Ok(fully_resolved) => {
344                            if !fully_resolved {
345                                result.success = false;
346                                result.error = Some(format!(
347                                    "Could not auto-resolve all conflicts in {}\n\n\
348                                    MANUAL CONFLICT RESOLUTION REQUIRED\n\
349                                    =====================================\n\n\
350                                    Some conflicts are too complex for auto-resolution.\n\n\
351                                    Step 1: Analyze remaining conflicts\n\
352                                    โ†’ Run: ca conflicts\n\
353                                    โ†’ Shows which files still have conflicts\n\
354                                    โ†’ Use --detailed flag for more info\n\n\
355                                    Step 2: Resolve conflicts in your editor\n\
356                                    โ†’ Open conflicted files (marked with โœ‹ in ca conflicts output)\n\
357                                    โ†’ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
358                                    โ†’ Keep the code you want\n\
359                                    โ†’ Save the files\n\n\
360                                    Step 3: Mark conflicts as resolved\n\
361                                    โ†’ Run: git add <resolved-files>\n\
362                                    โ†’ Or: git add -A (to stage all resolved files)\n\n\
363                                    Step 4: Complete the sync\n\
364                                    โ†’ Run: ca sync\n\
365                                    โ†’ Cascade will continue from where it left off\n\n\
366                                    Alternative: Abort and start over\n\
367                                    โ†’ Run: git cherry-pick --abort\n\
368                                    โ†’ Then: ca sync (starts fresh)\n\n\
369                                    BACKUP: If auto-resolution was wrong\n\
370                                    โ†’ Check for .cascade-backup files in your repo\n\
371                                    โ†’ These contain the original file content before auto-resolution",
372                                    &entry.commit_hash[..8]
373                                ));
374                                break;
375                            }
376
377                            // Commit the resolved changes
378                            let commit_message =
379                                format!("Auto-resolved conflicts in {}", &entry.commit_hash[..8]);
380                            match self.git_repo.commit(&commit_message) {
381                                Ok(new_commit_id) => {
382                                    Output::success("Auto-resolved conflicts");
383                                    result.new_commits.push(new_commit_id.clone());
384                                    let rebased_commit_id = new_commit_id;
385
386                                    // Update the original branch to point to this rebased commit
387                                    self.git_repo.update_branch_to_commit(
388                                        original_branch,
389                                        &rebased_commit_id,
390                                    )?;
391
392                                    // Track which branches need to be pushed (only those with PRs)
393                                    let tree_char = if index + 1 == entry_count {
394                                        "โ””โ”€"
395                                    } else {
396                                        "โ”œโ”€"
397                                    };
398
399                                    if let Some(pr_num) = &entry.pull_request_id {
400                                        println!(
401                                            "   {} {} (PR #{})",
402                                            tree_char, original_branch, pr_num
403                                        );
404                                        branches_to_push
405                                            .push((original_branch.clone(), pr_num.clone()));
406                                    } else {
407                                        println!(
408                                            "   {} {} (not submitted)",
409                                            tree_char, original_branch
410                                        );
411                                    }
412
413                                    result
414                                        .branch_mapping
415                                        .insert(original_branch.clone(), original_branch.clone());
416
417                                    // Update stack entry with new commit hash
418                                    self.update_stack_entry(
419                                        stack.id,
420                                        &entry.id,
421                                        original_branch,
422                                        &rebased_commit_id,
423                                    )?;
424
425                                    // This branch becomes the base for the next entry
426                                    current_base = original_branch.clone();
427                                }
428                                Err(commit_err) => {
429                                    result.success = false;
430                                    result.error = Some(format!(
431                                        "Could not commit auto-resolved conflicts: {}\n\n\
432                                        This usually means:\n\
433                                        - Git index is locked (another process accessing repo)\n\
434                                        - File permissions issue\n\
435                                        - Disk space issue\n\n\
436                                        Recovery:\n\
437                                        1. Check if another Git operation is running\n\
438                                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
439                                        3. Run 'git status' to check repo state\n\
440                                        4. Retry 'ca sync' after fixing the issue",
441                                        commit_err
442                                    ));
443                                    break;
444                                }
445                            }
446                        }
447                        Err(resolve_err) => {
448                            result.success = false;
449                            result.error = Some(format!(
450                                "Could not resolve conflicts: {}\n\n\
451                                Recovery:\n\
452                                1. Check repo state: 'git status'\n\
453                                2. If files are staged, commit or reset them: 'git reset --hard HEAD'\n\
454                                3. Remove any lock files: 'rm -f .git/index.lock'\n\
455                                4. Retry 'ca sync'",
456                                resolve_err
457                            ));
458                            break;
459                        }
460                    }
461                }
462            }
463        }
464
465        // Cleanup temp branches before returning to original branch
466        // Must checkout away from temp branches first
467        if !temp_branches.is_empty() {
468            // Reset working directory to clean state before checkout
469            // This prevents "uncommitted changes" warnings when switching branches
470            if let Err(e) = self.git_repo.reset_to_head() {
471                debug!("Could not reset working directory: {}", e);
472            }
473            
474            // Checkout base branch silently to allow temp branch deletion
475            if let Err(e) = self.git_repo.checkout_branch_silent(&target_base) {
476                Output::warning(format!("Could not checkout base for cleanup: {}", e));
477            }
478
479            // Delete all temp branches
480            for temp_branch in &temp_branches {
481                if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
482                    debug!("Could not delete temp branch {}: {}", temp_branch, e);
483                }
484            }
485        }
486
487        // Phase 2: Push all branches with PRs to remote (git CLI - after all libgit2 operations)
488        // This batch approach prevents index lock conflicts between libgit2 and git CLI
489        let pushed_count = branches_to_push.len();
490        let skipped_count = entry_count - pushed_count;
491
492        if !branches_to_push.is_empty() {
493            println!(); // Spacing before push phase
494            println!(
495                "Pushing {} branch{} to remote...",
496                pushed_count,
497                if pushed_count == 1 { "" } else { "es" }
498            );
499
500            for (branch_name, _pr_num) in &branches_to_push {
501                match self.git_repo.force_push_single_branch_auto(branch_name) {
502                    Ok(_) => {
503                        debug!("Pushed {} successfully", branch_name);
504                    }
505                    Err(e) => {
506                        Output::warning(format!("Could not push '{}': {}", branch_name, e));
507                        // Continue pushing other branches even if one fails
508                    }
509                }
510            }
511        }
512
513        // Update working branch to point to the top of the rebased stack
514        // This ensures subsequent `ca push` doesn't re-add old commits
515        if let Some(ref orig_branch) = original_branch {
516            // Get the last entry's branch (top of stack)
517            if let Some(last_entry) = stack.entries.last() {
518                let top_branch = &last_entry.branch;
519
520                // Force-update working branch to point to same commit as top entry
521                if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
522                    debug!(
523                        "Updating working branch '{}' to match top of stack ({})",
524                        orig_branch,
525                        &top_commit[..8]
526                    );
527
528                    if let Err(e) = self
529                        .git_repo
530                        .update_branch_to_commit(orig_branch, &top_commit)
531                    {
532                        Output::warning(format!(
533                            "Could not update working branch '{}' to top of stack: {}",
534                            orig_branch, e
535                        ));
536                    }
537                }
538            }
539
540            // Return to original working branch silently
541            if let Err(e) = self.git_repo.checkout_branch_silent(orig_branch) {
542                Output::warning(format!(
543                    "Could not return to original branch '{}': {}",
544                    orig_branch, e
545                ));
546            }
547        }
548
549        // Build summary message
550        result.summary = if pushed_count > 0 {
551            let pr_plural = if pushed_count == 1 { "" } else { "s" };
552            let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
553
554            if skipped_count > 0 {
555                format!(
556                    "{} {} rebased ({} PR{} updated, {} not yet submitted)",
557                    entry_count, entry_plural, pushed_count, pr_plural, skipped_count
558                )
559            } else {
560                format!(
561                    "{} {} rebased ({} PR{} updated)",
562                    entry_count, entry_plural, pushed_count, pr_plural
563                )
564            }
565        } else {
566            let plural = if entry_count == 1 { "entry" } else { "entries" };
567            format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
568        };
569
570        // Display result with proper formatting
571        println!(); // Spacing after tree
572        if result.success {
573            Output::success(&result.summary);
574        } else {
575            Output::error(format!("Rebase failed: {:?}", result.error));
576        }
577
578        // Save the updated stack metadata to disk
579        self.stack_manager.save_to_disk()?;
580
581        Ok(result)
582    }
583
584    /// Interactive rebase with user input
585    fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
586        info!("Starting interactive rebase for stack '{}'", stack.name);
587
588        let mut result = RebaseResult {
589            success: true,
590            branch_mapping: HashMap::new(),
591            conflicts: Vec::new(),
592            new_commits: Vec::new(),
593            error: None,
594            summary: String::new(),
595        };
596
597        println!("Interactive Rebase for Stack: {}", stack.name);
598        println!("   Base branch: {}", stack.base_branch);
599        println!("   Entries: {}", stack.entries.len());
600
601        if self.options.interactive {
602            println!("\nChoose action for each commit:");
603            println!("  (p)ick   - apply the commit");
604            println!("  (s)kip   - skip this commit");
605            println!("  (e)dit   - edit the commit message");
606            println!("  (q)uit   - abort the rebase");
607        }
608
609        // For now, automatically pick all commits
610        // In a real implementation, this would prompt the user
611        for entry in &stack.entries {
612            println!(
613                "  {} {} - {}",
614                entry.short_hash(),
615                entry.branch,
616                entry.short_message(50)
617            );
618
619            // Auto-pick for demo purposes
620            match self.cherry_pick_commit(&entry.commit_hash) {
621                Ok(new_commit) => result.new_commits.push(new_commit),
622                Err(_) => result.conflicts.push(entry.commit_hash.clone()),
623            }
624        }
625
626        result.summary = format!(
627            "Interactive rebase processed {} commits",
628            stack.entries.len()
629        );
630        Ok(result)
631    }
632
633    /// Cherry-pick a commit onto the current branch
634    fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
635        // Use the real cherry-pick implementation from GitRepository
636        let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
637
638        // Check for any leftover staged changes after successful cherry-pick
639        if let Ok(staged_files) = self.git_repo.get_staged_files() {
640            if !staged_files.is_empty() {
641                // Commit any leftover staged changes silently
642                let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
643                let _ = self.git_repo.commit_staged_changes(&cleanup_message);
644            }
645        }
646
647        Ok(new_commit_hash)
648    }
649
650    /// Attempt to automatically resolve conflicts
651    fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
652        debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
653
654        // Check if there are actually conflicts
655        if !self.git_repo.has_conflicts()? {
656            return Ok(true);
657        }
658
659        let conflicted_files = self.git_repo.get_conflicted_files()?;
660
661        if conflicted_files.is_empty() {
662            return Ok(true);
663        }
664
665        info!(
666            "Found conflicts in {} files: {:?}",
667            conflicted_files.len(),
668            conflicted_files
669        );
670
671        // Use the new conflict analyzer for detailed analysis
672        let analysis = self
673            .conflict_analyzer
674            .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
675
676        info!(
677            "๐Ÿ” Conflict analysis: {} total conflicts, {} auto-resolvable",
678            analysis.total_conflicts, analysis.auto_resolvable_count
679        );
680
681        // Display recommendations
682        for recommendation in &analysis.recommendations {
683            info!("๐Ÿ’ก {}", recommendation);
684        }
685
686        let mut resolved_count = 0;
687        let mut failed_files = Vec::new();
688
689        for file_analysis in &analysis.files {
690            if file_analysis.auto_resolvable {
691                match self.resolve_file_conflicts_enhanced(
692                    &file_analysis.file_path,
693                    &file_analysis.conflicts,
694                ) {
695                    Ok(ConflictResolution::Resolved) => {
696                        resolved_count += 1;
697                        info!("โœ… Auto-resolved conflicts in {}", file_analysis.file_path);
698                    }
699                    Ok(ConflictResolution::TooComplex) => {
700                        debug!(
701                            "โš ๏ธ  Conflicts in {} are too complex for auto-resolution",
702                            file_analysis.file_path
703                        );
704                        failed_files.push(file_analysis.file_path.clone());
705                    }
706                    Err(e) => {
707                        warn!(
708                            "โŒ Failed to resolve conflicts in {}: {}",
709                            file_analysis.file_path, e
710                        );
711                        failed_files.push(file_analysis.file_path.clone());
712                    }
713                }
714            } else {
715                failed_files.push(file_analysis.file_path.clone());
716                info!(
717                    "โš ๏ธ  {} requires manual resolution ({} conflicts)",
718                    file_analysis.file_path,
719                    file_analysis.conflicts.len()
720                );
721            }
722        }
723
724        if resolved_count > 0 {
725            info!(
726                "๐ŸŽ‰ Auto-resolved conflicts in {}/{} files",
727                resolved_count,
728                conflicted_files.len()
729            );
730
731            // Stage all resolved files
732            self.git_repo.stage_conflict_resolved_files()?;
733        }
734
735        // Return true only if ALL conflicts were resolved
736        let all_resolved = failed_files.is_empty();
737
738        if !all_resolved {
739            info!(
740                "โš ๏ธ  {} files still need manual resolution: {:?}",
741                failed_files.len(),
742                failed_files
743            );
744        }
745
746        Ok(all_resolved)
747    }
748
749    /// Resolve conflicts using enhanced analysis
750    fn resolve_file_conflicts_enhanced(
751        &self,
752        file_path: &str,
753        conflicts: &[crate::git::ConflictRegion],
754    ) -> Result<ConflictResolution> {
755        let repo_path = self.git_repo.path();
756        let full_path = repo_path.join(file_path);
757
758        // Read the file content with conflict markers
759        let mut content = std::fs::read_to_string(&full_path)
760            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
761
762        if conflicts.is_empty() {
763            return Ok(ConflictResolution::Resolved);
764        }
765
766        info!(
767            "Resolving {} conflicts in {} using enhanced analysis",
768            conflicts.len(),
769            file_path
770        );
771
772        let mut any_resolved = false;
773
774        // Process conflicts in reverse order to maintain string indices
775        for conflict in conflicts.iter().rev() {
776            match self.resolve_single_conflict_enhanced(conflict) {
777                Ok(Some(resolution)) => {
778                    // Replace the conflict region with the resolved content
779                    let before = &content[..conflict.start_pos];
780                    let after = &content[conflict.end_pos..];
781                    content = format!("{before}{resolution}{after}");
782                    any_resolved = true;
783                    debug!(
784                        "โœ… Resolved {} conflict at lines {}-{} in {}",
785                        format!("{:?}", conflict.conflict_type).to_lowercase(),
786                        conflict.start_line,
787                        conflict.end_line,
788                        file_path
789                    );
790                }
791                Ok(None) => {
792                    debug!(
793                        "โš ๏ธ  {} conflict at lines {}-{} in {} requires manual resolution",
794                        format!("{:?}", conflict.conflict_type).to_lowercase(),
795                        conflict.start_line,
796                        conflict.end_line,
797                        file_path
798                    );
799                    return Ok(ConflictResolution::TooComplex);
800                }
801                Err(e) => {
802                    debug!("โŒ Failed to resolve conflict in {}: {}", file_path, e);
803                    return Ok(ConflictResolution::TooComplex);
804                }
805            }
806        }
807
808        if any_resolved {
809            // Check if we resolved ALL conflicts in this file
810            let remaining_conflicts = self.parse_conflict_markers(&content)?;
811
812            if remaining_conflicts.is_empty() {
813                // SAFETY: Create backup before writing resolved content
814                // This allows recovery if auto-resolution is incorrect
815                let backup_path = full_path.with_extension("cascade-backup");
816                if let Ok(original_content) = std::fs::read_to_string(&full_path) {
817                    let _ = std::fs::write(&backup_path, original_content);
818                    debug!("Created backup at {:?}", backup_path);
819                }
820
821                // All conflicts resolved - write the file back atomically
822                crate::utils::atomic_file::write_string(&full_path, &content)?;
823
824                debug!("Successfully resolved all conflicts in {}", file_path);
825                return Ok(ConflictResolution::Resolved);
826            } else {
827                info!(
828                    "โš ๏ธ  Partially resolved conflicts in {} ({} remaining)",
829                    file_path,
830                    remaining_conflicts.len()
831                );
832            }
833        }
834
835        Ok(ConflictResolution::TooComplex)
836    }
837
838    /// Helper to count whitespace consistency (lower is better)
839    fn count_whitespace_consistency(content: &str) -> usize {
840        let mut inconsistencies = 0;
841        let lines: Vec<&str> = content.lines().collect();
842
843        for line in &lines {
844            // Check for mixed tabs and spaces
845            if line.contains('\t') && line.contains(' ') {
846                inconsistencies += 1;
847            }
848        }
849
850        // Penalize for inconsistencies
851        lines.len().saturating_sub(inconsistencies)
852    }
853
854    /// Resolve a single conflict using enhanced analysis
855    fn resolve_single_conflict_enhanced(
856        &self,
857        conflict: &crate::git::ConflictRegion,
858    ) -> Result<Option<String>> {
859        debug!(
860            "Resolving {} conflict in {} (lines {}-{})",
861            format!("{:?}", conflict.conflict_type).to_lowercase(),
862            conflict.file_path,
863            conflict.start_line,
864            conflict.end_line
865        );
866
867        use crate::git::ConflictType;
868
869        match conflict.conflict_type {
870            ConflictType::Whitespace => {
871                // SAFETY: Only resolve if the content is truly identical except for whitespace
872                // Otherwise, it might be intentional formatting changes
873                let our_normalized = conflict
874                    .our_content
875                    .split_whitespace()
876                    .collect::<Vec<_>>()
877                    .join(" ");
878                let their_normalized = conflict
879                    .their_content
880                    .split_whitespace()
881                    .collect::<Vec<_>>()
882                    .join(" ");
883
884                if our_normalized == their_normalized {
885                    // Content is identical - prefer the version with more consistent formatting
886                    // (fewer mixed spaces/tabs, more consistent indentation)
887                    let our_consistency = Self::count_whitespace_consistency(&conflict.our_content);
888                    let their_consistency =
889                        Self::count_whitespace_consistency(&conflict.their_content);
890
891                    if our_consistency >= their_consistency {
892                        Ok(Some(conflict.our_content.clone()))
893                    } else {
894                        Ok(Some(conflict.their_content.clone()))
895                    }
896                } else {
897                    // Content differs beyond whitespace - not safe to auto-resolve
898                    debug!(
899                        "Whitespace conflict has content differences - requires manual resolution"
900                    );
901                    Ok(None)
902                }
903            }
904            ConflictType::LineEnding => {
905                // Normalize to Unix line endings
906                let normalized = conflict
907                    .our_content
908                    .replace("\r\n", "\n")
909                    .replace('\r', "\n");
910                Ok(Some(normalized))
911            }
912            ConflictType::PureAddition => {
913                // SAFETY: Only merge if one side is empty (true addition)
914                // If both sides have content, it's not a pure addition - require manual resolution
915                if conflict.our_content.is_empty() {
916                    Ok(Some(conflict.their_content.clone()))
917                } else if conflict.their_content.is_empty() {
918                    Ok(Some(conflict.our_content.clone()))
919                } else {
920                    // Both sides have content - this could be:
921                    // - Duplicate function definitions
922                    // - Conflicting logic
923                    // - Different implementations of same feature
924                    // Too risky to auto-merge - require manual resolution
925                    debug!(
926                        "PureAddition conflict has content on both sides - requires manual resolution"
927                    );
928                    Ok(None)
929                }
930            }
931            ConflictType::ImportMerge => {
932                // SAFETY: Only merge simple single-line imports
933                // Multi-line imports or complex cases require manual resolution
934
935                // Check if all imports are single-line and look like imports
936                let our_lines: Vec<&str> = conflict.our_content.lines().collect();
937                let their_lines: Vec<&str> = conflict.their_content.lines().collect();
938
939                // Verify all lines look like simple imports (heuristic check)
940                let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
941                    let trimmed = line.trim();
942                    trimmed.starts_with("import ")
943                        || trimmed.starts_with("from ")
944                        || trimmed.starts_with("use ")
945                        || trimmed.starts_with("#include")
946                        || trimmed.is_empty()
947                });
948
949                if !all_simple {
950                    debug!("ImportMerge contains non-import lines - requires manual resolution");
951                    return Ok(None);
952                }
953
954                // Merge and deduplicate imports
955                let mut all_imports: Vec<&str> = our_lines
956                    .into_iter()
957                    .chain(their_lines)
958                    .filter(|line| !line.trim().is_empty())
959                    .collect();
960                all_imports.sort();
961                all_imports.dedup();
962                Ok(Some(all_imports.join("\n")))
963            }
964            ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
965                // These require manual resolution
966                Ok(None)
967            }
968        }
969    }
970
971    /// Resolve conflicts in a single file using smart strategies
972    #[allow(dead_code)]
973    fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
974        let repo_path = self.git_repo.path();
975        let full_path = repo_path.join(file_path);
976
977        // Read the file content with conflict markers
978        let content = std::fs::read_to_string(&full_path)
979            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
980
981        // Parse conflicts from the file
982        let conflicts = self.parse_conflict_markers(&content)?;
983
984        if conflicts.is_empty() {
985            // No conflict markers found - file might already be resolved
986            return Ok(ConflictResolution::Resolved);
987        }
988
989        info!(
990            "Found {} conflict regions in {}",
991            conflicts.len(),
992            file_path
993        );
994
995        // Try to resolve each conflict using our strategies
996        let mut resolved_content = content;
997        let mut any_resolved = false;
998
999        // Process conflicts in reverse order to maintain string indices
1000        for conflict in conflicts.iter().rev() {
1001            match self.resolve_single_conflict(conflict, file_path) {
1002                Ok(Some(resolution)) => {
1003                    // Replace the conflict region with the resolved content
1004                    let before = &resolved_content[..conflict.start];
1005                    let after = &resolved_content[conflict.end..];
1006                    resolved_content = format!("{before}{resolution}{after}");
1007                    any_resolved = true;
1008                    debug!(
1009                        "โœ… Resolved conflict at lines {}-{} in {}",
1010                        conflict.start_line, conflict.end_line, file_path
1011                    );
1012                }
1013                Ok(None) => {
1014                    debug!(
1015                        "โš ๏ธ  Conflict at lines {}-{} in {} too complex for auto-resolution",
1016                        conflict.start_line, conflict.end_line, file_path
1017                    );
1018                }
1019                Err(e) => {
1020                    debug!("โŒ Failed to resolve conflict in {}: {}", file_path, e);
1021                }
1022            }
1023        }
1024
1025        if any_resolved {
1026            // Check if we resolved ALL conflicts in this file
1027            let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
1028
1029            if remaining_conflicts.is_empty() {
1030                // All conflicts resolved - write the file back atomically
1031                crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
1032
1033                return Ok(ConflictResolution::Resolved);
1034            } else {
1035                info!(
1036                    "โš ๏ธ  Partially resolved conflicts in {} ({} remaining)",
1037                    file_path,
1038                    remaining_conflicts.len()
1039                );
1040            }
1041        }
1042
1043        Ok(ConflictResolution::TooComplex)
1044    }
1045
1046    /// Parse conflict markers from file content
1047    fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1048        let lines: Vec<&str> = content.lines().collect();
1049        let mut conflicts = Vec::new();
1050        let mut i = 0;
1051
1052        while i < lines.len() {
1053            if lines[i].starts_with("<<<<<<<") {
1054                // Found start of conflict
1055                let start_line = i + 1;
1056                let mut separator_line = None;
1057                let mut end_line = None;
1058
1059                // Find the separator and end
1060                for (j, line) in lines.iter().enumerate().skip(i + 1) {
1061                    if line.starts_with("=======") {
1062                        separator_line = Some(j + 1);
1063                    } else if line.starts_with(">>>>>>>") {
1064                        end_line = Some(j + 1);
1065                        break;
1066                    }
1067                }
1068
1069                if let (Some(sep), Some(end)) = (separator_line, end_line) {
1070                    // Calculate byte positions
1071                    let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1072                    let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1073
1074                    let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1075                    let their_content = lines[sep..(end - 1)].join("\n");
1076
1077                    conflicts.push(ConflictRegion {
1078                        start: start_pos,
1079                        end: end_pos,
1080                        start_line,
1081                        end_line: end,
1082                        our_content,
1083                        their_content,
1084                    });
1085
1086                    i = end;
1087                } else {
1088                    i += 1;
1089                }
1090            } else {
1091                i += 1;
1092            }
1093        }
1094
1095        Ok(conflicts)
1096    }
1097
1098    /// Resolve a single conflict using smart strategies
1099    fn resolve_single_conflict(
1100        &self,
1101        conflict: &ConflictRegion,
1102        file_path: &str,
1103    ) -> Result<Option<String>> {
1104        debug!(
1105            "Analyzing conflict in {} (lines {}-{})",
1106            file_path, conflict.start_line, conflict.end_line
1107        );
1108
1109        // Strategy 1: Whitespace-only differences
1110        if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
1111            debug!("Resolved as whitespace-only conflict");
1112            return Ok(Some(resolved));
1113        }
1114
1115        // Strategy 2: Line ending differences
1116        if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
1117            debug!("Resolved as line ending conflict");
1118            return Ok(Some(resolved));
1119        }
1120
1121        // Strategy 3: Pure addition conflicts (no overlapping changes)
1122        if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
1123            debug!("Resolved as pure addition conflict");
1124            return Ok(Some(resolved));
1125        }
1126
1127        // Strategy 4: Import/dependency reordering
1128        if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
1129            debug!("Resolved as import reordering conflict");
1130            return Ok(Some(resolved));
1131        }
1132
1133        // No strategy could resolve this conflict
1134        Ok(None)
1135    }
1136
1137    /// Resolve conflicts that only differ by whitespace
1138    fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1139        let our_normalized = self.normalize_whitespace(&conflict.our_content);
1140        let their_normalized = self.normalize_whitespace(&conflict.their_content);
1141
1142        if our_normalized == their_normalized {
1143            // Only whitespace differences - prefer the version with better formatting
1144            let resolved =
1145                if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1146                    conflict.our_content.clone()
1147                } else {
1148                    conflict.their_content.clone()
1149                };
1150
1151            return Ok(Some(resolved));
1152        }
1153
1154        Ok(None)
1155    }
1156
1157    /// Resolve conflicts that only differ by line endings
1158    fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1159        let our_normalized = conflict
1160            .our_content
1161            .replace("\r\n", "\n")
1162            .replace('\r', "\n");
1163        let their_normalized = conflict
1164            .their_content
1165            .replace("\r\n", "\n")
1166            .replace('\r', "\n");
1167
1168        if our_normalized == their_normalized {
1169            // Only line ending differences - prefer Unix line endings
1170            return Ok(Some(our_normalized));
1171        }
1172
1173        Ok(None)
1174    }
1175
1176    /// Resolve conflicts where both sides only add lines (no overlapping edits)
1177    fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1178        let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1179        let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1180
1181        // Check if one side is a subset of the other (pure addition)
1182        if our_lines.is_empty() {
1183            return Ok(Some(conflict.their_content.clone()));
1184        }
1185        if their_lines.is_empty() {
1186            return Ok(Some(conflict.our_content.clone()));
1187        }
1188
1189        // Try to merge additions intelligently
1190        let mut merged_lines = Vec::new();
1191        let mut our_idx = 0;
1192        let mut their_idx = 0;
1193
1194        while our_idx < our_lines.len() || their_idx < their_lines.len() {
1195            if our_idx >= our_lines.len() {
1196                // Only their lines left
1197                merged_lines.extend_from_slice(&their_lines[their_idx..]);
1198                break;
1199            } else if their_idx >= their_lines.len() {
1200                // Only our lines left
1201                merged_lines.extend_from_slice(&our_lines[our_idx..]);
1202                break;
1203            } else if our_lines[our_idx] == their_lines[their_idx] {
1204                // Same line - add once
1205                merged_lines.push(our_lines[our_idx]);
1206                our_idx += 1;
1207                their_idx += 1;
1208            } else {
1209                // Different lines - this might be too complex
1210                return Ok(None);
1211            }
1212        }
1213
1214        Ok(Some(merged_lines.join("\n")))
1215    }
1216
1217    /// Resolve import/dependency conflicts by sorting and merging
1218    fn resolve_import_conflict(
1219        &self,
1220        conflict: &ConflictRegion,
1221        file_path: &str,
1222    ) -> Result<Option<String>> {
1223        // Only apply to likely import sections in common file types
1224        let is_import_file = file_path.ends_with(".rs")
1225            || file_path.ends_with(".py")
1226            || file_path.ends_with(".js")
1227            || file_path.ends_with(".ts")
1228            || file_path.ends_with(".go")
1229            || file_path.ends_with(".java")
1230            || file_path.ends_with(".swift")
1231            || file_path.ends_with(".kt")
1232            || file_path.ends_with(".cs");
1233
1234        if !is_import_file {
1235            return Ok(None);
1236        }
1237
1238        let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1239        let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1240
1241        // Check if all lines look like imports/uses
1242        let our_imports = our_lines
1243            .iter()
1244            .all(|line| self.is_import_line(line, file_path));
1245        let their_imports = their_lines
1246            .iter()
1247            .all(|line| self.is_import_line(line, file_path));
1248
1249        if our_imports && their_imports {
1250            // Merge and sort imports
1251            let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1252            all_imports.sort();
1253            all_imports.dedup();
1254
1255            return Ok(Some(all_imports.join("\n")));
1256        }
1257
1258        Ok(None)
1259    }
1260
1261    /// Check if a line looks like an import statement
1262    fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1263        let trimmed = line.trim();
1264
1265        if trimmed.is_empty() {
1266            return true; // Empty lines are OK in import sections
1267        }
1268
1269        if file_path.ends_with(".rs") {
1270            return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1271        } else if file_path.ends_with(".py") {
1272            return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1273        } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1274            return trimmed.starts_with("import ")
1275                || trimmed.starts_with("const ")
1276                || trimmed.starts_with("require(");
1277        } else if file_path.ends_with(".go") {
1278            return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1279        } else if file_path.ends_with(".java") {
1280            return trimmed.starts_with("import ");
1281        } else if file_path.ends_with(".swift") {
1282            return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1283        } else if file_path.ends_with(".kt") {
1284            return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1285        } else if file_path.ends_with(".cs") {
1286            return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1287        }
1288
1289        false
1290    }
1291
1292    /// Normalize whitespace for comparison
1293    fn normalize_whitespace(&self, content: &str) -> String {
1294        content
1295            .lines()
1296            .map(|line| line.trim())
1297            .filter(|line| !line.is_empty())
1298            .collect::<Vec<_>>()
1299            .join("\n")
1300    }
1301
1302    /// Update a stack entry with new commit information
1303    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1304    fn update_stack_entry(
1305        &mut self,
1306        stack_id: Uuid,
1307        entry_id: &Uuid,
1308        _new_branch: &str,
1309        new_commit_hash: &str,
1310    ) -> Result<()> {
1311        debug!(
1312            "Updating entry {} in stack {} with new commit {}",
1313            entry_id, stack_id, new_commit_hash
1314        );
1315
1316        // Get the stack and update the entry
1317        let stack = self
1318            .stack_manager
1319            .get_stack_mut(&stack_id)
1320            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1321
1322        // Find and update the entry
1323        if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1324            debug!(
1325                "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1326                entry_id, entry.commit_hash, new_commit_hash, entry.branch
1327            );
1328
1329            // CRITICAL: Keep the original branch name to preserve PR mapping
1330            // Only update the commit hash to point to the new rebased commit
1331            entry.commit_hash = new_commit_hash.to_string();
1332
1333            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1334
1335            debug!(
1336                "Successfully updated entry {} in stack {}",
1337                entry_id, stack_id
1338            );
1339            Ok(())
1340        } else {
1341            Err(CascadeError::config(format!(
1342                "Entry {entry_id} not found in stack {stack_id}"
1343            )))
1344        }
1345    }
1346
1347    /// Pull latest changes from remote
1348    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1349        info!("Pulling latest changes for branch {}", branch);
1350
1351        // First try to fetch (this might fail if no remote exists)
1352        match self.git_repo.fetch() {
1353            Ok(_) => {
1354                debug!("Fetch successful");
1355                // Now try to pull the specific branch
1356                match self.git_repo.pull(branch) {
1357                    Ok(_) => {
1358                        info!("Pull completed successfully for {}", branch);
1359                        Ok(())
1360                    }
1361                    Err(e) => {
1362                        warn!("Pull failed for {}: {}", branch, e);
1363                        // Don't fail the entire rebase for pull issues
1364                        Ok(())
1365                    }
1366                }
1367            }
1368            Err(e) => {
1369                warn!("Fetch failed: {}", e);
1370                // Don't fail if there's no remote configured
1371                Ok(())
1372            }
1373        }
1374    }
1375
1376    /// Check if rebase is in progress
1377    pub fn is_rebase_in_progress(&self) -> bool {
1378        // Check for git rebase state files
1379        let git_dir = self.git_repo.path().join(".git");
1380        git_dir.join("REBASE_HEAD").exists()
1381            || git_dir.join("rebase-merge").exists()
1382            || git_dir.join("rebase-apply").exists()
1383    }
1384
1385    /// Abort an in-progress rebase
1386    pub fn abort_rebase(&self) -> Result<()> {
1387        info!("Aborting rebase operation");
1388
1389        let git_dir = self.git_repo.path().join(".git");
1390
1391        // Clean up rebase state files
1392        if git_dir.join("REBASE_HEAD").exists() {
1393            std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1394                CascadeError::Git(git2::Error::from_str(&format!(
1395                    "Failed to clean rebase state: {e}"
1396                )))
1397            })?;
1398        }
1399
1400        if git_dir.join("rebase-merge").exists() {
1401            std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1402                CascadeError::Git(git2::Error::from_str(&format!(
1403                    "Failed to clean rebase-merge: {e}"
1404                )))
1405            })?;
1406        }
1407
1408        if git_dir.join("rebase-apply").exists() {
1409            std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1410                CascadeError::Git(git2::Error::from_str(&format!(
1411                    "Failed to clean rebase-apply: {e}"
1412                )))
1413            })?;
1414        }
1415
1416        info!("Rebase aborted successfully");
1417        Ok(())
1418    }
1419
1420    /// Continue an in-progress rebase after conflict resolution
1421    pub fn continue_rebase(&self) -> Result<()> {
1422        info!("Continuing rebase operation");
1423
1424        // Check if there are still conflicts
1425        if self.git_repo.has_conflicts()? {
1426            return Err(CascadeError::branch(
1427                "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1428            ));
1429        }
1430
1431        // Stage resolved files
1432        self.git_repo.stage_conflict_resolved_files()?;
1433
1434        info!("Rebase continued successfully");
1435        Ok(())
1436    }
1437
1438    /// Check if there's an in-progress cherry-pick operation
1439    fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1440        let git_dir = self.git_repo.path().join(".git");
1441        Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1442    }
1443
1444    /// Handle resuming an in-progress cherry-pick from a previous failed sync
1445    fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1446        use crate::cli::output::Output;
1447
1448        let git_dir = self.git_repo.path().join(".git");
1449
1450        Output::section("Resuming in-progress sync");
1451        println!();
1452        Output::info("Detected unfinished cherry-pick from previous sync");
1453        println!();
1454
1455        // Check if conflicts are resolved
1456        if self.git_repo.has_conflicts()? {
1457            let conflicted_files = self.git_repo.get_conflicted_files()?;
1458
1459            let result = RebaseResult {
1460                success: false,
1461                branch_mapping: HashMap::new(),
1462                conflicts: conflicted_files.clone(),
1463                new_commits: Vec::new(),
1464                error: Some(format!(
1465                    "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1466                    MANUAL CONFLICT RESOLUTION REQUIRED\n\
1467                    =====================================\n\n\
1468                    Conflicted files:\n{}\n\n\
1469                    Step 1: Analyze conflicts\n\
1470                    โ†’ Run: ca conflicts\n\
1471                    โ†’ Shows detailed conflict analysis\n\n\
1472                    Step 2: Resolve conflicts in your editor\n\
1473                    โ†’ Open conflicted files and edit them\n\
1474                    โ†’ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1475                    โ†’ Keep the code you want\n\
1476                    โ†’ Save the files\n\n\
1477                    Step 3: Mark conflicts as resolved\n\
1478                    โ†’ Run: git add <resolved-files>\n\
1479                    โ†’ Or: git add -A (to stage all resolved files)\n\n\
1480                    Step 4: Complete the sync\n\
1481                    โ†’ Run: ca sync\n\
1482                    โ†’ Cascade will continue from where it left off\n\n\
1483                    Alternative: Abort and start over\n\
1484                    โ†’ Run: git cherry-pick --abort\n\
1485                    โ†’ Then: ca sync (starts fresh)",
1486                    conflicted_files.len(),
1487                    conflicted_files
1488                        .iter()
1489                        .map(|f| format!("  - {}", f))
1490                        .collect::<Vec<_>>()
1491                        .join("\n")
1492                )),
1493                summary: "Sync paused - conflicts need resolution".to_string(),
1494            };
1495
1496            return Ok(result);
1497        }
1498
1499        // Conflicts are resolved - continue the cherry-pick
1500        Output::info("Conflicts resolved, continuing cherry-pick...");
1501
1502        // Stage all resolved files
1503        self.git_repo.stage_conflict_resolved_files()?;
1504
1505        // Complete the cherry-pick by committing
1506        let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1507        let commit_message = if cherry_pick_msg_file.exists() {
1508            std::fs::read_to_string(&cherry_pick_msg_file)
1509                .unwrap_or_else(|_| "Resolved conflicts".to_string())
1510        } else {
1511            "Resolved conflicts".to_string()
1512        };
1513
1514        match self.git_repo.commit(&commit_message) {
1515            Ok(_new_commit_id) => {
1516                Output::success("Cherry-pick completed");
1517
1518                // Clean up cherry-pick state
1519                if git_dir.join("CHERRY_PICK_HEAD").exists() {
1520                    let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1521                }
1522                if cherry_pick_msg_file.exists() {
1523                    let _ = std::fs::remove_file(&cherry_pick_msg_file);
1524                }
1525
1526                println!();
1527                Output::info("Continuing with rest of stack...");
1528                println!();
1529
1530                // Now continue with the rest of the rebase
1531                // We need to restart the full rebase since we don't track which entry we were on
1532                self.rebase_with_force_push(stack)
1533            }
1534            Err(e) => {
1535                let result = RebaseResult {
1536                    success: false,
1537                    branch_mapping: HashMap::new(),
1538                    conflicts: Vec::new(),
1539                    new_commits: Vec::new(),
1540                    error: Some(format!(
1541                        "Failed to complete cherry-pick: {}\n\n\
1542                        This usually means:\n\
1543                        - Git index is locked (another process accessing repo)\n\
1544                        - File permissions issue\n\
1545                        - Disk space issue\n\n\
1546                        Recovery:\n\
1547                        1. Check if another Git operation is running\n\
1548                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1549                        3. Run 'git status' to check repo state\n\
1550                        4. Retry 'ca sync' after fixing the issue\n\n\
1551                        Or abort and start fresh:\n\
1552                        โ†’ Run: git cherry-pick --abort\n\
1553                        โ†’ Then: ca sync",
1554                        e
1555                    )),
1556                    summary: "Failed to complete cherry-pick".to_string(),
1557                };
1558
1559                Ok(result)
1560            }
1561        }
1562    }
1563}
1564
1565impl RebaseResult {
1566    /// Get a summary of the rebase operation
1567    pub fn get_summary(&self) -> String {
1568        if self.success {
1569            format!("โœ… {}", self.summary)
1570        } else {
1571            format!(
1572                "โŒ Rebase failed: {}",
1573                self.error.as_deref().unwrap_or("Unknown error")
1574            )
1575        }
1576    }
1577
1578    /// Check if any conflicts occurred
1579    pub fn has_conflicts(&self) -> bool {
1580        !self.conflicts.is_empty()
1581    }
1582
1583    /// Get the number of successful operations
1584    pub fn success_count(&self) -> usize {
1585        self.new_commits.len()
1586    }
1587}
1588
1589#[cfg(test)]
1590mod tests {
1591    use super::*;
1592    use std::path::PathBuf;
1593    use std::process::Command;
1594    use tempfile::TempDir;
1595
1596    #[allow(dead_code)]
1597    fn create_test_repo() -> (TempDir, PathBuf) {
1598        let temp_dir = TempDir::new().unwrap();
1599        let repo_path = temp_dir.path().to_path_buf();
1600
1601        // Initialize git repository
1602        Command::new("git")
1603            .args(["init"])
1604            .current_dir(&repo_path)
1605            .output()
1606            .unwrap();
1607        Command::new("git")
1608            .args(["config", "user.name", "Test"])
1609            .current_dir(&repo_path)
1610            .output()
1611            .unwrap();
1612        Command::new("git")
1613            .args(["config", "user.email", "test@test.com"])
1614            .current_dir(&repo_path)
1615            .output()
1616            .unwrap();
1617
1618        // Create initial commit
1619        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1620        Command::new("git")
1621            .args(["add", "."])
1622            .current_dir(&repo_path)
1623            .output()
1624            .unwrap();
1625        Command::new("git")
1626            .args(["commit", "-m", "Initial"])
1627            .current_dir(&repo_path)
1628            .output()
1629            .unwrap();
1630
1631        (temp_dir, repo_path)
1632    }
1633
1634    #[test]
1635    fn test_conflict_region_creation() {
1636        let region = ConflictRegion {
1637            start: 0,
1638            end: 50,
1639            start_line: 1,
1640            end_line: 3,
1641            our_content: "function test() {\n    return true;\n}".to_string(),
1642            their_content: "function test() {\n  return true;\n}".to_string(),
1643        };
1644
1645        assert_eq!(region.start_line, 1);
1646        assert_eq!(region.end_line, 3);
1647        assert!(region.our_content.contains("return true"));
1648        assert!(region.their_content.contains("return true"));
1649    }
1650
1651    #[test]
1652    fn test_rebase_strategies() {
1653        assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1654        assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1655    }
1656
1657    #[test]
1658    fn test_rebase_options() {
1659        let options = RebaseOptions::default();
1660        assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1661        assert!(!options.interactive);
1662        assert!(options.auto_resolve);
1663        assert_eq!(options.max_retries, 3);
1664    }
1665
1666    #[test]
1667    fn test_cleanup_guard_tracks_branches() {
1668        let mut guard = TempBranchCleanupGuard::new();
1669        assert!(guard.branches.is_empty());
1670
1671        guard.add_branch("test-branch-1".to_string());
1672        guard.add_branch("test-branch-2".to_string());
1673
1674        assert_eq!(guard.branches.len(), 2);
1675        assert_eq!(guard.branches[0], "test-branch-1");
1676        assert_eq!(guard.branches[1], "test-branch-2");
1677    }
1678
1679    #[test]
1680    fn test_cleanup_guard_prevents_double_cleanup() {
1681        use std::process::Command;
1682        use tempfile::TempDir;
1683
1684        // Create a temporary git repo
1685        let temp_dir = TempDir::new().unwrap();
1686        let repo_path = temp_dir.path();
1687
1688        Command::new("git")
1689            .args(["init"])
1690            .current_dir(repo_path)
1691            .output()
1692            .unwrap();
1693
1694        Command::new("git")
1695            .args(["config", "user.name", "Test"])
1696            .current_dir(repo_path)
1697            .output()
1698            .unwrap();
1699
1700        Command::new("git")
1701            .args(["config", "user.email", "test@test.com"])
1702            .current_dir(repo_path)
1703            .output()
1704            .unwrap();
1705
1706        // Create initial commit
1707        std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1708        Command::new("git")
1709            .args(["add", "."])
1710            .current_dir(repo_path)
1711            .output()
1712            .unwrap();
1713        Command::new("git")
1714            .args(["commit", "-m", "initial"])
1715            .current_dir(repo_path)
1716            .output()
1717            .unwrap();
1718
1719        let git_repo = GitRepository::open(repo_path).unwrap();
1720
1721        // Create a test branch
1722        git_repo.create_branch("test-temp", None).unwrap();
1723
1724        let mut guard = TempBranchCleanupGuard::new();
1725        guard.add_branch("test-temp".to_string());
1726
1727        // First cleanup should work
1728        guard.cleanup(&git_repo);
1729        assert!(guard.cleaned);
1730
1731        // Second cleanup should be a no-op (shouldn't panic)
1732        guard.cleanup(&git_repo);
1733        assert!(guard.cleaned);
1734    }
1735
1736    #[test]
1737    fn test_rebase_result() {
1738        let result = RebaseResult {
1739            success: true,
1740            branch_mapping: std::collections::HashMap::new(),
1741            conflicts: vec!["abc123".to_string()],
1742            new_commits: vec!["def456".to_string()],
1743            error: None,
1744            summary: "Test summary".to_string(),
1745        };
1746
1747        assert!(result.success);
1748        assert!(result.has_conflicts());
1749        assert_eq!(result.success_count(), 1);
1750    }
1751
1752    #[test]
1753    fn test_import_line_detection() {
1754        let (_temp_dir, repo_path) = create_test_repo();
1755        let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1756        let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1757        let options = RebaseOptions::default();
1758        let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1759
1760        // Test Swift import detection
1761        assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1762        assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1763        assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1764
1765        // Test Kotlin import detection
1766        assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1767        assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1768        assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1769
1770        // Test C# import detection
1771        assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1772        assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1773        assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1774        assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1775
1776        // Test empty lines are allowed in import sections
1777        assert!(rebase_manager.is_import_line("", "test.swift"));
1778        assert!(rebase_manager.is_import_line("   ", "test.kt"));
1779        assert!(rebase_manager.is_import_line("", "test.cs"));
1780    }
1781}