cascade_cli/stack/
rebase.rs

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