/rebase-stack:rebase-stack [--base <branch>] <branch1> <branch2> [branch3 ...]from rebase-stack
Rebases or reorders a stack of dependent PR branches, handling conflicts via sub-agent. Useful for maintaining clean Git branch chains across multiple PRs.
Ships in rebase-stack. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Rebase a chain of dependent branches in order. The first branch is rebased onto the base branch; each subsequent branch is rebased onto the previous (now-rebased) branch, keeping only that branch's own commits so nothing is duplicated.
The list you pass defines the target order and does not have to match the current chain — reordering is supported. Each branch's exclusion boundary is derived from where it actually forked, so moving a branch up or down the stack replays only its own commits. See Reordering for the extra steps a reorder needs.
Two shell scripts shipped with this skill do the mechanical work: rebase-stack.sh rewrites the local branches, and relink-stack.sh reconciles the GitHub stack and PR bases afterwards when the order changed. This skill calls them and, when the rebase pauses on a conflict, delegates the resolution to a sub-agent so the main context stays small.
Get the ordered branch list from $ARGUMENTS. The first branch is the bottom of the stack (closest to the base branch); each subsequent branch builds on the previous one. This is the target order — if it differs from the current chain, that's a reorder and the run will rewrite the stack's shape.
If no branches are supplied in $ARGUMENTS, infer the stack from the current branch.
Determine the base branch in this order:
--base <branch> if the user specifies one (it goes before the branch list)git config branch.<bottom>.parent, if set, still resolving to a commit, and not itself one of the stack branchesbin/base-branch if the script exists and is executablePass the result to both scripts as --base <branch> so they don't have to re-derive it.
gh stackThe repo may already track the chain as a GitHub stack (the gh stack extension). Ask it first:
gh stack view --json
gh-stack version, so inspect the JSON rather than assuming keys — expect a branch name, a PR number, and a merged/open status per entry. If the output includes the trunk/base branch itself as an entry, drop it: it's the rebase base, not part of the stack.current branch "X" is not part of a stack — fall back to the PR-walk below.gh: unknown command "stack" (extension not installed) — fall back to the PR-walk below.If gh stack view reports the trunk and the user passed --base, prefer the user's --base.
Get the current branch: git rev-parse --abbrev-ref HEAD.
Fetch all open PRs in one call:
gh pr list --state open --json number,headRefName,baseRefName --limit 200
Walk down to the bottom of the stack. Starting from the current branch, look up the PR whose headRefName matches it. If that PR's baseRefName is not the base branch, set current = baseRefName and repeat. Stop when baseRefName == base — that branch is the bottom.
If the current branch has no open PR, or no PR chain leads back to the base, ask the user for the stack rather than guessing.
Walk up from the bottom. Find the PR whose baseRefName equals the bottom branch — its headRefName is the next branch up. Repeat from each new branch until no PR has it as a base. That ordered list (bottom → top) is the stack.
If a branch is the base of more than one open PR, the stack forks. Stop, show the user the candidate branches, and ask which one to follow.
Show the inferred stack to the user with PR numbers — and note whether it came from gh stack or the PR walk — before running the rebase, so they can confirm or correct it.
If the requested order differs from the current chain, say so explicitly: list which branches move and what their new parents will be, and confirm before running. A reorder force-pushes a rewritten history to open PRs.
Run the pre-flight script with the branches bottom → top. Don't hand-write a shell loop for this step instead:
~/.claude/skills/rebase-stack/preflight-stack.sh <branch1> <branch2> [...]
It fetches each branch, creates a local branch from origin/<branch> where one is missing, and prints each branch's worktree and local/origin SHAs.
Exit 1 — a branch is neither on origin nor local. Ask the user; it may be misspelled or only exist on a fork.
Exit 5 — the branches under Needs worktree: have no worktree. Ask the user directly (in a plain message — do not use AskUserQuestion) before creating them. Wait for the user to confirm before proceeding.
How to create them depends on the project:
bin/worktree exists and is executable — use it, one branch at a time. If the project provides it, it likely sets up an isolated environment (DB, ports, env) and can take a few minutes per branch, so say that when asking, and don't run several in parallel against the same source data. Prefer it over git worktree add so tests can run with the full setup.git worktree add <path> <branch>, and tell the user the worktrees have no project environment set up, so tests may not be runnable in them.Once every branch has both a local ref and a worktree, proceed.
~/.claude/skills/rebase-stack/rebase-stack.sh --base <base-branch> <branch1> <branch2> [...]
The script will:
origin.git rebase --onto <new-base> <old-base> <branch>, and run it via git -C <worktree> (no cd required). <old-base> is the deepest merge-base between the branch and another branch below it, floored at its fork point from origin/<base>. The merge-base, not the other branch's tip: a branch has usually forked from an older commit of its parent, so the parent's tip is not an ancestor of it and can't be the boundary itself.branch.<branch>.parent) or precedes the branch in the list.↻ <branch> moves: <old parent> → <new parent> for any branch whose parent changes.4) — the symptom of a boundary that landed too far back.3) — the symptom of its commits having been absorbed into another branch.gh pr view --json state, falling back to git merge-base --is-ancestor). The next branch in the stack is then rebased onto origin/<base> directly while still excluding the merged branch's old commits.rebase skill: set branch.<branch>.parent to the branch it was rebased onto (the base branch for the bottom branch, the previous stack branch otherwise) and point refs/parent/<branch> at that commit. The config and ref are created if they don't already exist.--force-with-lease after each branch rebase, but only if the branch has an upstream. Branches without an upstream are rebased but left unpushed.$(git rev-parse --git-common-dir)/rebase-stack-state so it survives conflict pauses.Summary: block with one line per branch: its result (rebased, rebased with conflicts, up to date, or skipped (PR merged)), its own commit count, its push state (pushed, no upstream, or NOT in sync with upstream), and whether its net change matches the pre-rebase version. The net-change check compares a whitespace-insensitive git patch-id --stable of each file's diff before and after, so it lists the files whose change actually differs.Exit codes:
0 — done.1 — fatal error (e.g. a branch isn't in any worktree).2 — conflicts. State saved; resume after resolving.3 — a branch has no commits of its own. Nothing pushed; state saved. See Empty branches.4 — a branch would replay more commits than it owns. Nothing pushed; state saved. See Oversized replays.If the script exited with code 2, read its output to find the conflicting branch and worktree path.
First check the conflict is real. A wrong exclusion boundary produces conflicts that look like ordinary merge work but are the branch being replayed on top of itself, and a sub-agent will happily "resolve" dozens of duplicated commits. Two tells, both in the script's own output: the very first replayed commit conflicts, or the own commit(s) count on the → Rebasing line is far larger than the branch's real size. If either shows, stop, report the numbers to the user, and check the boundary — git -C <worktree> log --oneline $(git -C <worktree> merge-base <new-parent> <branch>)..<branch> is the count the branch should be replaying.
Once the conflict looks genuine, delegate the resolution to a sub-agent (via the Agent tool) so the main context stays small — don't read the conflicting files yourself. Spawn one sub-agent per conflicting branch with a prompt like the template below, filling in the branch name and worktree path:
Resolve the git rebase conflicts in the worktree at
<worktree>(branch<branch>), then drive the rebase to completion. Do not force-push and do not run anyrebase-stack.shcommand — stop once the rebase is clean.Loop until
git -C <worktree> statusshows no rebase in progress:
- List conflicting files:
git -C <worktree> diff --name-only --diff-filter=U.- Read each file and resolve the conflict, taking both sides into account — don't blindly pick one side. Understand the intent of each change and produce a result that incorporates both correctly.
- Stage resolved files:
git -C <worktree> add <file>.- Run tests related to the resolved files inside the worktree using a subshell so the parent shell's cwd never changes:
(cd <worktree> && <test command>). If tests fail due to your resolution, fix it. If failures look unrelated, verify by stashing:(cd <worktree> && git stash && <test command>; status=$?; git stash pop; exit $status)— failures present without your changes are pre-existing (note them and continue); failures only with your changes mean your resolution introduced the problem (investigate and fix).- Continue the rebase:
git -C <worktree> rebase --continue. If more conflicts surface, repeat from step 1.When the rebase is complete, report back a concise summary: each file you resolved with a one-line note on how, any edits you made outside the conflict hunks, which tests ran and their results, which related tests could not run and why, and anything ambiguous you had to make a judgement call on. End with a confidence rating (Low, Medium, or High) that the resolutions are correct and need no human review, plus one short sentence on the doubt when it isn't High.
When the sub-agent reports back, retain its summary — you'll need it for the Step 6 report. If it flagged an ambiguous conflict it had to guess at, surface that to the user now. Otherwise, resume the script:
~/.claude/skills/rebase-stack/rebase-stack.sh --continue
--continue force-pushes the just-finished branch (if it has an upstream), then proceeds to the next branch in the stack. If that branch also conflicts, the script exits 2 again — spawn a fresh sub-agent for it and repeat.
Repeat until the script prints ✅ Stacked rebase complete. If the script exits 3 or 4 instead, don't resolve anything — go to Empty branches or Oversized replays.
rebase-stack.sh rewrites local branches only. If the run changed the stack's order, the PR bases and the GitHub stack are now stale and must be reconciled — otherwise the PRs show wrong bases and wrong diffs. If the order didn't change, skip this step.
relink-stack.sh (shipped with this skill) does it. Pass the same branch list, bottom → top:
~/.claude/skills/rebase-stack/relink-stack.sh --base <base-branch> <branch-bottom> ... <branch-top>
It is a dry run by default: it prints each PR, the base it should have, and whether that's a change, then exits without touching anything. Show that plan to the user and confirm the CHANGE lines are the branches they expect to move. Then execute:
~/.claude/skills/rebase-stack/relink-stack.sh --base <base-branch> --yes <branch-bottom> ... <branch-top>
It unstacks the affected stack(s), runs gh stack link --base <base> <branches>, then re-reads gh pr list and verifies every base matches the target order, exiting non-zero if any don't.
Measured against a real 12-PR stack, not inferred from the help text:
gh stack link does reorder. Its help says "existing PRs are never removed," which reads as additive-only, but in practice it created a new stack containing all 12 PRs in the given order, migrated them off the old stack, and updated the one PR whose base needed changing. The old stack number disappeared. So link alone is usually enough.gh stack unstack can no-op while exiting 0. It printed ⚠ Some pull requests are queued for merge or have auto-merge enabled and remain stacked on GitHub / The stack was left in place, and returned success. Never assume the stack was dissolved because the command "worked" — a merged PR still sitting in the stack is enough to trigger this.gh pr list at the end and checks every base.gh pr edit <pr> --base <branch> is not an alternative for a stacked PR: it fails with Cannot change the base branch because the pull request is part of a stack.
--unstackThere is no gh stack list, and the stack number appears only in gh stack view --short (Stack #8899) — --json omits it, exposing only trunk, currentBranch, and branches. The script parses --short for this. It still can't see a stack that isn't tracked locally, so when the plan says Stacks to dissolve first: none detected but the PRs are stacked, import and read it:
(cd <worktree> && gh stack checkout <pr-number> && gh stack view --short)
Run that from the branch's own worktree. It prints failed to checkout ... already used by worktree for a branch checked out elsewhere; the import still succeeds and the view works. Then re-run with --unstack <stack-number> (comma-separate several). gh stack checkout also reveals the true membership — a stack that looks like 10 PRs from one worktree can be 12 once imported.
If link fails after an unstack succeeded, the PRs are left unstacked on GitHub. Bases are still set, so re-running the script rebuilds the stack; the script says so in that error path.
Don't plan around gh stack modify — an interactive TUI, not drivable by an agent. gh stack init creates a new stack rather than adjusting one, so it's also wrong here.
Build the report from the script's Summary: block and the sub-agents' summaries. Start with a table, one row per branch bottom → top: branch, PR number, result, push state, and conflicts (a short note on how each was resolved, or "none").
Below the table, list only what needs attention:
NOT in sync with upstream.Then give a confidence rating (Low, Medium, or High) that the conflict resolutions are correct and need no human review, for each branch that had conflicts. Base it on the sub-agent's own rating, lowered when its tests didn't run or a file's net change differs without a conflict. Branches that rebased cleanly with identical net change are High without a separate rating. When a rating isn't High, add one short sentence on the doubt behind it.
End with an overall rating (the lowest of the branches) and a final line: ✅ Stacked rebase complete.
To move a branch within the stack, pass the branches in the order you want. Nothing else changes — the exclusion boundaries come from where each branch forked, so the script replays each branch's own commits onto its new parent.
A reorder can destroy the moved branch's PR. Warn the user before starting.
When a branch moves down the stack, the branches that used to be below it end up containing it. Force-pushing one of those branches while the moved PR's base still points at it makes GitHub see "base contains head" and auto-close the PR as merged, then delete its remote branch — even though nothing reached the base branch.
Observed: moving branch
Abelow four integration branches closed A's PR as MERGED the instant branchB(one of those four) was force-pushed, and deletedorigin/A. A PR in that state cannot be reopened (can't be reopened because it was already merged), so its number, comments, and review history are gone; the only fix is a fresh PR.To avoid it, repoint the moved PR's base before any force-push. That needs the stack dissolved first (
gh pr edit --baseis refused for a stacked PR), and GitHub may refuse to unstack — see below. When it does, the loss is unavoidable: tell the user up front, then recreate the PR afterwards (gh pr create --base <new parent> --head <branch>, reusing the old title and body, and re-adding labels). No commits are ever at risk — only PR metadata.
Extra care for a reorder:
↻ moves: lines. They are the check that the script agrees with your intent. A branch you didn't expect to move signals the list is wrong — abort and re-derive it.relink-stack.sh.Exit 4 means the boundary the script derived gives the branch more commits than are actually missing from its new parent, so the rebase would replay commits the parent already has. Nothing was pushed. The cause is almost always a wrong branch order, or a stack whose real parent can't be identified from ancestry (see the "below" rule in Step 3) — set branch.<branch>.parent for the branch, or fix the order, and re-run.
The message prints both counts and a git log command for the commits the branch should own. Compare that list against the branch's PR; if the script's count is the right one and the parent genuinely carries duplicates of the branch's work, re-run with REBASE_STACK_ALLOW_OVERSIZED=1 to proceed anyway.
Exit 3 means a branch's commits were all already present in its new parent, so it has nothing of its own and its PR would show an empty diff. Nothing was pushed. Almost always this means the branch list was wrong — usually a branch further down absorbed commits that weren't its own.
Stop and investigate rather than pushing through:
git -C <worktree> log --oneline <new-parent>..<branch> (empty) and compare against its pre-rebase tip from --status.git -C <worktree> checkout -B <branch> <old-tip> — the script prints the exact command), fix the order, and start over. Any branch already force-pushed in this run needs restoring and re-pushing too.--continue, which pushes it and moves on.rebase-stack.sh never updates GitHub stack metadata or PR bases — relink-stack.sh (Step 5) is a separate command, not part of the rebase run.relink-stack.sh can't reliably discover stack numbers on its own (no gh stack list), so a reorder often needs --unstack <n> supplied by hand.gh stack unstack is refused by GitHub for PRs queued for merge or with auto-merge enabled (a merged PR still in the stack counts), and then leaves the whole stack in place while exiting 0.--abort aborts only the paused rebase, not the branches already rewritten in this run, and it drops the OLD_TIPS you'd need to recover them. Read --status before aborting.--continue always force-pushes BRANCHES[INDEX] before advancing. That's also how you resume mid-stack: point INDEX at an already-correct branch so the push is a no-op.~/.claude/skills/rebase-stack/rebase-stack.sh --status — show saved state, including OLD_TIPS (each branch's pre-rebase tip) and INDEX (the branch being worked on).~/.claude/skills/rebase-stack/rebase-stack.sh --abort — abort the paused rebase in its worktree and discard saved state. Does not undo rebases that already completed.git -C <worktree> checkout -B <branch> <old-tip>, taking <old-tip> from OLD_TIPS or git -C <worktree> reflog. Then force-push it if it was already pushed. Prefer checkout -B over reset --hard — it's equivalent here and survives sandboxes that block reset --hard.$(git rev-parse --git-common-dir)/rebase-stack-state so BRANCHES and OLD_TIPS describe the real current state, set INDEX to the last already-correct branch, set PARENT_NAME/PARENT_SHA for that branch, then run --continue.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ryanb/dotfiles --plugin rebase-stackOther plugins' skills for the same job