cascade_cli/stack/
rebase.rs

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