diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index ae35e44cd3ccf..824d4de1d52fc 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -4426,7 +4426,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); - it.effect("createPullRequest refuses a branch with commits it has not pushed", () => + it.effect("createPullRequest pushes the branch before opening its PR", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); yield* initRepo(repoDir); @@ -4434,27 +4434,94 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); yield* runGit(repoDir, ["push", "-u", "origin", "main"]); yield* runGit(repoDir, ["checkout", "-b", "feature/unpushed"]); - yield* runGit(repoDir, ["push", "-u", "origin", "feature/unpushed"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "first.txt"), "first\n"); + yield* runGit(repoDir, ["add", "first.txt"]); + yield* runGit(repoDir, ["commit", "-m", "First commit"]); + const remoteHead = (branch: string) => + runGit(repoDir, ["ls-remote", "origin", `refs/heads/${branch}`]).pipe( + Effect.map((result) => result.stdout.split("\t")[0]), + ); + const localHead = () => + runGit(repoDir, ["rev-parse", "HEAD"]).pipe(Effect.map((result) => result.stdout.trim())); + + // A branch without an upstream is published first. + const unpublished = yield* makeManager({ providerScenario: { prListSequence: [[], []] } }); + yield* unpublished.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Feature", + body: "Body", + }); + expect(yield* remoteHead("feature/unpushed")).toBe(yield* localHead()); + expect(created(unpublished.providerCalls)).toMatchObject([ + { headSelector: "feature/unpushed" }, + ]); + + // Commits made after publishing are pushed too. NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); yield* runGit(repoDir, ["add", "late.txt"]); yield* runGit(repoDir, ["commit", "-m", "Late commit"]); - const { manager, providerCalls } = yield* makeManager({ - providerScenario: { prListSequence: [[], []] }, + const ahead = yield* makeManager({ providerScenario: { prListSequence: [[], []] } }); + yield* ahead.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Feature", + body: "Body", }); - + expect(yield* remoteHead("feature/unpushed")).toBe(yield* localHead()); + expect(created(ahead.providerCalls)).toHaveLength(1); + + // A rejected push fails with git's reason and opens nothing; it never forces. + const otherDir = yield* makeTempDir("t3code-git-manager-other-"); + yield* runGit(otherDir, ["clone", "--branch", "feature/unpushed", remoteDir, "."]); + yield* runGit(otherDir, ["config", "user.email", "other@example.com"]); + yield* runGit(otherDir, ["config", "user.name", "Other"]); + NodeFS.writeFileSync(NodePath.join(otherDir, "theirs.txt"), "theirs\n"); + yield* runGit(otherDir, ["add", "theirs.txt"]); + yield* runGit(otherDir, ["commit", "-m", "Their commit"]); + yield* runGit(otherDir, ["push"]); + const theirHead = yield* remoteHead("feature/unpushed"); + NodeFS.writeFileSync(NodePath.join(repoDir, "mine.txt"), "mine\n"); + yield* runGit(repoDir, ["add", "mine.txt"]); + yield* runGit(repoDir, ["commit", "-m", "My commit"]); + const rejected = yield* makeManager({ providerScenario: { prListSequence: [[], []] } }); const error = yield* Effect.flip( - manager.createPullRequest({ + rejected.manager.createPullRequest({ cwd: repoDir, projectId: ProjectId.make("project-1"), title: "Feature", body: "Body", }), ); + expect(error.message).toContain("Could not push feature/unpushed"); + expect(error.message).toContain("Pull or rebase, then push again"); + expect(yield* remoteHead("feature/unpushed")).toBe(theirHead); + expect(created(rejected.providerCalls)).toEqual([]); + yield* runGit(repoDir, ["fetch", "origin"]); + yield* runGit(repoDir, ["reset", "--hard", "origin/feature/unpushed"]); + + // A publish whose upstream cannot be recorded says so instead of claiming nothing was pushed. + yield* runGit(repoDir, ["checkout", "-b", "feature/locked"]); + const lockPath = NodePath.join(repoDir, ".git", "config.lock"); + NodeFS.writeFileSync(lockPath, ""); + const locked = yield* makeManager({ providerScenario: { prListSequence: [[], []] } }); + // The upstream write retries on the real clock before giving up. + const lockedError = yield* Effect.flip( + TestClock.withLive( + locked.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Feature", + body: "Body", + }), + ), + ); + NodeFS.rmSync(lockPath); + expect(lockedError.message).toContain("could not record it as the branch's upstream"); + expect(yield* remoteHead("feature/locked")).toBe(yield* localHead()); + expect(created(locked.providerCalls)).toEqual([]); + yield* runGit(repoDir, ["checkout", "feature/unpushed"]); - expect(error.message).toContain("1 unpushed commit"); - expect(created(providerCalls)).toEqual([]); - - // An open PR is returned as it is; returning it publishes nothing. const open = { number: 7, title: "Feature", @@ -4462,7 +4529,14 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { baseRefName: "main", headRefName: "feature/unpushed", }; - const existing = yield* makeManager({ providerScenario: { prListSequence: [[open]] } }); + // Pushing into an open PR returns it, and status no longer reports the pushed commit. + NodeFS.writeFileSync(NodePath.join(repoDir, "into-open.txt"), "into open\n"); + yield* runGit(repoDir, ["add", "into-open.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Into open PR"]); + const existing = yield* makeManager({ + providerScenario: { prListSequence: [[open], [open], [open], [open]] }, + }); + expect((yield* existing.manager.status({ cwd: repoDir })).aheadCount).toBe(1); const found = yield* existing.manager.createPullRequest({ cwd: repoDir, projectId: ProjectId.make("project-1"), @@ -4470,6 +4544,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { body: "Body", }); expect(found).toMatchObject({ status: "opened_existing", number: 7 }); + expect((yield* existing.manager.status({ cwd: repoDir })).aheadCount).toBe(0); // A retry after a failed draft finds the open PR and still drafts it. const actions: Array = []; @@ -4492,7 +4567,6 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { ]); // A draft of a PR the host does not list yet fails, so a retry drafts it. - yield* runGit(repoDir, ["push"]); const unlisted = yield* makeManager({ providerScenario: { prListSequence: [[], []], createsDraftChangeRequests: false }, }); @@ -4533,6 +4607,73 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("createPullRequest pushes to the push remote and never to the base branch", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "add", "fork", forkDir]); + const readOrigin = (branch: string) => + runGit(repoDir, ["ls-remote", "origin", `refs/heads/${branch}`]).pipe( + Effect.map((result) => result.stdout), + ); + const commit = (file: string) => + Effect.gen(function* () { + NodeFS.writeFileSync(NodePath.join(repoDir, file), `${file}\n`); + yield* runGit(repoDir, ["add", file]); + yield* runGit(repoDir, ["commit", "-m", file]); + }); + const createPr = (manager: GitManager.GitManager["Service"]) => + manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Feature", + body: "Body", + }); + + // Commits on the base branch are never pushed to it. + yield* commit("on-main.txt"); + const originMain = yield* readOrigin("main"); + const onBase = yield* makeManager({ providerScenario: { prListSequence: [[]] } }); + const error = yield* Effect.flip(createPr(onBase.manager)); + expect(error.message).toContain("main is the base branch"); + expect(yield* readOrigin("main")).toBe(originMain); + expect(created(onBase.providerCalls)).toEqual([]); + yield* runGit(repoDir, ["reset", "--hard", "origin/main"]); + + // A push to a separate push remote leaves the upstream behind, and still opens the PR. + yield* runGit(repoDir, ["checkout", "-b", "topic"]); + yield* commit("topic.txt"); + yield* runGit(repoDir, ["push", "-u", "origin", "topic"]); + yield* commit("late.txt"); + yield* configureVisibleRemoteUrlWithLocalRewrite( + repoDir, + "origin", + "git@github.com:pingdotgg/codething-mvp.git", + originDir, + ); + yield* configureVisibleRemoteUrlWithLocalRewrite( + repoDir, + "fork", + "git@github.com:octocat/codething-mvp.git", + forkDir, + ); + yield* runGit(repoDir, ["config", "remote.pushDefault", "fork"]); + const viaFork = yield* makeManager(); + const result = yield* createPr(viaFork.manager); + expect(result.status).toBe("created"); + expect( + yield* runGit(forkDir, ["--git-dir=.", "log", "-1", "--pretty=%s", "topic"]), + ).toMatchObject({ stdout: "late.txt\n" }); + expect(created(viaFork.providerCalls)).toEqual([ + { baseRefName: "main", headSelector: "octocat:topic" }, + ]); + }), + ); + it.effect("generates PR content from the created worktree's selected remote base", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 92b961d763b46..b83d2dd1d8fae 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -187,7 +187,7 @@ export class GitManager extends Context.Service< input: GitRunStackedActionInput, options?: GitRunStackedActionOptions, ) => Effect.Effect; - /** Opens a PR for the checkout's pushed branch, or returns the one already open. */ + /** Pushes the checkout's branch when needed, then opens its PR or returns the one already open. */ readonly createPullRequest: (input: { readonly cwd: string; readonly projectId: ProjectId; @@ -845,6 +845,22 @@ export const make = Effect.gen(function* () { } return result; }); + const createPrNeedsPush = Effect.fn("GitManager.createPrNeedsPush")(function* ( + cwd: string, + status: { + readonly branch: string | null; + readonly hasUpstream: boolean; + readonly aheadCount: number; + }, + ) { + if (!status.branch) return false; + if (!status.hasUpstream || status.aheadCount > 0) return true; + // A current upstream says nothing about a separate push remote, which may lack HEAD. + const target = yield* gitCore + .resolvePushTarget(cwd, { branch: status.branch, hasUpstream: true }) + .pipe(Effect.orElseSucceed(() => null)); + return target?.viaPushRemote === true; + }); const readWorktreeCreationSettings = serverSettingsService.getSettings.pipe( Effect.map((settings) => ({ worktreesDirectory: settings.worktreesDirectory, @@ -2511,8 +2527,9 @@ export const make = Effect.gen(function* () { }; } - // A PR opened from the remote branch would leave out commits not pushed yet. - if (details.aheadCount > 0) { + // A PR opened from the remote branch would leave out commits not pushed yet. The ahead + // count is against the upstream, which a push to a separate push remote leaves behind. + if (!pushRemoteRef && details.aheadCount > 0) { return yield* new GitManagerError({ operation: "runPrStep", cwd, @@ -2649,17 +2666,57 @@ export const make = Effect.gen(function* () { const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( "GitManager.createPullRequest", )(function* (input) { - const result = yield* openPrFromBranch( - input.cwd, - null, - () => Effect.void, - undefined, - input.baseBranch, - input.draft === true, - () => Effect.succeed({ title: input.title, body: input.body }), + const status = yield* gitCore.statusDetails(input.cwd); + const needsPush = yield* createPrNeedsPush(input.cwd, status); + if (needsPush && status.branch) { + yield* ensurePrHeadIsNotBase( + input.cwd, + { ...status, branch: status.branch }, + (yield* changeRequestTermsFor(input.cwd)).shortLabelWithArticle, + ); + } + const push = needsPush + ? yield* pushCurrentBranch(input.cwd, status.branch).pipe( + Effect.mapError( + (cause) => + new GitManagerError({ + operation: "createPullRequest", + cwd: input.cwd, + detail: `Could not push ${status.branch}: ${cause.detail}${cause.reason === undefined ? "" : ` (${cause.reason})`}`, + cause, + }), + ), + ) + : null; + const result = yield* Effect.gen(function* () { + // Publishing records the upstream, which the PR step needs to find the head branch. + if (!status.hasUpstream && push?.status === "pushed" && push.setUpstream === false) { + return yield* new GitManagerError({ + operation: "createPullRequest", + cwd: input.cwd, + detail: `Pushed ${status.branch} to ${push.upstreamBranch}, but could not record it as the branch's upstream. Set the upstream, then try again.`, + }); + } + return yield* openPrFromBranch( + input.cwd, + null, + () => Effect.void, + push && "pushRemote" in push && push.pushRemote && push.upstreamBranch + ? { remoteName: push.pushRemote, upstreamRef: push.upstreamBranch } + : undefined, + input.baseBranch, + input.draft === true, + () => Effect.succeed({ title: input.title, body: input.body }), + ); + }).pipe( + // A push changes the ahead count, and a new PR changes the branch's PR lookup, so + // both leave cached status stale whatever the PR step does next. + Effect.onExit((exit) => + push?.status === "pushed" || (Exit.isSuccess(exit) && exit.value.status === "created") + ? invalidateStatus(input.cwd) + : Effect.void, + ), ); - // The thread's branch PR comes from status, which may hold the lookup from before. - if (result.status === "created") yield* invalidateStatus(input.cwd); const openedAsDraft = result.status === "created" && (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; @@ -3614,26 +3671,12 @@ export const make = Effect.gen(function* () { > { const initialStatus = yield* gitCore.statusDetails(input.cwd); const wantsCommit = isCommitAction(input.action); - const upToDateBranch = - input.action === "create_pr" && - initialStatus.hasUpstream && - initialStatus.aheadCount === 0 - ? initialStatus.branch - : null; - // A current upstream says nothing about a separate push remote, which may lack HEAD. - const pushTarget = upToDateBranch - ? yield* gitCore - .resolvePushTarget(input.cwd, { branch: upToDateBranch, hasUpstream: true }) - .pipe(Effect.orElseSucceed(() => null)) - : null; const wantsPush = input.action === "push" || input.action === "commit_push" || input.action === "commit_push_pr" || (input.action === "create_pr" && - (!initialStatus.hasUpstream || - initialStatus.aheadCount > 0 || - pushTarget?.viaPushRemote === true)); + (!initialStatus.hasUpstream || (yield* createPrNeedsPush(input.cwd, initialStatus)))); const wantsPr = input.action === "create_pr" || input.action === "commit_push_pr"; if (input.featureBranch && !wantsCommit) { diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index b65638addcadf..71d0a28d4e392 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -668,7 +668,7 @@ const ListPullRequestsTool = Tool.make("pull_request_list", { .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenWithoutForge); const CreatePullRequestTool = Tool.make("pull_request_create", { - description: "Open a PR from this thread's pushed branch and link it, or return its open PR.", + description: "Push this thread's branch, then open its PR and link it, or return its open PR.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, title: TrimmedNonEmptyString, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index d47a403c0115e..aa4cc9f365389 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 58404 + "mcpToolListJsonBytes": 58405 }