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 && commits.len() == stack.entries.len() {
801                                        // These are the old pre-rebase versions of stack entries
802                                        // Safe to update working branch to new rebased top
803                                        debug!(
804                                            "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
805                                        );
806                                    } else {
807                                        // These are truly new commits not in the stack!
808                                        Output::error(format!(
809                                            "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
810                                            orig_branch,
811                                            commits.len()
812                                        ));
813                                        println!();
814                                        Output::sub_item(
815                                            "These commits would be lost if we proceed:",
816                                        );
817                                        for (i, commit) in commits.iter().take(5).enumerate() {
818                                            let message =
819                                                commit.summary().unwrap_or("(no message)");
820                                            Output::sub_item(format!(
821                                                "  {}. {} - {}",
822                                                i + 1,
823                                                &commit.id().to_string()[..8],
824                                                message
825                                            ));
826                                        }
827                                        if commits.len() > 5 {
828                                            Output::sub_item(format!(
829                                                "  ... and {} more",
830                                                commits.len() - 5
831                                            ));
832                                        }
833                                        println!();
834                                        Output::tip("Add these commits to the stack first:");
835                                        Output::bullet("Run: ca stack push");
836                                        Output::bullet("Then run: ca sync");
837                                        println!();
838
839                                        // Restore original branch before returning error
840                                        if let Some(ref orig) = original_branch_for_cleanup {
841                                            let _ = self.git_repo.checkout_branch_unsafe(orig);
842                                        }
843
844                                        return Err(CascadeError::validation(
845                                            format!(
846                                                "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
847                                                orig_branch, commits.len()
848                                            )
849                                        ));
850                                    }
851                                }
852                            }
853                        }
854
855                        // Safe to update - working branch matches top of stack or is behind
856                        debug!(
857                            "Updating working branch '{}' to match top of stack ({})",
858                            orig_branch,
859                            &top_commit[..8]
860                        );
861
862                        if let Err(e) = self
863                            .git_repo
864                            .update_branch_to_commit(orig_branch, &top_commit)
865                        {
866                            Output::warning(format!(
867                                "Could not update working branch '{}' to top of stack: {}",
868                                orig_branch, e
869                            ));
870                        }
871                    }
872                }
873
874                // Return to original working branch
875                // Use unsafe checkout to force it (we're in cleanup phase, no uncommitted changes)
876                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
877                    debug!(
878                        "Could not return to original branch '{}': {}",
879                        orig_branch, e
880                    );
881                    // Non-critical: User is left on base branch instead of working branch
882                }
883            } else {
884                // User was on base branch - this is unusual but valid
885                // Don't update base branch, just checkout back to it
886                debug!(
887                    "Skipping working branch update - user was on base branch '{}'",
888                    orig_branch
889                );
890                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
891                    debug!("Could not return to base branch '{}': {}", orig_branch, e);
892                }
893            }
894        }
895        // Note: Summary is now built inside the successful rebase block above (around line 745)
896        // If rebase failed, we'll have an error message but no summary
897
898        // Display result with proper formatting
899        print_blank();
900        if result.success {
901            Output::success(&result.summary);
902        } else {
903            // Display error with proper icon
904            let error_msg = result
905                .error
906                .as_deref()
907                .unwrap_or("Rebase failed for unknown reason");
908            Output::error(error_msg);
909        }
910
911        // Save the updated stack metadata to disk
912        self.stack_manager.save_to_disk()?;
913
914        // CRITICAL: Return error if rebase failed
915        // Don't return Ok(result) with result.success = false - that's confusing!
916        if !result.success {
917            // Before returning error, try to restore original branch
918            if let Some(ref orig_branch) = original_branch {
919                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
920                    debug!(
921                        "Could not return to original branch '{}' after error: {}",
922                        orig_branch, e
923                    );
924                }
925            }
926
927            // Include the detailed error message (which contains conflict info)
928            let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
929            return Err(CascadeError::Branch(detailed_error.to_string()));
930        }
931
932        Ok(result)
933    }
934
935    /// Interactive rebase with user input
936    fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
937        tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
938
939        let mut result = RebaseResult {
940            success: true,
941            branch_mapping: HashMap::new(),
942            conflicts: Vec::new(),
943            new_commits: Vec::new(),
944            error: None,
945            summary: String::new(),
946        };
947
948        println!("Interactive Rebase for Stack: {}", stack.name);
949        println!("   Base branch: {}", stack.base_branch);
950        println!("   Entries: {}", stack.entries.len());
951
952        if self.options.interactive {
953            println!("\nChoose action for each commit:");
954            println!("  (p)ick   - apply the commit");
955            println!("  (s)kip   - skip this commit");
956            println!("  (e)dit   - edit the commit message");
957            println!("  (q)uit   - abort the rebase");
958        }
959
960        // For now, automatically pick all commits
961        // In a real implementation, this would prompt the user
962        for entry in &stack.entries {
963            println!(
964                "  {} {} - {}",
965                entry.short_hash(),
966                entry.branch,
967                entry.short_message(50)
968            );
969
970            // Auto-pick for demo purposes
971            match self.cherry_pick_commit(&entry.commit_hash) {
972                Ok(new_commit) => result.new_commits.push(new_commit),
973                Err(_) => result.conflicts.push(entry.commit_hash.clone()),
974            }
975        }
976
977        result.summary = format!(
978            "Interactive rebase processed {} commits",
979            stack.entries.len()
980        );
981        Ok(result)
982    }
983
984    /// Cherry-pick a commit onto the current branch
985    fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
986        // Use the real cherry-pick implementation from GitRepository
987        let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
988
989        // Check for any leftover staged changes after successful cherry-pick
990        if let Ok(staged_files) = self.git_repo.get_staged_files() {
991            if !staged_files.is_empty() {
992                // CRITICAL: Must commit staged changes - if this fails, user gets checkout warning
993                let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
994                match self.git_repo.commit_staged_changes(&cleanup_message) {
995                    Ok(Some(_)) => {
996                        debug!(
997                            "Committed {} leftover staged files after cherry-pick",
998                            staged_files.len()
999                        );
1000                    }
1001                    Ok(None) => {
1002                        // Files were unstaged between check and commit - not critical
1003                        debug!("Staged files were cleared before commit");
1004                    }
1005                    Err(e) => {
1006                        // This is serious - staged files will remain and cause checkout warning
1007                        tracing::warn!(
1008                            "Failed to commit {} staged files after cherry-pick: {}. \
1009                             User may see checkout warning with staged changes.",
1010                            staged_files.len(),
1011                            e
1012                        );
1013                        // Don't fail the entire rebase for this - but user will need to handle staged files
1014                    }
1015                }
1016            }
1017        }
1018
1019        Ok(new_commit_hash)
1020    }
1021
1022    /// Attempt to automatically resolve conflicts
1023    fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
1024        debug!("Starting auto-resolve for commit {}", commit_hash);
1025
1026        // Check if there are actually conflicts
1027        let has_conflicts = self.git_repo.has_conflicts()?;
1028        debug!("has_conflicts() = {}", has_conflicts);
1029
1030        // Check if cherry-pick is in progress
1031        let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
1032        let cherry_pick_in_progress = cherry_pick_head.exists();
1033
1034        if !has_conflicts {
1035            debug!("No conflicts detected by Git index");
1036
1037            // If cherry-pick is in progress but no conflicts detected, something is wrong
1038            if cherry_pick_in_progress {
1039                tracing::debug!(
1040                    "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
1041                );
1042
1043                // Abort the cherry-pick to clean up
1044                let _ = std::process::Command::new("git")
1045                    .args(["cherry-pick", "--abort"])
1046                    .current_dir(self.git_repo.path())
1047                    .output();
1048
1049                return Err(CascadeError::Branch(format!(
1050                    "Cherry-pick failed for {} but Git index shows no conflicts. \
1051                     This usually means the cherry-pick was aborted or failed in an unexpected way. \
1052                     Please try manual resolution.",
1053                    &commit_hash[..8]
1054                )));
1055            }
1056
1057            return Ok(true);
1058        }
1059
1060        let conflicted_files = self.git_repo.get_conflicted_files()?;
1061
1062        if conflicted_files.is_empty() {
1063            debug!("Conflicted files list is empty");
1064            return Ok(true);
1065        }
1066
1067        debug!(
1068            "Found conflicts in {} files: {:?}",
1069            conflicted_files.len(),
1070            conflicted_files
1071        );
1072
1073        // Use the new conflict analyzer for detailed analysis
1074        let analysis = self
1075            .conflict_analyzer
1076            .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1077
1078        debug!(
1079            "Conflict analysis: {} total conflicts, {} auto-resolvable",
1080            analysis.total_conflicts, analysis.auto_resolvable_count
1081        );
1082
1083        // Display recommendations
1084        for recommendation in &analysis.recommendations {
1085            debug!("{}", recommendation);
1086        }
1087
1088        let mut resolved_count = 0;
1089        let mut resolved_files = Vec::new(); // Track which files were actually resolved
1090        let mut failed_files = Vec::new();
1091
1092        for file_analysis in &analysis.files {
1093            debug!(
1094                "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1095                file_analysis.file_path,
1096                file_analysis.auto_resolvable,
1097                file_analysis.conflicts.len()
1098            );
1099
1100            if file_analysis.auto_resolvable {
1101                match self.resolve_file_conflicts_enhanced(
1102                    &file_analysis.file_path,
1103                    &file_analysis.conflicts,
1104                ) {
1105                    Ok(ConflictResolution::Resolved) => {
1106                        resolved_count += 1;
1107                        resolved_files.push(file_analysis.file_path.clone());
1108                        debug!("Successfully resolved {}", file_analysis.file_path);
1109                    }
1110                    Ok(ConflictResolution::TooComplex) => {
1111                        debug!(
1112                            "{} too complex for auto-resolution",
1113                            file_analysis.file_path
1114                        );
1115                        failed_files.push(file_analysis.file_path.clone());
1116                    }
1117                    Err(e) => {
1118                        debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1119                        failed_files.push(file_analysis.file_path.clone());
1120                    }
1121                }
1122            } else {
1123                failed_files.push(file_analysis.file_path.clone());
1124                debug!(
1125                    "{} requires manual resolution ({} conflicts)",
1126                    file_analysis.file_path,
1127                    file_analysis.conflicts.len()
1128                );
1129            }
1130        }
1131
1132        if resolved_count > 0 {
1133            debug!(
1134                "Resolved {}/{} files",
1135                resolved_count,
1136                conflicted_files.len()
1137            );
1138            debug!("Resolved files: {:?}", resolved_files);
1139
1140            // CRITICAL: Only stage files that were successfully resolved
1141            // This prevents staging files that still have conflict markers
1142            let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1143            debug!("Staging {} files", file_paths.len());
1144            self.git_repo.stage_files(&file_paths)?;
1145            debug!("Files staged successfully");
1146        } else {
1147            debug!("No files were resolved (resolved_count = 0)");
1148        }
1149
1150        // Return true only if ALL conflicts were resolved
1151        let all_resolved = failed_files.is_empty();
1152
1153        debug!(
1154            "all_resolved = {}, failed_files = {:?}",
1155            all_resolved, failed_files
1156        );
1157
1158        if !all_resolved {
1159            debug!("{} files still need manual resolution", failed_files.len());
1160        }
1161
1162        debug!("Returning all_resolved = {}", all_resolved);
1163        Ok(all_resolved)
1164    }
1165
1166    /// Resolve conflicts using enhanced analysis
1167    fn resolve_file_conflicts_enhanced(
1168        &self,
1169        file_path: &str,
1170        conflicts: &[crate::git::ConflictRegion],
1171    ) -> Result<ConflictResolution> {
1172        let repo_path = self.git_repo.path();
1173        let full_path = repo_path.join(file_path);
1174
1175        // Read the file content with conflict markers
1176        let mut content = std::fs::read_to_string(&full_path)
1177            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1178
1179        if conflicts.is_empty() {
1180            return Ok(ConflictResolution::Resolved);
1181        }
1182
1183        tracing::debug!(
1184            "Resolving {} conflicts in {} using enhanced analysis",
1185            conflicts.len(),
1186            file_path
1187        );
1188
1189        let mut any_resolved = false;
1190
1191        // Process conflicts in reverse order to maintain string indices
1192        for conflict in conflicts.iter().rev() {
1193            match self.resolve_single_conflict_enhanced(conflict) {
1194                Ok(Some(resolution)) => {
1195                    // Replace the conflict region with the resolved content
1196                    let before = &content[..conflict.start_pos];
1197                    let after = &content[conflict.end_pos..];
1198                    content = format!("{before}{resolution}{after}");
1199                    any_resolved = true;
1200                    debug!(
1201                        "✅ Resolved {} conflict at lines {}-{} in {}",
1202                        format!("{:?}", conflict.conflict_type).to_lowercase(),
1203                        conflict.start_line,
1204                        conflict.end_line,
1205                        file_path
1206                    );
1207                }
1208                Ok(None) => {
1209                    debug!(
1210                        "⚠️  {} conflict at lines {}-{} in {} requires manual resolution",
1211                        format!("{:?}", conflict.conflict_type).to_lowercase(),
1212                        conflict.start_line,
1213                        conflict.end_line,
1214                        file_path
1215                    );
1216                    return Ok(ConflictResolution::TooComplex);
1217                }
1218                Err(e) => {
1219                    debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1220                    return Ok(ConflictResolution::TooComplex);
1221                }
1222            }
1223        }
1224
1225        if any_resolved {
1226            // Check if we resolved ALL conflicts in this file
1227            let remaining_conflicts = self.parse_conflict_markers(&content)?;
1228
1229            if remaining_conflicts.is_empty() {
1230                debug!(
1231                    "All conflicts resolved in {}, content length: {} bytes",
1232                    file_path,
1233                    content.len()
1234                );
1235
1236                // CRITICAL SAFETY CHECK: Don't write empty files!
1237                if content.trim().is_empty() {
1238                    tracing::warn!(
1239                        "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1240                        file_path
1241                    );
1242                    return Ok(ConflictResolution::TooComplex);
1243                }
1244
1245                // SAFETY: Create backup before writing resolved content
1246                let backup_path = full_path.with_extension("cascade-backup");
1247                if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1248                    debug!(
1249                        "Backup for {} (original: {} bytes, resolved: {} bytes)",
1250                        file_path,
1251                        original_content.len(),
1252                        content.len()
1253                    );
1254                    let _ = std::fs::write(&backup_path, original_content);
1255                }
1256
1257                // All conflicts resolved - write the file back atomically
1258                crate::utils::atomic_file::write_string(&full_path, &content)?;
1259
1260                debug!("Wrote {} bytes to {}", content.len(), file_path);
1261                return Ok(ConflictResolution::Resolved);
1262            } else {
1263                tracing::debug!(
1264                    "Partially resolved conflicts in {} ({} remaining)",
1265                    file_path,
1266                    remaining_conflicts.len()
1267                );
1268            }
1269        }
1270
1271        Ok(ConflictResolution::TooComplex)
1272    }
1273
1274    /// Helper to count whitespace consistency (lower is better)
1275    #[allow(dead_code)]
1276    fn count_whitespace_consistency(content: &str) -> usize {
1277        let mut inconsistencies = 0;
1278        let lines: Vec<&str> = content.lines().collect();
1279
1280        for line in &lines {
1281            // Check for mixed tabs and spaces
1282            if line.contains('\t') && line.contains(' ') {
1283                inconsistencies += 1;
1284            }
1285        }
1286
1287        // Penalize for inconsistencies
1288        lines.len().saturating_sub(inconsistencies)
1289    }
1290
1291    /// Clean up .cascade-backup files from the repository after successful conflict resolution
1292    fn cleanup_backup_files(&self) -> Result<()> {
1293        use std::fs;
1294        use std::path::Path;
1295
1296        let repo_path = self.git_repo.path();
1297
1298        // Recursively find and remove all .cascade-backup files
1299        fn remove_backups_recursive(dir: &Path) {
1300            if let Ok(entries) = fs::read_dir(dir) {
1301                for entry in entries.flatten() {
1302                    let path = entry.path();
1303
1304                    if path.is_dir() {
1305                        // Skip .git directory
1306                        if path.file_name().and_then(|n| n.to_str()) != Some(".git") {
1307                            remove_backups_recursive(&path);
1308                        }
1309                    } else if let Some(ext) = path.extension() {
1310                        if ext == "cascade-backup" {
1311                            debug!("Cleaning up backup file: {}", path.display());
1312                            if let Err(e) = fs::remove_file(&path) {
1313                                // Log but don't fail - backup cleanup is not critical
1314                                tracing::warn!(
1315                                    "Could not remove backup file {}: {}",
1316                                    path.display(),
1317                                    e
1318                                );
1319                            }
1320                        }
1321                    }
1322                }
1323            }
1324        }
1325
1326        remove_backups_recursive(repo_path);
1327        Ok(())
1328    }
1329
1330    /// Resolve a single conflict using enhanced analysis
1331    fn resolve_single_conflict_enhanced(
1332        &self,
1333        conflict: &crate::git::ConflictRegion,
1334    ) -> Result<Option<String>> {
1335        debug!(
1336            "Resolving {} conflict in {} (lines {}-{})",
1337            format!("{:?}", conflict.conflict_type).to_lowercase(),
1338            conflict.file_path,
1339            conflict.start_line,
1340            conflict.end_line
1341        );
1342
1343        use crate::git::ConflictType;
1344
1345        match conflict.conflict_type {
1346            ConflictType::Whitespace => {
1347                // SAFETY: Only resolve if the content is truly identical except for whitespace
1348                // Otherwise, it might be intentional formatting changes
1349                let our_normalized = conflict
1350                    .our_content
1351                    .split_whitespace()
1352                    .collect::<Vec<_>>()
1353                    .join(" ");
1354                let their_normalized = conflict
1355                    .their_content
1356                    .split_whitespace()
1357                    .collect::<Vec<_>>()
1358                    .join(" ");
1359
1360                if our_normalized == their_normalized {
1361                    // Content is identical - in cherry-pick context, ALWAYS prefer THEIRS
1362                    // CRITICAL: In cherry-pick, OURS=base branch, THEIRS=commit being applied
1363                    // We must keep the commit's changes (THEIRS), not the base (OURS)
1364                    // Otherwise we delete the user's code!
1365                    Ok(Some(conflict.their_content.clone()))
1366                } else {
1367                    // Content differs beyond whitespace - not safe to auto-resolve
1368                    debug!(
1369                        "Whitespace conflict has content differences - requires manual resolution"
1370                    );
1371                    Ok(None)
1372                }
1373            }
1374            ConflictType::LineEnding => {
1375                // Normalize to Unix line endings
1376                let normalized = conflict
1377                    .our_content
1378                    .replace("\r\n", "\n")
1379                    .replace('\r', "\n");
1380                Ok(Some(normalized))
1381            }
1382            ConflictType::PureAddition => {
1383                // CRITICAL: In cherry-pick, OURS=base, THEIRS=commit being applied
1384                // We must respect what the commit does (THEIRS), not what the base has (OURS)
1385
1386                if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1387                    // Base is empty, commit adds content → keep the addition
1388                    Ok(Some(conflict.their_content.clone()))
1389                } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1390                    // Base has content, commit removes it → keep it removed (empty)
1391                    Ok(Some(String::new()))
1392                } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1393                    // Both empty → keep empty
1394                    Ok(Some(String::new()))
1395                } else {
1396                    // Both sides have content - this could be:
1397                    // - Duplicate function definitions
1398                    // - Conflicting logic
1399                    // - Different implementations of same feature
1400                    // Too risky to auto-merge - require manual resolution
1401                    debug!(
1402                        "PureAddition conflict has content on both sides - requires manual resolution"
1403                    );
1404                    Ok(None)
1405                }
1406            }
1407            ConflictType::ImportMerge => {
1408                // SAFETY: Only merge simple single-line imports
1409                // Multi-line imports or complex cases require manual resolution
1410
1411                // Check if all imports are single-line and look like imports
1412                let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1413                let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1414
1415                // Verify all lines look like simple imports (heuristic check)
1416                let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1417                    let trimmed = line.trim();
1418                    trimmed.starts_with("import ")
1419                        || trimmed.starts_with("from ")
1420                        || trimmed.starts_with("use ")
1421                        || trimmed.starts_with("#include")
1422                        || trimmed.is_empty()
1423                });
1424
1425                if !all_simple {
1426                    debug!("ImportMerge contains non-import lines - requires manual resolution");
1427                    return Ok(None);
1428                }
1429
1430                // Merge and deduplicate imports
1431                let mut all_imports: Vec<&str> = our_lines
1432                    .into_iter()
1433                    .chain(their_lines)
1434                    .filter(|line| !line.trim().is_empty())
1435                    .collect();
1436                all_imports.sort();
1437                all_imports.dedup();
1438                Ok(Some(all_imports.join("\n")))
1439            }
1440            ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1441                // These require manual resolution
1442                Ok(None)
1443            }
1444        }
1445    }
1446
1447    /// Parse conflict markers from file content
1448    fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1449        let lines: Vec<&str> = content.lines().collect();
1450        let mut conflicts = Vec::new();
1451        let mut i = 0;
1452
1453        while i < lines.len() {
1454            if lines[i].starts_with("<<<<<<<") {
1455                // Found start of conflict
1456                let start_line = i + 1;
1457                let mut separator_line = None;
1458                let mut end_line = None;
1459
1460                // Find the separator and end
1461                for (j, line) in lines.iter().enumerate().skip(i + 1) {
1462                    if line.starts_with("=======") {
1463                        separator_line = Some(j + 1);
1464                    } else if line.starts_with(">>>>>>>") {
1465                        end_line = Some(j + 1);
1466                        break;
1467                    }
1468                }
1469
1470                if let (Some(sep), Some(end)) = (separator_line, end_line) {
1471                    // Calculate byte positions
1472                    let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1473                    let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1474
1475                    let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1476                    let their_content = lines[sep..(end - 1)].join("\n");
1477
1478                    conflicts.push(ConflictRegion {
1479                        start: start_pos,
1480                        end: end_pos,
1481                        start_line,
1482                        end_line: end,
1483                        our_content,
1484                        their_content,
1485                    });
1486
1487                    i = end;
1488                } else {
1489                    i += 1;
1490                }
1491            } else {
1492                i += 1;
1493            }
1494        }
1495
1496        Ok(conflicts)
1497    }
1498
1499    /// Update a stack entry with new commit information
1500    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1501    fn update_stack_entry(
1502        &mut self,
1503        stack_id: Uuid,
1504        entry_id: &Uuid,
1505        _new_branch: &str,
1506        new_commit_hash: &str,
1507    ) -> Result<()> {
1508        debug!(
1509            "Updating entry {} in stack {} with new commit {}",
1510            entry_id, stack_id, new_commit_hash
1511        );
1512
1513        // Get the stack and update the entry
1514        let stack = self
1515            .stack_manager
1516            .get_stack_mut(&stack_id)
1517            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1518
1519        // Get entry info before mutation
1520        let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1521
1522        if entry_exists {
1523            let old_hash = stack
1524                .entries
1525                .iter()
1526                .find(|e| e.id == *entry_id)
1527                .map(|e| e.commit_hash.clone())
1528                .unwrap();
1529
1530            debug!(
1531                "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1532                entry_id, old_hash, new_commit_hash
1533            );
1534
1535            // CRITICAL: Keep the original branch name to preserve PR mapping
1536            // Only update the commit hash to point to the new rebased commit using safe wrapper
1537            stack
1538                .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1539                .map_err(CascadeError::config)?;
1540
1541            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1542
1543            debug!(
1544                "Successfully updated entry {} in stack {}",
1545                entry_id, stack_id
1546            );
1547            Ok(())
1548        } else {
1549            Err(CascadeError::config(format!(
1550                "Entry {entry_id} not found in stack {stack_id}"
1551            )))
1552        }
1553    }
1554
1555    /// Pull latest changes from remote
1556    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1557        tracing::debug!("Pulling latest changes for branch {}", branch);
1558
1559        // First try to fetch (this might fail if no remote exists)
1560        match self.git_repo.fetch() {
1561            Ok(_) => {
1562                debug!("Fetch successful");
1563                // Now try to pull the specific branch
1564                match self.git_repo.pull(branch) {
1565                    Ok(_) => {
1566                        tracing::debug!("Pull completed successfully for {}", branch);
1567                        Ok(())
1568                    }
1569                    Err(e) => {
1570                        tracing::debug!("Pull failed for {}: {}", branch, e);
1571                        // Don't fail the entire rebase for pull issues
1572                        Ok(())
1573                    }
1574                }
1575            }
1576            Err(e) => {
1577                tracing::debug!("Fetch failed: {}", e);
1578                // Don't fail if there's no remote configured
1579                Ok(())
1580            }
1581        }
1582    }
1583
1584    /// Check if rebase is in progress
1585    pub fn is_rebase_in_progress(&self) -> bool {
1586        // Check for git rebase state files
1587        let git_dir = self.git_repo.path().join(".git");
1588        git_dir.join("REBASE_HEAD").exists()
1589            || git_dir.join("rebase-merge").exists()
1590            || git_dir.join("rebase-apply").exists()
1591    }
1592
1593    /// Abort an in-progress rebase
1594    pub fn abort_rebase(&self) -> Result<()> {
1595        tracing::debug!("Aborting rebase operation");
1596
1597        let git_dir = self.git_repo.path().join(".git");
1598
1599        // Clean up rebase state files
1600        if git_dir.join("REBASE_HEAD").exists() {
1601            std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1602                CascadeError::Git(git2::Error::from_str(&format!(
1603                    "Failed to clean rebase state: {e}"
1604                )))
1605            })?;
1606        }
1607
1608        if git_dir.join("rebase-merge").exists() {
1609            std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1610                CascadeError::Git(git2::Error::from_str(&format!(
1611                    "Failed to clean rebase-merge: {e}"
1612                )))
1613            })?;
1614        }
1615
1616        if git_dir.join("rebase-apply").exists() {
1617            std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1618                CascadeError::Git(git2::Error::from_str(&format!(
1619                    "Failed to clean rebase-apply: {e}"
1620                )))
1621            })?;
1622        }
1623
1624        tracing::debug!("Rebase aborted successfully");
1625        Ok(())
1626    }
1627
1628    /// Continue an in-progress rebase after conflict resolution
1629    pub fn continue_rebase(&self) -> Result<()> {
1630        tracing::debug!("Continuing rebase operation");
1631
1632        // Check if there are still conflicts
1633        if self.git_repo.has_conflicts()? {
1634            return Err(CascadeError::branch(
1635                "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1636            ));
1637        }
1638
1639        // Stage resolved files
1640        self.git_repo.stage_conflict_resolved_files()?;
1641
1642        tracing::debug!("Rebase continued successfully");
1643        Ok(())
1644    }
1645
1646    /// Check if there's an in-progress cherry-pick operation
1647    fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1648        let git_dir = self.git_repo.path().join(".git");
1649        Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1650    }
1651
1652    /// Handle resuming an in-progress cherry-pick from a previous failed sync
1653    fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1654        use crate::cli::output::Output;
1655
1656        let git_dir = self.git_repo.path().join(".git");
1657
1658        Output::section("Resuming in-progress sync");
1659        println!();
1660        Output::info("Detected unfinished cherry-pick from previous sync");
1661        println!();
1662
1663        // Check if conflicts are resolved
1664        if self.git_repo.has_conflicts()? {
1665            let conflicted_files = self.git_repo.get_conflicted_files()?;
1666
1667            let result = RebaseResult {
1668                success: false,
1669                branch_mapping: HashMap::new(),
1670                conflicts: conflicted_files.clone(),
1671                new_commits: Vec::new(),
1672                error: Some(format!(
1673                    "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1674                    MANUAL CONFLICT RESOLUTION REQUIRED\n\
1675                    =====================================\n\n\
1676                    Conflicted files:\n{}\n\n\
1677                    Step 1: Analyze conflicts\n\
1678                    → Run: ca conflicts\n\
1679                    → Shows detailed conflict analysis\n\n\
1680                    Step 2: Resolve conflicts in your editor\n\
1681                    → Open conflicted files and edit them\n\
1682                    → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1683                    → Keep the code you want\n\
1684                    → Save the files\n\n\
1685                    Step 3: Mark conflicts as resolved\n\
1686                    → Run: git add <resolved-files>\n\
1687                    → Or: git add -A (to stage all resolved files)\n\n\
1688                    Step 4: Complete the sync\n\
1689                    → Run: ca sync\n\
1690                    → Cascade will continue from where it left off\n\n\
1691                    Alternative: Abort and start over\n\
1692                    → Run: git cherry-pick --abort\n\
1693                    → Then: ca sync (starts fresh)",
1694                    conflicted_files.len(),
1695                    conflicted_files
1696                        .iter()
1697                        .map(|f| format!("  - {}", f))
1698                        .collect::<Vec<_>>()
1699                        .join("\n")
1700                )),
1701                summary: "Sync paused - conflicts need resolution".to_string(),
1702            };
1703
1704            return Ok(result);
1705        }
1706
1707        // Conflicts are resolved - continue the cherry-pick
1708        Output::info("Conflicts resolved, continuing cherry-pick...");
1709
1710        // Stage all resolved files
1711        self.git_repo.stage_conflict_resolved_files()?;
1712
1713        // Complete the cherry-pick by committing
1714        let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1715        let commit_message = if cherry_pick_msg_file.exists() {
1716            std::fs::read_to_string(&cherry_pick_msg_file)
1717                .unwrap_or_else(|_| "Resolved conflicts".to_string())
1718        } else {
1719            "Resolved conflicts".to_string()
1720        };
1721
1722        match self.git_repo.commit(&commit_message) {
1723            Ok(_new_commit_id) => {
1724                Output::success("Cherry-pick completed");
1725
1726                // Clean up cherry-pick state
1727                if git_dir.join("CHERRY_PICK_HEAD").exists() {
1728                    let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1729                }
1730                if cherry_pick_msg_file.exists() {
1731                    let _ = std::fs::remove_file(&cherry_pick_msg_file);
1732                }
1733
1734                println!();
1735                Output::info("Continuing with rest of stack...");
1736                println!();
1737
1738                // Now continue with the rest of the rebase
1739                // We need to restart the full rebase since we don't track which entry we were on
1740                self.rebase_with_force_push(stack)
1741            }
1742            Err(e) => {
1743                let result = RebaseResult {
1744                    success: false,
1745                    branch_mapping: HashMap::new(),
1746                    conflicts: Vec::new(),
1747                    new_commits: Vec::new(),
1748                    error: Some(format!(
1749                        "Failed to complete cherry-pick: {}\n\n\
1750                        This usually means:\n\
1751                        - Git index is locked (another process accessing repo)\n\
1752                        - File permissions issue\n\
1753                        - Disk space issue\n\n\
1754                        Recovery:\n\
1755                        1. Check if another Git operation is running\n\
1756                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1757                        3. Run 'git status' to check repo state\n\
1758                        4. Retry 'ca sync' after fixing the issue\n\n\
1759                        Or abort and start fresh:\n\
1760                        → Run: git cherry-pick --abort\n\
1761                        → Then: ca sync",
1762                        e
1763                    )),
1764                    summary: "Failed to complete cherry-pick".to_string(),
1765                };
1766
1767                Ok(result)
1768            }
1769        }
1770    }
1771}
1772
1773impl RebaseResult {
1774    /// Get a summary of the rebase operation
1775    pub fn get_summary(&self) -> String {
1776        if self.success {
1777            format!("✅ {}", self.summary)
1778        } else {
1779            format!(
1780                "❌ Rebase failed: {}",
1781                self.error.as_deref().unwrap_or("Unknown error")
1782            )
1783        }
1784    }
1785
1786    /// Check if any conflicts occurred
1787    pub fn has_conflicts(&self) -> bool {
1788        !self.conflicts.is_empty()
1789    }
1790
1791    /// Get the number of successful operations
1792    pub fn success_count(&self) -> usize {
1793        self.new_commits.len()
1794    }
1795}
1796
1797#[cfg(test)]
1798mod tests {
1799    use super::*;
1800    use std::path::PathBuf;
1801    use std::process::Command;
1802    use tempfile::TempDir;
1803
1804    #[allow(dead_code)]
1805    fn create_test_repo() -> (TempDir, PathBuf) {
1806        let temp_dir = TempDir::new().unwrap();
1807        let repo_path = temp_dir.path().to_path_buf();
1808
1809        // Initialize git repository
1810        Command::new("git")
1811            .args(["init"])
1812            .current_dir(&repo_path)
1813            .output()
1814            .unwrap();
1815        Command::new("git")
1816            .args(["config", "user.name", "Test"])
1817            .current_dir(&repo_path)
1818            .output()
1819            .unwrap();
1820        Command::new("git")
1821            .args(["config", "user.email", "test@test.com"])
1822            .current_dir(&repo_path)
1823            .output()
1824            .unwrap();
1825
1826        // Create initial commit
1827        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1828        Command::new("git")
1829            .args(["add", "."])
1830            .current_dir(&repo_path)
1831            .output()
1832            .unwrap();
1833        Command::new("git")
1834            .args(["commit", "-m", "Initial"])
1835            .current_dir(&repo_path)
1836            .output()
1837            .unwrap();
1838
1839        (temp_dir, repo_path)
1840    }
1841
1842    #[test]
1843    fn test_conflict_region_creation() {
1844        let region = ConflictRegion {
1845            start: 0,
1846            end: 50,
1847            start_line: 1,
1848            end_line: 3,
1849            our_content: "function test() {\n    return true;\n}".to_string(),
1850            their_content: "function test() {\n  return true;\n}".to_string(),
1851        };
1852
1853        assert_eq!(region.start_line, 1);
1854        assert_eq!(region.end_line, 3);
1855        assert!(region.our_content.contains("return true"));
1856        assert!(region.their_content.contains("return true"));
1857    }
1858
1859    #[test]
1860    fn test_rebase_strategies() {
1861        assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1862        assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1863    }
1864
1865    #[test]
1866    fn test_rebase_options() {
1867        let options = RebaseOptions::default();
1868        assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1869        assert!(!options.interactive);
1870        assert!(options.auto_resolve);
1871        assert_eq!(options.max_retries, 3);
1872    }
1873
1874    #[test]
1875    fn test_cleanup_guard_tracks_branches() {
1876        let mut guard = TempBranchCleanupGuard::new();
1877        assert!(guard.branches.is_empty());
1878
1879        guard.add_branch("test-branch-1".to_string());
1880        guard.add_branch("test-branch-2".to_string());
1881
1882        assert_eq!(guard.branches.len(), 2);
1883        assert_eq!(guard.branches[0], "test-branch-1");
1884        assert_eq!(guard.branches[1], "test-branch-2");
1885    }
1886
1887    #[test]
1888    fn test_cleanup_guard_prevents_double_cleanup() {
1889        use std::process::Command;
1890        use tempfile::TempDir;
1891
1892        // Create a temporary git repo
1893        let temp_dir = TempDir::new().unwrap();
1894        let repo_path = temp_dir.path();
1895
1896        Command::new("git")
1897            .args(["init"])
1898            .current_dir(repo_path)
1899            .output()
1900            .unwrap();
1901
1902        Command::new("git")
1903            .args(["config", "user.name", "Test"])
1904            .current_dir(repo_path)
1905            .output()
1906            .unwrap();
1907
1908        Command::new("git")
1909            .args(["config", "user.email", "test@test.com"])
1910            .current_dir(repo_path)
1911            .output()
1912            .unwrap();
1913
1914        // Create initial commit
1915        std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1916        Command::new("git")
1917            .args(["add", "."])
1918            .current_dir(repo_path)
1919            .output()
1920            .unwrap();
1921        Command::new("git")
1922            .args(["commit", "-m", "initial"])
1923            .current_dir(repo_path)
1924            .output()
1925            .unwrap();
1926
1927        let git_repo = GitRepository::open(repo_path).unwrap();
1928
1929        // Create a test branch
1930        git_repo.create_branch("test-temp", None).unwrap();
1931
1932        let mut guard = TempBranchCleanupGuard::new();
1933        guard.add_branch("test-temp".to_string());
1934
1935        // First cleanup should work
1936        guard.cleanup(&git_repo);
1937        assert!(guard.cleaned);
1938
1939        // Second cleanup should be a no-op (shouldn't panic)
1940        guard.cleanup(&git_repo);
1941        assert!(guard.cleaned);
1942    }
1943
1944    #[test]
1945    fn test_rebase_result() {
1946        let result = RebaseResult {
1947            success: true,
1948            branch_mapping: std::collections::HashMap::new(),
1949            conflicts: vec!["abc123".to_string()],
1950            new_commits: vec!["def456".to_string()],
1951            error: None,
1952            summary: "Test summary".to_string(),
1953        };
1954
1955        assert!(result.success);
1956        assert!(result.has_conflicts());
1957        assert_eq!(result.success_count(), 1);
1958    }
1959}