cascade_cli/stack/
rebase.rs

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