From 1053266ced67ef4cef2c94197e83e57647709790 Mon Sep 17 00:00:00 2001 From: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:16:28 -0700 Subject: [PATCH 01/24] feat(server): agents read, open, update, respond to, and merge PRs through MCP tools Agents shelled out to gh and cafe for PR work (about 18,000 forge commands in 45 days across three machines), which spends the user's own quota and gives agents raw JSON to trim with --jq. Six new MCP tools route that work through PullRequestService, so it uses the server's forge sign-in (the T3 Code for GitHub app where it is signed in) and works on every forge T3 supports. - pull_request_read: summary, checks, conversation (unresolved threads by default) and diff, defaulting to the PR for the thread's branch. - pull_request_list, pull_request_update, pull_request_respond. - pull_request_create: GitManager.createPullRequest shares runPrStep's branch, upstream, existing-PR and base checks, takes the agent's title and body, and links the PR to the thread. - pull_request_merge: requires expectedHeadSha. PullRequestService refuses a merge whose head moved on every host, and GitHub also pins it atomically through expectedHeadOid. The tool list grows by 2,815 bytes. New mcp-tool-use cases pass 12/12 on Sonnet 5.5 (0/12 on main), the control stays 4/4, and the eval runner answers the new tools from each case's world. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/git/GitManager.ts | 131 +++++-- apps/server/src/mcp/McpHttpServer.test.ts | 3 + .../toolkits/pullRequests/handlers.test.ts | 175 +++++++++ .../src/mcp/toolkits/pullRequests/handlers.ts | 335 +++++++++++++++++- .../src/mcp/toolkits/pullRequests/tools.ts | 292 +++++++++++++++ .../src/provider/AgentContextBudget.test.ts | 2 + .../pullRequest/PullRequestService.test.ts | 24 ++ .../src/pullRequest/PullRequestService.ts | 30 +- docs/user/source-control.md | 4 + evals/mcp-tool-use/cases/pull-requests.ndjson | 4 + evals/mcp-tool-use/run.ts | 120 +++++++ packages/client-runtime/src/t3ToolSummary.ts | 102 ++++++ packages/contracts/src/pullRequest.ts | 2 + packages/shared/src/t3McpToolPresentation.ts | 32 ++ .../src/server/PullRequestProvider.ts | 2 + .../src/server/GitHubPullRequestApi.ts | 5 +- .../src/server/GitHubPullRequestProvider.ts | 3 + 17 files changed, 1225 insertions(+), 41 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 92d693a17382b..d39bc6c39609e 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -125,6 +125,16 @@ interface SourceControlTextGenerationSettings { readonly style: SourceControlWritingStyleSettings; } +export interface GitCreatePullRequestResult { + readonly status: "created" | "opened_existing"; + /** Absent when the host accepted the PR but did not list it back yet. */ + readonly url?: string; + readonly number?: number; + readonly baseBranch: string; + readonly headBranch: string; + readonly title: string; +} + export class GitManager extends Context.Service< GitManager, { @@ -175,6 +185,13 @@ 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. */ + readonly createPullRequest: (input: { + readonly cwd: string; + readonly title: string; + readonly body: string; + readonly baseBranch?: string | undefined; + }) => Effect.Effect; readonly subscribePullRequestStateChanges: Effect.Effect< Stream.Stream, never, @@ -2437,13 +2454,18 @@ export const make = Effect.gen(function* () { }); }); - const runPrStep = Effect.fn("runPrStep")(function* ( - settings: SourceControlTextGenerationSettings, + const openPrFromBranch = Effect.fn("openPrFromBranch")(function* ( cwd: string, fallbackBranch: string | null, - threadId: ThreadId | undefined, emit: GitActionProgressEmitter, - pushRemoteRef?: { readonly remoteName: string; readonly upstreamRef: string }, + pushRemoteRef: { readonly remoteName: string; readonly upstreamRef: string } | undefined, + requestedBase: string | undefined, + content: (input: { + readonly provider: SourceControlProvider.SourceControlProvider["Service"]; + readonly baseBranch: string; + readonly baseRef: string; + readonly headBranch: string; + }) => Effect.Effect<{ readonly title: string; readonly body: string }, E>, ) { const provider = yield* sourceControlProvider(cwd); const terms = sourceControlDefinitions.get(provider.kind).changeRequest; @@ -2483,42 +2505,14 @@ export const make = Effect.gen(function* () { }; } - const { baseBranch, baseRef } = yield* resolvePrBase( - cwd, - branch, - details.upstreamRef, - headContext, - ); - yield* emit({ - kind: "phase_started", - phase: "pr", - label: `Generating ${terms.shortLabel} content...`, - }); - const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef); - const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef); - const policy = yield* resolveStylePolicy(cwd, settings); - const changeRequestTemplate = - settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate - ? Option.getOrUndefined( - yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }), - ) - : undefined; - const threadContext = yield* readThreadContext(threadId); - - const generated = yield* textGeneration.generatePrContent({ - cwd, + const resolved = yield* resolvePrBase(cwd, branch, details.upstreamRef, headContext); + const baseBranch = requestedBase ?? resolved.baseBranch; + const generated = yield* content({ + provider, baseBranch, + baseRef: requestedBase ?? resolved.baseRef, headBranch: headContext.headBranch, - commitSummary: limitContext(rangeContext.commitSummary, 20_000), - diffSummary: limitContext(rangeContext.diffSummary, 20_000), - diffPatch: limitContext(rangeContext.diffPatch, 60_000), - ...(changeRequestTemplate ? { changeRequestTemplate } : {}), - ...(threadContext ? { threadContext } : {}), - ...(policy ? { policy } : {}), - modelSelection: settings.modelSelection, - projectId: settings.projectId, }); - const bodyFile = path.join( tempDir, `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`, @@ -2587,6 +2581,68 @@ export const make = Effect.gen(function* () { }; }); + const runPrStep = ( + settings: SourceControlTextGenerationSettings, + cwd: string, + fallbackBranch: string | null, + threadId: ThreadId | undefined, + emit: GitActionProgressEmitter, + pushRemoteRef?: { readonly remoteName: string; readonly upstreamRef: string }, + ) => + openPrFromBranch( + cwd, + fallbackBranch, + emit, + pushRemoteRef, + undefined, + ({ provider, baseBranch, baseRef, headBranch }) => + Effect.gen(function* () { + const terms = sourceControlDefinitions.get(provider.kind).changeRequest; + yield* emit({ + kind: "phase_started", + phase: "pr", + label: `Generating ${terms.shortLabel} content...`, + }); + const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseRef); + const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef); + const policy = yield* resolveStylePolicy(cwd, settings); + const changeRequestTemplate = + settings.style.followChangeRequestTemplates && provider.readChangeRequestTemplate + ? Option.getOrUndefined( + yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }), + ) + : undefined; + const threadContext = yield* readThreadContext(threadId); + + return yield* textGeneration.generatePrContent({ + cwd, + baseBranch, + headBranch, + commitSummary: limitContext(rangeContext.commitSummary, 20_000), + diffSummary: limitContext(rangeContext.diffSummary, 20_000), + diffPatch: limitContext(rangeContext.diffPatch, 60_000), + ...(changeRequestTemplate ? { changeRequestTemplate } : {}), + ...(threadContext ? { threadContext } : {}), + ...(policy ? { policy } : {}), + modelSelection: settings.modelSelection, + projectId: settings.projectId, + }); + }), + ); + + const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( + "GitManager.createPullRequest", + )(function* (input) { + return yield* openPrFromBranch( + input.cwd, + null, + () => Effect.void, + undefined, + input.baseBranch, + () => Effect.succeed({ title: input.title, body: input.body }), + ); + }); + const localStatus: GitManager["Service"]["localStatus"] = Effect.fn("localStatus")( function* (input, options) { const cacheKey = yield* normalizeStatusCacheKey(input.cwd); @@ -3726,6 +3782,7 @@ export const make = Effect.gen(function* () { resolvePullRequest, preparePullRequestThread, runStackedAction, + createPullRequest, subscribePullRequestStateChanges: PubSub.subscribe(pullRequestStateChanges).pipe( Effect.map((subscription) => Stream.fromSubscription(subscription)), ), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 5f9f8fec837c6..89a586bdeba0b 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -46,6 +46,7 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as PreviewManager from "../preview/Manager.ts"; import * as DeviceService from "../device/DeviceService.ts"; +import * as GitManager from "../git/GitManager.ts"; import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; import * as ServerConfig from "../config.ts"; @@ -108,6 +109,7 @@ const layerPullRequestsTest = McpHttpServer.layerPullRequestsToolkit.pipe( Layer.mock(ProjectService.ProjectService)({}), Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), Layer.mock(PullRequestService.PullRequestService)({}), + Layer.mock(GitManager.GitManager)({}), Layer.mock(Orchestrator.OrchestratorV2)({}), Layer.mock(ProjectionStore.ProjectionStoreV2)({}), NodeServices.layer, @@ -1793,6 +1795,7 @@ it.effect("lists pull request watch tools only to threads that are not delegated Layer.mock(ProjectService.ProjectService)({}), Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), Layer.mock(PullRequestService.PullRequestService)({}), + Layer.mock(GitManager.GitManager)({}), Layer.mock(Orchestrator.OrchestratorV2)({}), Layer.mock(ProjectionStore.ProjectionStoreV2)({}), NodeServices.layer, diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 3c454cbe6e48c..587ccec092a94 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -6,6 +6,9 @@ import { type OrchestrationV2ServerCommand as OrchestrationCommand, PullRequestOperationError, type OrchestrationProjectShell, + type PullRequestActionInput, + type PullRequestActivity, + type PullRequestDetail, type PullRequestRef, type PullRequestReviewGuideResult, type ThreadPullRequestLink, @@ -20,6 +23,7 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import type { Tool } from "effect/ai"; +import * as GitManager from "../../../git/GitManager.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import { type PullRequestTestThread, @@ -28,6 +32,7 @@ import { import * as ProjectService from "../../../project/ProjectService.ts"; import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; +import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; @@ -144,6 +149,8 @@ interface HarnessOptions { PullRequestReviewGuideResult & { started: boolean }, PullRequestOperationError >; + readonly pullRequests?: Partial; + readonly git?: Partial; } const NO_GUIDE: PullRequestReviewGuideResult = { guide: null, run: null, currentHeadSha: "head-1" }; @@ -196,6 +203,8 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null), dispatch, }), + Layer.mock(PullRequestService.PullRequestService)(options.pullRequests ?? {}), + Layer.mock(GitManager.GitManager)(options.git ?? {}), Layer.succeed(SecureRandom.SecureRandom, testCrypto), McpToolAccessTestkit.liveThreadsLayer, ); @@ -784,3 +793,169 @@ describe("pull request guide tools", () => { }), ); }); + +describe("source control tools", () => { + const branchThread = { + ...makeThread([]), + worktreePath: "/workspace/worktree", + branchPullRequest: { + projectId: PROJECT_ID, + repository: "t3tools/t3code", + number: 42, + url: "https://github.com/t3tools/t3code/pull/42", + }, + }; + const detail = { + title: "Add tools", + body: "Adds tools.", + state: "open", + isDraft: false, + author: null, + headBranch: "tools", + baseBranch: "main", + headSha: "abc123", + mergeability: "mergeable", + additions: 1, + deletions: 0, + changedFiles: 1, + labels: [], + reviewers: [], + checks: [{ name: "CI", status: "success", description: null, url: null }], + } as unknown as PullRequestDetail; + const reviewThread = (id: string, isResolved: boolean) => ({ + id, + path: "a.ts", + line: 1, + side: "right" as const, + isResolved, + isOutdated: false, + comments: [], + }); + const activity: PullRequestActivity = { + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [reviewThread("open-thread", false), reviewThread("done-thread", true)], + commits: [], + }; + + it.effect("reads the thread's branch PR, only the sections asked, without resolved threads", () => + Effect.gen(function* () { + const asked: Array = []; + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { + detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)), + activity: () => Effect.succeed(activity), + }, + }); + const result = yield* harness.call("pull_request_read", { + sections: ["summary", "conversation"], + }); + expect(asked).toEqual([ + { projectId: PROJECT_ID, host: "github.com", repository: "t3tools/t3code", number: 42 }, + ]); + expect(result.summary?.headSha).toBe("abc123"); + expect(result.checks).toBeUndefined(); + expect(result.conversation?.reviewThreads.map((thread) => thread.id)).toEqual([ + "open-thread", + ]); + expect(result.conversation?.hiddenResolvedThreads).toBe(1); + }), + ); + + it.effect("asks for a number when the thread's branch has no PR", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + const error = yield* harness.call("pull_request_read", {}).pipe(Effect.flip); + expect(error._tag).toBe("PullRequestBranchHasNoneError"); + }), + ); + + it.effect("merges pinned to the head the agent checked", () => + Effect.gen(function* () { + const actions: Array = []; + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { + runAction: (input) => Effect.sync(() => void actions.push(input)), + summary: () => Effect.succeed({ state: "open" } as never), + }, + }); + const result = yield* harness.call("pull_request_merge", { + expectedHeadSha: "abc123", + method: "squash", + auto: true, + }); + expect(result).toMatchObject({ number: 42, state: "open" }); + expect(actions).toMatchObject([ + { + number: 42, + action: "enable-auto-merge", + expectedHeadSha: "abc123", + mergeMethod: "squash", + }, + ]); + }), + ); + + it.effect("opens a PR from the thread's worktree, links it, and makes it a draft", () => + Effect.gen(function* () { + const actions: Array = []; + const opened: Array = []; + const harness = yield* makeHarness({ + thread: { ...makeThread([]), worktreePath: "/workspace/worktree" }, + git: { + createPullRequest: (input) => + Effect.sync(() => opened.push(input.cwd)).pipe( + Effect.as({ + status: "created" as const, + url: "https://github.com/t3tools/t3code/pull/43", + number: 43, + baseBranch: "main", + headBranch: "tools", + title: input.title, + }), + ), + }, + pullRequests: { runAction: (input) => Effect.sync(() => void actions.push(input)) }, + }); + const result = yield* harness.call("pull_request_create", { + title: "Add tools", + body: "Adds tools.", + draft: true, + }); + expect(result).toMatchObject({ number: 43, created: true }); + expect(opened).toEqual(["/workspace/worktree"]); + expect(actions).toMatchObject([{ number: 43, action: "draft" }]); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.link", number: 43, source: "created" }, + ]); + }), + ); + + it.effect("replies to and resolves a review thread, and refuses resolving without one", () => + Effect.gen(function* () { + const calls: Array = []; + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { + replyToThread: (input) => Effect.sync(() => calls.push(`reply ${input.threadId}`)), + setThreadResolution: (input) => + Effect.sync(() => calls.push(`resolve ${input.threadId} ${input.resolved}`)), + }, + }); + const result = yield* harness.call("pull_request_respond", { + reviewThreadId: "open-thread", + body: "Fixed.", + resolved: true, + }); + expect(result).toMatchObject({ replied: true, resolved: true }); + expect(calls).toEqual(["reply open-thread", "resolve open-thread true"]); + const error = yield* harness + .call("pull_request_respond", { body: "Done", resolved: true }) + .pipe(Effect.flip); + expect(error._tag).toBe("PullRequestNothingToDoError"); + }), + ); +}); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 46afff241f408..741ef09b158e7 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -1,5 +1,6 @@ import { CommandId, + type PullRequestRef, type OrchestrationProjectShell, type PullRequestState, type PullRequestWatchUntil, @@ -12,11 +13,13 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as GitManager from "../../../git/GitManager.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ProjectService from "../../../project/ProjectService.ts"; import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; import { resolveTarget, type ResolvedTarget } from "../../../pullRequest/pullRequestTarget.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; +import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts"; import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts"; import { @@ -32,6 +35,12 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import { threadNotFound } from "../../threadAccess.ts"; import { type ListThreadPullRequestsResult, + PullRequestBranchHasNoneError, + PullRequestForgeError, + PullRequestNothingToDoError, + type PullRequestReadSection, + type ReadPullRequestResult, + type ThreadPullRequestInput, PullRequestLinkFailedError, PullRequestUnlinkFailedError, PullRequestListFailedError, @@ -148,6 +157,8 @@ const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const watches = yield* PullRequestWatchService.PullRequestWatchService; + const pullRequests = yield* PullRequestService.PullRequestService; + const git = yield* GitManager.GitManager; const projects = yield* ProjectService.ProjectService; const random = yield* SecureRandom.SecureRandom; @@ -162,7 +173,8 @@ const make = Effect.gen(function* () { Failure: | typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError - | typeof PullRequestListFailedError, + | typeof PullRequestListFailedError + | typeof PullRequestForgeError, requested: ThreadId | undefined, ) { const scope = yield* McpInvocationContext.requireMcpCapability("pull-requests"); @@ -182,7 +194,10 @@ const make = Effect.gen(function* () { const projectOf = ( thread: OrchestrationV2ThreadShell, - Failure: typeof PullRequestLinkFailedError | typeof PullRequestUnlinkFailedError, + Failure: + | typeof PullRequestLinkFailedError + | typeof PullRequestUnlinkFailedError + | typeof PullRequestForgeError, ) => projects.getShell(thread.projectId).pipe( Effect.map(Option.getOrUndefined), @@ -280,6 +295,159 @@ const make = Effect.gen(function* () { handle: (params: P) => Effect.Effect, ) => McpToolAccess.writesThreads((params: P) => [params.threadId], handle); + const forgeFailure = (error: { readonly message: string }) => + new PullRequestForgeError({ detail: error.message, cause: error }); + + /** The thread's checkout, its project, and the PR the input names (default: the branch's). */ + const locate = Effect.fn("PullRequestsToolkit.locate")(function* (input: ThreadPullRequestInput) { + const thread = yield* requireThread(PullRequestForgeError, undefined); + const project = yield* projectOf(thread, PullRequestForgeError); + if (project === undefined) { + return yield* new PullRequestProjectNotFoundError({ repository: input.repository ?? "" }); + } + const branchPullRequest = thread.branchPullRequest ?? null; + const branchRepository = + project.repositoryIdentity == null + ? undefined + : (sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? undefined); + const named = + input.number !== undefined + ? { number: input.number, repository: input.repository ?? branchRepository } + : branchPullRequest === null + ? null + : { number: branchPullRequest.number, repository: branchPullRequest.repository }; + if (named === null) return yield* new PullRequestBranchHasNoneError(); + const target = yield* resolveTarget(named, project); + const ref: PullRequestRef = { + projectId: project.id, + host: target.host, + repository: target.repository, + number: target.number, + }; + return { thread, project, target, ref }; + }); + + const identityOf = (target: ResolvedTarget) => ({ + host: target.host, + repository: target.repository, + number: target.number, + url: target.url, + }); + + const readSections = Effect.fn("PullRequestsToolkit.readSections")(function* ( + ref: PullRequestRef, + sections: ReadonlyArray, + includeResolved: boolean, + diffCursor: string | undefined, + ) { + const wants = (section: PullRequestReadSection) => sections.includes(section); + const [detail, activity, diff] = yield* Effect.all( + [ + wants("summary") || wants("checks") + ? pullRequests.detail(ref).pipe(Effect.asSome) + : Effect.succeedNone, + wants("conversation") ? pullRequests.activity(ref).pipe(Effect.asSome) : Effect.succeedNone, + wants("diff") + ? pullRequests + .diff({ ...ref, ...(diffCursor === undefined ? {} : { cursor: diffCursor }) }) + .pipe(Effect.asSome) + : Effect.succeedNone, + ], + { concurrency: "unbounded" }, + ).pipe(Effect.mapError(forgeFailure)); + const result: Omit = { + ...(Option.isSome(detail) && wants("summary") + ? { + summary: { + title: detail.value.title, + body: detail.value.body, + state: detail.value.state, + isDraft: detail.value.isDraft, + author: detail.value.author?.login ?? null, + headBranch: detail.value.headBranch, + baseBranch: detail.value.baseBranch, + headSha: detail.value.headSha ?? null, + mergeability: detail.value.mergeability, + behindBy: detail.value.behindBy ?? null, + autoMergeEnabled: detail.value.autoMergeEnabled ?? null, + additions: detail.value.additions, + deletions: detail.value.deletions, + changedFiles: detail.value.changedFiles, + labels: detail.value.labels.map((label) => label.name), + reviewers: detail.value.reviewers.map((reviewer) => reviewer.login), + }, + } + : {}), + ...(Option.isSome(detail) && wants("checks") ? { checks: detail.value.checks } : {}), + ...(Option.isSome(activity) + ? { + conversation: { + comments: activity.value.comments.map((comment) => ({ + id: comment.id, + kind: comment.kind, + author: comment.author?.login ?? null, + body: comment.body, + createdAt: comment.createdAt, + path: comment.path, + reviewState: comment.reviewState, + })), + reviewThreads: activity.value.reviewThreads + .filter((thread) => includeResolved || !thread.isResolved) + .map((thread) => ({ + id: thread.id, + path: thread.path, + line: thread.line, + isResolved: thread.isResolved, + isOutdated: thread.isOutdated, + comments: thread.comments.map((comment) => ({ + author: comment.author?.login ?? null, + body: comment.body, + createdAt: comment.createdAt, + })), + moreComments: thread.nextCommentsCursor !== undefined, + })), + hiddenResolvedThreads: includeResolved + ? 0 + : activity.value.reviewThreads.filter((thread) => thread.isResolved).length, + truncated: + activity.value.commentsTruncated || activity.value.reviewThreadsTruncated === true, + }, + } + : {}), + ...(Option.isSome(diff) + ? { + diff: { + patch: diff.value.patch, + truncated: diff.value.truncated, + nextCursor: diff.value.nextCursor, + }, + } + : {}), + }; + return result; + }); + + const linkToThread = Effect.fn("PullRequestsToolkit.linkToThread")(function* ( + thread: OrchestrationV2ThreadShell, + target: ResolvedTarget, + ) { + if (threadPullRequestsOf(thread).some((link) => threadPullRequestKeysEqual(link, target))) { + return; + } + yield* engine + .dispatch({ + type: "thread.pull-request.link", + commandId: yield* commandId("mcp-pr-create", thread.id), + threadId: thread.id, + host: target.host, + repository: target.repository, + number: target.number, + url: target.url, + source: "created", + }) + .pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError))); + }); + return { link_pull_request: writesThread((input) => Effect.gen(function* () { @@ -539,6 +707,169 @@ const make = Effect.gen(function* () { }; }), ), + pull_request_read: McpToolAccess.reads((input) => + Effect.gen(function* () { + const { target, ref } = yield* locate(input); + const sections = input.sections ?? ["summary", "checks"]; + return { + ...identityOf(target), + ...(yield* readSections(ref, sections, input.includeResolved === true, input.diffCursor)), + }; + }), + ), + pull_request_list: McpToolAccess.reads((input) => + Effect.gen(function* () { + const thread = yield* requireThread(PullRequestForgeError, undefined); + const listed = yield* pullRequests + .list({ + projectId: thread.projectId, + state: input.state ?? "open", + involvement: input.involvement ?? "all", + limit: input.limit ?? 30, + ...(input.query === undefined ? {} : { query: input.query }), + }) + .pipe(Effect.mapError(forgeFailure)); + const failure = listed.errors[0]; + if (listed.entries.length === 0 && failure !== undefined) { + return yield* new PullRequestForgeError({ detail: failure.message }); + } + return { + pullRequests: listed.entries.map((entry) => ({ + number: entry.number, + title: entry.title, + url: entry.url, + author: entry.author?.login ?? null, + headBranch: entry.headBranch, + baseBranch: entry.baseBranch, + state: entry.state, + isDraft: entry.isDraft, + reviewDecision: entry.reviewDecision ?? null, + checksState: entry.checksState ?? null, + updatedAt: entry.updatedAt, + })), + truncated: listed.truncated, + }; + }), + ), + pull_request_create: McpToolAccess.writesWithCapability((input) => + Effect.gen(function* () { + const thread = yield* requireThread(PullRequestForgeError, undefined); + const project = yield* projectOf(thread, PullRequestForgeError); + if (project === undefined) { + return yield* new PullRequestProjectNotFoundError({ repository: "" }); + } + const created = yield* git + .createPullRequest({ + cwd: thread.worktreePath ?? project.workspaceRoot, + title: input.title, + body: input.body, + baseBranch: input.base, + }) + .pipe(Effect.mapError(forgeFailure)); + if (created.url === undefined) { + return yield* new PullRequestForgeError({ + detail: + "The host accepted the PR but does not list it yet. Find it with pull_request_list.", + }); + } + const target = yield* resolveTarget({ url: created.url }, project); + yield* linkToThread(thread, target); + if (input.draft === true && created.status === "created") { + yield* pullRequests + .runAction({ + projectId: project.id, + host: target.host, + repository: target.repository, + number: target.number, + action: "draft", + }) + .pipe(Effect.mapError(forgeFailure)); + } + return { + ...identityOf(target), + created: created.status === "created", + ...(thread.lineage.relationshipToParent === "subagent" + ? { next: CHILD_PULL_REQUEST_REPORT_NEXT } + : {}), + }; + }), + ), + pull_request_update: McpToolAccess.writesWithCapability((input) => + Effect.gen(function* () { + if (input.title === undefined && input.body === undefined && input.ready === undefined) { + return yield* new PullRequestNothingToDoError({ detail: "Pass title, body, or ready." }); + } + const { target, ref } = yield* locate(input); + if (input.title !== undefined || input.body !== undefined) { + yield* pullRequests + .update({ + ...ref, + ...(input.title === undefined ? {} : { title: input.title }), + ...(input.body === undefined ? {} : { body: input.body }), + }) + .pipe(Effect.mapError(forgeFailure)); + } + if (input.ready !== undefined) { + yield* pullRequests + .runAction({ ...ref, action: input.ready ? "ready" : "draft" }) + .pipe(Effect.mapError(forgeFailure)); + } + return identityOf(target); + }), + ), + pull_request_respond: McpToolAccess.writesWithCapability((input) => + Effect.gen(function* () { + if ( + input.body === undefined && + (input.reviewThreadId === undefined || input.resolved === undefined) + ) { + return yield* new PullRequestNothingToDoError({ + detail: "Pass body, or reviewThreadId with resolved.", + }); + } + if (input.reviewThreadId === undefined && input.resolved !== undefined) { + return yield* new PullRequestNothingToDoError({ + detail: "resolved needs reviewThreadId.", + }); + } + const { target, ref } = yield* locate(input); + const reviewThreadId = input.reviewThreadId; + if (input.body !== undefined) { + yield* ( + reviewThreadId === undefined + ? pullRequests.comment({ ...ref, body: input.body }) + : pullRequests.replyToThread({ ...ref, threadId: reviewThreadId, body: input.body }) + ).pipe(Effect.mapError(forgeFailure)); + } + if (reviewThreadId !== undefined && input.resolved !== undefined) { + yield* pullRequests + .setThreadResolution({ ...ref, threadId: reviewThreadId, resolved: input.resolved }) + .pipe(Effect.mapError(forgeFailure)); + } + return { + ...identityOf(target), + replied: input.body !== undefined, + resolved: input.resolved ?? null, + }; + }), + ), + pull_request_merge: McpToolAccess.writesWithCapability((input) => + Effect.gen(function* () { + const { target, ref } = yield* locate(input); + yield* pullRequests + .runAction({ + ...ref, + action: input.auto === true ? "enable-auto-merge" : "merge", + expectedHeadSha: input.expectedHeadSha, + ...(input.method === undefined ? {} : { mergeMethod: input.method }), + }) + .pipe(Effect.mapError(forgeFailure)); + const after = yield* pullRequests + .summary({ ...ref, allowStale: false }) + .pipe(Effect.mapError(forgeFailure)); + return { ...identityOf(target), state: after.state }; + }), + ), } satisfies McpToolAccess.Handlers; }); diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 685cfd02782b5..fcd734ecf76fe 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -3,6 +3,14 @@ import { OrchestratorMcpEnvironmentTarget, OrchestratorMcpFailure, PositiveInt, + PullRequestCheck, + PullRequestCommentKind, + PullRequestChecksState, + PullRequestInvolvement, + PullRequestListState, + PullRequestMergeability, + PullRequestMergeMethod, + PullRequestReviewDecision, PullRequestReviewGuide, PullRequestReviewGuideRun, PullRequestState, @@ -20,6 +28,7 @@ import * as Toolkit from "effect/ai/Toolkit"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as GitManager from "../../../git/GitManager.ts"; import * as ProjectService from "../../../project/ProjectService.ts"; import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts"; import { @@ -28,6 +37,7 @@ import { PullRequestHostRequiredError, PullRequestUrlUnavailableError, } from "../../../pullRequest/pullRequestTarget.ts"; +import * as PullRequestService from "../../../pullRequest/PullRequestService.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; const dependencies = [ @@ -37,6 +47,8 @@ const dependencies = [ ProjectService.ProjectService, ]; +const forgeDependencies = [...dependencies, PullRequestService.PullRequestService]; + const guideDependencies = [ ...dependencies, PullRequestReviewGuideService.PullRequestReviewGuideService, @@ -124,6 +136,33 @@ export class PullRequestGuideFailedError extends Schema.TaggedError()( + "PullRequestForgeError", + { detail: Schema.optional(Schema.String), cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return this.detail ?? "Could not read this thread's project."; + } +} + +export class PullRequestBranchHasNoneError extends Schema.TaggedError()( + "PullRequestBranchHasNoneError", + {}, +) { + override get message(): string { + return "This thread's branch has no known PR. Pass number, or open one with pull_request_create."; + } +} + +export class PullRequestNothingToDoError extends Schema.TaggedError()( + "PullRequestNothingToDoError", + { detail: Schema.String }, +) { + override get message(): string { + return this.detail; + } +} + export const PullRequestToolError = Schema.Union([ OrchestratorMcpFailure, McpCapabilityUnavailableError, @@ -141,6 +180,9 @@ export const PullRequestToolError = Schema.Union([ PullRequestWatchService.PullRequestWatchFromSubagentError, PullRequestProjectNotFoundError, PullRequestGuideFailedError, + PullRequestForgeError, + PullRequestBranchHasNoneError, + PullRequestNothingToDoError, ]); export type PullRequestToolError = typeof PullRequestToolError.Type; @@ -429,6 +471,250 @@ const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, true); +export const ThreadPullRequestInput = Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + number: Schema.optional(PositiveInt.annotate({ description: "Default: the branch's PR." })), + repository: Schema.optional(TrimmedNonEmptyString), +}); +export type ThreadPullRequestInput = typeof ThreadPullRequestInput.Type; + +export const PullRequestReadSection = Schema.Literals([ + "summary", + "checks", + "conversation", + "diff", +]); +export type PullRequestReadSection = typeof PullRequestReadSection.Type; + +const ReadComment = Schema.Struct({ + author: Schema.NullOr(Schema.String), + body: Schema.String, + createdAt: Schema.String, +}); + +export const ReadPullRequestResult = Schema.Struct({ + ...PullRequestIdentity, + summary: Schema.optional( + Schema.Struct({ + title: Schema.String, + body: Schema.String, + state: PullRequestState, + isDraft: Schema.Boolean, + author: Schema.NullOr(Schema.String), + headBranch: Schema.String, + baseBranch: Schema.String, + headSha: Schema.NullOr(Schema.String), + mergeability: PullRequestMergeability, + behindBy: Schema.NullOr(Schema.Int), + autoMergeEnabled: Schema.NullOr(Schema.Boolean), + additions: Schema.Int, + deletions: Schema.Int, + changedFiles: Schema.Int, + labels: Schema.Array(Schema.String), + reviewers: Schema.Array(Schema.String), + }), + ), + checks: Schema.optional(Schema.Array(PullRequestCheck)), + conversation: Schema.optional( + Schema.Struct({ + comments: Schema.Array( + Schema.Struct({ + ...ReadComment.fields, + id: Schema.String, + kind: PullRequestCommentKind, + path: Schema.NullOr(Schema.String), + reviewState: Schema.NullOr(Schema.String), + }), + ), + reviewThreads: Schema.Array( + Schema.Struct({ + id: Schema.String, + path: Schema.String, + line: Schema.NullOr(Schema.Int), + isResolved: Schema.Boolean, + isOutdated: Schema.Boolean, + comments: Schema.Array(ReadComment), + moreComments: Schema.Boolean, + }), + ), + hiddenResolvedThreads: Schema.Int, + truncated: Schema.Boolean, + }), + ), + diff: Schema.optional( + Schema.Struct({ + patch: Schema.String, + truncated: Schema.Boolean, + nextCursor: Schema.NullOr(Schema.String), + }), + ), +}); +export type ReadPullRequestResult = typeof ReadPullRequestResult.Type; + +export const ListPullRequestsResult = Schema.Struct({ + pullRequests: Schema.Array( + Schema.Struct({ + number: Schema.Int, + title: Schema.String, + url: Schema.String, + author: Schema.NullOr(Schema.String), + headBranch: Schema.String, + baseBranch: Schema.String, + state: PullRequestState, + isDraft: Schema.Boolean, + reviewDecision: Schema.NullOr(PullRequestReviewDecision), + checksState: Schema.NullOr(PullRequestChecksState), + updatedAt: Schema.String, + }), + ), + truncated: Schema.Boolean, +}); +export type ListPullRequestsResult = typeof ListPullRequestsResult.Type; + +export const CreatePullRequestResult = Schema.Struct({ + ...PullRequestIdentity, + created: Schema.Boolean.annotate({ + description: "False when the branch already had an open PR.", + }), + next: Schema.optional(Schema.String), +}); +export type CreatePullRequestResult = typeof CreatePullRequestResult.Type; + +export const RespondToPullRequestResult = Schema.Struct({ + ...PullRequestIdentity, + replied: Schema.Boolean, + resolved: Schema.NullOr(Schema.Boolean), +}); +export type RespondToPullRequestResult = typeof RespondToPullRequestResult.Type; + +export const MergePullRequestResult = Schema.Struct({ + ...PullRequestIdentity, + state: PullRequestState.annotate({ + description: "open while auto-merge or a merge queue waits for checks.", + }), +}); +export type MergePullRequestResult = typeof MergePullRequestResult.Type; + +const ReadPullRequestTool = Tool.make("pull_request_read", { + description: + "Read a PR in this thread's repository. Use instead of gh or cafe for PR state, checks, review comments, or diff.", + parameters: Schema.Struct({ + ...ThreadPullRequestInput.fields, + sections: Schema.optional( + Schema.Array(PullRequestReadSection).annotate({ + description: "Default: summary, checks. conversation: comments, review threads.", + }), + ), + includeResolved: Schema.optional(Schema.Boolean), + diffCursor: Schema.optional(TrimmedNonEmptyString), + }), + success: ReadPullRequestResult, + failure: PullRequestToolError, + dependencies: forgeDependencies, +}) + .annotate(Tool.Title, "Read pull request") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, true); + +const ListPullRequestsTool = Tool.make("pull_request_list", { + description: "List PRs in this thread's repository, recently updated first.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + state: Schema.optional(PullRequestListState.annotate({ description: "Default: open." })), + involvement: Schema.optional(PullRequestInvolvement), + query: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(200))), + limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))), + }), + success: ListPullRequestsResult, + failure: PullRequestToolError, + dependencies: forgeDependencies, +}) + .annotate(Tool.Title, "List pull requests") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, true); + +const CreatePullRequestTool = Tool.make("pull_request_create", { + description: + "Open a PR from this thread's pushed branch and link it. Returns the branch's open PR if one exists.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + title: TrimmedNonEmptyString, + body: Schema.String, + base: Schema.optional(TrimmedNonEmptyString), + draft: Schema.optional(Schema.Boolean), + }), + success: CreatePullRequestResult, + failure: PullRequestToolError, + dependencies: [...forgeDependencies, GitManager.GitManager], +}) + .annotate(Tool.Title, "Create pull request") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, true); + +const UpdatePullRequestTool = Tool.make("pull_request_update", { + description: "Change a PR's title or body, or mark it ready (ready=false: back to draft).", + parameters: Schema.Struct({ + ...ThreadPullRequestInput.fields, + title: Schema.optional(TrimmedNonEmptyString), + body: Schema.optional(Schema.String), + ready: Schema.optional(Schema.Boolean), + }), + success: Schema.Struct(PullRequestIdentity), + failure: PullRequestToolError, + dependencies: forgeDependencies, +}) + .annotate(Tool.Title, "Update pull request") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, true); + +const RespondToPullRequestTool = Tool.make("pull_request_respond", { + description: + "Reply to a review thread from pull_request_read, resolve or reopen it, or both. Without reviewThreadId, comment on the PR.", + parameters: Schema.Struct({ + ...ThreadPullRequestInput.fields, + reviewThreadId: Schema.optional(TrimmedNonEmptyString), + body: Schema.optional(TrimmedNonEmptyString), + resolved: Schema.optional(Schema.Boolean), + }), + success: RespondToPullRequestResult, + failure: PullRequestToolError, + dependencies: forgeDependencies, +}) + .annotate(Tool.Title, "Respond on pull request") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, true); + +const MergePullRequestTool = Tool.make("pull_request_merge", { + description: + "Merge a PR only when asked to land it. Refuses if the head is no longer expectedHeadSha, the summary headSha you checked.", + parameters: Schema.Struct({ + ...ThreadPullRequestInput.fields, + expectedHeadSha: TrimmedNonEmptyString, + method: Schema.optional(PullRequestMergeMethod), + auto: Schema.optional( + Schema.Boolean.annotate({ description: "Merge once required checks pass." }), + ), + }), + success: MergePullRequestResult, + failure: PullRequestToolError, + dependencies: forgeDependencies, +}) + .annotate(Tool.Title, "Merge pull request") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, true) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, true); + export const PullRequestsToolkit = Toolkit.make( LinkPullRequestTool, LinkPullRequestsTool, @@ -439,4 +725,10 @@ export const PullRequestsToolkit = Toolkit.make( UnwatchPullRequestTool, WritePullRequestGuidesTool, ReadPullRequestGuideTool, + ReadPullRequestTool, + ListPullRequestsTool, + CreatePullRequestTool, + UpdatePullRequestTool, + RespondToPullRequestTool, + MergePullRequestTool, ); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 5a2cf9188599f..c0a11aa3e6114 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -12,6 +12,7 @@ import { ServerSecretStore } from "../auth/ServerSecretStore.ts"; import { ServerConfig } from "../config.ts"; import { DeviceService } from "../device/DeviceService.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; +import { GitManager } from "../git/GitManager.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import { PreviewAutomationBroker } from "../mcp/PreviewAutomationBroker.ts"; @@ -75,6 +76,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(ProviderRegistry)({}), Layer.mock(PullRequestReviewGuideService)({}), Layer.mock(PullRequestService)({}), + Layer.mock(GitManager)({}), Layer.mock(RemoteDelegation)({}), Layer.mock(ScheduledTaskService)({}), Layer.mock(SecretRequests)({}), diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 827acef899357..b9ac3ad4acf5f 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -1428,6 +1428,30 @@ it.effect( }), ); +it.effect("refuses a merge whose head moved past expectedHeadSha and pins the host merge", () => + Effect.gen(function* () { + const pinned: Array = []; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequest: () => + Effect.succeed({ ...hostedChangeRequest("Body"), headSha: "new-head" }), + getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-09-03T00:00:00Z")), + runAction: (input) => Effect.sync(() => void pinned.push(input.expectedHeadSha)), + }), + ], + }); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const refused = yield* Effect.flip( + service.runAction({ ...reference, action: "merge", expectedHeadSha: "reviewed-head" }), + ); + assert.include(refused.message, "new-head"); + yield* service.runAction({ ...reference, action: "merge", expectedHeadSha: "new-head" }); + assert.deepStrictEqual(pinned, ["new-head"]); + }), +); + it.effect("publishes a merge for immediate settlement only after host confirmation", () => Effect.gen(function* () { const mergedAt = "2026-09-03T02:00:00.000Z"; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 271a3a62ef94e..a6868a60bc9b0 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -2255,7 +2255,32 @@ export const make = Effect.gen(function* () { ), ) : Effect.succeed(false); - return mergeSettings.pipe( + // Hosts that cannot pin a merge to a commit still refuse a head that already moved. + const headPinned = + input.expectedHeadSha === undefined + ? Effect.void + : project.api + .getChangeRequest({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + }) + .pipe( + Effect.mapError(toPullRequestError("runAction")), + Effect.flatMap((current) => + current.headSha === input.expectedHeadSha + ? Effect.void + : Effect.fail( + new PullRequestOperationError({ + operation: "runAction", + detail: `The head is now ${current.headSha ?? "unknown"}, not ${input.expectedHeadSha}. Review the new commits first.`, + }), + ), + ), + ); + return headPinned.pipe( + Effect.andThen(mergeSettings), Effect.flatMap((removeAgentCreditsOnMerge) => project.api .runAction({ @@ -2269,6 +2294,9 @@ export const make = Effect.gen(function* () { ...(input.expectedStackHeads === undefined ? {} : { expectedStackHeads: input.expectedStackHeads }), + ...(input.expectedHeadSha === undefined + ? {} + : { expectedHeadSha: input.expectedHeadSha }), ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }), ...(input.updateMethod === undefined ? {} diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 73a2b95154d47..bc0d63e581f3c 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -317,6 +317,10 @@ pull request link in the conversation. Creating a pull request from Git actions and so does an agent creating one with `gh pr create` or `glab mr create`. Agents can link other pull requests with the `link_pull_request` tool. +Agents can also read, open, update, reply on, and merge pull requests in the thread's repository +through T3 Code's own tools, which use the same sign-in as the Pull requests page. An agent merges +only the commit it last read: if someone pushed since, the merge is refused. + Use **Link pull request to thread** in the command palette to keep a pull request with the thread. From a review on the Pull requests page, **Link to thread** lets you search for an active thread. The review header also lists the threads that link to it, including archived threads, so you can return to their context. diff --git a/evals/mcp-tool-use/cases/pull-requests.ndjson b/evals/mcp-tool-use/cases/pull-requests.ndjson index b07a121db42ad..9c243771bf6f2 100644 --- a/evals/mcp-tool-use/cases/pull-requests.ndjson +++ b/evals/mcp-tool-use/cases/pull-requests.ndjson @@ -39,3 +39,7 @@ {"id": "schedule-fresh-session-per-run", "area": "pull-requests", "kind": "guard", "pattern": "recurring task that should not accumulate context", "experience": "A recurring triage task kept one thread so the user could read its history, but each run carried every earlier run's context into the next.", "rule": "schedule_task `freshSession: true` keeps runs in one thread while each run starts a fresh session.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Monday 2026-11-02, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-7", "title": "Triage new issues", "enabled": true, "projectId": "project-1", "boundThreadId": null, "freshSession": true, "schedule": {"type": "fixed_time", "timeOfDay": "09:00"}, "nextRunAt": "2026-11-03T09:00:00-08:00", "lastRunStatus": "never"}}}, "prompt": "Every morning at 9, triage new issues in acme/app. Keep all the runs in one thread so I can scroll back, but each run should start clean without remembering the previous days.", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "fixed_time", "freshSession": true}}], "notCalls": ["delegate_task", "run_scheduled_task_now"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-03: automations in one thread with separate provider sessions"}, "notes": "schedule-one-off-tomorrow is the control: an ordinary schedule must not set freshSession."} {"id": "babysit-merge-after-approval-until-merged", "area": "pull-requests", "kind": "bad", "pattern": "babysit until a teammate approves, then merge, watching only until checks finish", "experience": "Asked to babysit a PR and merge it once a teammate approved, the agent watched it only until checks finished, so the thread left Working as soon as checks passed while the agent still owned the merge.", "rule": "until: merged when you will act on the PR yourself, such as merging it after someone else approves", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The HTML preview frame has no accessible name. Fix it and open a PR."}, {"role": "assistant", "text": "Opened [PR #124](https://github.com/acme/app/pull/124). The preview frame now has the title \"HTML preview\".", "toolCalls": [{"tool": "Bash", "input": {"command": "git push -u origin fix/html-preview-title && gh pr create --fill"}, "result": "https://github.com/acme/app/pull/124"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "alreadyLinked": false}}]}], "mocks": {"watch_pull_request": "default", "link_pull_request": "default"}, "world": {"branch": "fix/html-preview-title", "commits": [{"sha": "abc1234", "subject": "fix(web): HTML preview frame gets an accessible title"}], "diff": "diff --git a/apps/web/src/HtmlPreview.tsx b/apps/web/src/HtmlPreview.tsx\n--- a/apps/web/src/HtmlPreview.tsx\n+++ b/apps/web/src/HtmlPreview.tsx\n@@ -1,3 +1,3 @@\n export function HtmlPreview({ html }: { html: string }) {\n- return