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