Skip to content

chore: stop concurrent agents colliding over git branches - #2230

Merged
carlos-alm merged 5 commits into
mainfrom
chore/agent-branch-collision-hardening
Aug 3, 2026
Merged

carlos-alm merged 5 commits into
mainfrom
chore/agent-branch-collision-hardening

Conversation

@carlos-alm

Copy link
Copy Markdown
Contributor

Ports optave/data-analytics-pipeline-svc#651 into this repo, and follows the foundry change in optave/ops-development-tool#32.

The failure

A branch can be checked out in exactly one worktree. Nothing collected finished agent worktrees, so each one held its branch name hostage:

fatal: 'fix/some-branch' is already checked out at '.claude/worktrees/wf_40037ee4-070-1'

gh pr checkout in a parallel /sweep or /resolve agent aborts on that, and the agent then improvises a local branch name of its own and pushes from it — unspecified, and easy to get wrong.

What changed

Area Change
.claude/scripts/gc-worktrees.sh New. Collects a worktree only when all four hold: under .claude/worktrees/, branch on a settled PR with no open PR, clean tree, not locked.
/sweep gh pr checkout --detach, assert HEAD == headRefOid, push by refspec.
/resolve Same detached checkout; push becomes git push origin HEAD:$HEAD_BRANCH.
/housekeep Phase 1 delegates staleness to the script instead of its own rule.
.gitattributes Pin *.sh to LF.

Two things reviewers should look at

Squash-merge makes the obvious staleness test a permanent no-op. The natural rule is git merge-base --is-ancestor <branch> origin/main. Under squash-merge a landed branch's tip is never an ancestor of the default branch, so that test looks right, reads right in review, and collects nothing, forever. The script resolves merged-ness from GitHub PR state instead, and detects the default branch rather than assuming main.

Orphans are reported, not hidden. A deliberate divergence from #651, where a worktree whose branch never had a PR is counted as "still in flight" and never named. Here the dry-run reports it as its own orphaned (no PR) bucket and lists the branches — those pin their names indefinitely and are usually the residue of exactly the improvised branch names this PR stops agents creating. Raised upstream on #651.

Verification

  • bash -n clean on the script; --dry-run exercised against a live 19-worktree repo (12 collected, 1 in flight, 6 orphaned; every open-PR branch vetoed, no uncommitted work touched).
  • An automated check enforces the invariant that matters most here — no file may detach and still contain a bare git push. A half-patched skill is worse than an untouched one, and each repo had drifted enough from the common template that exact-text patching left gaps. All repos in this rollout pass.

Note

.claude/worktrees/ is not cleaned by this PR. Preview with bash .claude/scripts/gc-worktrees.sh --dry-run.

A branch can be checked out in exactly one worktree. Nothing collected finished
agent worktrees, so each one held its branch name hostage: `gh pr checkout` in a
sweep/resolve agent aborted outright, and agents improvised local branch names
and pushed from those.

- Check out PR heads DETACHED (`gh pr checkout --detach`) and push by refspec
  (`git push origin HEAD:<branch>`). A detached HEAD claims no name, so it cannot
  collide with a concurrent agent or a leftover worktree.
- New `.claude/scripts/gc-worktrees.sh` collects finished worktrees. Four
  conditions, all required: under .claude/worktrees/, branch on a settled PR with
  no open PR, clean tree, not locked. Resolves merged-ness from GitHub PR state
  rather than `git branch --merged`, which is a permanent no-op under squash-merge.
- Pins *.sh to LF: under core.autocrlf=true a CR rides into the collector's
  here-strings and its exact branch-name matching silently never matches.

Ports optave/data-analytics-pipeline-svc#651.
@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR prevents concurrent agents from claiming the same Git branch and adds conservative cleanup for completed agent worktrees.

  • Checks out /sweep and /resolve PR heads in detached mode, validates the selected commit, and pushes through explicit refspecs.
  • Adds worktree collection based on PR state, cleanliness, scope, and lock status.
  • Delegates /housekeep worktree staleness handling to the new cleanup script and pins shell scripts to LF line endings.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains; both previously reported detached-push state-loss paths are corrected at the current head.

Important Files Changed

