fix(git): drop a terminal PR once its branch moves past it #9443
main fromrefs/pull/9443/head·opened View on GitHubRefs #4970.
A long-lived branch keeps matching a merged pull request by name forever. Release develop into main and every later thread on develop is stamped with that same historical number, and settles against its merged state.
There are two halves to it: the lookup that finds the stale match, and the discovery pass that puts it back after the lookup stops returning it.
1. The lookup#
lookupStatusPr already suppresses terminal matches, but only on the default branch:
if (details.isDefaultBranch && latest.state !== "open") {
return { pr: null, headContext };
}
An integration branch never qualifies, so it keeps its merged release PR indefinitely.
The branch is now compared against the commit the change request was opened from. A branch still sitting on that commit is described by it; a branch that has moved on was reused for later work.
ChangeRequestgains an optionalheadRefOid, from one extra field on thegh pr list --jsoncall that already runs — no extra request.- A terminal change request is dropped when the branch's own tip points elsewhere.
Why commits and not dates. Comparing the branch tip's date against updatedAt is simpler but breaks squash and rebase merges, and would have broken status finds a merged PR after its remote branch was deleted, which backdates the PR while committing "now". The recorded head commit is the head branch's own, so it survives any merge strategy.
Which ref. The local ref wins where there is one — that is where a thread's work lands, so unpushed commits still count as moving on. for-each-ref matches a pattern literally or up to a slash, so refs/heads/feature/foo also reports refs/heads/feature/foo/child; every row is matched back against the ref it has to be, the way branchPullRequest already reads its own branch ref.
2. The discovery pass#
Filtering the lookup is not enough on its own. ThreadPullRequestReactor restores a thread's saved branchPullRequest whenever detection returns null and the saved reference is merged or closed. A thread created after the release merged — while develop still sat on that change request's head — acquires the reference before its first turn moves the branch. The lookup then correctly reports nothing, discovery reads that as "not found", and restores the very reference the lookup rejected. That fallback runs on the reused branch, not only after a return to the default branch.
So null had to stop being ambiguous. The lookup now keeps what it rejected, and branchSupersededPullRequest(cwd, branch, pullRequest) answers whether this branch outgrew that specific change request. The retention fallback consults it and stands down only for that reference; numbers repeat across repositories, so the URLs have to agree.
It reads the entry the badge lookup already cached, so it costs no extra git or host work, and it is additive to the GitManager interface — existing callers and mocks are untouched.
Preserved on purpose: a saved reference the branch did not outgrow is still restored, explicit linkedPullRequest is untouched, and worktree threads skip the fallback exactly as before.
Not knowable means "keep it"#
The comparison returns false, preserving today's behaviour, when the forge reports no head commit (every non-GitHub provider today), when no ref resolves — the deleted-branch case from #6216 — or when the git call fails. Losing it can never drop a badge that is otherwise correct.
#7394 covers the separate stale-origin/HEAD case.
Tests#
Against real git repositories with a fake gh, each verified to fail without its fix:
status drops a merged PR once its long-lived branch moves past itstatus drops a merged PR once its branch is committed to without pushingstatus keeps a merged PR while its branch still sits on the merged commit— the squash-merge casebranch PR lookup ignores a nested child ref once the branch itself is gonebranch lookup reports the terminal PR a reused branch has outgrownclears a saved reference the branch outgrew and keeps the rest of its history— a thread created after the old PR merged, on that PR's head, then advanced; alongside one holding a different historical reference and one with an explicit link
800 tests pass across src/git/, src/sourceControl/ and src/orchestration/. Full-repo typecheck and lint clean. Rebased on main, keeping its isDraft/closedAt fields and its 60s PR_LOOKUP_CACHE_TTL.
No UI change — the badge stops appearing where it was wrong.
🤖 Generated with Claude Code
Summary by CodeRabbit#
- Bug Fixes
- Prevented merged or closed pull requests from being reattached to threads when their branches have been reused for newer changes.
- Improved handling of merged pull requests as branches advance, including shared and nested branch scenarios.
- Preserved pull request associations when a branch remains at the merged commit.
- Improved pull-request tracking by comparing the branch with the recorded pull-request commit, including cases where commit information is unavailable.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
🟡 Medium
git/GitManager.ts:407toPullRequestInfopreserves a closed or merged PR after its local branch advances without pushing, leaving a stale terminal-PR badge and allowing thread settlement to continue against that historical PR. ForwardingheadRefOidmakesreadBranchTipOidsmatch the retained remote-tracking ref at the old PR head; omitheadRefOidfrom this terminal-PR comparison.No longer relevant as of 2afe53b728c1539460d2b45673190927455c0a31
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).
Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.
Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f764477c7a69fac3153cad2cf652e013302d6408. Configure [here](https://www.cursor.com/dashboard/bugbot).apps/server/src/git/GitManager.ts line 1018OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -987,0 +998,21 @@998+ headContext: Pick<BranchHeadContext, "headBranch" | "localBranch" | "remoteName">,999+ ) {1000+ const patterns: string[] = [];1001+ appendUnique(patterns, `refs/heads/${headContext.localBranch}`);1002+ appendUnique(patterns, `refs/heads/${headContext.headBranch}`);1003+ appendUnique(1004+ patterns,1005+ headContext.remoteName === null1006+ ? `refs/remotes/*/${headContext.headBranch}`1007+ : `refs/remotes/${headContext.remoteName}/${headContext.headBranch}`,1008+ );1009+ const result = yield* gitCore.execute({1010+ operation: "GitManager.readBranchTipOids",1011+ cwd,1012+ args: ["for-each-ref", "--format=%(objectname)", ...patterns],1013+ timeoutMs: 5_000,1014+ });1015+ return result.stdout1016+ .split("\n")1017+ .map((line) => line.trim())1018+ .filter((line) => line.length > 0);Tip check matches sibling branch refs#
Medium Severity
Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit f764477c7a69fac3153cad2cf652e013302d6408. Configure [here](https://www.cursor.com/dashboard/bugbot).readBranchTipOidsfeedsfor-each-refpatterns and keeps everyobjectname, so prefix siblings (develop/development,feature/foo/feature/foo/child) count as this branch's tips. A leftover sibling SHA can pin a historical merged badge on a long-lived branch, and a nested child after the real refs are gone can drop a badge the fail-safe is supposed to keep.branchPullRequestalready exact-matchesrefnamefor this.Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This targeted fix changes production status and thread-settlement behavior by comparing terminal PR head OIDs with local or remote branch tips, alongside additive GitHub metadata plumbing. It also adds line-level static-analysis suppressions in the test file, so human review is warranted.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).Both review findings were real. Fixed in 2afe53b.
Cursor Bugbot — tip check matches sibling branch refs. Correct, with one refinement.
refs/heads/developdoes not reportrefs/heads/development(the prefix match stops at a slash), and git forbids holdingfeature/fooandfeature/foo/childat once:fatal: cannot lock ref 'refs/heads/feature/foo': 'refs/heads/feature/foo/child' existsSo a sibling can never pin a badge on a live branch. The other half is the real one: the child only surfaces once the branch itself is gone — exactly when the merged badge is meant to be kept — and standing in for the deleted branch dropped it. Every row is now matched back against the ref it has to be, following the exact-
refnamereadbranchPullRequestalready does.Macroscope — stale badge when the local branch advances without pushing. The underlying observation is right, but dropping the
headRefOidforwarding would have disabled the comparison entirely rather than tightened it. The actual cause was collecting every ref and keeping the badge if any of them matched, so a stale remote-tracking ref outvoted the local branch. It now reads one tip, preferring the local ref: that is where a thread's work lands, so a branch with unpushed commits has moved on from a merged change request.Head commits are also compared case-insensitively now.
Two tests added, both verified to fail against the previous commit:
status drops a merged PR once its branch is committed to without pushingbranch PR lookup ignores a nested child ref once the branch itself is gone
248 tests pass across
src/git/,src/sourceControl/andThreadSettlementReactor; full-repo typecheck and lint clean.On the flagged suppressions — the only ones added are
@effect-diagnostics-next-line preferSchemaOverJson:offon test fixtures, matching every otherJSON.stringifyfixture inGitManager.test.ts. Happy to drop them if you'd rather these fixtures went through a schema.github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:M
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
Both blocking findings are clear on 2afe53b — Cursor Bugbot pass (was 1 issue), Macroscope Correctness pass, and the approvability verdict no longer lists a blocking correctness issue.
On the remaining note about line-level static-analysis suppressions in the test file: I checked whether they can be dropped, and they can't. Removing the four this PR adds fails
typecheckwith hard errors:src/git/GitManager.test.ts(1484,13): error TS377026: This code uses `JSON.parse` or `JSON.stringify`. Use `Schema.UnknownFromJsonString` ... effect(preferSchemaOverJson)The fake
ghreturns raw JSON stdout, so a fixture has to be a string at that boundary.GitManager.test.tsalready carries 67 of these directives for exactly that reason; the four added here follow that convention rather than introducing it. Converting the fixtures to schemas would mean touching all 67 and is well outside this fix — happy to do it as a separate PR if that's wanted.That leaves the verdict resting on "human review is warranted" for a change to status and settlement behavior, which seems right — flagging it for a maintainer rather than something further I can address in code.
Note: GPT-6 on behalf of shivam (@shivamhwp).
The GitManager filter does not clear an already saved stale badge on a shared checkout. If a thread acquires the old merged
branchPullRequestbefore its first new commit, the later lookup correctly returns null, butThreadPullRequestReactorrestores the saved reference whenever its summary is merged or closed. That fallback also runs when the thread is still on the same reuseddevelopbranch, not only after switching back to the default branch.Please handle this downstream case too. Discovery needs enough information to distinguish a terminal match rejected because the branch moved from the legitimate historical-reference fallback. Preserve historical threads and explicit links. Include a new thread created after the old PR merged, initially on that PR's head, then advanced by its first turn.
The rebase must retain the current GitHub
isDraft/closedAtfields and the current lookup cache cadence. Non-GitHub providers still lackheadRefOid, as the description notes; #7394 covers the separate stale-default-branch case.Thanks — you're right, and the downstream case is the one that actually bites. Rebased onto main and handled in 34a3f5b.
The gap.
ThreadPullRequestReactor's retention fallback fires whenever detection returnsnulland the saved reference's summary is terminal. My filter made detection returnnullfor a reused branch, so the reactor read that as "not found" and restored the very reference the filter had just rejected. The badge came back, and as you say the fallback isn't limited to a return to the default branch.Distinguishing the two. The lookup now keeps what it rejected instead of discarding it, and a new
branchSupersededPullRequest(cwd, branch, pullRequest)answers whether this branch outgrew that specific change request. The retention fallback consults it and stands down only for that reference. Numbers repeat across repositories, so the URLs have to agree before it counts as the same one.It reads the same cache entry the badge lookup reads, so there's no extra git or host work, and it's additive to the
GitManagerinterface — existing callers and mocks are untouched.Preserved, as asked:
- a saved reference the branch did not outgrow is still restored (covered in the test);
- explicit
linkedPullRequestis untouched — thereplacementpath is unchanged; - worktree threads still skip the fallback exactly as before.
Your test case.
clears a saved reference the branch outgrew and keeps the rest of its historyinThreadPullRequestReactor.test.tsis the scenario you described — a thread created after the old PR merged, holding that reference from whendevelopstill sat on its head, then advanced. Alongside it, a thread on the same shared checkout holding a different historical reference, and one with an explicit link. I verified it fails without the reactor change.Rebase. Kept main's
isDraft/closedAtfields (headRefOidis inserted afterheadRefName, nothing dropped) and main's 60sPR_LOOKUP_CACHE_TTLwith its sweep-cadence rationale — my branch had been written against the old 2min value. No lockfile changes.Non-GitHub providers still have no
headRefOid, so they keep their current behaviour, and I've left the stale-origin/HEADcase to #7394.800 tests pass across
src/git/,src/sourceControl/andsrc/orchestration/; full-repo typecheck and lint clean.No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
c74e7b4b-144a-443d-8b49-1c8a6bfb5286📥 Commits
Reviewing files that changed from the base of the PR and between 2e3c82009d0723c2bbdcf36979573f3be9283a8f and 3f3d8b730e2a0b788f8ac5c9a7a1c940b80651b5.
📒 Files selected for processing (7)
apps/server/src/git/GitManager.test.tsapps/server/src/git/GitManager.tsapps/server/src/sourceControl/GitHubCli.test.tsapps/server/src/sourceControl/GitHubCli.tsapps/server/src/sourceControl/GitHubSourceControlProvider.test.tsapps/server/src/sourceControl/GitHubSourceControlProvider.tspackages/contracts/src/sourceControl.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/server/src/sourceControl/GitHubCli.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
📝 Walkthrough
Walkthrough#
The change propagates pull request head commit OIDs through GitHub integrations, detects superseded terminal pull requests after branch movement, and prevents stale thread references from being restored.
Changes#
Superseded pull request tracking
Layer / File(s) Summary Head commit data contract
packages/contracts/src/sourceControl.ts,apps/server/src/sourceControl/*GitHub queries and normalized records now carry optional headRefOidvalues. The provider maps these values intoChangeRequest.Branch supersession detection
apps/server/src/git/GitManager.ts,apps/server/src/git/GitManager.test.tsGitManagercompares branch tip OIDs with terminal pull request head OIDs. Branch lookup returns superseded pull requests separately, andbranchSupersededPullRequestverifies the matching pull request.Thread restoration guard
apps/server/src/orchestration/ThreadPullRequestReactor.ts,apps/server/src/orchestration/ThreadPullRequestReactor.test.tsThread restoration checks whether the saved pull request was superseded before restoring it. Tests cover shared checkouts and preserved unrelated references. Priority: ⬇️ Low
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix
Sequence Diagram(s)#
sequenceDiagram participant ThreadPullRequestReactor participant GitManager participant GitRefs ThreadPullRequestReactor->>GitManager: check branchSupersededPullRequest GitManager->>GitRefs: read branch tip OID GitManager-->>ThreadPullRequestReactor: return superseded status ThreadPullRequestReactor-->>ThreadPullRequestReactor: restore or clear branch pull requestSuggested reviewers:
juliusmarmingeMerge Risk: ⚪ Minimal · up to
3f3d8The change adds optional head-commit tracking to prevent stale terminal pull-request references from being restored. No actionable merge-blocking risk remains in the reviewed change.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 10 files. Write docstrings for the functions missing them to satisfy the coverage threshold. ✅ Passed checks (4 passed)
Check name Status Explanation Title check ✅ Passed The title clearly identifies the main fix: removing a terminal pull request association when its branch advances beyond the recorded commit. Description check ✅ Passed The description clearly explains the problem, implementation, rationale, preserved behavior, tests, and lack of UI changes. It does not use the template headings or checklist, but it contains the requ… Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request. Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request. - Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create PR with unit tests
Comment `@coderabbitai help` to get the list of available commands.Two follow-ups from the CodeRabbit pass, both fair.
Description/diff mismatch. Correct — the description still described only the original lookup filter and never mentioned the discovery work added in the rebase. Rewritten to match what the branch actually does now: the lookup half, the
ThreadPullRequestReactorhalf, and what each deliberately preserves.Docstring coverage. The 0% reading looks like the heuristic not recognising
const x = Effect.fn(...)assignments — four of the five functions it counted already carry doc comments. But it caught a real one:branchSupersededPullRequest's explanation sat only on the service interface, with nothing at the implementation. Documented there in 2e3c820.No code behaviour changed in either follow-up.
Rebased onto current main (
cc839c4).Main hadn't picked up a text conflict, but a merge check against it failed typecheck. The Forgejo head-matching test added in #11436 spreads a mapped
ChangeRequestintomatchesBranchHeadContext, andChangeRequest.headRefOid— aSchema.optionalfield — admits an explicitundefinedthat myPullRequestInfo.headRefOid?: string | nullrejected underexactOptionalPropertyTypes. Widened tostring | null | undefinedin 3f3d8b7, matching the neighbouringPullRequestHeadRemoteInfofields.No behaviour change. On the rebased branch: full-repo typecheck and lint clean, 869 tests pass across
src/git/,src/sourceControl/andsrc/orchestration/, no lockfile changes.Thanks for the PR. We're not taking changes to the orchestration and provider layers right now: that part of the server is being rewritten for V2, and merging into the current code would either conflict with or be thrown away by that work.
Closing for now. If this is still an issue once V2 lands, please reopen (or open a fresh PR against the new code) and we'll take a proper look.
juliusmarminge closed this
Sign in to join this conversation.

macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed