cascade_cli/stack/
rebase.rs

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