Skip to content

Commit 8c9417a

Browse files
only21milclaude
andcommitted
fix(server): move an existing PR branch before creating its worktree
The worktree used to be created at the branch's old commit and then moved onto the pull request head. A head that removed a submodule left the old checkout behind as untracked files, so later reopens saw local changes. The branch now moves first, under the same lossless rule the reused-worktree refresh uses, and the worktree is created at the head. That also drops the second submodule pass and its driver method. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 84288a1 commit 8c9417a

4 files changed

Lines changed: 228 additions & 134 deletions

File tree

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

Lines changed: 94 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -4340,6 +4340,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
43404340
it.effect.each([
43414341
{ localBranch: "ahead", expectedHead: "local", isOnPullRequestHead: false },
43424342
{ localBranch: "behind", expectedHead: "pull request", isOnPullRequestHead: true },
4343+
{ localBranch: "rewritten", expectedHead: "pull request", isOnPullRequestHead: true },
43434344
] as const)(
43444345
"moves an existing PR branch into a new worktree only when nothing is lost ($localBranch)",
43454346
({ localBranch, expectedHead, isOnPullRequestHead }) =>
@@ -4358,21 +4359,39 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
43584359
NodeFS.writeFileSync(NodePath.join(repoDir, "mine.txt"), "mine\n");
43594360
yield* runGit(repoDir, ["add", "mine.txt"]);
43604361
yield* runGit(repoDir, ["commit", "-m", "My unpublished commit"]);
4361-
} else {
4362+
} else if (localBranch === "behind") {
43624363
yield* runGit(repoDir, ["checkout", "-b", "author-push"]);
43634364
NodeFS.writeFileSync(NodePath.join(repoDir, "authored.txt"), "authored\n");
43644365
yield* runGit(repoDir, ["add", "authored.txt"]);
43654366
yield* runGit(repoDir, ["commit", "-m", "New PR head commit"]);
43664367
yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-existing"]);
4368+
} else {
4369+
const staleHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim();
4370+
yield* runGit(repoDir, ["checkout", "-b", "author-rewrite"]);
4371+
NodeFS.writeFileSync(NodePath.join(repoDir, "existing.txt"), "rewritten\n");
4372+
yield* runGit(repoDir, ["add", "existing.txt"]);
4373+
yield* runGit(repoDir, ["commit", "--amend", "-m", "Rewritten PR head"]);
4374+
yield* runGit(repoDir, [
4375+
"push",
4376+
"--force",
4377+
"origin",
4378+
"author-rewrite:feature/pr-existing",
4379+
]);
4380+
yield* runGit(repoDir, [
4381+
"update-ref",
4382+
"refs/remotes/origin/feature/pr-existing",
4383+
staleHead,
4384+
]);
43674385
}
43684386
const localHead = (yield* runGit(repoDir, [
43694387
"rev-parse",
43704388
"feature/pr-existing",
43714389
])).stdout.trim();
43724390
const pullHead = (yield* runGit(repoDir, [
4373-
"rev-parse",
4374-
"origin/feature/pr-existing",
4375-
])).stdout.trim();
4391+
"ls-remote",
4392+
"origin",
4393+
"refs/heads/feature/pr-existing",
4394+
])).stdout.split("\t")[0];
43764395
yield* runGit(repoDir, ["checkout", "main"]);
43774396

43784397
const { manager } = yield* makeManager({
@@ -4411,68 +4430,82 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
44114430
}),
44124431
);
44134432

