cascade_cli/stack/
rebase.rs

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