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