4414-
it.effect("checks out the submodules of the head an existing PR branch moves onto", () =>
4415-
Effect.gen(function* () {
4416-
// Git refuses `file:` submodule transports by default (CVE-2022-39253) and ignores
4417-
// repo-level config for it, so a local fixture needs the env allowance.
4418-
const previousAllowedProtocol = process.env.GIT_ALLOW_PROTOCOL;
4419-
process.env.GIT_ALLOW_PROTOCOL = "file";
4420-
yield* Effect.addFinalizer(() =>
4421-
Effect.sync(() => {
4422-
if (previousAllowedProtocol === undefined) {
4423-
delete process.env.GIT_ALLOW_PROTOCOL;
4424-
} else {
4425-
process.env.GIT_ALLOW_PROTOCOL = previousAllowedProtocol;
4426-
}
4427-
}),
4428-
);
4433+
it.effect.each(["adds", "removes"] as const)(
4434+
"checks out the submodules of the head an existing PR branch moves onto (head %s one)",
4435+
(headChange) =>
4436+
Effect.gen(function* () {
4437+
// Git refuses `file:` submodule transports by default (CVE-2022-39253) and ignores
4438+
// repo-level config for it, so a local fixture needs the env allowance.
4439+
const previousAllowedProtocol = process.env.GIT_ALLOW_PROTOCOL;
4440+
process.env.GIT_ALLOW_PROTOCOL = "file";
4441+
yield* Effect.addFinalizer(() =>
4442+
Effect.sync(() => {
4443+
if (previousAllowedProtocol === undefined) {
4444+
delete process.env.GIT_ALLOW_PROTOCOL;
4445+
} else {
4446+
process.env.GIT_ALLOW_PROTOCOL = previousAllowedProtocol;
4447+
}
4448+
}),
4449+
);
44294450

4430-
const submoduleDir = yield* makeTempDir("t3code-git-submodule-");
4431-
yield* initRepo(submoduleDir);
4432-
const repoDir = yield* makeTempDir("t3code-git-manager-");
4433-
yield* initRepo(repoDir);
4434-
const remoteDir = yield* createBareRemote();
4435-
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
4436-
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
4437-
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing"]);
4438-
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-existing"]);
4439-
yield* runGit(repoDir, ["checkout", "-b", "author-push"]);
4440-
yield* runGit(repoDir, ["submodule", "add", submoduleDir, "shared"]);
4441-
yield* runGit(repoDir, ["commit", "-m", "Add shared submodule"]);
4442-
yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-existing"]);
4443-
const pullHead = (yield* runGit(repoDir, ["rev-parse", "author-push"])).stdout.trim();
4444-
yield* runGit(repoDir, ["checkout", "main"]);
4451+
const submoduleDir = yield* makeTempDir("t3code-git-submodule-");
4452+
yield* initRepo(submoduleDir);
4453+
const repoDir = yield* makeTempDir("t3code-git-manager-");
4454+
yield* initRepo(repoDir);
4455+
const remoteDir = yield* createBareRemote();
4456+
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
4457+
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
4458+
yield* runGit(repoDir, ["checkout", "-b", "feature/pr-existing"]);
4459+
if (headChange === "removes") {
4460+
yield* runGit(repoDir, ["submodule", "add", submoduleDir, "shared"]);
4461+
yield* runGit(repoDir, ["commit", "-m", "Add shared submodule"]);
4462+
}
4463+
yield* runGit(repoDir, ["push", "-u", "origin", "feature/pr-existing"]);
4464+
yield* runGit(repoDir, ["checkout", "-b", "author-push"]);
4465+
if (headChange === "adds") {
4466+
yield* runGit(repoDir, ["submodule", "add", submoduleDir, "shared"]);
4467+
yield* runGit(repoDir, ["commit", "-m", "Add shared submodule"]);
4468+
} else {
4469+
yield* runGit(repoDir, ["rm", "shared"]);
4470+
yield* runGit(repoDir, ["commit", "-m", "Remove shared submodule"]);
4471+
}
4472+
yield* runGit(repoDir, ["push", "origin", "author-push:feature/pr-existing"]);
4473+
const pullHead = (yield* runGit(repoDir, ["rev-parse", "author-push"])).stdout.trim();
4474+
yield* runGit(repoDir, ["checkout", "main"]);
44454475

4446-
const { manager } = yield* makeManager({
4447-
providerScenario: {
4448-
pullRequest: {
4449-
number: 89,
4450-
title: "Submodule PR",
4451-
url: "https://github.com/pingdotgg/codething-mvp/pull/89",
4452-
baseRefName: "main",
4453-
headRefName: "feature/pr-existing",
4454-
state: "open",
4455-
isCrossRepository: false,
4456-
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
4457-
headRepositoryOwnerLogin: "pingdotgg",
4458-
},
4459-
repositoryCloneUrls: {
4460-
"pingdotgg/codething-mvp": { url: remoteDir, sshUrl: remoteDir },
4476+
const { manager } = yield* makeManager({
4477+
providerScenario: {
4478+
pullRequest: {
4479+
number: 89,
4480+
title: "Submodule PR",
4481+
url: "https://github.com/pingdotgg/codething-mvp/pull/89",
4482+
baseRefName: "main",
4483+
headRefName: "feature/pr-existing",
4484+
state: "open",
4485+
isCrossRepository: false,
4486+
headRepositoryNameWithOwner: "pingdotgg/codething-mvp",
4487+
headRepositoryOwnerLogin: "pingdotgg",
4488+
},
4489+
repositoryCloneUrls: {
4490+
"pingdotgg/codething-mvp": { url: remoteDir, sshUrl: remoteDir },
4491+
},
44614492
},
4462-
},
4463-
});
4493+
});
44644494

4465-
const result = yield* preparePullRequestThread(manager, {
4466-
cwd: repoDir,
4467-
reference: "89",
4468-
mode: "worktree",
4469-
});
4495+
const result = yield* preparePullRequestThread(manager, {
4496+
cwd: repoDir,
4497+
reference: "89",
4498+
mode: "worktree",
4499+
});
44704500

4471-
const worktreePath = result.worktreePath as string;
4472-
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(pullHead);
4473-
expect(NodeFS.existsSync(NodePath.join(worktreePath, "shared", "README.md"))).toBe(true);
4474-
expect(result).toMatchObject({ isOnPullRequestHead: true });
4475-
}),
4501+
const worktreePath = result.worktreePath as string;
4502+
expect((yield* runGit(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(pullHead);
4503+
expect(NodeFS.existsSync(NodePath.join(worktreePath, "shared", "README.md"))).toBe(
4504+
headChange === "adds",
4505+
);
4506+
expect((yield* runGit(worktreePath, ["status", "--porcelain"])).stdout).toBe("");
4507+
expect(result).toMatchObject({ isOnPullRequestHead: true });
4508+
}),
44764509
);
44774510

44784511
it.effect("refreshes a reused PR worktree onto the updated pull request head", () =>

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

Lines changed: 98 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2809,18 +2809,12 @@ export const make = Effect.gen(function* () {
28092809
const localPullRequestBranch =
28102810
resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);
28112811

2812-
const readWorktreeSubmodules = projectSettingsFor(input).pipe(
2813-
Effect.map(({ settings }) => settings.worktreeSubmodules),
2814-
Effect.orElseSucceed(() => null),
2815-
);
2816-
28172812
// Git refuses to move a branch that is checked out in a worktree, so the
28182813
// reuse paths cannot go through materializePullRequestHeadBranch and instead
28192814
// advance the checkout from inside the worktree.
28202815
const reuseExistingWorktree = Effect.fn("reuseExistingWorktree")(function* (
28212816
worktreePath: string,
28222817
checkedOutBranch: string,
2823-
isNewWorktree = false,
28242818
) {
28252819
if (checkedOutBranch !== localPullRequestBranch) {
28262820
// findLocalHeadBranch also accepts a branch that merely shares the head's bare name —
@@ -2893,16 +2887,9 @@ export const make = Effect.gen(function* () {
28932887
),
28942888
);
28952889

2896-
// A new worktree checked out its submodules for the commit it was created at.
2897-
if (isNewWorktree && refreshed.moved) {
2898-
yield* gitCore.updateWorktreeSubmodules(worktreePath, {
2899-
submodules: yield* readWorktreeSubmodules,
2900-
});
2901-
}
2902-
29032890
// Only when the checkout actually moved: another thread may be running in this worktree,
29042891
// and re-running the setup script under it buys nothing when the code did not change.
2905-
if (refreshed.moved || isNewWorktree) {
2892+
if (refreshed.moved) {
29062893
yield* maybeRunSetupScript(worktreePath);
29072894
}
29082895

@@ -2948,6 +2935,81 @@ export const make = Effect.gen(function* () {
29482935
return null;
29492936
});
29502937

2938+
// A branch no worktree has checked out can still carry commits nothing else holds, so it
2939+
// takes the head only where refreshCheckedOutBranch would move a checkout. It moves before
2940+
// its worktree exists because `git worktree add` checks out submodules for the commit it
2941+
// starts at, and a later move would leave them at the old commit's.
2942+
const moveIdleBranchToPullRequestHead = Effect.fn("moveIdleBranchToPullRequestHead")(
2943+
function* (branch: string) {
2944+
const { commitSha: branchCommit } = yield* gitCore.resolveCommit({
2945+
cwd: input.cwd,
2946+
revision: `refs/heads/${branch}`,
2947+
});
2948+
// Read before the upstream fetch, for the same reason as in reuseExistingWorktree.
2949+
const upstreamCommitBeforeFetch = yield* gitCore
2950+
.resolveCommit({ cwd: input.cwd, revision: `${branch}@{upstream}` })
2951+
.pipe(
2952+
Effect.map((resolved) => resolved.commitSha),
2953+
Effect.orElseSucceed(() => null),
2954+
);
2955+
2956+
yield* configurePullRequestHeadUpstream(input.cwd, pullRequestWithRemoteInfo, branch);
2957+
2958+
const { commitSha: targetCommit } = yield* changeRequestHeadRef(
2959+
input.cwd,
2960+
pullRequest.number,
2961+
).pipe(
2962+
Effect.flatMap((ref) => gitCore.fetchRefCommit({ cwd: input.cwd, ref })),
2963+
Effect.catch(() =>
2964+
Effect.gen(function* () {
2965+
const merge = yield* gitCore.readConfigValue(input.cwd, `branch.${branch}.merge`);
2966+
if (merge !== `refs/heads/${pullRequest.headBranch}`) {
2967+
return yield* new GitManagerError({
2968+
operation: "preparePullRequestThread",
2969+
cwd: input.cwd,
2970+
detail: "The pull request head could not be resolved for this branch.",
2971+
});
2972+
}
2973+
return yield* gitCore.resolveCommit({
2974+
cwd: input.cwd,
2975+
revision: `${branch}@{upstream}`,
2976+
});
2977+
}),
2978+
),
2979+
);
2980+
if (targetCommit === branchCommit) {
2981+
return true;
2982+
}
2983+
2984+
const isAncestor = yield* gitCore
2985+
.execute({
2986+
operation: "GitManager.preparePullRequestThread.isAncestor",
2987+
cwd: input.cwd,
2988+
args: ["merge-base", "--is-ancestor", branchCommit, targetCommit],
2989+
allowNonZeroExit: true,
2990+
})
2991+
.pipe(Effect.map((result) => result.exitCode === 0));
2992+
if (!isAncestor && branchCommit !== upstreamCommitBeforeFetch) {
2993+
return false;
2994+
}
2995+
if (!isAncestor) {
2996+
// As refreshCheckedOutBranch does, so the rewritten-away commit stays findable.
2997+
yield* gitCore.execute({
2998+
operation: "GitManager.preparePullRequestThread.keepPrevious",
2999+
cwd: input.cwd,
3000+
args: ["update-ref", "refs/t3code/pre-refresh", branchCommit],
3001+
});
3002+
}
3003+
// The old value makes git refuse the move if the branch changed since it was read.
3004+
yield* gitCore.execute({
3005+
operation: "GitManager.preparePullRequestThread.moveBranch",
3006+
cwd: input.cwd,
3007+
args: ["update-ref", `refs/heads/${branch}`, targetCommit, branchCommit],
3008+
});
3009+
return true;
3010+
},
3011+
);
3012+
29513013
const createPullRequestWorktree = Effect.fn("createPullRequestWorktree")(function* () {
29523014
return yield* gitCore.createWorktree(
29533015
{
@@ -2957,7 +3019,10 @@ export const make = Effect.gen(function* () {
29573019
},
29583020
{
29593021
worktreesDirectory: yield* readWorktreesDirectory,
2960-
submodules: yield* readWorktreeSubmodules,
3022+
submodules: yield* projectSettingsFor(input).pipe(
3023+
Effect.map(({ settings }) => settings.worktreeSubmodules),
3024+
Effect.orElseSucceed(() => null),
3025+
),
29613026
},
29623027
);
29633028
});
@@ -2983,16 +3048,26 @@ export const make = Effect.gen(function* () {
29833048
"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.",
29843049
});
29853050
}
2986-
// A branch no worktree has checked out can still carry commits nothing else holds, and
2987-
// materializing would force it onto the head. Check it out as it is, and let the reused
2988-
// worktree refresh move it only where that loses nothing.
3051+
// Materializing would force this branch onto the head.
29893052
if (existingBranchBeforeFetch !== null) {
2990-
const worktree = yield* createPullRequestWorktree();
2991-
return yield* reuseExistingWorktree(
2992-
worktree.worktree.path,
2993-
existingBranchBeforeFetch.name,
2994-
true,
3053+
const isOnPullRequestHead = yield* moveIdleBranchToPullRequestHead(
3054+
localPullRequestBranch,
3055+
).pipe(
3056+
Effect.catch((error) =>
3057+
Effect.logWarning("GitManager.preparePullRequestThread existing branch move failed", {
3058+
localBranch: localPullRequestBranch,
3059+
cause: error,
3060+
}).pipe(Effect.as(false)),
3061+
),
29953062
);
3063+
const worktree = yield* createPullRequestWorktree();
3064+
yield* maybeRunSetupScript(worktree.worktree.path);
3065+
return {
3066+
pullRequest,
3067+
branch: worktree.worktree.refName,
3068+
worktreePath: worktree.worktree.path,
3069+
isOnPullRequestHead,
3070+
};
29963071
}
29973072

29983073
yield* materializePullRequestHeadBranch(

‎apps/server/src/vcs/GitVcsDriver.ts‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -357,11 +357,6 @@ export class GitVcsDriver extends Context.Service<
357357
input: VcsCreateWorktreeInput,
358358
options?: CreateWorktreeOptions,
359359
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
360-
/** Checks out the submodules of the worktree's current revision, as `createWorktree` does. */
361-
readonly updateWorktreeSubmodules: (
362-
worktreePath: string,
363-
options?: CreateWorktreeOptions,
364-
) => Effect.Effect<void, never>;
365360
/** Force-updates local `branch` to the primary remote's `ref`. */
366361
readonly fetchRefIntoBranch: (
367362
input: GitFetchRefInput & { readonly branch: string },

0 commit comments

Comments
 (0)