Skip to content

Commit 87687d6

Browse files
t3dotggclaude
andcommitted
fix(server): address review on turn-end pull request refresh
- Serialize remote status writes per cwd so a poll that started before the turn-end refresh cannot overwrite the fresh pull request with its stale empty result. - Own-name fallback returns the remote that holds the branch, so a fork push is looked up as `owner:branch` instead of on origin. - Failure fallback resolves the same effective head context as the cached lookup, so the last-known own-name PR survives a later failed lookup. - Drift-follow returns the adopted branch and the pull request refresh accepts it, so a PR opened on a renamed branch is refreshed in the same turn. - Attach the isUnpublishedBranch doc to its declaration again and add the standard rationale to the new suppression. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 parent c8785aa commit 87687d6

6 files changed

Lines changed: 344 additions & 81 deletions

File tree

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1924,6 +1924,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
19241924
const { manager, ghCalls } = yield* makeManager({
19251925
ghScenario: {
19261926
prListByHeadSelector: {
1927+
// Fake gh returns raw JSON stdout, matching the CLI boundary under test.
19271928
// @effect-diagnostics-next-line preferSchemaOverJson:off
19281929
"feature/pushed-plain": JSON.stringify([
19291930
{
@@ -1947,6 +1948,112 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
19471948
}),
19481949
);
19491950

1951+
it.effect(
1952+
"status finds a fork PR pushed under the branch's own name despite a default upstream",
1953+
() =>
1954+
Effect.gen(function* () {
1955+
const repoDir = yield* makeTempDir("t3code-git-manager-");
1956+
yield* initRepo(repoDir);
1957+
const originDir = yield* createBareRemote();
1958+
const forkDir = yield* createBareRemote();
1959+
yield* runGit(repoDir, ["remote", "add", "origin", originDir]);
1960+
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
1961+
yield* runGit(repoDir, ["remote", "set-head", "origin", "main"]);
1962+
yield* configureRemote(repoDir, "team/fork", forkDir, "team/fork");
1963+
yield* runGit(repoDir, ["checkout", "-b", "feature/fork-plain", "origin/main"]);
1964+
// Pushed to the fork without -u: upstream stays origin/main.
1965+
yield* runGit(repoDir, ["push", "team/fork", "feature/fork-plain"]);
1966+
yield* configureVisibleRemoteUrlWithLocalRewrite(
1967+
repoDir,
1968+
"origin",
1969+
"[email protected]:pingdotgg/codething-mvp.git",
1970+
originDir,
1971+
);
1972+
yield* configureVisibleRemoteUrlWithLocalRewrite(
1973+
repoDir,
1974+
"team/fork",
1975+
"[email protected]:contributor/codething-mvp.git",
1976+
forkDir,
1977+
);
1978+
1979+
const { manager, ghCalls } = yield* makeManager({
1980+
ghScenario: {
1981+
prListByHeadSelector: {
1982+
// Fake gh returns raw JSON stdout, matching the CLI boundary under test.
1983+
// @effect-diagnostics-next-line preferSchemaOverJson:off
1984+
"contributor:feature/fork-plain": JSON.stringify([
1985+
{
1986+
number: 89,
1987+
title: "Fork PR pushed without -u",
1988+
url: "https://github.com/pingdotgg/codething-mvp/pull/89",
1989+
baseRefName: "main",
1990+
headRefName: "feature/fork-plain",
1991+
state: "OPEN",
1992+
updatedAt: "2026-05-01T10:00:00Z",
1993+
isCrossRepository: true,
1994+
headRepository: { nameWithOwner: "contributor/codething-mvp" },
1995+
headRepositoryOwner: { login: "contributor" },
1996+
},
1997+
]),
1998+
},
1999+
},
2000+
});
2001+
2002+
const status = yield* manager.status({ cwd: repoDir });
2003+
expect(status.pr?.number).toBe(89);
2004+
expect(ghCalls.some((call) => call.includes("--head contributor:feature/fork-plain"))).toBe(
2005+
true,
2006+
);
2007+
expect(ghCalls.some((call) => call.includes("--head main"))).toBe(false);
2008+
}),
2009+
);
2010+
2011+
it.effect("status keeps an own-name PR when a later lookup fails on a default upstream", () =>
2012+
Effect.gen(function* () {
2013+
const repoDir = yield* makeTempDir("t3code-git-manager-");
2014+
yield* initRepo(repoDir);
2015+
const remoteDir = yield* createBareRemote();
2016+
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
2017+
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
2018+
yield* runGit(repoDir, ["remote", "set-head", "origin", "main"]);
2019+
yield* runGit(repoDir, ["checkout", "-b", "feature/sticky-plain", "origin/main"]);
2020+
yield* runGit(repoDir, ["push", "origin", "feature/sticky-plain"]);
2021+
2022+
const { manager } = yield* makeManager({
2023+
ghScenario: {
2024+
prListByHeadSelector: {
2025+
// Fake gh returns raw JSON stdout, matching the CLI boundary under test.
2026+
// @effect-diagnostics-next-line preferSchemaOverJson:off
2027+
"feature/sticky-plain": JSON.stringify([
2028+
{
2029+
number: 90,
2030+
title: "Sticky own-name PR",
2031+
url: "https://github.com/pingdotgg/codething-mvp/pull/90",
2032+
baseRefName: "main",
2033+
headRefName: "feature/sticky-plain",
2034+
state: "OPEN",
2035+
updatedAt: "2026-05-01T10:00:00Z",
2036+
},
2037+
]),
2038+
},
2039+
failWith: new GitHubCli.GitHubCliUnavailableError({
2040+
command: "gh",
2041+
cwd: repoDir,
2042+
cause: new Error("rate limited"),
2043+
}),
2044+
failAfterCalls: 1,
2045+
},
2046+
});
2047+
2048+
const first = yield* manager.status({ cwd: repoDir });
2049+
expect(first.pr?.number).toBe(90);
2050+
2051+
yield* manager.invalidateStatus(repoDir);
2052+
const second = yield* manager.status({ cwd: repoDir });
2053+
expect(second.pr?.number).toBe(90);
2054+
}),
2055+
);
2056+
19502057
it.effect("status prefers open PR when merged PR has newer updatedAt", () =>
19512058
Effect.gen(function* () {
19522059
const repoDir = yield* makeTempDir("t3code-git-manager-");

‎apps/server/src/git/GitManager.ts‎

Lines changed: 95 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1003,37 +1003,9 @@ export const make = Effect.gen(function* () {
10031003
...(remoteName.length > 0 ? { remoteName } : {}),
10041004
};
10051005
return Effect.gen(function* () {
1006-
const headContext = yield* resolveBranchHeadContext(cwd, details);
1007-
const upstreamHeadIsDefault =
1008-
headContext.headBranch === details.defaultBranch ||
1009-
(details.defaultBranch === null &&
1010-
(headContext.headBranch === "main" || headContext.headBranch === "master"));
1011-
// `git worktree add -b feature origin/main` makes the new local branch
1012-
// track origin/main. That upstream is the branch's base, not its
1013-
// published PR head. Looking up PRs for it can attach an old reverse
1014-
// merge from main and auto-settle an unrelated feature thread.
1015-
//
1016-
// The branch may still have been pushed under its own name by a plain
1017-
// `git push origin feature` that never moved the upstream. When a
1018-
// remote-tracking ref for the local name exists, look the PR up by
1019-
// that name instead of giving up. Without the ref there is nothing to
1020-
// ask the host about, so no API call is spent.
1021-
if (
1022-
headContext.headBranch !== details.branch &&
1023-
upstreamHeadIsDefault &&
1024-
!headContext.isCrossRepository
1025-
) {
1026-
const publishedUnderOwnName = yield* hasRemoteTrackingRef(cwd, details.branch);
1027-
if (!publishedUnderOwnName) {
1028-
return { latest: null, headContext };
1029-
}
1030-
const ownNameContext = yield* resolveBranchHeadContext(cwd, {
1031-
branch: details.branch,
1032-
upstreamRef: null,
1033-
remoteName: headContext.remoteName ?? "origin",
1034-
});
1035-
const latest = yield* findLatestPrForHeadContext(cwd, ownNameContext);
1036-
return { latest, headContext: ownNameContext };
1006+
const { headContext, lookup } = yield* resolveLookupHeadContext(cwd, details);
1007+
if (!lookup) {
1008+
return { latest: null, headContext };
10371009
}
10381010
// Only skip when the branch is untracked as well: anything carrying an
10391011
// upstream keeps the old behaviour.
@@ -1169,8 +1141,8 @@ export const make = Effect.gen(function* () {
11691141
}
11701142
: {}),
11711143
}),
1172-
Effect.andThen(resolveBranchHeadContext(cwd, details)),
1173-
Effect.map((headContext) =>
1144+
Effect.andThen(resolveLookupHeadContext(cwd, details)),
1145+
Effect.map(({ headContext }) =>
11741146
resolveLastKnownPr(branchKey, {
11751147
upstreamRef: details.upstreamRef,
11761148
headBranch: headContext.headBranch,
@@ -1356,6 +1328,96 @@ export const make = Effect.gen(function* () {
13561328
} satisfies BranchHeadContext;
13571329
});
13581330

1331+
// The remote that holds a ref named after the local branch, or null when
1332+
// none does. Remote names may contain slashes, so refs are matched literally
1333+
// per remote instead of with a glob. When several remotes hold the name, the
1334+
// preferred remote wins, then origin, then the first configured remote.
1335+
const findRemoteTrackingRemote = Effect.fn("findRemoteTrackingRemote")(function* (
1336+
cwd: string,
1337+
branch: string,
1338+
preferredRemoteName: string | null,
1339+
) {
1340+
if (branch.length === 0) return null;
1341+
return yield* Effect.gen(function* () {
1342+
const remoteNames = (yield* gitCore.execute({
1343+
operation: "GitManager.findRemoteTrackingRemote.remotes",
1344+
cwd,
1345+
args: ["remote"],
1346+
timeoutMs: 5_000,
1347+
})).stdout
1348+
.split("\n")
1349+
.map((name) => name.trim())
1350+
.filter((name) => name.length > 0);
1351+
if (remoteNames.length === 0) return null;
1352+
const refs = new Set(
1353+
(yield* gitCore.execute({
1354+
operation: "GitManager.findRemoteTrackingRemote.refs",
1355+
cwd,
1356+
args: [
1357+
"for-each-ref",
1358+
"--format=%(refname)",
1359+
...remoteNames.map((name) => `refs/remotes/${name}/${branch}`),
1360+
],
1361+
timeoutMs: 5_000,
1362+
})).stdout
1363+
.split("\n")
1364+
.map((ref) => ref.trim())
1365+
.filter((ref) => ref.length > 0),
1366+
);
1367+
const matching = remoteNames.filter((name) => refs.has(`refs/remotes/${name}/${branch}`));
1368+
if (preferredRemoteName !== null && matching.includes(preferredRemoteName)) {
1369+
return preferredRemoteName;
1370+
}
1371+
if (matching.includes("origin")) return "origin";
1372+
return matching[0] ?? null;
1373+
}).pipe(Effect.orElseSucceed(() => null));
1374+
});
1375+
1376+
// `git worktree add -b feature origin/main` makes the new local branch track
1377+
// origin/main. That upstream is the branch's base, not its published PR
1378+
// head. Looking up PRs for it can attach an old reverse merge from main and
1379+
// auto-settle an unrelated feature thread.
1380+
//
1381+
// The branch may still have been pushed under its own name by a plain
1382+
// `git push <remote> feature` that never moved the upstream. When a remote
1383+
// holds a ref for the local name, look the PR up by that name on that
1384+
// remote. Without such a ref there is nothing to ask the host about, so
1385+
// `lookup` is false and no API call is spent. Both the cached lookup and the
1386+
// failure fallback resolve through here so the last-known PR compares
1387+
// against the same head branch.
1388+
const resolveLookupHeadContext = Effect.fn("resolveLookupHeadContext")(function* (
1389+
cwd: string,
1390+
details: {
1391+
branch: string;
1392+
upstreamRef: string | null;
1393+
defaultBranch: string | null;
1394+
remoteName?: string;
1395+
},
1396+
) {
1397+
const headContext = yield* resolveBranchHeadContext(cwd, details);
1398+
const upstreamHeadIsDefault =
1399+
headContext.headBranch === details.defaultBranch ||
1400+
(details.defaultBranch === null &&
1401+
(headContext.headBranch === "main" || headContext.headBranch === "master"));
1402+
if (
1403+
headContext.headBranch === details.branch ||
1404+
!upstreamHeadIsDefault ||
1405+
headContext.isCrossRepository
1406+
) {
1407+
return { headContext, lookup: true };
1408+
}
1409+
const remoteName = yield* findRemoteTrackingRemote(cwd, details.branch, headContext.remoteName);
1410+
if (remoteName === null) {
1411+
return { headContext, lookup: false };
1412+
}
1413+
const ownNameContext = yield* resolveBranchHeadContext(cwd, {
1414+
branch: details.branch,
1415+
upstreamRef: null,
1416+
remoteName,
1417+
});
1418+
return { headContext: ownNameContext, lookup: true };
1419+
});
1420+
13591421
/**
13601422
* Whether git has no record of this branch on any remote, so a change request
13611423
* cannot exist for it and asking the provider is a guaranteed-empty API call.
@@ -1369,24 +1431,6 @@ export const make = Effect.gen(function* () {
13691431
* because then every branch looks unpublished; it, and any failed probe,
13701432
* keeps the lookup.
13711433
*/
1372-
// True when any remote holds a ref named after the local branch.
1373-
const hasRemoteTrackingRef = Effect.fn("hasRemoteTrackingRef")(function* (
1374-
cwd: string,
1375-
branch: string,
1376-
) {
1377-
if (branch.length === 0) return false;
1378-
return yield* gitCore
1379-
.execute({
1380-
operation: "GitManager.hasRemoteTrackingRef",
1381-
cwd,
1382-
args: ["for-each-ref", "--count=1", "--format=%(refname)", `refs/remotes/*/${branch}`],
1383-
timeoutMs: 5_000,
1384-
})
1385-
.pipe(
1386-
Effect.map((result) => result.stdout.trim().length > 0),
1387-
Effect.orElseSucceed(() => false),
1388-
);
1389-
});
13901434
const isUnpublishedBranch = Effect.fn("isUnpublishedBranch")(function* (
13911435
cwd: string,
13921436
headContext: Pick<BranchHeadContext, "headBranch" | "localBranch">,

‎apps/server/src/orchestration/Layers/CheckpointReactor.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,30 @@ describe("CheckpointReactor", () => {
582582
expect(pullRequestRefreshCalls).toEqual([harness.cwd]);
583583
});
584584

585+
it("re-asks for the pull request after adopting a drifted checkout", async () => {
586+
const pullRequestRefreshCalls: string[] = [];
587+
const harness = await createHarness({
588+
seedFilesystemCheckpoints: false,
589+
threadBranch: "t3code/original-branch",
590+
localStatusRefName: "t3code/renamed-by-agent",
591+
pullRequestRefreshCalls,
592+
});
593+
594+
harness.provider.emit({
595+
type: "turn.completed",
596+
eventId: EventId.make("evt-turn-completed-drift-pr"),
597+
provider: ProviderDriverKind.make("codex"),
598+
createdAt: "2026-01-01T00:00:00.000Z",
599+
threadId: ThreadId.make("thread-1"),
600+
turnId: asTurnId("turn-drift-pr"),
601+
payload: { state: "completed" },
602+
});
603+
604+
await harness.drain();
605+
606+
expect(pullRequestRefreshCalls).toEqual([harness.cwd]);
607+
});
608+
585609
it("does not re-ask for the pull request at turn end on the default branch", async () => {
586610
const pullRequestRefreshCalls: string[] = [];
587611
const harness = await createHarness({

0 commit comments

Comments
 (0)