Claude
Skills
Sign in
Back

stacked-pr-rebase

Included with Lifetime
$97 forever

Rebase stacked PRs after parent PR is merged, preserving only your commits. Use when the user asks to "rebase my PR after parent merged", "update stacked PR", "fix PR after dependency merged", "cherry-pick my commits to new base", "sync stacked PR", or when a PR contains commits from a merged parent PR that need to be removed. Also trigger when the user mentions stacked PRs, dependent PRs, PR chains, or parent PR merges affecting their branch. Boundary: not for regular rebases onto main or resolving merge conflicts in non-stacked PRs.

Code Review

What this skill does


# Stacked PR Rebase

Automate rebasing of stacked PRs after their parent PR is merged. Identifies your commits, handles different merge types (regular, squash, rebase), and cherry-picks only your work onto the updated base.

## Core Principles

1. **Analyze Before Acting** - Always understand the dependency relationship and merge type before making changes
2. **Preserve User Work** - Only cherry-pick/rebase the user's own commits; never lose work
3. **Smart Detection** - Automatically detect parent PR and merge type when possible; ask user only when uncertain
4. **Handle Conflicts Gracefully** - Auto-resolve simple conflicts; ask user for complex semantic conflicts
5. **Safe Operations** - Always create backup branch; use `--force-with-lease`; require confirmation for force push
6. **Clear Reporting** - Show exactly what will happen before and after

## Quick Start

### Basic Usage

```
User: My PR depends on PR #123 which just got merged. Help me rebase.
```

Workflow:
1. Analyze current PR's commit history
2. Identify parent PR (from branch/commits analysis or ask user)
3. Detect how parent PR was merged (regular/squash/rebase)
4. Classify commits: "parent's" vs "your own"
5. Create backup branch
6. Cherry-pick your commits to updated base
7. Handle any conflicts
8. Force push with user confirmation
9. Generate summary report

### With Explicit Parent PR

```
User: Rebase my PR, parent was PR #456
```

## Workflow Overview

### Phase 1: Situation Analysis

Gather context about the current PR and identify the parent PR.

```bash
# Get current PR info
gh pr view <PR_NUMBER> --json number,title,headRefName,baseRefName,commits

# Find merge-base with target branch
git merge-base HEAD origin/<baseRefName>

# List commits from merge-base to HEAD
git log --oneline $(git merge-base HEAD origin/<baseRefName>)..HEAD

# Get recently merged PRs targeting the same base branch
gh pr list --state merged --base <baseRefName> --limit 20 \
  --json number,title,headRefName,mergeCommit,commits

# For stacked PRs (baseRefName != main/master):
# Find the PR whose head branch IS your base branch — that's likely the parent PR
gh pr list --state merged --head <baseRefName> --limit 5 \
  --json number,title,headRefName,mergeCommit,commits
```

**Detection Strategy (try in order):**

1. **Check commit containment** (most reliable for squash merge):
   - Get original commits from each recently merged PR via GitHub API
   - Check if current PR's commits **contain** those original commits
   - If current PR contains merged PR's original commits → that's the parent PR

   ```
   Merged PR #123 original commits (from API): A, B
   Current PR commits (from git log): A, B, C, D

   → Current PR contains A, B → Parent PR is #123
   → C, D are "your own" commits to keep
   ```

2. **Check branch relationship**: Look for branch naming patterns (e.g., `feature-x` → `feature-x-part2`)
3. **Check commit messages**: Look for PR references like `(#123)` in commit messages
4. **Ask user**: If no clear match, present candidates and ask

> **Note:** This strategy works regardless of how the parent PR was merged (regular, squash, or rebase), because we compare against the **original commits stored in GitHub API**, not against what's currently in main.

**Confidence Criteria:**

