The best way to control Claude Code, Codex and more from any computer or phone
perf(server): merged-PR threads no longer re-read git state every minute (#24099)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Batuhan1999 committed
Nov 12, 2026 at 23:50 UTC
a0844eaec603e60a19de540963807ce53a7a6963
6 files changed
+368
-6
apps/server/src/git/GitManager.test.ts
+6
@@ -1152,6 +1152,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1152
"for-each-ref",
1153
]);
1154
expect(freshLookups()).toBe(0);
1155
+ gitCommands.length = 0;
1156
+ yield* manager.branchPullRequest(
1157
+ { cwd: repoDir, branch: "feature/settled" },
1158
+ { confirmTerminal: false },
1159
+ );
1160
+ expect(gitCommands).toEqual([]);
1161
1162
NodeFS.writeFileSync(NodePath.join(repoDir, "settled.txt"), "new work\n");
1163
yield* runGit(repoDir, ["add", "settled.txt"]);
apps/server/src/git/GitManager.ts
+20
-4
@@ -136,10 +136,18 @@ export class GitManager extends Context.Service<
136
input: VcsStatusInput,
137
options?: GitRemoteStatusOptions,
138
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
139
- /** refresh queries the host; freshGitState rereads only git state and is required before persisting. */
139
+ /**
140
+ * refresh queries the host; freshGitState rereads only git state and is required before persisting.
141
+ * A merged or closed answer is confirmed against git state unless confirmTerminal is false;
142
+ * callers that opt out confirm before acting on it.
143
+ */
144
readonly branchPullRequest: (
145
input: { readonly cwd: string; readonly branch: string },
142
- options?: { readonly refresh?: boolean; readonly freshGitState?: boolean },
146
+ options?: {
147
+ readonly refresh?: boolean;
148
+ readonly freshGitState?: boolean;
149
+ readonly confirmTerminal?: boolean;
150
+ },
151
) => Effect.Effect<GitBranchPullRequest | null, GitManagerServiceError>;
152
/** Whether T3 checked this pull request out onto the branch, which ties it to later threads. */
153
readonly checkedOutPullRequest: (input: {
@@ -2492,7 +2500,8 @@ export const make = Effect.gen(function* () {
2500
});
2501
return mergeGitStatusParts(local, remote);
2502
});
2495
- // Closed PR results can settle threads or remove worktrees; confirm fresh git state before persisting.
2503
+ // Closed PR results can settle threads or remove worktrees; confirm fresh git state before
2504
+ // persisting, and before acting when a caller skipped confirmation (`confirmTerminal: false`).
2505
const prLookupGitStateByKey = new Map<
2506
string,
2507
{ readonly readAtMs: number; readonly value: string | null }
@@ -2789,7 +2798,14 @@ export const make = Effect.gen(function* () {
2798
refresh,
2799
freshGitState,
2800
});
2792
- if (pullRequest === null || pullRequest.state === "open" || freshGitState) return pullRequest;
2801
+ if (
2802
+ pullRequest === null ||
2803
+ pullRequest.state === "open" ||
2804
+ freshGitState ||
2805
+ options?.confirmTerminal === false
2806
+ ) {
2807
+ return pullRequest;
2808
+ }
2809
// A confirmed closed or merged result stays final until the branch or remotes change,
2810
// with a periodic fresh lookup so a new PR from a reused branch still shows up.
2811
const settledKey = `${cacheCwd}\u0000${branch}`;
apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts
+246
@@ -832,4 +832,250 @@ describe("ThreadPullRequestServiceV2 reads", () => {
832
}),
833
),
834
);
835
+
836
+ it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
837
+ Effect.scoped(
838
+ Effect.gen(function* () {
839
+ const savedReference = {
840
+ projectId: ProjectId.make("project-1"),
841
+ repository: "acme/project",
842
+ number: 42,
843
+ url: "https://github.com/acme/project/pull/42",
844
+ };
845
+ const thread = {
846
+ ...threadShell("merged-branch-thread"),
847
+ branch: "feature/merged",
848
+ branchPullRequest: savedReference,
849
+ };
850
+ const project: OrchestrationProjectShell = {
851
+ id: thread.projectId,
852
+ title: "Project",
853
+ workspaceRoot: "/workspace/project",
854
+ defaultModelSelection: null,
855
+ scripts: [],
856
+ createdAt: "2026-08-01T00:00:00.000Z",
857
+ updatedAt: "2026-08-01T00:00:00.000Z",
858
+ };
859
+ const activation = yield* Deferred.make<void>();
860
+ const sweeps = yield* Queue.unbounded<void>();
861
+ const commands: Array<OrchestrationV2ServerCommand> = [];
862
+ const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
863
+ [];
864
+ const dependencies = Layer.mergeAll(
865
+ Layer.mock(Orchestrator.OrchestratorV2)({
866
+ streamDomainEvents: Stream.never,
867
+ getPullRequestSnapshot: () =>
868
+ Queue.offer(sweeps, undefined).pipe(
869
+ Effect.as({
870
+ schemaVersion: 2,
871
+ snapshotSequence: 1,
872
+ threads: [thread],
873
+ archivedThreads: [],
874
+ }),
875
+ ),
876
+ dispatch: (command) =>
877
+ Effect.sync(() => {
878
+ commands.push(command);
879
+ return { sequence: 2, storedEvents: [] };
880
+ }),
881
+ }),
882
+ Layer.mock(ProjectStore.ProjectStoreV2)({
883
+ listShells: () => Effect.succeed([project]),
884
+ getShell: () => Effect.succeedSome(project),
885
+ }),
886
+ Layer.mock(GitManager.GitManager)({
887
+ branchPullRequest: (_input, options) =>
888
+ Effect.sync(() => {
889
+ lookups.push(options);
890
+ return {
891
+ number: 42,
892
+ title: "Merged work",
893
+ url: savedReference.url,
894
+ baseRef: "main",
895
+ headRef: thread.branch,
896
+ state: "merged" as const,
897
+ repositoryKey: "github.com/acme/project",
898
+ updatedAt: "2026-09-19T00:00:00.000Z",
899
+ closedAt: null,
900
+ mergedAt: "2026-09-19T00:00:00.000Z",
901
+ };
902
+ }),
903
+ }),
904
+ Layer.mock(PullRequestService.PullRequestService)({}),
905
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
906
+ resolve: () =>
907
+ Effect.succeed({
908
+ canonicalKey: "github.com/acme/project",
909
+ locator: {
910
+ source: "git-remote" as const,
911
+ remoteName: "origin",
912
+ remoteUrl: "git@github.com:acme/project.git",
913
+ },
914
+ provider: SourceControlProviderKind.make("github"),
915
+ owner: "acme",
916
+ name: "project",
917
+ }),
918
+ }),
919
+ // A connected client keeps the periodic sweep running.
920
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
921
+ shouldRunOpportunisticWork: Effect.succeed(true),
922
+ }),
923
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
924
+ Layer.succeed(
925
+ SecureRandom.SecureRandom,
926
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
927
+ ),
928
+ FileSystem.layerNoop({}),
929
+ Path.layer,
930
+ );
931
+ yield* Effect.gen(function* () {
932
+ const service = yield* ThreadPullRequestService.make;
933
+ yield* service.start();
934
+ yield* Deferred.succeed(activation, undefined);
935
+ yield* Queue.take(sweeps);
936
+ yield* service.drain;
937
+ yield* TestClock.adjust("1 minute");
938
+ yield* Queue.take(sweeps);
939
+ yield* service.drain;
940
+ }).pipe(Effect.provide(dependencies));
941
+
942
+ expect(commands).toEqual([]);
943
+ expect(lookups).toHaveLength(2);
944
+ // GitManager rereads git state on request, and by default whenever its
945
+ // remembered answer is merged or closed.
946
+ expect(
947
+ lookups.filter(
948
+ (options) =>
949
+ options?.refresh === true ||
950
+ options?.freshGitState === true ||
951
+ options?.confirmTerminal !== false,
952
+ ),
953
+ ).toEqual([]);
954
+ }),
955
+ ),
956
+ );
957
+
958
+ const mergedPullRequest43 = {
959
+ number: 43,
960
+ title: "Replacement work",
961
+ url: "https://github.com/acme/project/pull/43",
962
+ baseRef: "main",
963
+ headRef: "feature/replaced",
964
+ state: "merged" as const,
965
+ repositoryKey: "github.com/acme/project",
966
+ updatedAt: "2026-09-19T00:00:00.000Z",
967
+ closedAt: null,
968
+ mergedAt: "2026-09-19T00:00:00.000Z",
969
+ };
970
+
971
+ it.effect.each([
972
+ { name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
973
+ { name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
974
+ ])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
975
+ Effect.scoped(
976
+ Effect.gen(function* () {
977
+ const savedReference = {
978
+ projectId: ProjectId.make("project-1"),
979
+ repository: "acme/project",
980
+ number: 42,
981
+ url: "https://github.com/acme/project/pull/42",
982
+ };
983
+ const thread = {
984
+ ...threadShell("replaced-branch-thread"),
985
+ createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
986
+ branch: mergedPullRequest43.headRef,
987
+ branchPullRequest: savedReference,
988
+ };
989
+ const project: OrchestrationProjectShell = {
990
+ id: thread.projectId,
991
+ title: "Project",
992
+ workspaceRoot: "/workspace/project",
993
+ defaultModelSelection: null,
994
+ scripts: [],
995
+ createdAt: "2026-08-01T00:00:00.000Z",
996
+ updatedAt: "2026-08-01T00:00:00.000Z",
997
+ };
998
+ const activation = yield* Deferred.make<void>();
999
+ const sweeps = yield* Queue.unbounded<void>();
1000
+ const commands: Array<OrchestrationV2ServerCommand> = [];
1001
+ const dependencies = Layer.mergeAll(
1002
+ Layer.mock(Orchestrator.OrchestratorV2)({
1003
+ streamDomainEvents: Stream.never,
1004
+ getPullRequestSnapshot: () =>
1005
+ Queue.offer(sweeps, undefined).pipe(
1006
+ Effect.as({
1007
+ schemaVersion: 2,
1008
+ snapshotSequence: 1,
1009
+ threads: [thread],
1010
+ archivedThreads: [],
1011
+ }),
1012
+ ),
1013
+ dispatch: (command) =>
1014
+ Effect.sync(() => {
1015
+ commands.push(command);
1016
+ return { sequence: 2, storedEvents: [] };
1017
+ }),
1018
+ }),
1019
+ Layer.mock(ProjectStore.ProjectStoreV2)({
1020
+ listShells: () => Effect.succeed([project]),
1021
+ getShell: () => Effect.succeedSome(project),
1022
+ }),
1023
+ // Only the fresh read disagrees with the remembered detection.
1024
+ Layer.mock(GitManager.GitManager)({
1025
+ branchPullRequest: (_input, options) =>
1026
+ Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1027
+ }),
1028
+ Layer.mock(PullRequestService.PullRequestService)({}),
1029
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1030
+ resolve: () =>
1031
+ Effect.succeed({
1032
+ canonicalKey: "github.com/acme/project",
1033
+ locator: {
1034
+ source: "git-remote" as const,
1035
+ remoteName: "origin",
1036
+ remoteUrl: "git@github.com:acme/project.git",
1037
+ },
1038
+ provider: SourceControlProviderKind.make("github"),
1039
+ owner: "acme",
1040
+ name: "project",
1041
+ }),
1042
+ }),
1043
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1044
+ shouldRunOpportunisticWork: Effect.succeed(true),
1045
+ }),
1046
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1047
+ Layer.succeed(
1048
+ SecureRandom.SecureRandom,
1049
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1050
+ ),
1051
+ FileSystem.layerNoop({}),
1052
+ Path.layer,
1053
+ );
1054
+ yield* Effect.gen(function* () {
1055
+ const service = yield* ThreadPullRequestService.make;
1056
+ yield* service.start();
1057
+ yield* Deferred.succeed(activation, undefined);
1058
+ yield* Queue.take(sweeps);
1059
+ yield* service.drain;
1060
+ }).pipe(Effect.provide(dependencies));
1061
+
1062
+ expect(
1063
+ commands.map((command) =>
1064
+ command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1065
+ ),
1066
+ ).toEqual(
1067
+ writes
1068
+ ? [
1069
+ {
1070
+ projectId: project.id,
1071
+ repository: "acme/project",
1072
+ number: 43,
1073
+ url: mergedPullRequest43.url,
1074
+ },
1075
+ ]
1076
+ : [],
1077
+ );
1078
+ }),
1079
+ ),
1080
+ );
1081
});
apps/server/src/orchestration-v2/ThreadPullRequestService.ts
+2
-1
@@ -204,12 +204,13 @@ export const make = Effect.gen(function* () {
204
.pipe(Effect.orElseSucceed(() => true)))
205
? first.worktreePath
206
: project.workspaceRoot;
207
+ // A detected PR is confirmed against fresh git state before it is saved.
208
const detected =
209
first.branch === null
210
? null
211
: yield* git.branchPullRequest(
212
{ cwd, branch: first.branch },
212
- { refresh: request.refresh },
213
+ { refresh: request.refresh, confirmTerminal: false },
214
);
215
if (detected !== null && !pullRequestMatchesProject(detected, resolvedProject)) {
216
return finishBackfill(group);
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+85
@@ -553,6 +553,18 @@ function makeBranchPullRequest(state: "open" | "closed" | "merged") {
553
} satisfies GitManager.GitBranchPullRequest;
554
}
555
556
+// GitManager rereads git state on request, and by default whenever its
557
+// remembered answer is merged or closed.
558
+function readsFreshGitState(
559
+ options: Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1],
560
+): boolean {
561
+ return (
562
+ options?.refresh === true ||
563
+ options?.freshGitState === true ||
564
+ options?.confirmTerminal !== false
565
+ );
566
+}
567
+
568
interface HarnessOptions {
569
readonly snapshot: SettlementSnapshot;
570
readonly settings?: ContractServerSettings;
@@ -1744,6 +1756,79 @@ describe("ThreadSettlementServiceV2 worker", () => {
1756
),
1757
);
1758
1759
+ it.effect("a merged branch PR that cannot settle its thread rereads no git state", () =>
1760
+ Effect.scoped(
1761
+ Effect.gen(function* () {
1762
+ yield* TestClock.setTime(Date.parse(NOW));
1763
+ const freshReads = yield* Ref.make(0);
1764
+ const fixture = yield* makeHarness({
1765
+ snapshot: makeSnapshot([
1766
+ makeThread("worked-after-merge", {
1767
+ branch: "merged-feature",
1768
+ latestUserAuthoredMessageAt: DateTime.makeUnsafe("2026-08-28T06:00:00.000Z"),
1769
+ }),
1770
+ ]),
1771
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1772
+ branchPullRequest: (_input, lookupOptions) =>
1773
+ Ref.update(
1774
+ freshReads,
1775
+ (count) => count + (readsFreshGitState(lookupOptions) ? 1 : 0),
1776
+ ).pipe(
1777
+ Effect.as({
1778
+ ...makeBranchPullRequest("merged"),
1779
+ mergedAt: "2026-08-27T00:00:00.000Z",
1780
+ }),
1781
+ ),
1782
+ });
1783
+
1784
+ yield* Effect.gen(function* () {
1785
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1786
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1787
+ yield* TestClock.adjust("1 minute");
1788
+ yield* Queue.take(fixture.snapshotReads);
1789
+ yield* reactor.drain;
1790
+
1791
+ assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
1792
+ assert.strictEqual(yield* Ref.get(freshReads), 0);
1793
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1794
+ }).pipe(Effect.provide(fixture.layer));
1795
+ }),
1796
+ ),
1797
+ );
1798
+
1799
+ it.effect("a remembered merged branch PR settles only after fresh git state agrees", () =>
1800
+ Effect.scoped(
1801
+ Effect.gen(function* () {
1802
+ yield* TestClock.setTime(Date.parse(NOW));
1803
+ const freshState = yield* Ref.make<"open" | "merged">("open");
1804
+ const fixture = yield* makeHarness({
1805
+ snapshot: makeSnapshot([makeThread("merged-branch", { branch: "merged-feature" })]),
1806
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1807
+ branchPullRequest: (_input, lookupOptions) =>
1808
+ readsFreshGitState(lookupOptions)
1809
+ ? Ref.get(freshState).pipe(Effect.map(makeBranchPullRequest))
1810
+ : Effect.succeed(makeBranchPullRequest("merged")),
1811
+ });
1812
+
1813
+ yield* Effect.gen(function* () {
1814
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1815
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1816
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1817
+
1818
+ yield* Ref.set(freshState, "merged");
1819
+ yield* TestClock.adjust("1 minute");
1820
+ yield* Queue.take(fixture.snapshotReads);
1821
+ yield* reactor.drain;
1822
+
1823
+ assert.deepStrictEqual(
1824
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1825
+ [ThreadId.make("merged-branch")],
1826
+ );
1827
+ }).pipe(Effect.provide(fixture.layer));
1828
+ }),
1829
+ ),
1830
+ );
1831
+
1832
it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
1833
Effect.scoped(
1834
Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadSettlementService.ts
+9
-1
@@ -541,7 +541,15 @@ export const make = Effect.gen(function* () {
541
return yield* Effect.die(new Error("thread project not found"));
542
}
543
const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0;
544
- return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { refresh });
544
+ // Remembered git state is enough to rule a thread out; only an answer
545
+ // that would settle it is confirmed against fresh git state.
546
+ const remembered = yield* git.branchPullRequest(
547
+ { cwd, branch: thread.branch },
548
+ { refresh, confirmTerminal: false },
549
+ );
550
+ if (refresh || remembered === null || remembered.state === "open") return remembered;
551
+ if (!(yield* wouldSettle(group, remembered))) return undefined;
552
+ return yield* git.branchPullRequest({ cwd, branch: thread.branch }, { freshGitState: true });
553
});
554
555
yield* Effect.forEach(