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            // Force checkout to base branch to allow temp branch deletion
469            // Use unsafe checkout to bypass safety checks since we know this is cleanup
470            if let Err(e) = self.git_repo.checkout_branch_unsafe(&target_base) {
471                Output::warning(format!("Could not checkout base for cleanup: {}", e));
472                // If we can't checkout, we can't delete temp branches
473                // This is non-critical - temp branches will be cleaned up eventually
474            } else {
475                // Successfully checked out - now delete temp branches
476                for temp_branch in &temp_branches {
477                    if let Err(e) = self.git_repo.delete_branch_unsafe(temp_branch) {
478                        debug!("Could not delete temp branch {}: {}", temp_branch, e);
479                    }
480                }
481            }
482        }
483
484        // Phase 2: Push all branches with PRs to remote (git CLI - after all libgit2 operations)
485        // This batch approach prevents index lock conflicts between libgit2 and git CLI
486        let pushed_count = branches_to_push.len();
487        let skipped_count = entry_count - pushed_count;
488
489        if !branches_to_push.is_empty() {
490            println!(); // Spacing before push phase
491            println!(
492                "Pushing {} branch{} to remote...",
493                pushed_count,
494                if pushed_count == 1 { "" } else { "es" }
495            );
496
497            for (branch_name, _pr_num) in &branches_to_push {
498                match self.git_repo.force_push_single_branch_auto(branch_name) {
499                    Ok(_) => {
500                        debug!("Pushed {} successfully", branch_name);
501                    }
502                    Err(e) => {
503                        Output::warning(format!("Could not push '{}': {}", branch_name, e));
504                        // Continue pushing other branches even if one fails
505                    }
506                }
507            }
508        }
509
510        // Update working branch to point to the top of the rebased stack
511        // This ensures subsequent `ca push` doesn't re-add old commits
512        if let Some(ref orig_branch) = original_branch {
513            // Get the last entry's branch (top of stack)
514            if let Some(last_entry) = stack.entries.last() {
515                let top_branch = &last_entry.branch;
516
517                // Force-update working branch to point to same commit as top entry
518                if let Ok(top_commit) = self.git_repo.get_branch_head(top_branch) {
519                    debug!(
520                        "Updating working branch '{}' to match top of stack ({})",
521                        orig_branch,
522                        &top_commit[..8]
523                    );
524
525                    if let Err(e) = self
526                        .git_repo
527                        .update_branch_to_commit(orig_branch, &top_commit)
528                    {
529                        Output::warning(format!(
530                            "Could not update working branch '{}' to top of stack: {}",
531                            orig_branch, e
532                        ));
533                    }
534                }
535            }
536
537            // Return to original working branch
538            // Use unsafe checkout to force it (we're in cleanup phase, no uncommitted changes)
539            if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
540                debug!(
541                    "Could not return to original branch '{}': {}",
542                    orig_branch, e
543                );
544                // Non-critical: User is left on base branch instead of working branch
545            }
546        }
547
548        // Build summary message
549        result.summary = if pushed_count > 0 {
550            let pr_plural = if pushed_count == 1 { "" } else { "s" };
551            let entry_plural = if entry_count == 1 { "entry" } else { "entries" };
552
553            if skipped_count > 0 {
554                format!(
555                    "{} {} rebased ({} PR{} updated, {} not yet submitted)",
556                    entry_count, entry_plural, pushed_count, pr_plural, skipped_count
557                )
558            } else {
559                format!(
560                    "{} {} rebased ({} PR{} updated)",
561                    entry_count, entry_plural, pushed_count, pr_plural
562                )
563            }
564        } else {
565            let plural = if entry_count == 1 { "entry" } else { "entries" };
566            format!("{} {} rebased (no PRs to update yet)", entry_count, plural)
567        };
568
569        // Display result with proper formatting
570        println!(); // Spacing after tree
571        if result.success {
572            Output::success(&result.summary);
573        } else {
574            Output::error(format!("Rebase failed: {:?}", result.error));
575        }
576
577        // Save the updated stack metadata to disk
578        self.stack_manager.save_to_disk()?;
579
580        Ok(result)
581    }
582
583    /// Interactive rebase with user input
584    fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
585        info!("Starting interactive rebase for stack '{}'", stack.name);
586
587        let mut result = RebaseResult {
588            success: true,
589            branch_mapping: HashMap::new(),
590            conflicts: Vec::new(),
591            new_commits: Vec::new(),
592            error: None,
593            summary: String::new(),
594        };
595
596        println!("Interactive Rebase for Stack: {}", stack.name);
597        println!("   Base branch: {}", stack.base_branch);
598        println!("   Entries: {}", stack.entries.len());
599
600        if self.options.interactive {
601            println!("\nChoose action for each commit:");
602            println!("  (p)ick   - apply the commit");
603            println!("  (s)kip   - skip this commit");
604            println!("  (e)dit   - edit the commit message");
605            println!("  (q)uit   - abort the rebase");
606        }
607
608        // For now, automatically pick all commits
609        // In a real implementation, this would prompt the user
610        for entry in &stack.entries {
611            println!(
612                "  {} {} - {}",
613                entry.short_hash(),
614                entry.branch,
615                entry.short_message(50)
616            );
617
618            // Auto-pick for demo purposes
619            match self.cherry_pick_commit(&entry.commit_hash) {
620                Ok(new_commit) => result.new_commits.push(new_commit),
621                Err(_) => result.conflicts.push(entry.commit_hash.clone()),
622            }
623        }
624
625        result.summary = format!(
626            "Interactive rebase processed {} commits",
627            stack.entries.len()
628        );
629        Ok(result)
630    }
631
632    /// Cherry-pick a commit onto the current branch
633    fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
634        // Use the real cherry-pick implementation from GitRepository
635        let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
636
637        // Check for any leftover staged changes after successful cherry-pick
638        if let Ok(staged_files) = self.git_repo.get_staged_files() {
639            if !staged_files.is_empty() {
640                // Commit any leftover staged changes silently
641                let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
642                let _ = self.git_repo.commit_staged_changes(&cleanup_message);
643            }
644        }
645
646        Ok(new_commit_hash)
647    }
648
649    /// Attempt to automatically resolve conflicts
650    fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
651        debug!("Attempting to auto-resolve conflicts for {}", commit_hash);
652
653        // Check if there are actually conflicts
654        if !self.git_repo.has_conflicts()? {
655            return Ok(true);
656        }
657
658        let conflicted_files = self.git_repo.get_conflicted_files()?;
659
660        if conflicted_files.is_empty() {
661            return Ok(true);
662        }
663
664        info!(
665            "Found conflicts in {} files: {:?}",
666            conflicted_files.len(),
667            conflicted_files
668        );
669
670        // Use the new conflict analyzer for detailed analysis
671        let analysis = self
672            .conflict_analyzer
673            .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
674
675        info!(
676            "๐Ÿ” Conflict analysis: {} total conflicts, {} auto-resolvable",
677            analysis.total_conflicts, analysis.auto_resolvable_count
678        );
679
680        // Display recommendations
681        for recommendation in &analysis.recommendations {
682            info!("๐Ÿ’ก {}", recommendation);
683        }
684
685        let mut resolved_count = 0;
686        let mut failed_files = Vec::new();
687
688        for file_analysis in &analysis.files {
689            if file_analysis.auto_resolvable {
690                match self.resolve_file_conflicts_enhanced(
691                    &file_analysis.file_path,
692                    &file_analysis.conflicts,
693                ) {
694                    Ok(ConflictResolution::Resolved) => {
695                        resolved_count += 1;
696                        info!("โœ… Auto-resolved conflicts in {}", file_analysis.file_path);
697                    }
698                    Ok(ConflictResolution::TooComplex) => {
699                        debug!(
700                            "โš ๏ธ  Conflicts in {} are too complex for auto-resolution",
701                            file_analysis.file_path
702                        );
703                        failed_files.push(file_analysis.file_path.clone());
704                    }
705                    Err(e) => {
706                        warn!(
707                            "โŒ Failed to resolve conflicts in {}: {}",
708                            file_analysis.file_path, e
709                        );
710                        failed_files.push(file_analysis.file_path.clone());
711                    }
712                }
713            } else {
714                failed_files.push(file_analysis.file_path.clone());
715                info!(
716                    "โš ๏ธ  {} requires manual resolution ({} conflicts)",
717                    file_analysis.file_path,
718                    file_analysis.conflicts.len()
719                );
720            }
721        }
722
723        if resolved_count > 0 {
724            info!(
725                "๐ŸŽ‰ Auto-resolved conflicts in {}/{} files",
726                resolved_count,
727                conflicted_files.len()
728            );
729
730            // Stage all resolved files
731            self.git_repo.stage_conflict_resolved_files()?;
732        }
733
734        // Return true only if ALL conflicts were resolved
735        let all_resolved = failed_files.is_empty();
736
737        if !all_resolved {
738            info!(
739                "โš ๏ธ  {} files still need manual resolution: {:?}",
740                failed_files.len(),
741                failed_files
742            );
743        }
744
745        Ok(all_resolved)
746    }
747
748    /// Resolve conflicts using enhanced analysis
749    fn resolve_file_conflicts_enhanced(
750        &self,
751        file_path: &str,
752        conflicts: &[crate::git::ConflictRegion],
753    ) -> Result<ConflictResolution> {
754        let repo_path = self.git_repo.path();
755        let full_path = repo_path.join(file_path);
756
757        // Read the file content with conflict markers
758        let mut content = std::fs::read_to_string(&full_path)
759            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
760
761        if conflicts.is_empty() {
762            return Ok(ConflictResolution::Resolved);
763        }
764
765        info!(
766            "Resolving {} conflicts in {} using enhanced analysis",
767            conflicts.len(),
768            file_path
769        );
770
771        let mut any_resolved = false;
772
773        // Process conflicts in reverse order to maintain string indices
774        for conflict in conflicts.iter().rev() {
775            match self.resolve_single_conflict_enhanced(conflict) {
776                Ok(Some(resolution)) => {
777                    // Replace the conflict region with the resolved content
778                    let before = &content[..conflict.start_pos];
779                    let after = &content[conflict.end_pos..];
780                    content = format!("{before}{resolution}{after}");
781                    any_resolved = true;
782                    debug!(
783                        "โœ… Resolved {} conflict at lines {}-{} in {}",
784                        format!("{:?}", conflict.conflict_type).to_lowercase(),
785                        conflict.start_line,
786                        conflict.end_line,
787                        file_path
788                    );
789                }
790                Ok(None) => {
791                    debug!(
792                        "โš ๏ธ  {} conflict at lines {}-{} in {} requires manual resolution",
793                        format!("{:?}", conflict.conflict_type).to_lowercase(),
794                        conflict.start_line,
795                        conflict.end_line,
796                        file_path
797                    );
798                    return Ok(ConflictResolution::TooComplex);
799                }
800                Err(e) => {
801                    debug!("โŒ Failed to resolve conflict in {}: {}", file_path, e);
802                    return Ok(ConflictResolution::TooComplex);
803                }
804            }
805        }
806
807        if any_resolved {
808            // Check if we resolved ALL conflicts in this file
809            let remaining_conflicts = self.parse_conflict_markers(&content)?;
810
811            if remaining_conflicts.is_empty() {
812                // SAFETY: Create backup before writing resolved content
813                // This allows recovery if auto-resolution is incorrect
814                let backup_path = full_path.with_extension("cascade-backup");
815                if let Ok(original_content) = std::fs::read_to_string(&full_path) {
816                    let _ = std::fs::write(&backup_path, original_content);
817                    debug!("Created backup at {:?}", backup_path);
818                }
819
820                // All conflicts resolved - write the file back atomically
821                crate::utils::atomic_file::write_string(&full_path, &content)?;
822
823                debug!("Successfully resolved all conflicts in {}", file_path);
824                return Ok(ConflictResolution::Resolved);
825            } else {
826                info!(
827                    "โš ๏ธ  Partially resolved conflicts in {} ({} remaining)",
828                    file_path,
829                    remaining_conflicts.len()
830                );
831            }
832        }
833
834        Ok(ConflictResolution::TooComplex)
835    }
836
837    /// Helper to count whitespace consistency (lower is better)
838    fn count_whitespace_consistency(content: &str) -> usize {
839        let mut inconsistencies = 0;
840        let lines: Vec<&str> = content.lines().collect();
841
842        for line in &lines {
843            // Check for mixed tabs and spaces
844            if line.contains('\t') && line.contains(' ') {
845                inconsistencies += 1;
846            }
847        }
848
849        // Penalize for inconsistencies
850        lines.len().saturating_sub(inconsistencies)
851    }
852
853    /// Resolve a single conflict using enhanced analysis
854    fn resolve_single_conflict_enhanced(
855        &self,
856        conflict: &crate::git::ConflictRegion,
857    ) -> Result<Option<String>> {
858        debug!(
859            "Resolving {} conflict in {} (lines {}-{})",
860            format!("{:?}", conflict.conflict_type).to_lowercase(),
861            conflict.file_path,
862            conflict.start_line,
863            conflict.end_line
864        );
865
866        use crate::git::ConflictType;
867
868        match conflict.conflict_type {
869            ConflictType::Whitespace => {
870                // SAFETY: Only resolve if the content is truly identical except for whitespace
871                // Otherwise, it might be intentional formatting changes
872                let our_normalized = conflict
873                    .our_content
874                    .split_whitespace()
875                    .collect::<Vec<_>>()
876                    .join(" ");
877                let their_normalized = conflict
878                    .their_content
879                    .split_whitespace()
880                    .collect::<Vec<_>>()
881                    .join(" ");
882
883                if our_normalized == their_normalized {
884                    // Content is identical - prefer the version with more consistent formatting
885                    // (fewer mixed spaces/tabs, more consistent indentation)
886                    let our_consistency = Self::count_whitespace_consistency(&conflict.our_content);
887                    let their_consistency =
888                        Self::count_whitespace_consistency(&conflict.their_content);
889
890                    if our_consistency >= their_consistency {
891                        Ok(Some(conflict.our_content.clone()))
892                    } else {
893                        Ok(Some(conflict.their_content.clone()))
894                    }
895                } else {
896                    // Content differs beyond whitespace - not safe to auto-resolve
897                    debug!(
898                        "Whitespace conflict has content differences - requires manual resolution"
899                    );
900                    Ok(None)
901                }
902            }
903            ConflictType::LineEnding => {
904                // Normalize to Unix line endings
905                let normalized = conflict
906                    .our_content
907                    .replace("\r\n", "\n")
908                    .replace('\r', "\n");
909                Ok(Some(normalized))
910            }
911            ConflictType::PureAddition => {
912                // SAFETY: Only merge if one side is empty (true addition)
913                // If both sides have content, it's not a pure addition - require manual resolution
914                if conflict.our_content.is_empty() {
915                    Ok(Some(conflict.their_content.clone()))
916                } else if conflict.their_content.is_empty() {
917                    Ok(Some(conflict.our_content.clone()))
918                } else {
919                    // Both sides have content - this could be:
920                    // - Duplicate function definitions
921                    // - Conflicting logic
922                    // - Different implementations of same feature
923                    // Too risky to auto-merge - require manual resolution
924                    debug!(
925                        "PureAddition conflict has content on both sides - requires manual resolution"
926                    );
927                    Ok(None)
928                }
929            }
930            ConflictType::ImportMerge => {
931                // SAFETY: Only merge simple single-line imports
932                // Multi-line imports or complex cases require manual resolution
933
934                // Check if all imports are single-line and look like imports
935                let our_lines: Vec<&str> = conflict.our_content.lines().collect();
936                let their_lines: Vec<&str> = conflict.their_content.lines().collect();
937
938                // Verify all lines look like simple imports (heuristic check)
939                let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
940                    let trimmed = line.trim();
941                    trimmed.starts_with("import ")
942                        || trimmed.starts_with("from ")
943                        || trimmed.starts_with("use ")
944                        || trimmed.starts_with("#include")
945                        || trimmed.is_empty()
946                });
947
948                if !all_simple {
949                    debug!("ImportMerge contains non-import lines - requires manual resolution");
950                    return Ok(None);
951                }
952
953                // Merge and deduplicate imports
954                let mut all_imports: Vec<&str> = our_lines
955                    .into_iter()
956                    .chain(their_lines)
957                    .filter(|line| !line.trim().is_empty())
958                    .collect();
959                all_imports.sort();
960                all_imports.dedup();
961                Ok(Some(all_imports.join("\n")))
962            }
963            ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
964                // These require manual resolution
965                Ok(None)
966            }
967        }
968    }
969
970    /// Resolve conflicts in a single file using smart strategies
971    #[allow(dead_code)]
972    fn resolve_file_conflicts(&self, file_path: &str) -> Result<ConflictResolution> {
973        let repo_path = self.git_repo.path();
974        let full_path = repo_path.join(file_path);
975
976        // Read the file content with conflict markers
977        let content = std::fs::read_to_string(&full_path)
978            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
979
980        // Parse conflicts from the file
981        let conflicts = self.parse_conflict_markers(&content)?;
982
983        if conflicts.is_empty() {
984            // No conflict markers found - file might already be resolved
985            return Ok(ConflictResolution::Resolved);
986        }
987
988        info!(
989            "Found {} conflict regions in {}",
990            conflicts.len(),
991            file_path
992        );
993
994        // Try to resolve each conflict using our strategies
995        let mut resolved_content = content;
996        let mut any_resolved = false;
997
998        // Process conflicts in reverse order to maintain string indices
999        for conflict in conflicts.iter().rev() {
1000            match self.resolve_single_conflict(conflict, file_path) {
1001                Ok(Some(resolution)) => {
1002                    // Replace the conflict region with the resolved content
1003                    let before = &resolved_content[..conflict.start];
1004                    let after = &resolved_content[conflict.end..];
1005                    resolved_content = format!("{before}{resolution}{after}");
1006                    any_resolved = true;
1007                    debug!(
1008                        "โœ… Resolved conflict at lines {}-{} in {}",
1009                        conflict.start_line, conflict.end_line, file_path
1010                    );
1011                }
1012                Ok(None) => {
1013                    debug!(
1014                        "โš ๏ธ  Conflict at lines {}-{} in {} too complex for auto-resolution",
1015                        conflict.start_line, conflict.end_line, file_path
1016                    );
1017                }
1018                Err(e) => {
1019                    debug!("โŒ Failed to resolve conflict in {}: {}", file_path, e);
1020                }
1021            }
1022        }
1023
1024        if any_resolved {
1025            // Check if we resolved ALL conflicts in this file
1026            let remaining_conflicts = self.parse_conflict_markers(&resolved_content)?;
1027
1028            if remaining_conflicts.is_empty() {
1029                // All conflicts resolved - write the file back atomically
1030                crate::utils::atomic_file::write_string(&full_path, &resolved_content)?;
1031
1032                return Ok(ConflictResolution::Resolved);
1033            } else {
1034                info!(
1035                    "โš ๏ธ  Partially resolved conflicts in {} ({} remaining)",
1036                    file_path,
1037                    remaining_conflicts.len()
1038                );
1039            }
1040        }
1041
1042        Ok(ConflictResolution::TooComplex)
1043    }
1044
1045    /// Parse conflict markers from file content
1046    fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1047        let lines: Vec<&str> = content.lines().collect();
1048        let mut conflicts = Vec::new();
1049        let mut i = 0;
1050
1051        while i < lines.len() {
1052            if lines[i].starts_with("<<<<<<<") {
1053                // Found start of conflict
1054                let start_line = i + 1;
1055                let mut separator_line = None;
1056                let mut end_line = None;
1057
1058                // Find the separator and end
1059                for (j, line) in lines.iter().enumerate().skip(i + 1) {
1060                    if line.starts_with("=======") {
1061                        separator_line = Some(j + 1);
1062                    } else if line.starts_with(">>>>>>>") {
1063                        end_line = Some(j + 1);
1064                        break;
1065                    }
1066                }
1067
1068                if let (Some(sep), Some(end)) = (separator_line, end_line) {
1069                    // Calculate byte positions
1070                    let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1071                    let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1072
1073                    let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1074                    let their_content = lines[sep..(end - 1)].join("\n");
1075
1076                    conflicts.push(ConflictRegion {
1077                        start: start_pos,
1078                        end: end_pos,
1079                        start_line,
1080                        end_line: end,
1081                        our_content,
1082                        their_content,
1083                    });
1084
1085                    i = end;
1086                } else {
1087                    i += 1;
1088                }
1089            } else {
1090                i += 1;
1091            }
1092        }
1093
1094        Ok(conflicts)
1095    }
1096
1097    /// Resolve a single conflict using smart strategies
1098    fn resolve_single_conflict(
1099        &self,
1100        conflict: &ConflictRegion,
1101        file_path: &str,
1102    ) -> Result<Option<String>> {
1103        debug!(
1104            "Analyzing conflict in {} (lines {}-{})",
1105            file_path, conflict.start_line, conflict.end_line
1106        );
1107
1108        // Strategy 1: Whitespace-only differences
1109        if let Some(resolved) = self.resolve_whitespace_conflict(conflict)? {
1110            debug!("Resolved as whitespace-only conflict");
1111            return Ok(Some(resolved));
1112        }
1113
1114        // Strategy 2: Line ending differences
1115        if let Some(resolved) = self.resolve_line_ending_conflict(conflict)? {
1116            debug!("Resolved as line ending conflict");
1117            return Ok(Some(resolved));
1118        }
1119
1120        // Strategy 3: Pure addition conflicts (no overlapping changes)
1121        if let Some(resolved) = self.resolve_addition_conflict(conflict)? {
1122            debug!("Resolved as pure addition conflict");
1123            return Ok(Some(resolved));
1124        }
1125
1126        // Strategy 4: Import/dependency reordering
1127        if let Some(resolved) = self.resolve_import_conflict(conflict, file_path)? {
1128            debug!("Resolved as import reordering conflict");
1129            return Ok(Some(resolved));
1130        }
1131
1132        // No strategy could resolve this conflict
1133        Ok(None)
1134    }
1135
1136    /// Resolve conflicts that only differ by whitespace
1137    fn resolve_whitespace_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1138        let our_normalized = self.normalize_whitespace(&conflict.our_content);
1139        let their_normalized = self.normalize_whitespace(&conflict.their_content);
1140
1141        if our_normalized == their_normalized {
1142            // Only whitespace differences - prefer the version with better formatting
1143            let resolved =
1144                if conflict.our_content.trim().len() >= conflict.their_content.trim().len() {
1145                    conflict.our_content.clone()
1146                } else {
1147                    conflict.their_content.clone()
1148                };
1149
1150            return Ok(Some(resolved));
1151        }
1152
1153        Ok(None)
1154    }
1155
1156    /// Resolve conflicts that only differ by line endings
1157    fn resolve_line_ending_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1158        let our_normalized = conflict
1159            .our_content
1160            .replace("\r\n", "\n")
1161            .replace('\r', "\n");
1162        let their_normalized = conflict
1163            .their_content
1164            .replace("\r\n", "\n")
1165            .replace('\r', "\n");
1166
1167        if our_normalized == their_normalized {
1168            // Only line ending differences - prefer Unix line endings
1169            return Ok(Some(our_normalized));
1170        }
1171
1172        Ok(None)
1173    }
1174
1175    /// Resolve conflicts where both sides only add lines (no overlapping edits)
1176    fn resolve_addition_conflict(&self, conflict: &ConflictRegion) -> Result<Option<String>> {
1177        let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1178        let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1179
1180        // Check if one side is a subset of the other (pure addition)
1181        if our_lines.is_empty() {
1182            return Ok(Some(conflict.their_content.clone()));
1183        }
1184        if their_lines.is_empty() {
1185            return Ok(Some(conflict.our_content.clone()));
1186        }
1187
1188        // Try to merge additions intelligently
1189        let mut merged_lines = Vec::new();
1190        let mut our_idx = 0;
1191        let mut their_idx = 0;
1192
1193        while our_idx < our_lines.len() || their_idx < their_lines.len() {
1194            if our_idx >= our_lines.len() {
1195                // Only their lines left
1196                merged_lines.extend_from_slice(&their_lines[their_idx..]);
1197                break;
1198            } else if their_idx >= their_lines.len() {
1199                // Only our lines left
1200                merged_lines.extend_from_slice(&our_lines[our_idx..]);
1201                break;
1202            } else if our_lines[our_idx] == their_lines[their_idx] {
1203                // Same line - add once
1204                merged_lines.push(our_lines[our_idx]);
1205                our_idx += 1;
1206                their_idx += 1;
1207            } else {
1208                // Different lines - this might be too complex
1209                return Ok(None);
1210            }
1211        }
1212
1213        Ok(Some(merged_lines.join("\n")))
1214    }
1215
1216    /// Resolve import/dependency conflicts by sorting and merging
1217    fn resolve_import_conflict(
1218        &self,
1219        conflict: &ConflictRegion,
1220        file_path: &str,
1221    ) -> Result<Option<String>> {
1222        // Only apply to likely import sections in common file types
1223        let is_import_file = file_path.ends_with(".rs")
1224            || file_path.ends_with(".py")
1225            || file_path.ends_with(".js")
1226            || file_path.ends_with(".ts")
1227            || file_path.ends_with(".go")
1228            || file_path.ends_with(".java")
1229            || file_path.ends_with(".swift")
1230            || file_path.ends_with(".kt")
1231            || file_path.ends_with(".cs");
1232
1233        if !is_import_file {
1234            return Ok(None);
1235        }
1236
1237        let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1238        let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1239
1240        // Check if all lines look like imports/uses
1241        let our_imports = our_lines
1242            .iter()
1243            .all(|line| self.is_import_line(line, file_path));
1244        let their_imports = their_lines
1245            .iter()
1246            .all(|line| self.is_import_line(line, file_path));
1247
1248        if our_imports && their_imports {
1249            // Merge and sort imports
1250            let mut all_imports: Vec<&str> = our_lines.into_iter().chain(their_lines).collect();
1251            all_imports.sort();
1252            all_imports.dedup();
1253
1254            return Ok(Some(all_imports.join("\n")));
1255        }
1256
1257        Ok(None)
1258    }
1259
1260    /// Check if a line looks like an import statement
1261    fn is_import_line(&self, line: &str, file_path: &str) -> bool {
1262        let trimmed = line.trim();
1263
1264        if trimmed.is_empty() {
1265            return true; // Empty lines are OK in import sections
1266        }
1267
1268        if file_path.ends_with(".rs") {
1269            return trimmed.starts_with("use ") || trimmed.starts_with("extern crate");
1270        } else if file_path.ends_with(".py") {
1271            return trimmed.starts_with("import ") || trimmed.starts_with("from ");
1272        } else if file_path.ends_with(".js") || file_path.ends_with(".ts") {
1273            return trimmed.starts_with("import ")
1274                || trimmed.starts_with("const ")
1275                || trimmed.starts_with("require(");
1276        } else if file_path.ends_with(".go") {
1277            return trimmed.starts_with("import ") || trimmed == "import (" || trimmed == ")";
1278        } else if file_path.ends_with(".java") {
1279            return trimmed.starts_with("import ");
1280        } else if file_path.ends_with(".swift") {
1281            return trimmed.starts_with("import ") || trimmed.starts_with("@testable import ");
1282        } else if file_path.ends_with(".kt") {
1283            return trimmed.starts_with("import ") || trimmed.starts_with("@file:");
1284        } else if file_path.ends_with(".cs") {
1285            return trimmed.starts_with("using ") || trimmed.starts_with("extern alias ");
1286        }
1287
1288        false
1289    }
1290
1291    /// Normalize whitespace for comparison
1292    fn normalize_whitespace(&self, content: &str) -> String {
1293        content
1294            .lines()
1295            .map(|line| line.trim())
1296            .filter(|line| !line.is_empty())
1297            .collect::<Vec<_>>()
1298            .join("\n")
1299    }
1300
1301    /// Update a stack entry with new commit information
1302    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1303    fn update_stack_entry(
1304        &mut self,
1305        stack_id: Uuid,
1306        entry_id: &Uuid,
1307        _new_branch: &str,
1308        new_commit_hash: &str,
1309    ) -> Result<()> {
1310        debug!(
1311            "Updating entry {} in stack {} with new commit {}",
1312            entry_id, stack_id, new_commit_hash
1313        );
1314
1315        // Get the stack and update the entry
1316        let stack = self
1317            .stack_manager
1318            .get_stack_mut(&stack_id)
1319            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1320
1321        // Find and update the entry
1322        if let Some(entry) = stack.entries.iter_mut().find(|e| e.id == *entry_id) {
1323            debug!(
1324                "Found entry {} - updating commit from '{}' to '{}' (keeping original branch '{}')",
1325                entry_id, entry.commit_hash, new_commit_hash, entry.branch
1326            );
1327
1328            // CRITICAL: Keep the original branch name to preserve PR mapping
1329            // Only update the commit hash to point to the new rebased commit
1330            entry.commit_hash = new_commit_hash.to_string();
1331
1332            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1333
1334            debug!(
1335                "Successfully updated entry {} in stack {}",
1336                entry_id, stack_id
1337            );
1338            Ok(())
1339        } else {
1340            Err(CascadeError::config(format!(
1341                "Entry {entry_id} not found in stack {stack_id}"
1342            )))
1343        }
1344    }
1345
1346    /// Pull latest changes from remote
1347    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1348        info!("Pulling latest changes for branch {}", branch);
1349
1350        // First try to fetch (this might fail if no remote exists)
1351        match self.git_repo.fetch() {
1352            Ok(_) => {
1353                debug!("Fetch successful");
1354                // Now try to pull the specific branch
1355                match self.git_repo.pull(branch) {
1356                    Ok(_) => {
1357                        info!("Pull completed successfully for {}", branch);
1358                        Ok(())
1359                    }
1360                    Err(e) => {
1361                        warn!("Pull failed for {}: {}", branch, e);
1362                        // Don't fail the entire rebase for pull issues
1363                        Ok(())
1364                    }
1365                }
1366            }
1367            Err(e) => {
1368                warn!("Fetch failed: {}", e);
1369                // Don't fail if there's no remote configured
1370                Ok(())
1371            }
1372        }
1373    }
1374
1375    /// Check if rebase is in progress
1376    pub fn is_rebase_in_progress(&self) -> bool {
1377        // Check for git rebase state files
1378        let git_dir = self.git_repo.path().join(".git");
1379        git_dir.join("REBASE_HEAD").exists()
1380            || git_dir.join("rebase-merge").exists()
1381            || git_dir.join("rebase-apply").exists()
1382    }
1383
1384    /// Abort an in-progress rebase
1385    pub fn abort_rebase(&self) -> Result<()> {
1386        info!("Aborting rebase operation");
1387
1388        let git_dir = self.git_repo.path().join(".git");
1389
1390        // Clean up rebase state files
1391        if git_dir.join("REBASE_HEAD").exists() {
1392            std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1393                CascadeError::Git(git2::Error::from_str(&format!(
1394                    "Failed to clean rebase state: {e}"
1395                )))
1396            })?;
1397        }
1398
1399        if git_dir.join("rebase-merge").exists() {
1400            std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1401                CascadeError::Git(git2::Error::from_str(&format!(
1402                    "Failed to clean rebase-merge: {e}"
1403                )))
1404            })?;
1405        }
1406
1407        if git_dir.join("rebase-apply").exists() {
1408            std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1409                CascadeError::Git(git2::Error::from_str(&format!(
1410                    "Failed to clean rebase-apply: {e}"
1411                )))
1412            })?;
1413        }
1414
1415        info!("Rebase aborted successfully");
1416        Ok(())
1417    }
1418
1419    /// Continue an in-progress rebase after conflict resolution
1420    pub fn continue_rebase(&self) -> Result<()> {
1421        info!("Continuing rebase operation");
1422
1423        // Check if there are still conflicts
1424        if self.git_repo.has_conflicts()? {
1425            return Err(CascadeError::branch(
1426                "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1427            ));
1428        }
1429
1430        // Stage resolved files
1431        self.git_repo.stage_conflict_resolved_files()?;
1432
1433        info!("Rebase continued successfully");
1434        Ok(())
1435    }
1436
1437    /// Check if there's an in-progress cherry-pick operation
1438    fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1439        let git_dir = self.git_repo.path().join(".git");
1440        Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1441    }
1442
1443    /// Handle resuming an in-progress cherry-pick from a previous failed sync
1444    fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1445        use crate::cli::output::Output;
1446
1447        let git_dir = self.git_repo.path().join(".git");
1448
1449        Output::section("Resuming in-progress sync");
1450        println!();
1451        Output::info("Detected unfinished cherry-pick from previous sync");
1452        println!();
1453
1454        // Check if conflicts are resolved
1455        if self.git_repo.has_conflicts()? {
1456            let conflicted_files = self.git_repo.get_conflicted_files()?;
1457
1458            let result = RebaseResult {
1459                success: false,
1460                branch_mapping: HashMap::new(),
1461                conflicts: conflicted_files.clone(),
1462                new_commits: Vec::new(),
1463                error: Some(format!(
1464                    "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1465                    MANUAL CONFLICT RESOLUTION REQUIRED\n\
1466                    =====================================\n\n\
1467                    Conflicted files:\n{}\n\n\
1468                    Step 1: Analyze conflicts\n\
1469                    โ†’ Run: ca conflicts\n\
1470                    โ†’ Shows detailed conflict analysis\n\n\
1471                    Step 2: Resolve conflicts in your editor\n\
1472                    โ†’ Open conflicted files and edit them\n\
1473                    โ†’ Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1474                    โ†’ Keep the code you want\n\
1475                    โ†’ Save the files\n\n\
1476                    Step 3: Mark conflicts as resolved\n\
1477                    โ†’ Run: git add <resolved-files>\n\
1478                    โ†’ Or: git add -A (to stage all resolved files)\n\n\
1479                    Step 4: Complete the sync\n\
1480                    โ†’ Run: ca sync\n\
1481                    โ†’ Cascade will continue from where it left off\n\n\
1482                    Alternative: Abort and start over\n\
1483                    โ†’ Run: git cherry-pick --abort\n\
1484                    โ†’ Then: ca sync (starts fresh)",
1485                    conflicted_files.len(),
1486                    conflicted_files
1487                        .iter()
1488                        .map(|f| format!("  - {}", f))
1489                        .collect::<Vec<_>>()
1490                        .join("\n")
1491                )),
1492                summary: "Sync paused - conflicts need resolution".to_string(),
1493            };
1494
1495            return Ok(result);
1496        }
1497
1498        // Conflicts are resolved - continue the cherry-pick
1499        Output::info("Conflicts resolved, continuing cherry-pick...");
1500
1501        // Stage all resolved files
1502        self.git_repo.stage_conflict_resolved_files()?;
1503
1504        // Complete the cherry-pick by committing
1505        let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1506        let commit_message = if cherry_pick_msg_file.exists() {
1507            std::fs::read_to_string(&cherry_pick_msg_file)
1508                .unwrap_or_else(|_| "Resolved conflicts".to_string())
1509        } else {
1510            "Resolved conflicts".to_string()
1511        };
1512
1513        match self.git_repo.commit(&commit_message) {
1514            Ok(_new_commit_id) => {
1515                Output::success("Cherry-pick completed");
1516
1517                // Clean up cherry-pick state
1518                if git_dir.join("CHERRY_PICK_HEAD").exists() {
1519                    let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1520                }
1521                if cherry_pick_msg_file.exists() {
1522                    let _ = std::fs::remove_file(&cherry_pick_msg_file);
1523                }
1524
1525                println!();
1526                Output::info("Continuing with rest of stack...");
1527                println!();
1528
1529                // Now continue with the rest of the rebase
1530                // We need to restart the full rebase since we don't track which entry we were on
1531                self.rebase_with_force_push(stack)
1532            }
1533            Err(e) => {
1534                let result = RebaseResult {
1535                    success: false,
1536                    branch_mapping: HashMap::new(),
1537                    conflicts: Vec::new(),
1538                    new_commits: Vec::new(),
1539                    error: Some(format!(
1540                        "Failed to complete cherry-pick: {}\n\n\
1541                        This usually means:\n\
1542                        - Git index is locked (another process accessing repo)\n\
1543                        - File permissions issue\n\
1544                        - Disk space issue\n\n\
1545                        Recovery:\n\
1546                        1. Check if another Git operation is running\n\
1547                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1548                        3. Run 'git status' to check repo state\n\
1549                        4. Retry 'ca sync' after fixing the issue\n\n\
1550                        Or abort and start fresh:\n\
1551                        โ†’ Run: git cherry-pick --abort\n\
1552                        โ†’ Then: ca sync",
1553                        e
1554                    )),
1555                    summary: "Failed to complete cherry-pick".to_string(),
1556                };
1557
1558                Ok(result)
1559            }
1560        }
1561    }
1562}
1563
1564impl RebaseResult {
1565    /// Get a summary of the rebase operation
1566    pub fn get_summary(&self) -> String {
1567        if self.success {
1568            format!("โœ… {}", self.summary)
1569        } else {
1570            format!(
1571                "โŒ Rebase failed: {}",
1572                self.error.as_deref().unwrap_or("Unknown error")
1573            )
1574        }
1575    }
1576
1577    /// Check if any conflicts occurred
1578    pub fn has_conflicts(&self) -> bool {
1579        !self.conflicts.is_empty()
1580    }
1581
1582    /// Get the number of successful operations
1583    pub fn success_count(&self) -> usize {
1584        self.new_commits.len()
1585    }
1586}
1587
1588#[cfg(test)]
1589mod tests {
1590    use super::*;
1591    use std::path::PathBuf;
1592    use std::process::Command;
1593    use tempfile::TempDir;
1594
1595    #[allow(dead_code)]
1596    fn create_test_repo() -> (TempDir, PathBuf) {
1597        let temp_dir = TempDir::new().unwrap();
1598        let repo_path = temp_dir.path().to_path_buf();
1599
1600        // Initialize git repository
1601        Command::new("git")
1602            .args(["init"])
1603            .current_dir(&repo_path)
1604            .output()
1605            .unwrap();
1606        Command::new("git")
1607            .args(["config", "user.name", "Test"])
1608            .current_dir(&repo_path)
1609            .output()
1610            .unwrap();
1611        Command::new("git")
1612            .args(["config", "user.email", "test@test.com"])
1613            .current_dir(&repo_path)
1614            .output()
1615            .unwrap();
1616
1617        // Create initial commit
1618        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1619        Command::new("git")
1620            .args(["add", "."])
1621            .current_dir(&repo_path)
1622            .output()
1623            .unwrap();
1624        Command::new("git")
1625            .args(["commit", "-m", "Initial"])
1626            .current_dir(&repo_path)
1627            .output()
1628            .unwrap();
1629
1630        (temp_dir, repo_path)
1631    }
1632
1633    #[test]
1634    fn test_conflict_region_creation() {
1635        let region = ConflictRegion {
1636            start: 0,
1637            end: 50,
1638            start_line: 1,
1639            end_line: 3,
1640            our_content: "function test() {\n    return true;\n}".to_string(),
1641            their_content: "function test() {\n  return true;\n}".to_string(),
1642        };
1643
1644        assert_eq!(region.start_line, 1);
1645        assert_eq!(region.end_line, 3);
1646        assert!(region.our_content.contains("return true"));
1647        assert!(region.their_content.contains("return true"));
1648    }
1649
1650    #[test]
1651    fn test_rebase_strategies() {
1652        assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1653        assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1654    }
1655
1656    #[test]
1657    fn test_rebase_options() {
1658        let options = RebaseOptions::default();
1659        assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1660        assert!(!options.interactive);
1661        assert!(options.auto_resolve);
1662        assert_eq!(options.max_retries, 3);
1663    }
1664
1665    #[test]
1666    fn test_cleanup_guard_tracks_branches() {
1667        let mut guard = TempBranchCleanupGuard::new();
1668        assert!(guard.branches.is_empty());
1669
1670        guard.add_branch("test-branch-1".to_string());
1671        guard.add_branch("test-branch-2".to_string());
1672
1673        assert_eq!(guard.branches.len(), 2);
1674        assert_eq!(guard.branches[0], "test-branch-1");
1675        assert_eq!(guard.branches[1], "test-branch-2");
1676    }
1677
1678    #[test]
1679    fn test_cleanup_guard_prevents_double_cleanup() {
1680        use std::process::Command;
1681        use tempfile::TempDir;
1682
1683        // Create a temporary git repo
1684        let temp_dir = TempDir::new().unwrap();
1685        let repo_path = temp_dir.path();
1686
1687        Command::new("git")
1688            .args(["init"])
1689            .current_dir(repo_path)
1690            .output()
1691            .unwrap();
1692
1693        Command::new("git")
1694            .args(["config", "user.name", "Test"])
1695            .current_dir(repo_path)
1696            .output()
1697            .unwrap();
1698
1699        Command::new("git")
1700            .args(["config", "user.email", "test@test.com"])
1701            .current_dir(repo_path)
1702            .output()
1703            .unwrap();
1704
1705        // Create initial commit
1706        std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1707        Command::new("git")
1708            .args(["add", "."])
1709            .current_dir(repo_path)
1710            .output()
1711            .unwrap();
1712        Command::new("git")
1713            .args(["commit", "-m", "initial"])
1714            .current_dir(repo_path)
1715            .output()
1716            .unwrap();
1717
1718        let git_repo = GitRepository::open(repo_path).unwrap();
1719
1720        // Create a test branch
1721        git_repo.create_branch("test-temp", None).unwrap();
1722
1723        let mut guard = TempBranchCleanupGuard::new();
1724        guard.add_branch("test-temp".to_string());
1725
1726        // First cleanup should work
1727        guard.cleanup(&git_repo);
1728        assert!(guard.cleaned);
1729
1730        // Second cleanup should be a no-op (shouldn't panic)
1731        guard.cleanup(&git_repo);
1732        assert!(guard.cleaned);
1733    }
1734
1735    #[test]
1736    fn test_rebase_result() {
1737        let result = RebaseResult {
1738            success: true,
1739            branch_mapping: std::collections::HashMap::new(),
1740            conflicts: vec!["abc123".to_string()],
1741            new_commits: vec!["def456".to_string()],
1742            error: None,
1743            summary: "Test summary".to_string(),
1744        };
1745
1746        assert!(result.success);
1747        assert!(result.has_conflicts());
1748        assert_eq!(result.success_count(), 1);
1749    }
1750
1751    #[test]
1752    fn test_import_line_detection() {
1753        let (_temp_dir, repo_path) = create_test_repo();
1754        let git_repo = crate::git::GitRepository::open(&repo_path).unwrap();
1755        let stack_manager = crate::stack::StackManager::new(&repo_path).unwrap();
1756        let options = RebaseOptions::default();
1757        let rebase_manager = RebaseManager::new(stack_manager, git_repo, options);
1758
1759        // Test Swift import detection
1760        assert!(rebase_manager.is_import_line("import Foundation", "test.swift"));
1761        assert!(rebase_manager.is_import_line("@testable import MyModule", "test.swift"));
1762        assert!(!rebase_manager.is_import_line("class MyClass {", "test.swift"));
1763
1764        // Test Kotlin import detection
1765        assert!(rebase_manager.is_import_line("import kotlin.collections.*", "test.kt"));
1766        assert!(rebase_manager.is_import_line("@file:JvmName(\"Utils\")", "test.kt"));
1767        assert!(!rebase_manager.is_import_line("fun myFunction() {", "test.kt"));
1768
1769        // Test C# import detection
1770        assert!(rebase_manager.is_import_line("using System;", "test.cs"));
1771        assert!(rebase_manager.is_import_line("using System.Collections.Generic;", "test.cs"));
1772        assert!(rebase_manager.is_import_line("extern alias GridV1;", "test.cs"));
1773        assert!(!rebase_manager.is_import_line("namespace MyNamespace {", "test.cs"));
1774
1775        // Test empty lines are allowed in import sections
1776        assert!(rebase_manager.is_import_line("", "test.swift"));
1777        assert!(rebase_manager.is_import_line("   ", "test.kt"));
1778        assert!(rebase_manager.is_import_line("", "test.cs"));
1779    }
1780}