**Overlap formula:** `overlap = |parent_commits ∩ current_commits| / |parent_commits|` (ratio of parent PR's commits found in current branch). When parent PR has ≤3 commits, cap confidence at MEDIUM to require user confirmation.

| Confidence | Criteria | Action |
|------------|----------|--------|
| **HIGH** | Single candidate with overlap ≥80%; parent PR has >3 commits; SHAs match exactly | Proceed automatically, show classification for confirmation |
| **MEDIUM** | Multiple candidates; or overlap 50-79%; or parent PR has ≤3 commits; or branch naming suggests relationship | Present candidates with recommendation |
| **LOW** | Overlap <50%; or no commit overlap; only branch naming or commit message hints; or user's branch was rebased/amended | Must ask user before proceeding |

**Output (HIGH confidence):**
```
Situation Analysis:
- Current PR: #456 (feature-y)
- Base branch: main
- Parent PR: #123 (feature-x) - merged 2 hours ago
- Confidence: HIGH (2/2 parent commits found in current branch)
- Proceeding with PR #123 as parent. Review classification below before execution.
```

**Output (MEDIUM/LOW confidence) — Present Options:**

When confidence is not HIGH, present structured options to the user:

```
I found the following recently merged PRs that could be the parent of your PR #456:

1. PR #123 (feature-x) — merged 2h ago via squash
   - 2 of 5 commits match by SHA
   - Branch name suggests relationship
   → Recommended: most likely parent

2. PR #100 (refactor-auth) — merged 1d ago via rebase
   - 1 of 5 commits has matching message
   - No branch name relationship
   → Possible but less likely

3. None of the above — I'll specify the parent PR number manually

4. No parent PR — my branch was created directly from main
   (use regular rebase instead)

Which option? [1/2/3/4]
```

**When no candidates found:**
```
I couldn't automatically identify a parent PR for your PR #456.

Possible reasons:
- The parent PR was merged long ago (>20 recent merges)
- Your branch was force-pushed or rebased, changing commit SHAs
- The parent branch was deleted before merging

Options:
1. Enter the parent PR number manually
2. Show me ALL recently merged PRs so I can pick one
3. Skip parent detection — I'll manually specify which commits to keep

Which option? [1/2/3]
```

### Phase 2: Merge Type Detection

Determine how the parent PR was merged to choose the correct rebase strategy.

```bash
# Get parent PR's merge commit details
gh api graphql -f query='
{
  repository(owner: "<OWNER>", name: "<REPO>") {
    pullRequest(number: <PARENT_PR_NUMBER>) {
      mergeCommit {
        oid
        parents(first: 2) {
          nodes { oid }
        }
      }
      commits(first: 100) {
        nodes {
          commit { oid message }
        }
      }
    }
  }
}'
```

**Detection Logic:**

| Merge Type | Detection | Strategy |
|------------|-----------|----------|
| **Regular Merge** | `mergeCommit.parents` has 2 nodes | Cherry-pick own commits |
| **Squash Merge** | 1 parent + original commits not in main | Cherry-pick own commits |
| **Rebase Merge** | 1 parent + original commits rewritten in main | Cherry-pick own commits |

> **Note:** We use cherry-pick for ALL merge types for consistency and predictability.

```
Decision Tree:
                    mergeCommit.parents.length
                           │
            ┌──────────────┴──────────────┐
            │                              │
          2 parents                    1 parent
            │                              │
            ▼                              ▼
      REGULAR MERGE          Check if original commits in main
                                          │
                               ┌──────────┴──────────┐
                               │                      │
                          Not found            Found (rewritten)
                               │                      │
                               ▼                      ▼
                        SQUASH MERGE           REBASE MERGE
```

### Phase 3: Commit Classification

Identify which commits are "parent's" (to exclude) vs "your own" (to keep).

**Key Insight for Squash Merge:**
- The parent PR's original commits (A, B) still exist in your branch
- They were squashed in main, but GitHub API still has their SHAs
- Compare your branch commits against parent PR's original commits from API

```bash
# Get parent PR's original commits from GitHub API
# Note: GitHub REST API returns max 250 commits per page.
# For PRs with 250+ commits, paginate or fall back to manual selection.
gh api repos/<OWNER>/<REPO>/pulls/<PARENT_PR>/commits --paginate --jq '.[].sha'
# Output: aaa1111, bbb2222

# List 

Related in Code Review