cascade_cli/stack/
rebase.rs

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