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