From 453f2fec3b63ce08fc71395de31fca07090daa16 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade Date: Mon, 30 Nov 2026 13:03:47 -0400 Subject: [PATCH 1/4] fix(server): pull_request_read reflects the push the agent just made Co-Authored-By: Claude Fable 5.2 --- apps/server/src/git/GitManager.test.ts | 31 +++++++++ apps/server/src/git/GitManager.ts | 28 ++++++++ .../toolkits/pullRequests/handlers.test.ts | 64 +++++++++++++++++++ .../src/mcp/toolkits/pullRequests/handlers.ts | 30 ++++++++- .../pullRequest/PullRequestService.test.ts | 35 ++++++++++ 5 files changed, 185 insertions(+), 3 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 6a69ec458fa09..b35a6b1300d32 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1850,6 +1850,37 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("reports where each remote was last seen holding a 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, ["remote", "add", "team/fork", forkDir]); + const { manager } = yield* makeManager(); + const tracked = manager.remoteTrackingCommits({ cwd: repoDir, branch: "feature" }); + const head = runGit(repoDir, ["rev-parse", "HEAD"]).pipe( + Effect.map((result) => result.stdout.trim()), + ); + yield* runGit(repoDir, ["push", "origin", "HEAD:refs/heads/feature/below"]); + expect(yield* tracked).toEqual([]); + + yield* runGit(repoDir, ["checkout", "-b", "feature"]); + yield* runGit(repoDir, ["push", "team/fork", "feature"]); + const first = yield* head; + expect(yield* tracked).toEqual([first]); + + yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "next"]); + expect(yield* tracked).toEqual([first]); + yield* runGit(repoDir, ["push", "team/fork", "feature"]); + expect(yield* tracked).toEqual([yield* head]); + expect(yield* manager.remoteTrackingCommits({ cwd: "/nowhere", branch: "feature" })).toEqual( + [], + ); + }), + ); + 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..b2292dd24d920 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -203,6 +203,11 @@ export class GitManager extends Context.Service< readonly branch: string; readonly url: string; }) => Effect.Effect; + /** Where this checkout last saw `branch` on its remotes: what its own push left there. */ + readonly remoteTrackingCommits: (input: { + readonly cwd: string; + readonly branch: string; + }) => Effect.Effect>; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; readonly invalidateStatus: (cwd: string) => Effect.Effect; @@ -3722,6 +3727,28 @@ export const make = Effect.gen(function* () { return checkedOutUrl === url; }); + const remoteTrackingCommits: GitManager["Service"]["remoteTrackingCommits"] = Effect.fn( + "remoteTrackingCommits", + )( + function* ({ cwd, branch }) { + const remoteNames = yield* readLookupRemotes(cwd, "GitManager.remoteTrackingCommits.remotes"); + if (remoteNames.length === 0) return []; + const refs = new Set(remoteNames.map((name) => `refs/remotes/${name}/${branch}`)); + const listed = yield* gitCore.execute({ + operation: "GitManager.remoteTrackingCommits", + 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. + return listed.stdout + .split("\n") + .map((line) => trimAsciiWhitespace(line).split("\u0000")) + .flatMap(([ref, oid]) => (ref !== undefined && oid && refs.has(ref) ? [oid] : [])); + }, + Effect.orElseSucceed((): ReadonlyArray => []), + ); + const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn( "invalidateLocalStatus", )(function* (cwd) { @@ -4476,6 +4503,7 @@ export const make = Effect.gen(function* () { status, branchPullRequest, checkedOutPullRequest, + remoteTrackingCommits, 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..ea4dd2bea2647 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -19,6 +19,7 @@ import { SourceControlProviderKind, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; +import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -26,6 +27,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { McpSchema, type Tool } from "effect/ai"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; @@ -954,6 +956,68 @@ describe("source control tools", () => { }), ); + it.effect("reads the host again when the checkout pushed past the cached head", () => + Effect.gen(function* () { + // The service's cache: a read is held until the PR is invalidated. + let hostHead = "abc123"; + let held: PullRequestDetail | undefined; + let hostReads = 0; + let pushed: ReadonlyArray = ["abc123"]; + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { + detail: () => + Effect.map(Clock.currentTimeMillis, (observedAt) => { + if (held === undefined) { + hostReads += 1; + held = { ...detail, headSha: hostHead, observedAt }; + } + return held; + }), + activity: () => Effect.succeed(activity), + invalidate: () => Effect.sync(() => void (held = undefined)), + }, + git: { + remoteTrackingCommits: ({ cwd, branch }) => + Effect.sync(() => { + expect({ cwd, branch }).toEqual({ cwd: "/workspace/worktree", branch: "tools" }); + return pushed; + }), + }, + }); + const readHead = TestClock.adjust("1 second").pipe( + Effect.andThen(harness.call("pull_request_read", {})), + Effect.map((result) => result.headSha), + ); + expect(yield* readHead).toBe("abc123"); + expect(yield* readHead).toBe("abc123"); + expect(hostReads).toBe(1); + + // The agent pushes: the host and the tracking ref move, the cache does not. + hostHead = "def456"; + pushed = ["def456"]; + expect(yield* readHead).toBe("def456"); + expect(yield* readHead).toBe("def456"); + expect(hostReads).toBe(2); + + // A push from elsewhere that this checkout never fetched leaves no local trace. + hostHead = "fed789"; + expect(yield* readHead).toBe("def456"); + pushed = []; + expect(yield* readHead).toBe("def456"); + expect(hostReads).toBe(2); + + // The host can lag a push, so a read that still differs is asked again next time, + // but a read that just came from the host is not repeated. + pushed = ["0a0a0a"]; + expect(yield* readHead).toBe("fed789"); + expect(hostReads).toBe(3); + held = undefined; + expect(yield* readHead).toBe("fed789"); + expect(hostReads).toBe(4); + }), + ); + 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..f6a71cdb9f056 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -17,6 +17,7 @@ import { TrimmedNonEmptyString, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -673,13 +674,15 @@ 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( + const startedAt = yield* Clock.currentTimeMillis; + const read = Effect.all( [ // Agents pin merges to this headSha, so it must not come from a stale snapshot. pullRequests.detail({ ...ref, allowStale: false }), @@ -692,6 +695,21 @@ const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ).pipe(Effect.mapError(forgeFailure)); + let [detail, activity, diff] = yield* read; + // The agent's own `git push` clears no cache, but it moves the checkout's remote-tracking + // ref. A cached head that ref has left is from before the push, so the host is asked again. + if ( + detail.state === "open" && + detail.headSha !== undefined && + detail.observedAt !== undefined && + detail.observedAt < startedAt + ) { + const pushed = yield* git.remoteTrackingCommits({ cwd, branch: detail.headBranch }); + if (pushed.length > 0 && !pushed.includes(detail.headSha)) { + yield* pullRequests.invalidate({ reference: ref }); + [detail, activity, diff] = yield* read; + } + } const wantsThreads = wants("threads"); const wantsComments = wants("comments"); const page = @@ -1074,7 +1092,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 +1109,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, + )), }; }), ), diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index e89ba5a092a77..c994305017152 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -5808,3 +5808,38 @@ it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "ref assert.strictEqual(diffReads, 2); }), ); + +it.effect("an agent's read holds the head and checks from before a push until invalidated", () => + Effect.gen(function* () { + let headSha = "before"; + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequest: () => + Effect.sync(() => ({ + ...hostedChangeRequest("body"), + headSha, + checks: [ + { name: `CI for ${headSha}`, status: "success", description: null, url: null }, + ], + })), + }), + ], + }); + const read = service + .detail({ ...reference, allowStale: false }) + .pipe(Effect.map((detail) => [detail.headSha, detail.checks[0]?.name])); + assert.deepStrictEqual(yield* read, ["before", "CI for before"]); + headSha = "after"; + yield* TestClock.adjust("30 seconds"); + assert.deepStrictEqual(yield* read, ["before", "CI for before"]); + yield* service.invalidate({ reference }); + assert.deepStrictEqual(yield* read, ["after", "CI for after"]); + assert.deepStrictEqual( + (yield* service.checks(reference))?.checks.map((check) => check.name), + ["CI for after"], + ); + }), +); From c2e71c66f868f220e8cbc907a5028bcf2ca2f187 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade Date: Mon, 30 Nov 2026 13:09:41 -0400 Subject: [PATCH 2/4] fix(server): only re-read for a head the checkout holds Co-Authored-By: Claude Fable 5.2 --- apps/server/src/git/GitManager.test.ts | 28 ++++++++------ apps/server/src/git/GitManager.ts | 37 +++++++++++++------ .../toolkits/pullRequests/handlers.test.ts | 18 +++------ .../src/mcp/toolkits/pullRequests/handlers.ts | 14 ++++--- .../pullRequest/PullRequestService.test.ts | 35 ------------------ 5 files changed, 55 insertions(+), 77 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index b35a6b1300d32..4544cec670084 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1850,7 +1850,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); - it.effect("reports where each remote was last seen holding a branch", () => + it.effect("tells a commit its own push left behind from one it never fetched", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); yield* initRepo(repoDir); @@ -1859,25 +1859,29 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { yield* runGit(repoDir, ["remote", "add", "origin", originDir]); yield* runGit(repoDir, ["remote", "add", "team/fork", forkDir]); const { manager } = yield* makeManager(); - const tracked = manager.remoteTrackingCommits({ cwd: repoDir, branch: "feature" }); + const left = (commit: string, branch = "feature") => + manager.remoteBranchLeftCommit({ cwd: repoDir, branch, commit }); const head = runGit(repoDir, ["rev-parse", "HEAD"]).pipe( Effect.map((result) => result.stdout.trim()), ); + const first = yield* head; + // A ref below the branch's name is not the branch. yield* runGit(repoDir, ["push", "origin", "HEAD:refs/heads/feature/below"]); - expect(yield* tracked).toEqual([]); + yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "next"]); + expect(yield* left(first)).toBe(false); - yield* runGit(repoDir, ["checkout", "-b", "feature"]); + yield* runGit(repoDir, ["checkout", "-b", "feature", first]); yield* runGit(repoDir, ["push", "team/fork", "feature"]); - const first = yield* head; - expect(yield* tracked).toEqual([first]); + expect(yield* left(first)).toBe(false); - yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "next"]); - expect(yield* tracked).toEqual([first]); + yield* runGit(repoDir, ["commit", "--allow-empty", "-m", "pushed"]); + expect(yield* left(first)).toBe(false); yield* runGit(repoDir, ["push", "team/fork", "feature"]); - expect(yield* tracked).toEqual([yield* head]); - expect(yield* manager.remoteTrackingCommits({ cwd: "/nowhere", branch: "feature" })).toEqual( - [], - ); + expect(yield* left(first)).toBe(true); + expect(yield* left(yield* head)).toBe(false); + // Someone else's push that this checkout has not fetched. + expect(yield* left("0123456789abcdef0123456789abcdef01234567")).toBe(false); + expect(yield* left(first, "other")).toBe(false); }), ); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index b2292dd24d920..4ce6c58e960ff 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -203,11 +203,15 @@ export class GitManager extends Context.Service< readonly branch: string; readonly url: string; }) => Effect.Effect; - /** Where this checkout last saw `branch` on its remotes: what its own push left there. */ - readonly remoteTrackingCommits: (input: { + /** + * Whether this checkout holds `commit` and last saw its remotes hold `branch` elsewhere, as + * after its own push. A commit it never fetched is someone else's push, which is newer. + */ + readonly remoteBranchLeftCommit: (input: { readonly cwd: string; readonly branch: string; - }) => Effect.Effect>; + readonly commit: string; + }) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; readonly invalidateStatus: (cwd: string) => Effect.Effect; @@ -3727,26 +3731,35 @@ export const make = Effect.gen(function* () { return checkedOutUrl === url; }); - const remoteTrackingCommits: GitManager["Service"]["remoteTrackingCommits"] = Effect.fn( - "remoteTrackingCommits", + const remoteBranchLeftCommit: GitManager["Service"]["remoteBranchLeftCommit"] = Effect.fn( + "remoteBranchLeftCommit", )( - function* ({ cwd, branch }) { - const remoteNames = yield* readLookupRemotes(cwd, "GitManager.remoteTrackingCommits.remotes"); - if (remoteNames.length === 0) return []; + function* ({ cwd, branch, commit }) { + 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.remoteTrackingCommits", + 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. - return listed.stdout + 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((): ReadonlyArray => []), + Effect.orElseSucceed(() => false), ); const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn( @@ -4503,7 +4516,7 @@ export const make = Effect.gen(function* () { status, branchPullRequest, checkedOutPullRequest, - remoteTrackingCommits, + remoteBranchLeftCommit, 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 ea4dd2bea2647..e3217cef13156 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -962,7 +962,7 @@ describe("source control tools", () => { let hostHead = "abc123"; let held: PullRequestDetail | undefined; let hostReads = 0; - let pushed: ReadonlyArray = ["abc123"]; + let left: ReadonlyArray = []; const harness = yield* makeHarness({ thread: branchThread, pullRequests: { @@ -978,10 +978,10 @@ describe("source control tools", () => { invalidate: () => Effect.sync(() => void (held = undefined)), }, git: { - remoteTrackingCommits: ({ cwd, branch }) => + remoteBranchLeftCommit: ({ cwd, branch, commit }) => Effect.sync(() => { expect({ cwd, branch }).toEqual({ cwd: "/workspace/worktree", branch: "tools" }); - return pushed; + return left.includes(commit); }), }, }); @@ -995,21 +995,15 @@ describe("source control tools", () => { // The agent pushes: the host and the tracking ref move, the cache does not. hostHead = "def456"; - pushed = ["def456"]; + left = ["abc123"]; expect(yield* readHead).toBe("def456"); expect(yield* readHead).toBe("def456"); expect(hostReads).toBe(2); - // A push from elsewhere that this checkout never fetched leaves no local trace. - hostHead = "fed789"; - expect(yield* readHead).toBe("def456"); - pushed = []; - expect(yield* readHead).toBe("def456"); - expect(hostReads).toBe(2); - // The host can lag a push, so a read that still differs is asked again next time, // but a read that just came from the host is not repeated. - pushed = ["0a0a0a"]; + hostHead = "fed789"; + left = ["abc123", "def456", "fed789"]; expect(yield* readHead).toBe("fed789"); expect(hostReads).toBe(3); held = undefined; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index f6a71cdb9f056..446b596fa5033 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -702,13 +702,15 @@ const make = Effect.gen(function* () { detail.state === "open" && detail.headSha !== undefined && detail.observedAt !== undefined && - detail.observedAt < startedAt + detail.observedAt < startedAt && + (yield* git.remoteBranchLeftCommit({ + cwd, + branch: detail.headBranch, + commit: detail.headSha, + })) ) { - const pushed = yield* git.remoteTrackingCommits({ cwd, branch: detail.headBranch }); - if (pushed.length > 0 && !pushed.includes(detail.headSha)) { - yield* pullRequests.invalidate({ reference: ref }); - [detail, activity, diff] = yield* read; - } + yield* pullRequests.invalidate({ reference: ref }); + [detail, activity, diff] = yield* read; } const wantsThreads = wants("threads"); const wantsComments = wants("comments"); diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index c994305017152..e89ba5a092a77 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -5808,38 +5808,3 @@ it.effect.each(["expiry", "commit expiry", "cache hit", "commit cache hit", "ref assert.strictEqual(diffReads, 2); }), ); - -it.effect("an agent's read holds the head and checks from before a push until invalidated", () => - Effect.gen(function* () { - let headSha = "before"; - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakePullRequestProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => - Effect.sync(() => ({ - ...hostedChangeRequest("body"), - headSha, - checks: [ - { name: `CI for ${headSha}`, status: "success", description: null, url: null }, - ], - })), - }), - ], - }); - const read = service - .detail({ ...reference, allowStale: false }) - .pipe(Effect.map((detail) => [detail.headSha, detail.checks[0]?.name])); - assert.deepStrictEqual(yield* read, ["before", "CI for before"]); - headSha = "after"; - yield* TestClock.adjust("30 seconds"); - assert.deepStrictEqual(yield* read, ["before", "CI for before"]); - yield* service.invalidate({ reference }); - assert.deepStrictEqual(yield* read, ["after", "CI for after"]); - assert.deepStrictEqual( - (yield* service.checks(reference))?.checks.map((check) => check.name), - ["CI for after"], - ); - }), -); From 4e3e62ae177d42174fb262defecd548df0f7fd49 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 30 Nov 2026 18:11:08 +0000 Subject: [PATCH 3/4] refactor(server): name the remoteBranchLeftCommit span after its service Co-Authored-By: Claude Opus 5.5 --- apps/server/src/git/GitManager.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 4ce6c58e960ff..ead0750fafb2a 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -3732,7 +3732,7 @@ export const make = Effect.gen(function* () { }); const remoteBranchLeftCommit: GitManager["Service"]["remoteBranchLeftCommit"] = Effect.fn( - "remoteBranchLeftCommit", + "GitManager.remoteBranchLeftCommit", )( function* ({ cwd, branch, commit }) { if (!/^[0-9a-f]{7,64}$/i.test(commit)) return false; From e852877e7f0cdcf0bc362ad7d36da86a653f5cb6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 30 Nov 2026 18:22:52 +0000 Subject: [PATCH 4/4] refactor(server): move the pushed-head refresh into GitManager The MCP handler decided cache freshness, queried Git, invalidated and re-read. GitManager.pullRequestDetail now owns that read: GitManager already depends on PullRequestService, so this adds no layer cycle. The handler passes the thread's checkout and reads activity and diff after the detail, so they see the refreshed cache. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/git/GitManager.test.ts | 68 +++++++++++++++---- apps/server/src/git/GitManager.ts | 43 +++++++++--- .../toolkits/pullRequests/handlers.test.ts | 61 +++-------------- .../src/mcp/toolkits/pullRequests/handlers.ts | 28 ++------ 4 files changed, 104 insertions(+), 96 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 4544cec670084..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,7 +1855,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); - it.effect("tells a commit its own push left behind from one it never fetched", () => + 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); @@ -1858,30 +1863,67 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { const forkDir = yield* createBareRemote(); yield* runGit(repoDir, ["remote", "add", "origin", originDir]); yield* runGit(repoDir, ["remote", "add", "team/fork", forkDir]); - const { manager } = yield* makeManager(); - const left = (commit: string, branch = "feature") => - manager.remoteBranchLeftCommit({ cwd: repoDir, branch, commit }); + // 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* left(first)).toBe(false); + 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* left(first)).toBe(false); + 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"]); - expect(yield* left(first)).toBe(false); yield* runGit(repoDir, ["push", "team/fork", "feature"]); - expect(yield* left(first)).toBe(true); - expect(yield* left(yield* head)).toBe(false); - // Someone else's push that this checkout has not fetched. - expect(yield* left("0123456789abcdef0123456789abcdef01234567")).toBe(false); - expect(yield* left(first, "other")).toBe(false); + 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); }), ); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index ead0750fafb2a..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, @@ -204,14 +206,13 @@ export class GitManager extends Context.Service< readonly url: string; }) => Effect.Effect; /** - * Whether this checkout holds `commit` and last saw its remotes hold `branch` elsewhere, as - * after its own push. A commit it never fetched is someone else's push, which is newer. + * 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 remoteBranchLeftCommit: (input: { + readonly pullRequestDetail: (input: { readonly cwd: string; - readonly branch: string; - readonly commit: string; - }) => Effect.Effect; + readonly reference: PullRequestRef; + }) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; readonly invalidateStatus: (cwd: string) => Effect.Effect; @@ -3731,10 +3732,10 @@ export const make = Effect.gen(function* () { return checkedOutUrl === url; }); - const remoteBranchLeftCommit: GitManager["Service"]["remoteBranchLeftCommit"] = Effect.fn( - "GitManager.remoteBranchLeftCommit", - )( - function* ({ cwd, branch, commit }) { + // 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, @@ -3762,6 +3763,26 @@ export const make = Effect.gen(function* () { 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) { @@ -4516,7 +4537,7 @@ export const make = Effect.gen(function* () { status, branchPullRequest, checkedOutPullRequest, - remoteBranchLeftCommit, + 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 e3217cef13156..2689dcb69ed87 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -19,7 +19,6 @@ import { SourceControlProviderKind, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; -import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -27,7 +26,6 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import { McpSchema, type Tool } from "effect/ai"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; @@ -218,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, @@ -956,59 +959,17 @@ describe("source control tools", () => { }), ); - it.effect("reads the host again when the checkout pushed past the cached head", () => + it.effect("reads the detail through the thread's checkout", () => Effect.gen(function* () { - // The service's cache: a read is held until the PR is invalidated. - let hostHead = "abc123"; - let held: PullRequestDetail | undefined; - let hostReads = 0; - let left: ReadonlyArray = []; const harness = yield* makeHarness({ thread: branchThread, - pullRequests: { - detail: () => - Effect.map(Clock.currentTimeMillis, (observedAt) => { - if (held === undefined) { - hostReads += 1; - held = { ...detail, headSha: hostHead, observedAt }; - } - return held; - }), - activity: () => Effect.succeed(activity), - invalidate: () => Effect.sync(() => void (held = undefined)), - }, + pullRequests: { activity: () => Effect.succeed(activity) }, git: { - remoteBranchLeftCommit: ({ cwd, branch, commit }) => - Effect.sync(() => { - expect({ cwd, branch }).toEqual({ cwd: "/workspace/worktree", branch: "tools" }); - return left.includes(commit); - }), + pullRequestDetail: ({ cwd }) => + Effect.succeed({ ...detail, headSha: cwd === "/workspace/worktree" ? "def456" : "" }), }, }); - const readHead = TestClock.adjust("1 second").pipe( - Effect.andThen(harness.call("pull_request_read", {})), - Effect.map((result) => result.headSha), - ); - expect(yield* readHead).toBe("abc123"); - expect(yield* readHead).toBe("abc123"); - expect(hostReads).toBe(1); - - // The agent pushes: the host and the tracking ref move, the cache does not. - hostHead = "def456"; - left = ["abc123"]; - expect(yield* readHead).toBe("def456"); - expect(yield* readHead).toBe("def456"); - expect(hostReads).toBe(2); - - // The host can lag a push, so a read that still differs is asked again next time, - // but a read that just came from the host is not repeated. - hostHead = "fed789"; - left = ["abc123", "def456", "fed789"]; - expect(yield* readHead).toBe("fed789"); - expect(hostReads).toBe(3); - held = undefined; - expect(yield* readHead).toBe("fed789"); - expect(hostReads).toBe(4); + expect((yield* harness.call("pull_request_read", {})).headSha).toBe("def456"); }), ); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 446b596fa5033..0d4ac296ea852 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -17,7 +17,6 @@ import { TrimmedNonEmptyString, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import * as Clock from "effect/Clock"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; @@ -681,11 +680,13 @@ const make = Effect.gen(function* () { ) { const wants = (section: PullRequestReadSection) => sections.includes(section); const diffCursor = cursor !== undefined && "diff" in cursor ? cursor.diff : undefined; - const startedAt = yield* Clock.currentTimeMillis; - const read = 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 @@ -695,23 +696,6 @@ const make = Effect.gen(function* () { ], { concurrency: "unbounded" }, ).pipe(Effect.mapError(forgeFailure)); - let [detail, activity, diff] = yield* read; - // The agent's own `git push` clears no cache, but it moves the checkout's remote-tracking - // ref. A cached head that ref has left is from before the push, so the host is asked again. - if ( - detail.state === "open" && - detail.headSha !== undefined && - detail.observedAt !== undefined && - detail.observedAt < startedAt && - (yield* git.remoteBranchLeftCommit({ - cwd, - branch: detail.headBranch, - commit: detail.headSha, - })) - ) { - yield* pullRequests.invalidate({ reference: ref }); - [detail, activity, diff] = yield* read; - } const wantsThreads = wants("threads"); const wantsComments = wants("comments"); const page =