diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 6a69ec458fa09..c9072c6f393b5 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1,6 +1,10 @@ import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts"; -import { type PullRequestActionInput, SourceControlProviderKind } from "@t3tools/contracts"; +import { + type PullRequestActionInput, + type PullRequestDetail, + SourceControlProviderKind, +} from "@t3tools/contracts"; // @effect-diagnostics nodeBuiltinImport:off import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; @@ -22,6 +26,7 @@ import * as Result from "effect/Result"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import * as Clock from "effect/Clock"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { ChildProcessSpawner } from "effect/process"; import { expect } from "vite-plus/test"; @@ -1850,6 +1855,78 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("reads a pull request again when this checkout pushed past its cached head", () => + 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, ["remote", "add", "team/fork", forkDir]); + // The service's cache: a read is held until the pull request is invalidated. + let hostHead = ""; + let held: PullRequestDetail | undefined; + let hostReads = 0; + const { manager } = yield* makeManager({ + pullRequests: { + detail: () => + Effect.map(Clock.currentTimeMillis, (observedAt) => { + if (held === undefined) { + hostReads += 1; + held = { + state: "open", + headBranch: "feature", + headSha: hostHead, + observedAt, + } as unknown as PullRequestDetail; + } + return held; + }), + invalidate: () => Effect.sync(() => void (held = undefined)), + }, + }); + const readHead = TestClock.adjust("1 second").pipe( + Effect.andThen( + manager.pullRequestDetail({ + cwd: repoDir, + reference: { projectId: ProjectId.make("project"), repository: "acme/app", number: 1 }, + }), + ), + Effect.map((detail) => detail.headSha), + ); + const head = runGit(repoDir, ["rev-parse", "HEAD"]).pipe( + Effect.map((result) => result.stdout.trim()), + ); + const first = yield* head; + hostHead = first; + // A ref below the branch's name is not the branch. + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/heads/feature/below"]); + yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "next"]); + expect(yield* readHead).toBe(first); + expect(yield* readHead).toBe(first); + + yield* runGit(repoDir, ["checkout", "-b", "feature", first]); + yield* runGit(repoDir, ["push", "team/fork", "feature"]); + expect(yield* readHead).toBe(first); + expect(hostReads).toBe(1); + + // The agent pushes: the host and the tracking ref move, the cache does not. + yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "pushed"]); + yield* runGit(repoDir, ["push", "team/fork", "feature"]); + hostHead = yield* head; + expect(yield* readHead).toBe(hostHead); + expect(yield* readHead).toBe(hostHead); + expect(hostReads).toBe(2); + + // Someone else's push that this checkout has not fetched is newer than its view. + hostHead = "0123456789abcdef0123456789abcdef01234567"; + held = undefined; + expect(yield* readHead).toBe(hostHead); + expect(yield* readHead).toBe(hostHead); + expect(hostReads).toBe(3); + }), + ); + it.effect("finds a fork PR when the remote name contains a slash", () => 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 e9fd19df254cb..3ad24ec166a19 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -40,6 +40,8 @@ import { type ProjectId, PROVIDER_DISPLAY_NAMES, ProviderDriverKind, + type PullRequestDetail, + type PullRequestRef, SourceControlProviderError, type SourceControlWritingStyleSettings, type ThreadId, @@ -203,6 +205,14 @@ export class GitManager extends Context.Service< readonly branch: string; readonly url: string; }) => Effect.Effect; + /** + * A pull request's detail, read again when its cached head is one this checkout's own push + * left behind. A shell `git push` clears no cache, but it moves the remote-tracking ref. + */ + readonly pullRequestDetail: (input: { + readonly cwd: string; + readonly reference: PullRequestRef; + }) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; readonly invalidateStatus: (cwd: string) => Effect.Effect; @@ -3722,6 +3732,57 @@ export const make = Effect.gen(function* () { return checkedOutUrl === url; }); + // Whether this checkout holds `commit` and last saw its remotes hold `branch` elsewhere. A + // commit it never fetched is someone else's push, which is newer than the checkout's view. + const remoteBranchLeftCommit = Effect.fn("GitManager.remoteBranchLeftCommit")( + function* (cwd: string, branch: string, commit: string) { + if (!/^[0-9a-f]{7,64}$/i.test(commit)) return false; + const remoteNames = yield* readLookupRemotes( + cwd, + "GitManager.remoteBranchLeftCommit.remotes", + ); + if (remoteNames.length === 0) return false; + const refs = new Set(remoteNames.map((name) => `refs/remotes/${name}/${branch}`)); + const listed = yield* gitCore.execute({ + operation: "GitManager.remoteBranchLeftCommit", + cwd, + args: ["for-each-ref", "--format=%(refname)%00%(objectname)", ...refs], + timeoutMs: 5_000, + }); + // for-each-ref also lists refs below a pattern, such as origin/feature/x for feature. + const tracked = listed.stdout + .split("\n") + .map((line) => trimAsciiWhitespace(line).split("\u0000")) + .flatMap(([ref, oid]) => (ref !== undefined && oid && refs.has(ref) ? [oid] : [])); + if (tracked.length === 0 || tracked.some((oid) => oid.startsWith(commit.toLowerCase()))) { + return false; + } + yield* gitCore.resolveCommit({ cwd, revision: commit }); + return true; + }, + Effect.orElseSucceed(() => false), + ); + + const pullRequestDetail: GitManager["Service"]["pullRequestDetail"] = Effect.fn( + "GitManager.pullRequestDetail", + )(function* ({ cwd, reference }) { + const startedAt = yield* Clock.currentTimeMillis; + // Agents pin merges to this headSha, so it must not come from a stale snapshot. + const read = pullRequests.detail({ ...reference, allowStale: false }); + const detail = yield* read; + if ( + detail.state !== "open" || + detail.headSha === undefined || + detail.observedAt === undefined || + detail.observedAt >= startedAt || + !(yield* remoteBranchLeftCommit(cwd, detail.headBranch, detail.headSha)) + ) { + return detail; + } + yield* pullRequests.invalidate({ reference }); + return yield* read; + }); + const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn( "invalidateLocalStatus", )(function* (cwd) { @@ -4476,6 +4537,7 @@ export const make = Effect.gen(function* () { status, branchPullRequest, checkedOutPullRequest, + pullRequestDetail, invalidateLocalStatus, invalidateRemoteStatus, invalidateStatus, diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 7241e92dc3a65..2689dcb69ed87 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -216,7 +216,12 @@ const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* ( addressedProject: () => Effect.succeed(project ?? undefined), ...options.pullRequests, }), - Layer.mock(GitManager.GitManager)(options.git ?? {}), + Layer.mock(GitManager.GitManager)({ + pullRequestDetail: ({ reference }) => + options.pullRequests?.detail?.({ ...reference, allowStale: false }) ?? + Effect.die("pullRequests.detail is not mocked"), + ...options.git, + }), Layer.succeed(SecureRandom.SecureRandom, testCrypto), ServerSettings.layerTest({}, options.managedPolicy), McpToolAccessTestkit.liveThreadsLayer, @@ -954,6 +959,20 @@ describe("source control tools", () => { }), ); + it.effect("reads the detail through the thread's checkout", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { activity: () => Effect.succeed(activity) }, + git: { + pullRequestDetail: ({ cwd }) => + Effect.succeed({ ...detail, headSha: cwd === "/workspace/worktree" ? "def456" : "" }), + }, + }); + expect((yield* harness.call("pull_request_read", {})).headSha).toBe("def456"); + }), + ); + it.effect("reads an Azure DevOps PR by number at its organization and project", () => Effect.gen(function* () { const asked: Array = []; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 4fbfdc535e47b..0d4ac296ea852 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -673,16 +673,20 @@ const make = Effect.gen(function* () { const readSections = Effect.fn("PullRequestsToolkit.readSections")(function* ( ref: PullRequestRef, + cwd: string, sections: ReadonlyArray, includeResolved: boolean, cursor: ReadCursor | undefined, ) { const wants = (section: PullRequestReadSection) => sections.includes(section); const diffCursor = cursor !== undefined && "diff" in cursor ? cursor.diff : undefined; - const [detail, activity, diff] = yield* Effect.all( + // Detail first: when the checkout's own push left its cached head behind, the read that + // refreshes it also clears the activity and diff read after it. + const detail = yield* git + .pullRequestDetail({ cwd, reference: ref }) + .pipe(Effect.mapError(forgeFailure)); + const [activity, diff] = yield* Effect.all( [ - // Agents pin merges to this headSha, so it must not come from a stale snapshot. - pullRequests.detail({ ...ref, allowStale: false }), pullRequests.activity(ref), wants("diff") ? pullRequests @@ -1074,7 +1078,7 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const cursor = input.cursor === undefined ? undefined : yield* readCursors.decode(input.cursor); - const { target, ref } = yield* locate(input); + const { thread, project, target, ref } = yield* locate(input); // A cursor continues the one section it came from, with that read's options. const sections: ReadonlyArray = cursor === undefined @@ -1091,7 +1095,13 @@ const make = Effect.gen(function* () { : input.includeResolved === true; return { ...identityOf(target), - ...(yield* readSections(ref, sections, includeResolved, cursor)), + ...(yield* readSections( + ref, + thread.worktreePath ?? project.workspaceRoot, + sections, + includeResolved, + cursor, + )), }; }), ),