cascade_cli/stack/
rebase.rs

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