cascade_cli/stack/
rebase.rs

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