/agent-traffic-control:gh-pr-merge-worktree-checkout-trapfrom agent-traffic-control
Diagnose and bypass `gh pr merge --squash --delete-branch` failing with "failed to run git: fatal: 'main' is already used by worktree at ..." when another git worktree has main checked out. Use when: (1) you run gh pr merge and see this exact error, (2) you have multiple worktrees in the repo (e.g. `.claude/worktrees/*`), (3) the error appears even though the GitHub merge itself looks fine. The merge SUCCEEDED on GitHub — only gh's local-side effect (post-merge `git checkout main`) failed. Verify via `gh pr view N --json state,mergedAt`; if state=MERGED, you're done. This also applies to `gh pr checkout` and any other `gh` subcommand that tries to touch the local main branch while another worktree has it claimed. v1.2.0 (2026-05-26) adds the sequential-error variant: if you re-run from the main-repo worktree after the first error, you can then hit "cannot delete branch <feature-branch> used by worktree at <feature-worktree>" — same one-checkout-per-branch invariant, this time applied to the feature branch. Cleanup order: `git worktree remove` BEFORE `git branch -D`. v1.3.0 (2026-05-27) adds the `--auto --delete-branch` enable-time variant: when checks are still pending, `gh pr merge N --auto --squash --delete-branch` fails locally (same "main is already used by worktree" message) BEFORE the auto-merge intent is registered server-side — `gh pr view N --json autoMergeRequest` returns null. Workaround: drop `--delete-branch` (`gh pr merge N --auto --squash`), then `git worktree remove` + `git branch -D` manually after the merge lands. The post-merge variant in v1.0-1.2 succeeds the merge first then chokes on cleanup; this v1.3 variant chokes BEFORE the server-side enable, so verifying with `--json autoMergeRequest` (not just `state`) is required.
Trending skills
7-day visitors to each skill page
Ships in agent-traffic-control. 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.
None: SKILL.md is the whole skill.
gh pr merge Worktree-on-Main Checkout Trapgh pr merge --squash --delete-branch (and similar commands) fail with:
failed to run git: fatal: 'main' is already used by worktree at '/path/to/another/worktree'
even when the user has every right to merge the PR. The error makes it look like the merge failed, prompting the user to retry or panic.
The merge actually succeeded on GitHub. Only gh's post-merge local
side-effect — switching the local working tree to main so it's "ready"
after the merge — failed because git refuses to check out a branch that's
already checked out in another worktree.
You are in the right place if all of these are true:
gh pr merge <number> (any merge mode: --squash / --merge / --rebase).fatal: 'main' is already used by worktree at.git worktree entries (run git worktree list to confirm).main (or whichever branch the PR merged into).The command's first action is the GitHub merge API call; the local checkout is downstream of that. Failures in the local step do NOT roll back the merge.
gh pr view <number> --json state,mergedAt
# {"state":"MERGED","mergedAt":"YYYY-MM-DDTHH:MM:SSZ"}
If state is MERGED: the PR is merged. The error was a local cleanup
side-effect, not a merge failure. You can stop here. Optionally clean up
local artifacts:
# delete the remote branch (gh's --delete-branch flag also failed silently)
git push origin --delete <feature-branch-name>
# delete the local feature branch (it's already orphaned by the merge)
git branch -D <feature-branch-name>
# remove the worktree you used to develop the feature
git worktree remove .claude/worktrees/<your-feature-worktree>
# prune stale worktree refs
git worktree prune
If state is OPEN or CLOSED (without merge): something else went wrong.
The worktree error is masking a real failure. Re-run the merge with --admin
or check branch protection / required checks.
If you already know gh pr merge will fail — because you're always in a
worktree where main is locked — skip gh pr merge entirely and call the
GitHub REST API directly. This avoids the error and the verify-after dance:
gh api repos/<owner>/<repo>/pulls/<number>/merge \
--method PUT \
--field merge_method=squash \
--field commit_title="your squash commit title" \
--field commit_message="optional body"
Expected response on success:
{"sha":"<merge-commit-sha>","merged":true,"message":"Pull Request successfully merged"}
merge_method accepts squash, merge, or rebase. The commit_title and
commit_message fields only apply to the squash method.
Note: this form does NOT delete the remote branch — add a separate
gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/<branch> if needed,
or rely on the repo's auto-delete-head-branches setting.
If you frequently hit this, you have two options:
Option A — Don't keep a long-lived worktree on main. When you need to
sync local main, use a transient worktree (git worktree add /tmp/main main)
or just git fetch origin main from the feature worktree without checking it
out. This is the cleanest pattern.
Option B — Run gh from the worktree that already has main checked out.
That worktree's git is the one gh will succeed in checking out into.
Option C — Use gh api PUT directly (Step 1b above) instead of gh pr merge whenever you're in a long-lived worktree session. Two-liner, no
local checkout side-effect, no verify-after needed.
Most users won't bother with prevention — the post-failure gh pr view
verification is two seconds and the merge already worked.
gh pr view <number> --json state,mergedAt,mergeCommit
Expected after a "failed" merge that actually succeeded:
{
"state": "MERGED",
"mergedAt": "2026-04-27T15:04:53Z",
"mergeCommit": {"oid": "a4bd3004..."}
}
The presence of mergedAt and mergeCommit.oid confirms the merge landed.
Symptom (real-world, S109a 2026-04-27):
$ gh pr merge 122 --squash --delete-branch
failed to run git: fatal: 'main' is already used by worktree at '/Users/<user>/Documents/the-project-repo/.claude/worktrees/compassionate-ishizaka-b7e3b7'
I had ~40 worktrees in .claude/worktrees/ from previous parallel sessions,
one of which was on main. gh tried git checkout main after the merge,
git refused.
$ gh pr view 122 --json state,mergedAt
{"mergedAt":"2026-04-27T15:04:53Z","state":"MERGED"}
Resolution: the merge had succeeded; the error was just gh's local cleanup choking. Same trap fired again 10 minutes later on PR #123 — same root cause (the same long-lived worktree was still on main).
--delete-branch. Any post-merge action that
switches branches will hit it. The --delete-branch portion does seem to
also fail silently when the local checkout fails, so manually delete the
remote branch with git push origin --delete <branch> or
gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/<branch> after.base of an open dependent stacked PR
(PR2 was opened with --base <PR1-branch> instead of --base main),
using gh api -X DELETE on the ref will silently auto-close the dependent
PR and the close is not reversible — gh pr reopen and gh pr edit --base main both fail because the base no longer exists. See
stacked-pr-base-branch-deletion-auto-closes-dependent
for the recovery (open a fresh PR) and the prevention pattern (retarget
the dependent PR to main BEFORE deleting the base branch, OR merge both
PRs before any cleanup).gh api -X DELETE …/refs/heads/<branch> cleanup above is
ONLY safe once the merge is confirmed landed. If the gh pr merge returned
a transient GraphQL error — e.g. "Base branch was modified. Review and try
the merge again." (common right after you push a follow-up commit and
GitHub is mid-recompute) — the PR is still OPEN and UNMERGED. Deleting its
head ref at that point auto-closes the PR unmerged (and the branch is
gone, so a naive gh pr reopen fails until you re-push the branch). This is
the same auto-close mechanism as the stacked-PR warning above, but applied to
the PR's own head, not a dependent's base. Do not bundle the ref-delete in
the same command block as the merge — that's how it runs unconditionally
after a failed merge. Gate it:
gh pr merge <n> --squash # NO --delete-branch (it half-runs on error)
test "$(gh pr view <n> --json mergedAt --jq .mergedAt)" != "null" \
&& gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/<branch> # only if merged
Recovery if you already deleted the head of an unmerged PR: git push -u origin <branch> (re-creates the ref from your still-intact local commits) →
gh pr reopen <n> → gh pr merge <n> --squash (no --delete-branch) →
verify mergedAt → THEN delete the ref. Nothing is lost as long as the local
branch still holds the commits.gh pr checkout <number> if the target branch is
already checked out elsewhere.failed to delete local branch <feature-branch>: failed to run git: error:
cannot delete branch '<feature-branch>' used by worktree at '<feature-worktree>'
The PR is already merged at this point (gh's "already merged" message
precedes the error). The local cleanup is failing because the FEATURE
worktree still has the feature branch checked out. Recovery order
matters — clean up in this sequence from the main-repo worktree:
git fetch origin
git pull --ff-only # sync main locally
git worktree remove ../<feature-worktree> # release the branch
git branch -D <feature-branch> # now safe to delete
If you swap steps 3 and 4, the branch-delete fails for the same reason
the second error fired. The first error ("'main' is already used by
worktree") and this second error ("cannot delete branch ... used by
worktree") are symmetric instances of the same one-checkout-per-branch
invariant — first applied to main, then applied to the feature branch.git worktree list is the diagnostic — find the worktree on main and
decide whether to keep it.--auto --delete-branch enable-time variant (v1.3, S19 2026-05-27):
the v1.0-1.2 variants all describe a POST-merge cleanup failure where
the GitHub merge already succeeded. There is a sibling PRE-merge
variant when checks are still pending:
$ gh pr merge 88 --auto --squash --delete-branch
failed to run git: fatal: 'main' is already used by worktree at '...'
This time the local --delete-branch cleanup attempt fires BEFORE the
auto-merge intent is registered server-side. gh pr view N --json autoMergeRequest returns null (no auto-merge enabled) AND the PR
isn't merged. Workaround: re-run without --delete-branch:
gh pr merge 88 --auto --squash
# then verify
gh pr view 88 --json autoMergeRequest,state
Auto-merge enables; when checks pass the PR merges; then delete the
worktree + branch manually:
git worktree remove .claude/worktrees/<feature-worktree>
git branch -D <feature-branch> # may already be auto-deleted on
# remote depending on repo setting
Diagnostic difference from v1.0-1.2: with the post-merge variant,
gh pr view N --json state returns MERGED. With this enable-time
variant, state is still OPEN AND autoMergeRequest is null.
Always check BOTH fields before concluding the PR is done.When the post-merge local checkout fails, --delete-branch's remote deletion can also be
skipped — git ls-remote origin <branch> still shows the ref even though the PR reports MERGED.
Two downstream consequences observed:
<sha> "on main"
when it is NOT an ancestor of main — it only resolves via the leftover branch and goes dead
the moment someone prunes. Annotate such SHAs ("pre-squash branch commit, not on main") or
cite the PR number instead.gh api -X DELETE repos/<owner>/<repo>/git/refs/heads/<branch>
git ls-remote origin <branch> | wc -l # expect 0
After ANY gh pr merge --delete-branch that printed the worktree error, check the remote ref —
don't assume only the local checkout failed.
git worktree docs: git-worktree(1) — explains the
one-checkout-per-branch invariant that produces this error.gh pr merge source: github.com/cli/cli — the local checkout
step is wrapped around the GitHub API merge call; failures in the wrapper
do not roll back the API call.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub wan-huiyan/agent-traffic-control --plugin agent-traffic-control118 skills in this plugin
/agent-refusal-with-evidence-beats-literal-complianceA dispatched agent that does exactly what you asked can ship a defect you would
have stopped yourself, because it can see something at the worksite that you
could not see when you wrote the brief. Use when: (1) you are writing a brief
that prescribes a specific fix, threshold, wording or value rather than the
outcome you want; (2) an agent reports that it did not do what you asked and
you are deciding whether that is insubordination or judgement; (3) an agent
asserts "this is fine" or "not needed" with no measurement behind it; (4) you
are reviewing overnight output and want to know which decisions were checked
and which were assumed. Two halves, and both are needed: give the agent
explicit permission to satisfy the INTENT of an instruction while refusing its
letter, and REQUIRE the evidence with the refusal — what it built or measured,
what that showed, what it did instead. Evidence is the whole difference between
a refusal you can bank and one you have to re-litigate. Four agents correctly
declined an instruction in a single run; one built the suggested fix, measured
that it turned a silent safe refusal into a permanently red pipeline, and
reverted it unpushed.
/auto-merge-rearms-while-agent-live-kill-then-disarm-verifyDisarming auto-merge on a PR whose agent is still running does not hold it —
the agent re-arms within minutes and the PR merges, because arming is a step in
the agent's brief and disarming is not an instruction to the agent at all. Use
when: (1) you want to STOP a pull request from merging that an agent opened and
armed, for review, for a rethink, or because it is landing into a queue you are
trying to drain; (2) a PR you disarmed merged anyway; (3) you are telling agents
which PRs are on hold and want the hold to be enforced rather than announced;
(4) you are about to run `gh pr merge --disable-auto` and have not decided what
to do about the agent. The order is KILL THE AGENT FIRST, THEN DISARM, THEN
VERIFY the disarm by reading `autoMergeRequest` back — a disarm you did not read
back is not a hold. The stronger form needs no ordering at all: convert the PR
to a draft with `gh pr ready --undo`. A draft cannot merge whatever any agent
does to it, so the hold survives an agent you missed, an agent that restarts,
and an agent you did not know about.
/batch-member-cites-a-path-only-a-non-member-addsYou wrote something correct that the default reader cannot reach: a batch member citing a
path only a NON-member adds, or a rule, ruling or ledger sitting on an unlanded branch.
/batch-merge-subject-is-not-evidence-a-member-landedYou are about to close, delete the branch of, or mark as landed a pull
request because a batch, roll-up or merge-train commit on the target branch
names it in the subject line, and because the member's own commits all
predate that merge by wall clock. Neither of those is evidence. A batch
branch is assembled at some moment BEFORE it merges, so anything the member
pushed after assembly is outside it, and the subject records INTENT at
assembly time rather than CONTENT at merge time. Use before closing a
member, when an ancestry check against a squashed batch says no, or when a
member's branch still shows commits ahead of the target. Compare file
content against the target branch instead, expecting exactly one legitimate
difference: the shared aggregate file every member appends to.
/check-a-stale-branch-is-not-undoing-newer-main-workA branch built on an out-of-date main is about to merge, or has merged, and may undo work
that landed since. Use when a green, conflict-free PR deletes files you never touched,
newer values or a whole redesign vanish after a sibling PR merged, rows of a shared ledger
(tracker, registry, CHANGELOG) disappear or revert, or when `git diff main...HEAD` or a
reviewer says your small PR touches dozens of files you did not change.
/ci-leg-skipping-moves-minutes-it-does-not-remove-themYou are about to propose, price or approve a CI cost saving that works by
making a job or matrix leg SKIP on pull requests — a path filter, a safe
list, a changed-files gate, an exemption list. Check first whether the
pipeline runs a complement or backstop on merge, on push, or nightly:
many do, and then the legs a pull request skipped are exactly the legs some
later run executes, so a branch that goes green once and merges bills the
same total either way and the wall clock does not move at all. Use when
pricing a filter change, when a percentage saving is quoted with no basis,
or when choosing between filtering legs and batching pull requests. The
question that separates money from bookkeeping is whether the change
removes RUNS or merely moves LEGS.