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        if let Some(ref orig_branch) = original_branch {
703            // CRITICAL: Never update the base branch! Only update working branches
704            if orig_branch != &target_base {
705                // Get the last entry's branch (top of stack)
706                if let Some(last_entry) = stack.entries.last() {
707                    let top_branch = &last_entry.branch;
708
709                    // SAFETY CHECK: Detect if working branch has commits beyond the last stack entry
710                    // If it does, we need to preserve them - don't force-update the working branch
711                    if let (Ok(working_head), Ok(top_commit)) = (
712                        self.git_repo.get_branch_head(orig_branch),
713                        self.git_repo.get_branch_head(top_branch),
714                    ) {
715                        // Check if working branch is ahead of top stack entry
716                        if working_head != top_commit {
717                            // Get commits between top of stack and working branch head
718                            if let Ok(commits) = self
719                                .git_repo
720                                .get_commits_between(&top_commit, &working_head)
721                            {
722                                if !commits.is_empty() {
723                                    // Check if these commits match the stack entry messages
724                                    // If so, they're likely old pre-rebase versions, not new work
725                                    let stack_messages: Vec<String> = stack
726                                        .entries
727                                        .iter()
728                                        .map(|e| e.message.trim().to_string())
729                                        .collect();
730
731                                    let all_match_stack = commits.iter().all(|commit| {
732                                        if let Some(msg) = commit.summary() {
733                                            stack_messages
734                                                .iter()
735                                                .any(|stack_msg| stack_msg == msg.trim())
736                                        } else {
737                                            false
738                                        }
739                                    });
740
741                                    if all_match_stack {
742                                        // These are the old pre-rebase versions of stack entries
743                                        // Safe to update working branch to new rebased top
744                                        // Note: commits.len() may be less than stack.entries.len() if only
745                                        // some entries were rebased (e.g., after amending one entry)
746                                        debug!(
747                                            "Working branch has old pre-rebase commits (matching stack messages) - safe to update"
748                                        );
749                                    } else {
750                                        // These are truly new commits not in the stack!
751                                        Output::error(format!(
752                                            "Cannot sync: Working branch '{}' has {} commit(s) not in the stack",
753                                            orig_branch,
754                                            commits.len()
755                                        ));
756                                        println!();
757                                        Output::sub_item(
758                                            "These commits would be lost if we proceed:",
759                                        );
760                                        for (i, commit) in commits.iter().take(5).enumerate() {
761                                            let message =
762                                                commit.summary().unwrap_or("(no message)");
763                                            Output::sub_item(format!(
764                                                "  {}. {} - {}",
765                                                i + 1,
766                                                &commit.id().to_string()[..8],
767                                                message
768                                            ));
769                                        }
770                                        if commits.len() > 5 {
771                                            Output::sub_item(format!(
772                                                "  ... and {} more",
773                                                commits.len() - 5
774                                            ));
775                                        }
776                                        println!();
777                                        Output::tip("Add these commits to the stack first:");
778                                        Output::bullet("Run: ca stack push");
779                                        Output::bullet("Then run: ca sync");
780                                        println!();
781
782                                        // Restore original branch before returning error
783                                        if let Some(ref orig) = original_branch_for_cleanup {
784                                            let _ = self.git_repo.checkout_branch_unsafe(orig);
785                                        }
786
787                                        return Err(CascadeError::validation(
788                                            format!(
789                                                "Working branch '{}' has {} untracked commit(s). Add them to the stack with 'ca stack push' before syncing.",
790                                                orig_branch, commits.len()
791                                            )
792                                        ));
793                                    }
794                                }
795                            }
796                        }
797
798                        // Safe to update - working branch matches top of stack or is behind
799                        debug!(
800                            "Updating working branch '{}' to match top of stack ({})",
801                            orig_branch,
802                            &top_commit[..8]
803                        );
804
805                        if let Err(e) = self
806                            .git_repo
807                            .update_branch_to_commit(orig_branch, &top_commit)
808                        {
809                            Output::warning(format!(
810                                "Could not update working branch '{}' to top of stack: {}",
811                                orig_branch, e
812                            ));
813                        }
814                    }
815                }
816
817                // Return to original working branch
818                // Use unsafe checkout to force it (we're in cleanup phase, no uncommitted changes)
819                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
820                    debug!(
821                        "Could not return to original branch '{}': {}",
822                        orig_branch, e
823                    );
824                    // Non-critical: User is left on base branch instead of working branch
825                }
826            } else {
827                // User was on base branch - this is unusual but valid
828                // Don't update base branch, just checkout back to it
829                debug!(
830                    "Skipping working branch update - user was on base branch '{}'",
831                    orig_branch
832                );
833                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
834                    debug!("Could not return to base branch '{}': {}", orig_branch, e);
835                }
836            }
837        }
838        // Note: Summary is now built inside the successful rebase block above (around line 745)
839        // If rebase failed, we'll have an error message but no summary
840
841        // Display result with proper formatting
842        println!();
843        if result.success {
844            Output::success(&result.summary);
845        } else {
846            // Display error with proper icon
847            let error_msg = result
848                .error
849                .as_deref()
850                .unwrap_or("Rebase failed for unknown reason");
851            Output::error(error_msg);
852        }
853
854        // Save the updated stack metadata to disk
855        self.stack_manager.save_to_disk()?;
856
857        // CRITICAL: Return error if rebase failed
858        // Don't return Ok(result) with result.success = false - that's confusing!
859        if !result.success {
860            // Before returning error, try to restore original branch
861            if let Some(ref orig_branch) = original_branch {
862                if let Err(e) = self.git_repo.checkout_branch_unsafe(orig_branch) {
863                    debug!(
864                        "Could not return to original branch '{}' after error: {}",
865                        orig_branch, e
866                    );
867                }
868            }
869
870            // Include the detailed error message (which contains conflict info)
871            let detailed_error = result.error.as_deref().unwrap_or("Rebase failed");
872            return Err(CascadeError::Branch(detailed_error.to_string()));
873        }
874
875        Ok(result)
876    }
877
878    /// Interactive rebase with user input
879    fn rebase_interactive(&mut self, stack: &Stack) -> Result<RebaseResult> {
880        tracing::debug!("Starting interactive rebase for stack '{}'", stack.name);
881
882        let mut result = RebaseResult {
883            success: true,
884            branch_mapping: HashMap::new(),
885            conflicts: Vec::new(),
886            new_commits: Vec::new(),
887            error: None,
888            summary: String::new(),
889        };
890
891        println!("Interactive Rebase for Stack: {}", stack.name);
892        println!("   Base branch: {}", stack.base_branch);
893        println!("   Entries: {}", stack.entries.len());
894
895        if self.options.interactive {
896            println!("\nChoose action for each commit:");
897            println!("  (p)ick   - apply the commit");
898            println!("  (s)kip   - skip this commit");
899            println!("  (e)dit   - edit the commit message");
900            println!("  (q)uit   - abort the rebase");
901        }
902
903        // For now, automatically pick all commits
904        // In a real implementation, this would prompt the user
905        for entry in &stack.entries {
906            println!(
907                "  {} {} - {}",
908                entry.short_hash(),
909                entry.branch,
910                entry.short_message(50)
911            );
912
913            // Auto-pick for demo purposes
914            match self.cherry_pick_commit(&entry.commit_hash) {
915                Ok(new_commit) => result.new_commits.push(new_commit),
916                Err(_) => result.conflicts.push(entry.commit_hash.clone()),
917            }
918        }
919
920        result.summary = format!(
921            "Interactive rebase processed {} commits",
922            stack.entries.len()
923        );
924        Ok(result)
925    }
926
927    /// Cherry-pick a commit onto the current branch
928    fn cherry_pick_commit(&self, commit_hash: &str) -> Result<String> {
929        // Use the real cherry-pick implementation from GitRepository
930        let new_commit_hash = self.git_repo.cherry_pick(commit_hash)?;
931
932        // Check for any leftover staged changes after successful cherry-pick
933        if let Ok(staged_files) = self.git_repo.get_staged_files() {
934            if !staged_files.is_empty() {
935                // CRITICAL: Must commit staged changes - if this fails, user gets checkout warning
936                let cleanup_message = format!("Cleanup after cherry-pick {}", &commit_hash[..8]);
937                match self.git_repo.commit_staged_changes(&cleanup_message) {
938                    Ok(Some(_)) => {
939                        debug!(
940                            "Committed {} leftover staged files after cherry-pick",
941                            staged_files.len()
942                        );
943                    }
944                    Ok(None) => {
945                        // Files were unstaged between check and commit - not critical
946                        debug!("Staged files were cleared before commit");
947                    }
948                    Err(e) => {
949                        // This is serious - staged files will remain and cause checkout warning
950                        tracing::warn!(
951                            "Failed to commit {} staged files after cherry-pick: {}. \
952                             User may see checkout warning with staged changes.",
953                            staged_files.len(),
954                            e
955                        );
956                        // Don't fail the entire rebase for this - but user will need to handle staged files
957                    }
958                }
959            }
960        }
961
962        Ok(new_commit_hash)
963    }
964
965    /// Attempt to automatically resolve conflicts
966    fn auto_resolve_conflicts(&self, commit_hash: &str) -> Result<bool> {
967        debug!("Starting auto-resolve for commit {}", commit_hash);
968
969        // Check if there are actually conflicts
970        let has_conflicts = self.git_repo.has_conflicts()?;
971        debug!("has_conflicts() = {}", has_conflicts);
972
973        // Check if cherry-pick is in progress
974        let cherry_pick_head = self.git_repo.path().join(".git").join("CHERRY_PICK_HEAD");
975        let cherry_pick_in_progress = cherry_pick_head.exists();
976
977        if !has_conflicts {
978            debug!("No conflicts detected by Git index");
979
980            // If cherry-pick is in progress but no conflicts detected, something is wrong
981            if cherry_pick_in_progress {
982                tracing::debug!(
983                    "CHERRY_PICK_HEAD exists but no conflicts in index - aborting cherry-pick"
984                );
985
986                // Abort the cherry-pick to clean up
987                let _ = std::process::Command::new("git")
988                    .args(["cherry-pick", "--abort"])
989                    .current_dir(self.git_repo.path())
990                    .output();
991
992                return Err(CascadeError::Branch(format!(
993                    "Cherry-pick failed for {} but Git index shows no conflicts. \
994                     This usually means the cherry-pick was aborted or failed in an unexpected way. \
995                     Please try manual resolution.",
996                    &commit_hash[..8]
997                )));
998            }
999
1000            return Ok(true);
1001        }
1002
1003        let conflicted_files = self.git_repo.get_conflicted_files()?;
1004
1005        if conflicted_files.is_empty() {
1006            debug!("Conflicted files list is empty");
1007            return Ok(true);
1008        }
1009
1010        debug!(
1011            "Found conflicts in {} files: {:?}",
1012            conflicted_files.len(),
1013            conflicted_files
1014        );
1015
1016        // Use the new conflict analyzer for detailed analysis
1017        let analysis = self
1018            .conflict_analyzer
1019            .analyze_conflicts(&conflicted_files, self.git_repo.path())?;
1020
1021        debug!(
1022            "Conflict analysis: {} total conflicts, {} auto-resolvable",
1023            analysis.total_conflicts, analysis.auto_resolvable_count
1024        );
1025
1026        // Display recommendations
1027        for recommendation in &analysis.recommendations {
1028            debug!("{}", recommendation);
1029        }
1030
1031        let mut resolved_count = 0;
1032        let mut resolved_files = Vec::new(); // Track which files were actually resolved
1033        let mut failed_files = Vec::new();
1034
1035        for file_analysis in &analysis.files {
1036            debug!(
1037                "Processing file: {} (auto_resolvable: {}, conflicts: {})",
1038                file_analysis.file_path,
1039                file_analysis.auto_resolvable,
1040                file_analysis.conflicts.len()
1041            );
1042
1043            if file_analysis.auto_resolvable {
1044                match self.resolve_file_conflicts_enhanced(
1045                    &file_analysis.file_path,
1046                    &file_analysis.conflicts,
1047                ) {
1048                    Ok(ConflictResolution::Resolved) => {
1049                        resolved_count += 1;
1050                        resolved_files.push(file_analysis.file_path.clone());
1051                        debug!("Successfully resolved {}", file_analysis.file_path);
1052                    }
1053                    Ok(ConflictResolution::TooComplex) => {
1054                        debug!(
1055                            "{} too complex for auto-resolution",
1056                            file_analysis.file_path
1057                        );
1058                        failed_files.push(file_analysis.file_path.clone());
1059                    }
1060                    Err(e) => {
1061                        debug!("Failed to resolve {}: {}", file_analysis.file_path, e);
1062                        failed_files.push(file_analysis.file_path.clone());
1063                    }
1064                }
1065            } else {
1066                failed_files.push(file_analysis.file_path.clone());
1067                debug!(
1068                    "{} requires manual resolution ({} conflicts)",
1069                    file_analysis.file_path,
1070                    file_analysis.conflicts.len()
1071                );
1072            }
1073        }
1074
1075        if resolved_count > 0 {
1076            debug!(
1077                "Resolved {}/{} files",
1078                resolved_count,
1079                conflicted_files.len()
1080            );
1081            debug!("Resolved files: {:?}", resolved_files);
1082
1083            // CRITICAL: Only stage files that were successfully resolved
1084            // This prevents staging files that still have conflict markers
1085            let file_paths: Vec<&str> = resolved_files.iter().map(|s| s.as_str()).collect();
1086            debug!("Staging {} files", file_paths.len());
1087            self.git_repo.stage_files(&file_paths)?;
1088            debug!("Files staged successfully");
1089        } else {
1090            debug!("No files were resolved (resolved_count = 0)");
1091        }
1092
1093        // Return true only if ALL conflicts were resolved
1094        let all_resolved = failed_files.is_empty();
1095
1096        debug!(
1097            "all_resolved = {}, failed_files = {:?}",
1098            all_resolved, failed_files
1099        );
1100
1101        if !all_resolved {
1102            debug!("{} files still need manual resolution", failed_files.len());
1103        }
1104
1105        debug!("Returning all_resolved = {}", all_resolved);
1106        Ok(all_resolved)
1107    }
1108
1109    /// Resolve conflicts using enhanced analysis
1110    fn resolve_file_conflicts_enhanced(
1111        &self,
1112        file_path: &str,
1113        conflicts: &[crate::git::ConflictRegion],
1114    ) -> Result<ConflictResolution> {
1115        let repo_path = self.git_repo.path();
1116        let full_path = repo_path.join(file_path);
1117
1118        // Read the file content with conflict markers
1119        let mut content = std::fs::read_to_string(&full_path)
1120            .map_err(|e| CascadeError::config(format!("Failed to read file {file_path}: {e}")))?;
1121
1122        if conflicts.is_empty() {
1123            return Ok(ConflictResolution::Resolved);
1124        }
1125
1126        tracing::debug!(
1127            "Resolving {} conflicts in {} using enhanced analysis",
1128            conflicts.len(),
1129            file_path
1130        );
1131
1132        let mut any_resolved = false;
1133
1134        // Process conflicts in reverse order to maintain string indices
1135        for conflict in conflicts.iter().rev() {
1136            match self.resolve_single_conflict_enhanced(conflict) {
1137                Ok(Some(resolution)) => {
1138                    // Replace the conflict region with the resolved content
1139                    let before = &content[..conflict.start_pos];
1140                    let after = &content[conflict.end_pos..];
1141                    content = format!("{before}{resolution}{after}");
1142                    any_resolved = true;
1143                    debug!(
1144                        "✅ Resolved {} conflict at lines {}-{} in {}",
1145                        format!("{:?}", conflict.conflict_type).to_lowercase(),
1146                        conflict.start_line,
1147                        conflict.end_line,
1148                        file_path
1149                    );
1150                }
1151                Ok(None) => {
1152                    debug!(
1153                        "⚠️  {} conflict at lines {}-{} in {} requires manual resolution",
1154                        format!("{:?}", conflict.conflict_type).to_lowercase(),
1155                        conflict.start_line,
1156                        conflict.end_line,
1157                        file_path
1158                    );
1159                    return Ok(ConflictResolution::TooComplex);
1160                }
1161                Err(e) => {
1162                    debug!("❌ Failed to resolve conflict in {}: {}", file_path, e);
1163                    return Ok(ConflictResolution::TooComplex);
1164                }
1165            }
1166        }
1167
1168        if any_resolved {
1169            // Check if we resolved ALL conflicts in this file
1170            let remaining_conflicts = self.parse_conflict_markers(&content)?;
1171
1172            if remaining_conflicts.is_empty() {
1173                debug!(
1174                    "All conflicts resolved in {}, content length: {} bytes",
1175                    file_path,
1176                    content.len()
1177                );
1178
1179                // CRITICAL SAFETY CHECK: Don't write empty files!
1180                if content.trim().is_empty() {
1181                    tracing::warn!(
1182                        "SAFETY CHECK: Resolved content for {} is empty! Aborting auto-resolution.",
1183                        file_path
1184                    );
1185                    return Ok(ConflictResolution::TooComplex);
1186                }
1187
1188                // SAFETY: Create backup before writing resolved content
1189                let backup_path = full_path.with_extension("cascade-backup");
1190                if let Ok(original_content) = std::fs::read_to_string(&full_path) {
1191                    debug!(
1192                        "Backup for {} (original: {} bytes, resolved: {} bytes)",
1193                        file_path,
1194                        original_content.len(),
1195                        content.len()
1196                    );
1197                    let _ = std::fs::write(&backup_path, original_content);
1198                }
1199
1200                // All conflicts resolved - write the file back atomically
1201                crate::utils::atomic_file::write_string(&full_path, &content)?;
1202
1203                debug!("Wrote {} bytes to {}", content.len(), file_path);
1204                return Ok(ConflictResolution::Resolved);
1205            } else {
1206                tracing::debug!(
1207                    "Partially resolved conflicts in {} ({} remaining)",
1208                    file_path,
1209                    remaining_conflicts.len()
1210                );
1211            }
1212        }
1213
1214        Ok(ConflictResolution::TooComplex)
1215    }
1216
1217    /// Helper to count whitespace consistency (lower is better)
1218    #[allow(dead_code)]
1219    fn count_whitespace_consistency(content: &str) -> usize {
1220        let mut inconsistencies = 0;
1221        let lines: Vec<&str> = content.lines().collect();
1222
1223        for line in &lines {
1224            // Check for mixed tabs and spaces
1225            if line.contains('\t') && line.contains(' ') {
1226                inconsistencies += 1;
1227            }
1228        }
1229
1230        // Penalize for inconsistencies
1231        lines.len().saturating_sub(inconsistencies)
1232    }
1233
1234    /// Clean up .cascade-backup files from the repository after successful conflict resolution
1235    fn cleanup_backup_files(&self) -> Result<()> {
1236        use std::fs;
1237        use std::path::Path;
1238
1239        let repo_path = self.git_repo.path();
1240
1241        // Recursively find and remove all .cascade-backup files
1242        fn remove_backups_recursive(dir: &Path) {
1243            if let Ok(entries) = fs::read_dir(dir) {
1244                for entry in entries.flatten() {
1245                    let path = entry.path();
1246
1247                    if path.is_dir() {
1248                        // Skip .git directory
1249                        if path.file_name().and_then(|n| n.to_str()) != Some(".git") {
1250                            remove_backups_recursive(&path);
1251                        }
1252                    } else if let Some(ext) = path.extension() {
1253                        if ext == "cascade-backup" {
1254                            debug!("Cleaning up backup file: {}", path.display());
1255                            if let Err(e) = fs::remove_file(&path) {
1256                                // Log but don't fail - backup cleanup is not critical
1257                                tracing::warn!(
1258                                    "Could not remove backup file {}: {}",
1259                                    path.display(),
1260                                    e
1261                                );
1262                            }
1263                        }
1264                    }
1265                }
1266            }
1267        }
1268
1269        remove_backups_recursive(repo_path);
1270        Ok(())
1271    }
1272
1273    /// Resolve a single conflict using enhanced analysis
1274    fn resolve_single_conflict_enhanced(
1275        &self,
1276        conflict: &crate::git::ConflictRegion,
1277    ) -> Result<Option<String>> {
1278        debug!(
1279            "Resolving {} conflict in {} (lines {}-{})",
1280            format!("{:?}", conflict.conflict_type).to_lowercase(),
1281            conflict.file_path,
1282            conflict.start_line,
1283            conflict.end_line
1284        );
1285
1286        use crate::git::ConflictType;
1287
1288        match conflict.conflict_type {
1289            ConflictType::Whitespace => {
1290                // SAFETY: Only resolve if the content is truly identical except for whitespace
1291                // Otherwise, it might be intentional formatting changes
1292                let our_normalized = conflict
1293                    .our_content
1294                    .split_whitespace()
1295                    .collect::<Vec<_>>()
1296                    .join(" ");
1297                let their_normalized = conflict
1298                    .their_content
1299                    .split_whitespace()
1300                    .collect::<Vec<_>>()
1301                    .join(" ");
1302
1303                if our_normalized == their_normalized {
1304                    // Content is identical - in cherry-pick context, ALWAYS prefer THEIRS
1305                    // CRITICAL: In cherry-pick, OURS=base branch, THEIRS=commit being applied
1306                    // We must keep the commit's changes (THEIRS), not the base (OURS)
1307                    // Otherwise we delete the user's code!
1308                    Ok(Some(conflict.their_content.clone()))
1309                } else {
1310                    // Content differs beyond whitespace - not safe to auto-resolve
1311                    debug!(
1312                        "Whitespace conflict has content differences - requires manual resolution"
1313                    );
1314                    Ok(None)
1315                }
1316            }
1317            ConflictType::LineEnding => {
1318                // Normalize to Unix line endings
1319                let normalized = conflict
1320                    .our_content
1321                    .replace("\r\n", "\n")
1322                    .replace('\r', "\n");
1323                Ok(Some(normalized))
1324            }
1325            ConflictType::PureAddition => {
1326                // CRITICAL: In cherry-pick, OURS=base, THEIRS=commit being applied
1327                // We must respect what the commit does (THEIRS), not what the base has (OURS)
1328
1329                if conflict.our_content.is_empty() && !conflict.their_content.is_empty() {
1330                    // Base is empty, commit adds content → keep the addition
1331                    Ok(Some(conflict.their_content.clone()))
1332                } else if conflict.their_content.is_empty() && !conflict.our_content.is_empty() {
1333                    // Base has content, commit removes it → keep it removed (empty)
1334                    Ok(Some(String::new()))
1335                } else if conflict.our_content.is_empty() && conflict.their_content.is_empty() {
1336                    // Both empty → keep empty
1337                    Ok(Some(String::new()))
1338                } else {
1339                    // Both sides have content - this could be:
1340                    // - Duplicate function definitions
1341                    // - Conflicting logic
1342                    // - Different implementations of same feature
1343                    // Too risky to auto-merge - require manual resolution
1344                    debug!(
1345                        "PureAddition conflict has content on both sides - requires manual resolution"
1346                    );
1347                    Ok(None)
1348                }
1349            }
1350            ConflictType::ImportMerge => {
1351                // SAFETY: Only merge simple single-line imports
1352                // Multi-line imports or complex cases require manual resolution
1353
1354                // Check if all imports are single-line and look like imports
1355                let our_lines: Vec<&str> = conflict.our_content.lines().collect();
1356                let their_lines: Vec<&str> = conflict.their_content.lines().collect();
1357
1358                // Verify all lines look like simple imports (heuristic check)
1359                let all_simple = our_lines.iter().chain(their_lines.iter()).all(|line| {
1360                    let trimmed = line.trim();
1361                    trimmed.starts_with("import ")
1362                        || trimmed.starts_with("from ")
1363                        || trimmed.starts_with("use ")
1364                        || trimmed.starts_with("#include")
1365                        || trimmed.is_empty()
1366                });
1367
1368                if !all_simple {
1369                    debug!("ImportMerge contains non-import lines - requires manual resolution");
1370                    return Ok(None);
1371                }
1372
1373                // Merge and deduplicate imports
1374                let mut all_imports: Vec<&str> = our_lines
1375                    .into_iter()
1376                    .chain(their_lines)
1377                    .filter(|line| !line.trim().is_empty())
1378                    .collect();
1379                all_imports.sort();
1380                all_imports.dedup();
1381                Ok(Some(all_imports.join("\n")))
1382            }
1383            ConflictType::Structural | ConflictType::ContentOverlap | ConflictType::Complex => {
1384                // These require manual resolution
1385                Ok(None)
1386            }
1387        }
1388    }
1389
1390    /// Parse conflict markers from file content
1391    fn parse_conflict_markers(&self, content: &str) -> Result<Vec<ConflictRegion>> {
1392        let lines: Vec<&str> = content.lines().collect();
1393        let mut conflicts = Vec::new();
1394        let mut i = 0;
1395
1396        while i < lines.len() {
1397            if lines[i].starts_with("<<<<<<<") {
1398                // Found start of conflict
1399                let start_line = i + 1;
1400                let mut separator_line = None;
1401                let mut end_line = None;
1402
1403                // Find the separator and end
1404                for (j, line) in lines.iter().enumerate().skip(i + 1) {
1405                    if line.starts_with("=======") {
1406                        separator_line = Some(j + 1);
1407                    } else if line.starts_with(">>>>>>>") {
1408                        end_line = Some(j + 1);
1409                        break;
1410                    }
1411                }
1412
1413                if let (Some(sep), Some(end)) = (separator_line, end_line) {
1414                    // Calculate byte positions
1415                    let start_pos = lines[..i].iter().map(|l| l.len() + 1).sum::<usize>();
1416                    let end_pos = lines[..end].iter().map(|l| l.len() + 1).sum::<usize>();
1417
1418                    let our_content = lines[(i + 1)..(sep - 1)].join("\n");
1419                    let their_content = lines[sep..(end - 1)].join("\n");
1420
1421                    conflicts.push(ConflictRegion {
1422                        start: start_pos,
1423                        end: end_pos,
1424                        start_line,
1425                        end_line: end,
1426                        our_content,
1427                        their_content,
1428                    });
1429
1430                    i = end;
1431                } else {
1432                    i += 1;
1433                }
1434            } else {
1435                i += 1;
1436            }
1437        }
1438
1439        Ok(conflicts)
1440    }
1441
1442    /// Update a stack entry with new commit information
1443    /// NOTE: We keep the original branch name to preserve PR mapping, only update commit hash
1444    fn update_stack_entry(
1445        &mut self,
1446        stack_id: Uuid,
1447        entry_id: &Uuid,
1448        _new_branch: &str,
1449        new_commit_hash: &str,
1450    ) -> Result<()> {
1451        debug!(
1452            "Updating entry {} in stack {} with new commit {}",
1453            entry_id, stack_id, new_commit_hash
1454        );
1455
1456        // Get the stack and update the entry
1457        let stack = self
1458            .stack_manager
1459            .get_stack_mut(&stack_id)
1460            .ok_or_else(|| CascadeError::config(format!("Stack {stack_id} not found")))?;
1461
1462        // Get entry info before mutation
1463        let entry_exists = stack.entries.iter().any(|e| e.id == *entry_id);
1464
1465        if entry_exists {
1466            let old_hash = stack
1467                .entries
1468                .iter()
1469                .find(|e| e.id == *entry_id)
1470                .map(|e| e.commit_hash.clone())
1471                .unwrap();
1472
1473            debug!(
1474                "Found entry {} - updating commit from '{}' to '{}' (keeping original branch)",
1475                entry_id, old_hash, new_commit_hash
1476            );
1477
1478            // CRITICAL: Keep the original branch name to preserve PR mapping
1479            // Only update the commit hash to point to the new rebased commit using safe wrapper
1480            stack
1481                .update_entry_commit_hash(entry_id, new_commit_hash.to_string())
1482                .map_err(CascadeError::config)?;
1483
1484            // Note: Stack will be saved by the caller (StackManager) after rebase completes
1485
1486            debug!(
1487                "Successfully updated entry {} in stack {}",
1488                entry_id, stack_id
1489            );
1490            Ok(())
1491        } else {
1492            Err(CascadeError::config(format!(
1493                "Entry {entry_id} not found in stack {stack_id}"
1494            )))
1495        }
1496    }
1497
1498    /// Pull latest changes from remote
1499    fn pull_latest_changes(&self, branch: &str) -> Result<()> {
1500        tracing::debug!("Pulling latest changes for branch {}", branch);
1501
1502        // First try to fetch (this might fail if no remote exists)
1503        match self.git_repo.fetch() {
1504            Ok(_) => {
1505                debug!("Fetch successful");
1506                // Now try to pull the specific branch
1507                match self.git_repo.pull(branch) {
1508                    Ok(_) => {
1509                        tracing::debug!("Pull completed successfully for {}", branch);
1510                        Ok(())
1511                    }
1512                    Err(e) => {
1513                        tracing::debug!("Pull failed for {}: {}", branch, e);
1514                        // Don't fail the entire rebase for pull issues
1515                        Ok(())
1516                    }
1517                }
1518            }
1519            Err(e) => {
1520                tracing::debug!("Fetch failed: {}", e);
1521                // Don't fail if there's no remote configured
1522                Ok(())
1523            }
1524        }
1525    }
1526
1527    /// Check if rebase is in progress
1528    pub fn is_rebase_in_progress(&self) -> bool {
1529        // Check for git rebase state files
1530        let git_dir = self.git_repo.path().join(".git");
1531        git_dir.join("REBASE_HEAD").exists()
1532            || git_dir.join("rebase-merge").exists()
1533            || git_dir.join("rebase-apply").exists()
1534    }
1535
1536    /// Abort an in-progress rebase
1537    pub fn abort_rebase(&self) -> Result<()> {
1538        tracing::debug!("Aborting rebase operation");
1539
1540        let git_dir = self.git_repo.path().join(".git");
1541
1542        // Clean up rebase state files
1543        if git_dir.join("REBASE_HEAD").exists() {
1544            std::fs::remove_file(git_dir.join("REBASE_HEAD")).map_err(|e| {
1545                CascadeError::Git(git2::Error::from_str(&format!(
1546                    "Failed to clean rebase state: {e}"
1547                )))
1548            })?;
1549        }
1550
1551        if git_dir.join("rebase-merge").exists() {
1552            std::fs::remove_dir_all(git_dir.join("rebase-merge")).map_err(|e| {
1553                CascadeError::Git(git2::Error::from_str(&format!(
1554                    "Failed to clean rebase-merge: {e}"
1555                )))
1556            })?;
1557        }
1558
1559        if git_dir.join("rebase-apply").exists() {
1560            std::fs::remove_dir_all(git_dir.join("rebase-apply")).map_err(|e| {
1561                CascadeError::Git(git2::Error::from_str(&format!(
1562                    "Failed to clean rebase-apply: {e}"
1563                )))
1564            })?;
1565        }
1566
1567        tracing::debug!("Rebase aborted successfully");
1568        Ok(())
1569    }
1570
1571    /// Continue an in-progress rebase after conflict resolution
1572    pub fn continue_rebase(&self) -> Result<()> {
1573        tracing::debug!("Continuing rebase operation");
1574
1575        // Check if there are still conflicts
1576        if self.git_repo.has_conflicts()? {
1577            return Err(CascadeError::branch(
1578                "Cannot continue rebase: there are unresolved conflicts. Resolve conflicts and stage files first.".to_string()
1579            ));
1580        }
1581
1582        // Stage resolved files
1583        self.git_repo.stage_conflict_resolved_files()?;
1584
1585        tracing::debug!("Rebase continued successfully");
1586        Ok(())
1587    }
1588
1589    /// Check if there's an in-progress cherry-pick operation
1590    fn has_in_progress_cherry_pick(&self) -> Result<bool> {
1591        let git_dir = self.git_repo.path().join(".git");
1592        Ok(git_dir.join("CHERRY_PICK_HEAD").exists())
1593    }
1594
1595    /// Handle resuming an in-progress cherry-pick from a previous failed sync
1596    fn handle_in_progress_cherry_pick(&mut self, stack: &Stack) -> Result<RebaseResult> {
1597        use crate::cli::output::Output;
1598
1599        let git_dir = self.git_repo.path().join(".git");
1600
1601        Output::section("Resuming in-progress sync");
1602        println!();
1603        Output::info("Detected unfinished cherry-pick from previous sync");
1604        println!();
1605
1606        // Check if conflicts are resolved
1607        if self.git_repo.has_conflicts()? {
1608            let conflicted_files = self.git_repo.get_conflicted_files()?;
1609
1610            let result = RebaseResult {
1611                success: false,
1612                branch_mapping: HashMap::new(),
1613                conflicts: conflicted_files.clone(),
1614                new_commits: Vec::new(),
1615                error: Some(format!(
1616                    "Cannot continue: {} file(s) still have unresolved conflicts\n\n\
1617                    MANUAL CONFLICT RESOLUTION REQUIRED\n\
1618                    =====================================\n\n\
1619                    Conflicted files:\n{}\n\n\
1620                    Step 1: Analyze conflicts\n\
1621                    → Run: ca conflicts\n\
1622                    → Shows detailed conflict analysis\n\n\
1623                    Step 2: Resolve conflicts in your editor\n\
1624                    → Open conflicted files and edit them\n\
1625                    → Remove conflict markers (<<<<<<, ======, >>>>>>)\n\
1626                    → Keep the code you want\n\
1627                    → Save the files\n\n\
1628                    Step 3: Mark conflicts as resolved\n\
1629                    → Run: git add <resolved-files>\n\
1630                    → Or: git add -A (to stage all resolved files)\n\n\
1631                    Step 4: Complete the sync\n\
1632                    → Run: ca sync\n\
1633                    → Cascade will continue from where it left off\n\n\
1634                    Alternative: Abort and start over\n\
1635                    → Run: git cherry-pick --abort\n\
1636                    → Then: ca sync (starts fresh)",
1637                    conflicted_files.len(),
1638                    conflicted_files
1639                        .iter()
1640                        .map(|f| format!("  - {}", f))
1641                        .collect::<Vec<_>>()
1642                        .join("\n")
1643                )),
1644                summary: "Sync paused - conflicts need resolution".to_string(),
1645            };
1646
1647            return Ok(result);
1648        }
1649
1650        // Conflicts are resolved - continue the cherry-pick
1651        Output::info("Conflicts resolved, continuing cherry-pick...");
1652
1653        // Stage all resolved files
1654        self.git_repo.stage_conflict_resolved_files()?;
1655
1656        // Complete the cherry-pick by committing
1657        let cherry_pick_msg_file = git_dir.join("CHERRY_PICK_MSG");
1658        let commit_message = if cherry_pick_msg_file.exists() {
1659            std::fs::read_to_string(&cherry_pick_msg_file)
1660                .unwrap_or_else(|_| "Resolved conflicts".to_string())
1661        } else {
1662            "Resolved conflicts".to_string()
1663        };
1664
1665        match self.git_repo.commit(&commit_message) {
1666            Ok(_new_commit_id) => {
1667                Output::success("Cherry-pick completed");
1668
1669                // Clean up cherry-pick state
1670                if git_dir.join("CHERRY_PICK_HEAD").exists() {
1671                    let _ = std::fs::remove_file(git_dir.join("CHERRY_PICK_HEAD"));
1672                }
1673                if cherry_pick_msg_file.exists() {
1674                    let _ = std::fs::remove_file(&cherry_pick_msg_file);
1675                }
1676
1677                println!();
1678                Output::info("Continuing with rest of stack...");
1679                println!();
1680
1681                // Now continue with the rest of the rebase
1682                // We need to restart the full rebase since we don't track which entry we were on
1683                self.rebase_with_force_push(stack)
1684            }
1685            Err(e) => {
1686                let result = RebaseResult {
1687                    success: false,
1688                    branch_mapping: HashMap::new(),
1689                    conflicts: Vec::new(),
1690                    new_commits: Vec::new(),
1691                    error: Some(format!(
1692                        "Failed to complete cherry-pick: {}\n\n\
1693                        This usually means:\n\
1694                        - Git index is locked (another process accessing repo)\n\
1695                        - File permissions issue\n\
1696                        - Disk space issue\n\n\
1697                        Recovery:\n\
1698                        1. Check if another Git operation is running\n\
1699                        2. Run 'rm -f .git/index.lock' if stale lock exists\n\
1700                        3. Run 'git status' to check repo state\n\
1701                        4. Retry 'ca sync' after fixing the issue\n\n\
1702                        Or abort and start fresh:\n\
1703                        → Run: git cherry-pick --abort\n\
1704                        → Then: ca sync",
1705                        e
1706                    )),
1707                    summary: "Failed to complete cherry-pick".to_string(),
1708                };
1709
1710                Ok(result)
1711            }
1712        }
1713    }
1714}
1715
1716impl RebaseResult {
1717    /// Get a summary of the rebase operation
1718    pub fn get_summary(&self) -> String {
1719        if self.success {
1720            format!("✅ {}", self.summary)
1721        } else {
1722            format!(
1723                "❌ Rebase failed: {}",
1724                self.error.as_deref().unwrap_or("Unknown error")
1725            )
1726        }
1727    }
1728
1729    /// Check if any conflicts occurred
1730    pub fn has_conflicts(&self) -> bool {
1731        !self.conflicts.is_empty()
1732    }
1733
1734    /// Get the number of successful operations
1735    pub fn success_count(&self) -> usize {
1736        self.new_commits.len()
1737    }
1738}
1739
1740#[cfg(test)]
1741mod tests {
1742    use super::*;
1743    use std::path::PathBuf;
1744    use std::process::Command;
1745    use tempfile::TempDir;
1746
1747    #[allow(dead_code)]
1748    fn create_test_repo() -> (TempDir, PathBuf) {
1749        let temp_dir = TempDir::new().unwrap();
1750        let repo_path = temp_dir.path().to_path_buf();
1751
1752        // Initialize git repository
1753        Command::new("git")
1754            .args(["init"])
1755            .current_dir(&repo_path)
1756            .output()
1757            .unwrap();
1758        Command::new("git")
1759            .args(["config", "user.name", "Test"])
1760            .current_dir(&repo_path)
1761            .output()
1762            .unwrap();
1763        Command::new("git")
1764            .args(["config", "user.email", "test@test.com"])
1765            .current_dir(&repo_path)
1766            .output()
1767            .unwrap();
1768
1769        // Create initial commit
1770        std::fs::write(repo_path.join("README.md"), "# Test").unwrap();
1771        Command::new("git")
1772            .args(["add", "."])
1773            .current_dir(&repo_path)
1774            .output()
1775            .unwrap();
1776        Command::new("git")
1777            .args(["commit", "-m", "Initial"])
1778            .current_dir(&repo_path)
1779            .output()
1780            .unwrap();
1781
1782        (temp_dir, repo_path)
1783    }
1784
1785    #[test]
1786    fn test_conflict_region_creation() {
1787        let region = ConflictRegion {
1788            start: 0,
1789            end: 50,
1790            start_line: 1,
1791            end_line: 3,
1792            our_content: "function test() {\n    return true;\n}".to_string(),
1793            their_content: "function test() {\n  return true;\n}".to_string(),
1794        };
1795
1796        assert_eq!(region.start_line, 1);
1797        assert_eq!(region.end_line, 3);
1798        assert!(region.our_content.contains("return true"));
1799        assert!(region.their_content.contains("return true"));
1800    }
1801
1802    #[test]
1803    fn test_rebase_strategies() {
1804        assert_eq!(RebaseStrategy::ForcePush, RebaseStrategy::ForcePush);
1805        assert_eq!(RebaseStrategy::Interactive, RebaseStrategy::Interactive);
1806    }
1807
1808    #[test]
1809    fn test_rebase_options() {
1810        let options = RebaseOptions::default();
1811        assert_eq!(options.strategy, RebaseStrategy::ForcePush);
1812        assert!(!options.interactive);
1813        assert!(options.auto_resolve);
1814        assert_eq!(options.max_retries, 3);
1815    }
1816
1817    #[test]
1818    fn test_cleanup_guard_tracks_branches() {
1819        let mut guard = TempBranchCleanupGuard::new();
1820        assert!(guard.branches.is_empty());
1821
1822        guard.add_branch("test-branch-1".to_string());
1823        guard.add_branch("test-branch-2".to_string());
1824
1825        assert_eq!(guard.branches.len(), 2);
1826        assert_eq!(guard.branches[0], "test-branch-1");
1827        assert_eq!(guard.branches[1], "test-branch-2");
1828    }
1829
1830    #[test]
1831    fn test_cleanup_guard_prevents_double_cleanup() {
1832        use std::process::Command;
1833        use tempfile::TempDir;
1834
1835        // Create a temporary git repo
1836        let temp_dir = TempDir::new().unwrap();
1837        let repo_path = temp_dir.path();
1838
1839        Command::new("git")
1840            .args(["init"])
1841            .current_dir(repo_path)
1842            .output()
1843            .unwrap();
1844
1845        Command::new("git")
1846            .args(["config", "user.name", "Test"])
1847            .current_dir(repo_path)
1848            .output()
1849            .unwrap();
1850
1851        Command::new("git")
1852            .args(["config", "user.email", "test@test.com"])
1853            .current_dir(repo_path)
1854            .output()
1855            .unwrap();
1856
1857        // Create initial commit
1858        std::fs::write(repo_path.join("test.txt"), "test").unwrap();
1859        Command::new("git")
1860            .args(["add", "."])
1861            .current_dir(repo_path)
1862            .output()
1863            .unwrap();
1864        Command::new("git")
1865            .args(["commit", "-m", "initial"])
1866            .current_dir(repo_path)
1867            .output()
1868            .unwrap();
1869
1870        let git_repo = GitRepository::open(repo_path).unwrap();
1871
1872        // Create a test branch
1873        git_repo.create_branch("test-temp", None).unwrap();
1874
1875        let mut guard = TempBranchCleanupGuard::new();
1876        guard.add_branch("test-temp".to_string());
1877
1878        // First cleanup should work
1879        guard.cleanup(&git_repo);
1880        assert!(guard.cleaned);
1881
1882        // Second cleanup should be a no-op (shouldn't panic)
1883        guard.cleanup(&git_repo);
1884        assert!(guard.cleaned);
1885    }
1886
1887    #[test]
1888    fn test_rebase_result() {
1889        let result = RebaseResult {
1890            success: true,
1891            branch_mapping: std::collections::HashMap::new(),
1892            conflicts: vec!["abc123".to_string()],
1893            new_commits: vec!["def456".to_string()],
1894            error: None,
1895            summary: "Test summary".to_string(),
1896        };
1897
1898        assert!(result.success);
1899        assert!(result.has_conflicts());
1900        assert_eq!(result.success_count(), 1);
1901    }
1902}