Filename Overview
.claude/scripts/gc-worktrees.sh Adds fail-closed collection of clean, unlocked agent worktrees whose branches belong to settled pull requests.
.claude/skills/resolve/SKILL.md Uses detached checkout and restores the persisted PR head branch in Phase 7 before pushing by explicit refspec.
.claude/skills/sweep/SKILL.md Converts parallel sweep agents to detached checkouts and re-derives the PR branch within every push command.
.claude/skills/housekeep/SKILL.md Makes the cleanup script the source of truth for worktree staleness and documents orphan reporting.
.gitattributes Enforces LF line endings for shell scripts.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Agent worktree] --> B[Checkout PR head detached]
  B --> C[Validate HEAD against PR head OID]
  C --> D[Apply fixes or conflict resolution]
  D --> E[Re-derive PR head branch]
  E --> F[Push HEAD to explicit remote ref]
  G[Housekeep] --> H[Inspect agent worktrees]
  H --> I{Scoped, settled, clean, unlocked?}
  I -->|Yes| J[Remove worktree]
  I -->|No| K[Keep and report]
Loading

Reviews (4): Last reviewed commit: "fix(skills): re-derive PR branch name at..." | Re-trigger Greptile

Comment on lines +571 to +575
# Push BY REFSPEC: Phase 1 checked out detached (so the checkout could not collide with
# another worktree holding this branch), and a bare `git push origin "HEAD:$HEAD_BRANCH"` from a detached HEAD fails
# with "You are not currently on a branch". HEAD:<branch> is still a normal
# fast-forward-only push — a non-fast-forward is rejected exactly as before.
echo "Pushing to origin/$HEAD_BRANCH..."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Missing detached push branch

When /resolve reaches Phase 7, that independently executed block restores only BASE_BRANCH, so $HEAD_BRANCH expands to an empty string and git push origin "HEAD:$HEAD_BRANCH" fails instead of publishing the conflict resolution.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — Phase 7 now re-derives HEAD_BRANCH from .codegraph/resolve/head-branch at the top of its own block, matching every other phase's pattern. It previously only restored BASE_BRANCH, so $HEAD_BRANCH was unset by the time this separate Bash invocation ran.

Comment thread .claude/skills/sweep/SKILL.md Outdated
Comment on lines +93 to +100
head=$(gh pr view <number> --json headRefName -q .headRefName)
oid=$(gh pr view <number> --json headRefOid -q .headRefOid)
gh pr checkout <number> --detach
# Fail closed if HEAD is not the PR head (stale fetch, or the head moved as you started).
[ "$(git rev-parse HEAD)" = "$oid" ] || { echo "ABORT: HEAD is not PR <number>'s head"; exit 1; }
```

Every later `git push origin "HEAD:$head"` in this skill then becomes `git push origin "HEAD:$head"` (and the commitlint-amend exception, `git push --force-with-lease origin "HEAD:$head"`) — a bare `git push` fails from a detached HEAD with *"You are not currently on a branch"*. Re-read `headRefOid` immediately before pushing; on a live PR the sha you captured here may no longer be the head.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Transient refspec branch state

When a detached sweep agent pushes from a later Bash call, the head variable initialized during checkout is no longer defined, so the prescribed git push origin "HEAD:$head" expands to an invalid HEAD: refspec and leaves the fixes unpushed.

Fix in Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed — every push in /sweep now re-derives the branch name inline via gh pr view <number> --json headRefName -q .headRefName in the same Bash call as the push, instead of relying on a $head shell variable captured in an earlier, separate Bash tool call (which does not persist).

carlos-alm and others added 4 commits August 2, 2026 16:16
Phase 7 only restored BASE_BRANCH from state, leaving HEAD_BRANCH
unset and the push refspec empty on a detached HEAD.
Bash tool calls do not share shell state, so a $head variable
captured during Step 2a's detached checkout is gone by the time a
later step pushes — the refspec silently expands to the invalid
'HEAD:' and fixes go unpushed. Every push now re-derives the branch
name via gh in the same call.
@carlos-alm

Copy link
Copy Markdown
Contributor Author

@greptileai

@carlos-alm
carlos-alm merged commit c5fdd4a into main Aug 3, 2026
35 checks passed
@carlos-alm
carlos-alm deleted the chore/agent-branch-collision-hardening branch August 3, 2026 01:57
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 3, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant