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