cascade_cli/stack/
rebase.rs

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