Skip to content

Commit c7cd5c6

Browse files
rookmateclaude
andcommitted
fix(source-control): one credential per grouped read, no Enterprise tokens in agents
The Pull Requests service now groups repositories by one key, the host and the credential each repository is read with, everywhere it shares work between them: viewer lookups, batched searches across repositories, and line-count reads. Grouping by login merged repositories whose credentials differed; the line-count path no longer resolves viewers just to group. Agents only get GH_TOKEN for github.com and GHE.com workspaces. gh sends GH_ENTERPRISE_TOKEN to any host a command names, so Enterprise Server workspaces keep gh's own per-host login instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b13f378 commit c7cd5c6

5 files changed

Lines changed: 92 additions & 44 deletions

File tree

‎apps/server/src/orchestration-v2/RuntimePolicy.test.ts‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -157,12 +157,12 @@ it.layer(layerTest)("RuntimePolicyV2", (it) => {
157157
});
158158

159159
const tokenReads: Array<string | null | undefined> = [];
160-
const identityFor = (owner: string) => ({
161-
canonicalKey: `github.com/${owner}/web`,
160+
const identityFor = (owner: string, host = "github.com") => ({
161+
canonicalKey: `${host}/${owner}/web`,
162162
locator: {
163163
source: "git-remote" as const,
164164
remoteName: "origin",
165-
remoteUrl: `git@github.com:${owner}/web.git`,
165+
remoteUrl: `git@${host}:${owner}/web.git`,
166166
},
167167
owner,
168168
name: "web",
@@ -174,7 +174,11 @@ const layerWithAccounts = layerTest.pipe(
174174
Layer.mergeAll(
175175
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
176176
resolve: (cwd) =>
177-
Effect.succeed(identityFor(cwd === "/project-worktree" ? "acme" : "someone")),
177+
Effect.succeed(
178+
cwd === "/enterprise-worktree"
179+
? identityFor("acme", "github.acme-corp.example")
180+
: identityFor(cwd === "/project-worktree" ? "acme" : "someone"),
181+
),
178182
}),
179183
Layer.mock(GitHubCredentials.GitHubCredentials)({
180184
accountFor: (_host, repository) =>
@@ -217,6 +221,15 @@ it.layer(layerWithAccounts)("RuntimePolicyV2 with GitHub accounts", (it) => {
217221
assert.isUndefined(personal.environment);
218222
// A workspace no rule covers never asks gh for a token.
219223
assert.deepEqual(tokenReads, ["acme/web"]);
224+
225+
// gh would send an Enterprise Server token to any host a command names, so none is handed
226+
// out there, even where a rule picks an account.
227+
const enterprise = yield* policy.resolve({
228+
thread: makeThread({ now, worktreePath: "/enterprise-worktree" }),
229+
modelSelection,
230+
});
231+
assert.isUndefined(enterprise.environment);
232+
assert.deepEqual(tokenReads, ["acme/web"]);
220233
}),
221234
);
222235
});

‎apps/server/src/pullRequest/PullRequestService.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4160,6 +4160,53 @@ it.effect("reads an open pull request again once an account choice changes", ()
41604160
}),
41614161
);
41624162

4163+
it.effect("never shares a search or a line-count read between two credentials of one login", () =>
4164+
Effect.gen(function* () {
4165+
const searches: Array<string> = [];
4166+
const statsAsked: Array<string> = [];
4167+
const service = yield* makeService({
4168+
projects: [
4169+
project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
4170+
project({ id: "p2", title: "api", workspaceRoot: "/b", repository: "acme/api" }),
4171+
],
4172+
providers: [
4173+
fakeProvider(SourceControlProviderKind.make("github"), {
4174+
// Two tokens that sign in as the same login, such as one gh refreshed and one held.
4175+
credentialScope: ({ repository }) =>
4176+
Effect.succeed(repository === "acme/web" ? "token-a" : "token-b"),
4177+
getViewer: () => Effect.succeed("bilal"),
4178+
listChangeRequestsAcross: (input) =>
4179+
Effect.sync(() => {
4180+
searches.push(input.repositories.join(","));
4181+
return {
4182+
items: input.repositories.map((repository) =>
4183+
batchedChangeRequest(1, repository, "2026-07-02T00:00:00Z"),
4184+
),
4185+
truncated: false,
4186+
};
4187+
}),
4188+
listChangeRequestStats: (input) =>
4189+
Effect.sync(() => {
4190+
statsAsked.push(input.changeRequests.map((entry) => entry.repository).join(","));
4191+
return [];
4192+
}),
4193+
}),
4194+
],
4195+
});
4196+
4197+
const result = yield* service.list({ state: "open", involvement: "all" });
4198+
yield* service.listStats({
4199+
refs: result.entries.map(({ projectId, repository, number }) => ({
4200+
projectId,
4201+
repository,
4202+
number,
4203+
})),
4204+
});
4205+
assert.deepStrictEqual(searches.toSorted(), ["acme/api", "acme/web"]);
4206+
assert.deepStrictEqual(statsAsked.toSorted(), ["acme/api", "acme/web"]);
4207+
}),
4208+
);
4209+
41634210
it.effect("leaves only the repositories of an account that cannot be read unavailable", () =>
41644211
Effect.gen(function* () {
41654212
const service = yield* makeService({

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -930,7 +930,9 @@ export const make = Effect.gen(function* () {
930930
readonly viewer: string | null;
931931
readonly error: PullRequestProviderError | null;
932932
};
933-
const viewerKey = (host: string, scope: string) => `${host}\n${scope}`;
933+
// Every grouping of repositories goes through this key: a group is read with one credential, so
934+
// it can share a viewer, a batched search and a line-count read without mixing two accounts.
935+
const credentialKey = (host: string, scope: string) => `${host}\n${scope}`;
934936
const viewersByHost = new Map<string, { readonly at: number; readonly result: ResolvedViewer }>();
935937
const viewerFlights = yield* Cache.makeWith(
936938
(key: string): Effect.Effect<ResolvedViewer> => {
@@ -960,7 +962,7 @@ export const make = Effect.gen(function* () {
960962
})),
961963
Effect.tap((result) =>
962964
Effect.map(Clock.currentTimeMillis, (at) =>
963-
viewersByHost.set(viewerKey(host, scope), { at, result }),
965+
viewersByHost.set(credentialKey(host, scope), { at, result }),
964966
),
965967
),
966968
Effect.catch((error) =>
@@ -989,15 +991,15 @@ export const make = Effect.gen(function* () {
989991
options?: { readonly allowPaused: boolean },
990992
) =>
991993
Effect.forEach(
992-
[...new Set(projects.map((project) => viewerKey(project.host, project.credentialScope)))],
994+
[...new Set(projects.map((project) => credentialKey(project.host, project.credentialScope)))],
993995
(accountKey) =>
994996
Effect.flatMap(Clock.currentTimeMillis, (now): Effect.Effect<ResolvedViewer> => {
995997
const held = viewersByHost.get(accountKey);
996998
if (held !== undefined && now - held.at <= Duration.toMillis(VIEWER_CACHE_TTL)) {
997999
return Effect.succeed(held.result);
9981000
}
9991001
const forAccount = projects.filter(
1000-
(project) => viewerKey(project.host, project.credentialScope) === accountKey,
1002+
(project) => credentialKey(project.host, project.credentialScope) === accountKey,
10011003
);
10021004
const { host, api } = forAccount[0]!;
10031005
const scope = forAccount[0]!.credentialScope;
@@ -1140,11 +1142,11 @@ export const make = Effect.gen(function* () {
11401142
const viewers: Record<string, string> = {};
11411143
for (const result of viewerResults) {
11421144
if (result.viewer === null) continue;
1143-
viewerByAccount.set(viewerKey(result.host, result.scope), result.viewer);
1145+
viewerByAccount.set(credentialKey(result.host, result.scope), result.viewer);
11441146
viewers[result.host] ??= result.viewer;
11451147
}
11461148
const viewerFor = (project: SupportedProject): string | undefined =>
1147-
viewerByAccount.get(viewerKey(project.host, project.credentialScope));
1149+
viewerByAccount.get(credentialKey(project.host, project.credentialScope));
11481150

11491151
const providers: ReadonlyArray<PullRequestProviderSummary> = [
11501152
...[...new Set(viewerResults.map((result) => result.host))].map((host) => {
@@ -1192,8 +1194,8 @@ export const make = Effect.gen(function* () {
11921194
result.error === null ||
11931195
!selected.some(
11941196
(project) =>
1195-
viewerKey(project.host, project.credentialScope) ===
1196-
viewerKey(result.host, result.scope),
1197+
credentialKey(project.host, project.credentialScope) ===
1198+
credentialKey(result.host, result.scope),
11971199
)
11981200
? []
11991201
: [result.error],
@@ -1388,7 +1390,7 @@ export const make = Effect.gen(function* () {
13881390
separate.push(project);
13891391
continue;
13901392
}
1391-
const key = `${project.host}\n${viewerFor(project)}\n${cursorOf(project)?.updatedBefore ?? ""}`;
1393+
const key = `${credentialKey(project.host, project.credentialScope)}\n${cursorOf(project)?.updatedBefore ?? ""}`;
13921394
const group = together.get(key);
13931395
if (group === undefined) together.set(key, [project]);
13941396
else group.push(project);
@@ -2423,7 +2425,7 @@ export const make = Effect.gen(function* () {
24232425
const listStatsUncached: PullRequestService["Service"]["listStats"] = (input) =>
24242426
Effect.gen(function* () {
24252427
if (input.refs.length === 0) return { stats: [] };
2426-
const { supported, viewerRoots } = yield* listWorkspaceProjects({});
2428+
const { supported } = yield* listWorkspaceProjects({});
24272429
const byProject = new Map(supported.map((project) => [project.project.id, project]));
24282430
const wanted = new Map<
24292431
string,
@@ -2440,22 +2442,9 @@ export const make = Effect.gen(function* () {
24402442
}
24412443
wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number });
24422444
}
2443-
// One read carries one account's token, so rows are grouped by who the listing read them
2444-
// as: the viewer the listing already resolved, or the scope where it could not.
2445-
const viewerResults = yield* resolveViewers(
2446-
[...wanted.values()].map(({ project }) => project),
2447-
viewerRoots,
2448-
);
2449-
const accountOf = (project: SupportedProject) => {
2450-
const scope = project.credentialScope;
2451-
const viewer = viewerResults.find(
2452-
(result) => result.host === project.host && result.scope === scope,
2453-
)?.viewer;
2454-
return `${project.host}\n${viewer == null ? `scope ${scope}` : `viewer ${viewer}`}`;
2455-
};
24562445
const byAccount = new Map<string, Array<{ project: SupportedProject; number: number }>>();
24572446
for (const entry of wanted.values()) {
2458-
const key = accountOf(entry.project);
2447+
const key = credentialKey(entry.project.host, entry.project.credentialScope);
24592448
const held = byAccount.get(key);
24602449
if (held === undefined) byAccount.set(key, [entry]);
24612450
else held.push(entry);

‎apps/server/src/sourceControl/GitHubWorkspaceAccount.ts‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,19 @@ export const workspaceGitHubCredential = Effect.fn("GitHubWorkspaceAccount.crede
4242
});
4343

4444
/**
45-
* Variables for the agent processes working in `cwd`, so `gh` and git over HTTPS inside them act
46-
* as the account Settings choose for the repository. Empty unless Settings picked a login
47-
* of their own: an environment token reaches the agent already, and gh's active login is what an
48-
* agent without `GH_TOKEN` gets anyway.
45+
* Variables for the agent processes working in `cwd`, so `gh` inside them acts as the account
46+
* Settings choose for the repository. Empty unless Settings picked a login of their own on
47+
* github.com or GHE.com: an environment token reaches the agent already, and gh's active login is
48+
* what an agent without `GH_TOKEN` gets anyway.
4949
*/
5050
export const agentGitHubEnvironment = Effect.fn("GitHubWorkspaceAccount.agentEnvironment")(
5151
function* (cwd: string) {
5252
const none: Readonly<Record<string, Redacted.Redacted<string>>> = {};
5353
const workspace = yield* workspaceGitHubRepository(cwd);
54-
if (workspace === null) return none;
54+
// gh sends `GH_TOKEN` only to github.com and GHE.com, but `GH_ENTERPRISE_TOKEN` to every other
55+
// host it is pointed at, so an Enterprise Server token is never handed to an agent: there gh's
56+
// own login, which it keeps per host, stays in charge.
57+
if (workspace === null || !GitHubCredentials.isGitHubDotCom(workspace.host)) return none;
5558
const credentials = yield* GitHubCredentials.GitHubCredentials;
5659
// Settings first, so a turn in a workspace no rule covers never waits on `gh`.
5760
if ((yield* credentials.accountFor(workspace.host, workspace.repository)) === undefined) {
@@ -61,10 +64,6 @@ export const agentGitHubEnvironment = Effect.fn("GitHubWorkspaceAccount.agentEnv
6164
.get(workspace.host, workspace.repository)
6265
.pipe(Effect.orElseSucceed(() => null));
6366
if (credential?.account === undefined) return none;
64-
// gh reads `GH_ENTERPRISE_TOKEN` for every host but github.com and GHE.com.
65-
const variable = GitHubCredentials.isGitHubDotCom(credential.host)
66-
? "GH_TOKEN"
67-
: "GH_ENTERPRISE_TOKEN";
68-
return { [variable]: credential.token };
67+
return { GH_TOKEN: credential.token };
6968
},
7069
);

‎docs/user/source-control.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ repository can use a different account from its owner: pick it in that project's
3434
control** settings. A repository's pull requests are read and acted on as its account, **Mine**
3535
and **Reviewing** include the pull requests of every account, and agents in its projects get the
3636
account's token as `GH_TOKEN`. Codex, Claude, Grok, Antigravity, OpenCode 1.x, and Pi agents
37-
receive it; OpenCode 2.x and Cursor agents keep using `gh`'s active account. After you change an
38-
account, Claude agents use the new one from their next turn; other agents switch once their
39-
session restarts, for example after you stop the thread. On mobile, the same
40-
choices are under **Settings → Source control → GitHub accounts**, and with a project selected
41-
in Settings. A saved token or `GH_TOKEN` takes precedence over every account choice; a host
42-
turned off stays off either way.
37+
receive it on github.com and GHE.com; on GitHub Enterprise Server, and for OpenCode 2.x and Cursor
38+
agents, `gh`'s own login stays in use. After you change an account, Claude agents use the new one
39+
from their next turn; other agents switch once their session restarts, for example after you stop
40+
the thread. On mobile, the same choices are under **Settings → Source control → GitHub accounts**,
41+
and with a project selected in Settings. A saved token or `GH_TOKEN` takes precedence over every
42+
account choice; a host turned off stays off either way.
4343

4444
For GitHub Enterprise, sign in with `gh auth login --hostname YOUR_HOST`. T3 Code treats a
4545
custom server name as GitHub once it has a credential for that host.

0 commit comments

Comments
 (0)