Open History to see the last commit
1import { requireSettingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";
2import * as DateTime from "effect/DateTime";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import {
6 GraphQL,
7 GraphQLClient,
8 GraphQLClientError,
9 GraphQLGroup,
10 GraphQLResolver,
11} from "effect/graphql";
12import * as Option from "effect/Option";
13import * as RequestResolver from "effect/RequestResolver";
14import * as Result from "effect/Result";
15import * as Schema from "effect/Schema";
16import {
17 SourceControlProviderError,
18 TrimmedNonEmptyString,
19 type ChangeRequest,
20 type SourceControlProviderDiscoveryItem,
21 type SourceControlRepositoryCloneUrls,
22} from "@t3tools/contracts";
23import { normalizeGitRemoteUrl } from "@t3tools/shared/git";
24import * as HostProcess from "@t3tools/shared/HostProcess";
25import { decodeJsonResult } from "@t3tools/shared/schemaJson";
26import { isSshRemoteUrl } from "@t3tools/shared/sourceControl";
27
28import { GH_PROCESS_CONCURRENCY } from "./GitHubCredentials.ts";
29import * as GitHubAppSignIn from "./GitHubAppSignIn.ts";
30import * as GitHubRest from "./GitHubRest.ts";
31import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
32import * as GitHubChangeRequestTemplate from "./gitHubChangeRequestTemplate.ts";
33import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts";
34import {
35 normalizeGitHubPullRequestRecord,
36 type NormalizedGitHubPullRequestRecord,
37} from "./gitHubPullRequests.ts";
38import {
39 gitHubApiHostForRemote,
40 parseFetchRemotes,
41 parseGitHubRepositorySelector,
42 parsePullRequestReference,
43 resolveGitHubRepository,
44 type GitHubRepositoryLocator,
45} from "./gitHubRepositoryResolution.ts";
46import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
47import {
48 effectiveGitHubAccount,
49 findAuthenticatedGitHubAccount,
50 parseGitHubAuthStatus,
51 type GitHubAuthStatusAccount,
52} from "./gitHubAuthStatus.ts";
53import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider";
54import {
55 combinedAuthOutput,
56 firstSafeAuthLine,
57 probeSourceControlProvider,
58 providerAuth,
59 type SourceControlAuthProbeInput,
60 type SourceControlCliDiscoverySpec,
61 type SourceControlManagedCliDiscoverySpec,
62} from "@t3tools/source-control-core/server/discovery";
63import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
64import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";
65
66import * as GitHubClient from "../shared/definition.ts";
67import {
68 PullRequestByNumber,
69 PullRequestNode,
70 PullRequestsByHead,
71} from "./sourceControlProvider.graphql.ts";
72
73// Decode rows separately to isolate malformed PRs within shared documents.
74const LenientPullRequestsByHead = GraphQL.query(PullRequestsByHead.name, {
75 // `GraphQLResolver.aliased` needs a template per lookup.
76 document: PullRequestsByHead.template!,
77 variables: PullRequestsByHead.variables,
78 result: Schema.Struct({
79 repository: Schema.NullOr(
80 Schema.Struct({
81 pullRequests: Schema.Struct({ nodes: Schema.NullOr(Schema.Array(Schema.Unknown)) }),
82 }),
83 ),
84 }),
85});
86const decodePullRequestNode = Schema.decodeUnknownOption(PullRequestNode);
87
88const decodeLinkSubject = Schema.decodeUnknownEffect(
89 Schema.fromJsonString(
90 Schema.Struct({ title: Schema.String, body: Schema.optional(Schema.NullOr(Schema.String)) }),
91 ),
92);
93
94function toChangeRequest(record: NormalizedGitHubPullRequestRecord): ChangeRequest {
95 return { provider: SourceControlProviderKind.make("github"), ...record };
96}
97
98function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {
99 return accounts.map((entry) => ({
100 host: entry.host,
101 account: entry.account,
102 active: entry.active,
103 authenticated: entry.authenticated,
104 ...(entry.error === null ? {} : { error: entry.error }),
105 ...(entry.environmentVariable === null
106 ? {}
107 : { environmentVariable: entry.environmentVariable }),
108 }));
109}
110
111export function parseGitHubAuth(
112 input: SourceControlAuthProbeInput,
113 settings: GitHubClient.GitHubSettings = readSourceControlHostSettings(GitHubClient.settings, {}),
114) {
115 const output = combinedAuthOutput(input);
116 const authStatus = parseGitHubAuthStatus(input.stdout);
117 const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];
118 const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);
119 const orderedHosts = fallback
120 ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]
121 : hosts;
122 const chosen = orderedHosts
123 .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))
124 .find((entry) => entry !== undefined);
125 const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};
126
127 if (chosen) {
128 return {
129 ...providerAuth({
130 status: "authenticated",
131 account: chosen.account,
132 host: chosen.host,
133 detail:
134 chosen.environmentVariable === null
135 ? undefined
136 : `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,
137 }),
138 ...accounts,
139 };
140 }
141
142 if (fallback) {
143 return {
144 ...providerAuth({
145 status: "unauthenticated",
146 host: fallback.host,
147 detail: "Every GitHub host gh is signed in to is turned off in Settings → Source Control.",
148 }),
149 ...accounts,
150 };
151 }
152
153 const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];
154 if (authStatus.parsed) {
155 return {
156 ...providerAuth({
157 status: "unauthenticated",
158 host: failedAccount?.host,
159 detail:
160 failedAccount?.error ??
161 "Run `gh auth login` to authenticate GitHub CLI with an active account.",
162 }),
163 ...accounts,
164 };
165 }
166
167 // gh before 2.81.0 rejects --json with a nonzero exit that resembles a signed-out CLI.
168 if (input.exitCode !== 0 && output.includes("unknown flag: --json")) {
169 return providerAuth({
170 status: "unknown",
171 detail:
172 "GitHub CLI is too old to report sign-in status. Update `gh` to 2.81.0 or newer (for example `brew upgrade gh`) and rescan.",
173 });
174 }
175
176 if (input.exitCode !== 0) {
177 return providerAuth({
178 status: "unauthenticated",
179 detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",
180 });
181 }
182
183 return providerAuth({
184 status: "unknown",
185 detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",
186 });
187}
188
189export const discovery = {
190 type: "cli",
191 kind: SourceControlProviderKind.make("github"),
192 label: "GitHub",
193 executable: "gh",
194 versionArgs: ["--version"],
195 authArgs: ["auth", "status", "--json", "hosts"],
196 parseAuth: parseGitHubAuth,
197 installHint:
198 "Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).",
199} satisfies SourceControlCliDiscoverySpec;
200
201const decodeViewer = Schema.decodeUnknownOption(
202 Schema.fromJsonString(Schema.Struct({ login: Schema.String })),
203);
204
205function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null {
206 return ["GH_TOKEN", "GITHUB_TOKEN"].find((name) => environment[name]?.trim()) ?? null;
207}
208
209// `gh auth status` may not know environment tokens; check the API.
210export const makeDiscovery = Effect.gen(function* () {
211 const api = yield* GitHubRest.GitHubRest;
212 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
213 const process = sourceControlHost.process;
214 const environment = yield* HostProcess.Environment;
215 const appSignIn = yield* GitHubAppSignIn.GitHubAppSignIn;
216 const offerAppSignIn = <A extends SourceControlProviderDiscoveryItem>(item: A): A =>
217 appSignIn.enabled ? { ...item, appSignIn: true } : item;
218
219 return {
220 type: "managed-cli",
221 kind: discovery.kind,
222 label: discovery.label,
223 installHint: discovery.installHint,
224 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {
225 const current = yield* sourceControlHost.settings
226 .getWithSecrets(GitHubClient.definition.kind)
227 .pipe(Effect.orElseSucceed(() => undefined));
228 const settings = readSourceControlHostSettings(
229 GitHubClient.settings,
230 current?.sourceControlHosts[GitHubClient.definition.kind],
231 );
232 const cli = yield* probeSourceControlProvider({
233 cwd,
234 process: {
235 run: (input) => process.run({ ...input, concurrency: GH_PROCESS_CONCURRENCY }),
236 },
237 spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },
238 });
239 const saved = yield* Effect.result(
240 requireSettingsSecretLiteral(settings.tokens["github.com"], current?.secretProviders ?? {}),
241 );
242 if (Result.isFailure(saved) && settings.hosts["github.com"]?.enabled !== false) {
243 return offerAppSignIn({
244 ...cli,
245 status: "available" as const,
246 auth: providerAuth({
247 status: "unauthenticated",
248 host: "github.com",
249 detail: saved.failure.message,
250 }),
251 });
252 }
253 const savedToken = Result.isSuccess(saved) && saved.success.trim() !== "";
254 const signedIn =
255 appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== "";
256 const variable = environmentTokenVariable(environment);
257 const appName = GitHubClient.APP_SIGN_IN.appName;
258 const tokenSource = savedToken
259 ? "the token saved in Settings"
260 : signedIn
261 ? `the ${appName} sign-in`
262 : variable;
263 if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) {
264 return offerAppSignIn(cli);
265 }
266 const viewer = yield* api
267 .rest({ host: "github.com", operation: "discovery", path: "user" })
268 .pipe(Effect.result);
269 const login = Result.isSuccess(viewer)
270 ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login
271 : undefined;
272 const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };
273 return offerAppSignIn({
274 ...cli,
275 status: "available" as const,
276 auth: {
277 ...(login !== undefined
278 ? providerAuth({
279 status: "authenticated",
280 account: login,
281 host: "github.com",
282 detail: savedToken
283 ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."
284 : signedIn
285 ? `Signed in with ${appName}.`
286 : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,
287 })
288 : Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"
289 ? providerAuth({
290 status: "unknown",
291 host: "github.com",
292 detail: `Could not check ${savedToken || signedIn ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,
293 })
294 : providerAuth({
295 status: "unauthenticated",
296 host: "github.com",
297 detail: savedToken
298 ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."
299 : signedIn
300 ? `GitHub refused the ${appName} sign-in. Sign in again in Settings → Source Control.`
301 : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,
302 })),
303 ...accounts,
304 },
305 } satisfies SourceControlProviderDiscoveryItem);
306 }),
307 // Claim disabled hosts so errors identify the setting.
308 refineUnknownRemote: ({ context }) => {
309 const url = URL.parse(context.provider.baseUrl);
310 if (!url?.host) return Effect.succeed(null);
311 const host = gitHubApiHostForRemote(context.remoteUrl) ?? url.host;
312 // A timeout or keyring failure propagates: the registry does not keep that answer.
313 return api.credential(host).pipe(
314 Effect.as(true),
315 Effect.catchTags({
316 GitHubCliMissingError: () => Effect.succeed(false),
317 GitHubHostDisabledError: () => Effect.succeed(true),
318 GitHubNotSignedInError: () => Effect.succeed(false),
319 }),
320 Effect.map((known) =>
321 known
322 ? ({
323 kind: SourceControlProviderKind.make("github"),
324 name: host === "github.com" ? "GitHub" : "GitHub Self-Hosted",
325 baseUrl: host === url.host ? context.provider.baseUrl : `https://${host}`,
326 } as const)
327 : null,
328 ),
329 );
330 },
331 } satisfies SourceControlManagedCliDiscoverySpec;
332});
333
334class GitHubFailure extends Schema.TaggedError<GitHubFailure>()("GitHubFailure", {
335 detail: Schema.String,
336 cause: Schema.Defect(),
337}) {}
338
339const failure = (detail: string, cause?: unknown) => new GitHubFailure({ detail, cause });
340
341const PULL_REQUEST_NOT_FOUND = "Pull request not found. Check the PR number or URL and try again.";
342const REPOSITORY_NOT_FOUND = "Repository not found. Check the owner and name and try again.";
343
344function fromGitHubApiError(
345 error: GitHubRequestPolicy.GitHubApiError,
346 notFound = PULL_REQUEST_NOT_FOUND,
347): GitHubFailure {
348 switch (error._tag) {
349 case "GitHubCliMissingError":
350 return failure(
351 "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.",
352 error,
353 );
354 case "GitHubNotSignedInError":
355 case "GitHubHostDisabledError":
356 case "SettingsSecretUnresolvedError":
357 return failure(error.message, error);
358 case "GitHubApiAuthenticationError":
359 return failure(
360 "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.",
361 error,
362 );
363 case "GitHubApiRateLimitError":
364 case "SourceControlRateLimitPausedError":
365 return failure(
366 "GitHub API rate limit exceeded. Requests resume when the limit resets.",
367 error,
368 );
369 case "GitHubApiNotFoundError":
370 return failure(notFound, error);
371 case "GitHubCliFailedError":
372 case "GitHubAppSessionError":
373 case "GitHubApiResponseError":
374 case "GitHubApiRequestError":
375 return failure(error.message.trim() || "GitHub request failed.", error);
376 }
377}
378
379const notFound = (cause: string) => failure(PULL_REQUEST_NOT_FOUND, new Error(cause));
380
381const RawRepositorySchema = Schema.Struct({
382 full_name: TrimmedNonEmptyString,
383 html_url: TrimmedNonEmptyString,
384 ssh_url: TrimmedNonEmptyString,
385 default_branch: Schema.optional(Schema.NullOr(Schema.String)),
386});
387const decodeRawRepository = decodeJsonResult(RawRepositorySchema);
388
389function repositoryCloneUrls(
390 raw: Schema.Schema.Type<typeof RawRepositorySchema>,
391): SourceControlRepositoryCloneUrls {
392 return { nameWithOwner: raw.full_name, url: raw.html_url, sshUrl: raw.ssh_url };
393}
394
395const decodeViewerLogin = decodeJsonResult(Schema.Struct({ login: TrimmedNonEmptyString }));
396
397const decodeRestPullRequests = decodeJsonResult(Schema.Array(Schema.Unknown));
398const decodeRestPullRequest = Schema.decodeUnknownOption(
399 Schema.Struct({
400 number: Schema.Number,
401 title: Schema.String,
402 html_url: Schema.String,
403 state: Schema.String,
404 draft: Schema.optional(Schema.Boolean),
405 merged_at: Schema.NullOr(Schema.String),
406 closed_at: Schema.NullOr(Schema.String),
407 updated_at: Schema.String,
408 base: Schema.Struct({ ref: Schema.String, repo: Schema.Struct({ full_name: Schema.String }) }),
409 head: Schema.Struct({
410 ref: Schema.String,
411 sha: Schema.String,
412 repo: Schema.NullOr(
413 Schema.Struct({
414 name: Schema.String,
415 full_name: Schema.String,
416 owner: Schema.Struct({ login: Schema.String, type: Schema.String }),
417 }),
418 ),
419 }),
420 }),
421);
422
423/** Reshapes a REST pull request into the GraphQL node so both decode the same way. */
424function restPullRequestNode(entry: unknown) {
425 const pr = Option.getOrNull(decodeRestPullRequest(entry));
426 if (pr === null) return null;
427 return {
428 number: pr.number,
429 title: pr.title,
430 url: pr.html_url,
431 baseRefName: pr.base.ref,
432 headRefName: pr.head.ref,
433 headRefOid: pr.head.sha,
434 state: pr.merged_at === null ? pr.state.toUpperCase() : "MERGED",
435 isDraft: pr.draft === true,
436 mergedAt: pr.merged_at,
437 closedAt: pr.closed_at,
438 updatedAt: pr.updated_at,
439 isCrossRepository: pr.head.repo?.full_name !== pr.base.repo.full_name,
440 headRepository: pr.head.repo && {
441 name: pr.head.repo.name,
442 nameWithOwner: pr.head.repo.full_name,
443 },
444 headRepositoryOwner: pr.head.repo && {
445 __typename: pr.head.repo.owner.type,
446 login: pr.head.repo.owner.login,
447 },
448 };
449}
450
451type PullRequestListState = "open" | "closed" | "merged" | "all";
452
453const GRAPHQL_STATES: Record<
454 PullRequestListState,
455 NonNullable<PullRequestsByHead.Variables["states"]>
456> = {
457 open: ["OPEN"],
458 closed: ["CLOSED"],
459 merged: ["MERGED"],
460 all: ["OPEN", "CLOSED", "MERGED"],
461};
462/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
463const HEAD_LOOKUPS_PER_DOCUMENT = 50;
464/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
465const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
466const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
467/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
468const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
469const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
470const OWNER_HEAD_SCAN_LIMIT = 100;
471
472function trimmed(value: string): string | null {
473 const text = value.trim();
474 return text.length > 0 ? text : null;
475}
476
477/** Null isolates unusable PRs from the rest of a listing. */
478function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
479 const title = trimmed(node.title);
480 const url = trimmed(node.url);
481 const baseRefName = trimmed(node.baseRefName);
482 const headRefName = trimmed(node.headRefName);
483 const updatedAt = DateTime.make(node.updatedAt);
484 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
485 if (Option.isNone(updatedAt)) return null;
486 return normalizeGitHubPullRequestRecord({
487 ...node,
488 title,
489 url,
490 baseRefName,
491 headRefName,
492 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
493 });
494}
495
496export function pullRequestCheckoutBranchName(input: {
497 readonly headRefName: string;
498 readonly headOwner: string | null;
499 readonly isCrossRepository: boolean;
500 readonly defaultBranch: string | null;
501}): string {
502 return input.isCrossRepository &&
503 input.headOwner !== null &&
504 input.defaultBranch !== null &&
505 input.headRefName === input.defaultBranch
506 ? `${input.headOwner}/${input.headRefName}`
507 : input.headRefName;
508}
509
510const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
511 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
512
513export const make = Effect.gen(function* () {
514 const api = yield* GitHubRest.GitHubRest;
515 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
516 const process = sourceControlHost.process;
517 const environment = yield* HostProcess.Environment;
518 const git = sourceControlHost.git;
519 const fileSystem = yield* FileSystem.FileSystem;
520
521 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
522 process.run({
523 operation: "GitHubSourceControlProvider.resolveRepository",
524 command: "git",
525 args,
526 cwd,
527 allowNonZeroExit: true,
528 timeoutMs: 5_000,
529 });
530
531 const readRemotes = (cwd: string) =>
532 Effect.all([
533 gitRead(cwd, ["remote", "-v"]),
534 gitRead(cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
535 ]).pipe(
536 Effect.orElseSucceed(() => [null, null] as const),
537 Effect.map(([remotes, resolved]) => ({
538 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
539 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
540 })),
541 );
542
543 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
544 function* (input: {
545 readonly cwd: string;
546 readonly host?: string | undefined;
547 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
548 }) {
549 const envRepository = environment.GH_REPO?.trim();
550 const hostHint = input.host ?? contextHost(input.context);
551 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
552 if (envRepository) {
553 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
554 if (locator !== null) return locator;
555 }
556 const { host, locator } = resolveGitHubRepository({
557 ...(yield* readRemotes(input.cwd)),
558 hostHint,
559 defaultHost,
560 });
561 if (locator !== null) return locator;
562 if (input.context) {
563 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
564 const fallback = parseGitHubRepositorySelector(
565 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
566 host,
567 );
568 if (fallback !== null) return fallback;
569 }
570 return yield* failure(
571 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
572 );
573 },
574 );
575
576 const client = yield* GraphQLClient.make(
577 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
578 GitHubGraphQlClient.GitHubGraphQlAuth,
579 ),
580 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
581
582 const graphqlRead = <A, E, R>(
583 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
584 decodeDetail: string,
585 effect: Effect.Effect<A, E, R>,
586 ) =>
587 effect.pipe(
588 GitHubGraphQlClient.call(target),
589 Effect.mapError((error) =>
590 GraphQLClientError.isGraphQLClientError(error)
591 ? failure(decodeDetail, error)
592 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
593 ),
594 );
595
596 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
597 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
598
599 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
600 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
601 batchKey: GitHubGraphQlClient.batchKey,
602 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
603 const interactiveHeadResolver = headResolver.pipe(
604 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
605 );
606 const backgroundHeadResolver = headResolver.pipe(
607 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
608 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
609 );
610
611 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
612 readonly cwd: string;
613 readonly headSelector: string;
614 readonly state: PullRequestListState;
615 readonly limit: number;
616 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
617 readonly host?: string | undefined;
618 readonly allowReserve: boolean;
619 }) {
620 const locator = yield* resolveRepository(input);
621 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
622 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
623 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
624 if (ownerMatch) {
625 // GraphQL cannot filter heads by owner, and names like a fork's `main` match thousands.
626 const query = new URLSearchParams({
627 head: `${ownerMatch[1]}:${headRefName}`,
628 state: input.state === "all" || input.state === "open" ? input.state : "closed",
629 sort: "created",
630 direction: "desc",
631 per_page: String(OWNER_HEAD_SCAN_LIMIT),
632 });
633 const response = yield* rest({
634 host: locator.host,
635 operation: "listPullRequestsByHead",
636 allowReserve: input.allowReserve,
637 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls?${query}`,
638 });
639 const decoded = decodeRestPullRequests(response.body);
640 if (Result.isFailure(decoded)) {
641 return yield* failure("GitHub returned an invalid change request list.", decoded.failure);
642 }
643 return decoded.success
644 .flatMap((entry) => {
645 const node = Option.getOrNull(decodePullRequestNode(restPullRequestNode(entry)));
646 const record = node === null ? null : toPullRequestRecord(node);
647 return record === null ? [] : [record];
648 })
649 .filter((row) => input.state === "all" || row.state === input.state)
650 .slice(0, limit);
651 }
652 const result = yield* graphqlRead(
653 {
654 host: locator.host,
655 operation: "listPullRequestsByHead",
656 allowReserve: input.allowReserve,
657 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
658 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
659 },
660 "GitHub returned an invalid change request list.",
661 GraphQLResolver.request(
662 {
663 owner: locator.owner,
664 name: locator.name,
665 head: headRefName,
666 states: GRAPHQL_STATES[input.state],
667 first: limit,
668 },
669 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
670 ),
671 );
672 if (result.repository === null) return yield* notFound("The repository could not be read.");
673 return (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
674 const node = Option.getOrNull(decodePullRequestNode(entry));
675 const record = node === null ? null : toPullRequestRecord(node);
676 return record === null ? [] : [record];
677 });
678 });
679
680 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
681 function* (input: {
682 readonly cwd: string;
683 readonly reference: string;
684 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
685 readonly host?: string | undefined;
686 }) {
687 const parsed = parsePullRequestReference(input.reference);
688 if (parsed.kind === "branch") {
689 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
690 const lookup = (state: PullRequestListState) =>
691 listByHead({
692 cwd: input.cwd,
693 headSelector: parsed.headSelector,
694 state,
695 limit: 1,
696 host: input.host,
697 context: input.context,
698 allowReserve: true,
699 });
700 const [open] = yield* lookup("open");
701 const found = open ?? (yield* lookup("all"))[0];
702 if (found === undefined) return yield* notFound("No pull request has this head branch.");
703 return found;
704 }
705 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
706 const decodeDetail = "GitHub returned an invalid pull request.";
707 const result = yield* graphqlRead(
708 { host: locator.host, operation: "getPullRequest", allowReserve: true },
709 decodeDetail,
710 client.PullRequestByNumber({
711 owner: locator.owner,
712 name: locator.name,
713 number: parsed.number,
714 }),
715 );
716 const node = result.repository?.pullRequest;
717 if (node == null) return yield* notFound("The pull request does not exist.");
718 const record = toPullRequestRecord(node);
719 if (record === null)
720 return yield* failure(decodeDetail, new Error("Malformed pull request."));
721 return record;
722 },
723 );
724
725 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
726 locator: GitHubRepositoryLocator,
727 ) {
728 const response = yield* rest(
729 {
730 host: locator.host,
731 operation: "getRepository",
732 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
733 allowReserve: true,
734 },
735 REPOSITORY_NOT_FOUND,
736 );
737 const decoded = decodeRawRepository(response.body);
738 if (Result.isFailure(decoded)) {
739 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
740 }
741 return decoded.success;
742 });
743
744 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
745 host: string,
746 ) {
747 const response = yield* rest({
748 host,
749 operation: "getViewer",
750 path: "user",
751 allowReserve: true,
752 });
753 const decoded = decodeViewerLogin(response.body);
754 if (Result.isFailure(decoded)) {
755 return yield* failure("GitHub request failed.", decoded.failure);
756 }
757 return decoded.success.login;
758 });
759
760 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
761 const gitFailure = (cause: unknown) =>
762 failure("The pull request could not be checked out with git.", cause);
763
764 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
765 git.execute({
766 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
767 cwd,
768 args,
769 });
770
771 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
772 function* (input: {
773 readonly cwd: string;
774 readonly reference: string;
775 readonly force?: boolean;
776 readonly context?: SourceControlProvider.SourceControlProviderContext;
777 }) {
778 const reference = parsePullRequestReference(input.reference);
779 const pullRequest = yield* readPullRequest(input);
780 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
781 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
782 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
783 const isCrossRepository =
784 pullRequest.isCrossRepository ??
785 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
786 const headOwner =
787 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
788
789 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
790 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
791 Effect.mapError(gitFailure),
792 );
793 const remoteFor = (nameWithOwner: string) =>
794 parseFetchRemotes(remotes).find(
795 (remote) =>
796 (gitHubApiHostForRemote(remote.url) ??
797 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
798 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
799 nameWithOwner.toLowerCase(),
800 )?.name ?? null;
801 const baseRemote = Effect.suspend(() => {
802 const known = remoteFor(baseNameWithOwner);
803 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
804 });
805 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
806 const defaultBranch = isCrossRepository
807 ? yield* readRepository(base).pipe(
808 Effect.map((repository) => repository.default_branch ?? null),
809 )
810 : null;
811 const localBranch = pullRequestCheckoutBranchName({
812 headRefName: pullRequest.headRefName,
813 headOwner,
814 isCrossRepository,
815 defaultBranch,
816 });
817
818 const headRemote = Effect.gen(function* () {
819 if (!isCrossRepository) return yield* baseRemote;
820 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
821 const known = remoteFor(headNameWithOwner);
822 if (known !== null) return known;
823 const [owner, name] = headNameWithOwner.split("/");
824 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
825 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
826 return yield* git.ensureRemote({
827 cwd: input.cwd,
828 preferredName: headOwner ?? "fork",
829 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
830 });
831 });
832
833 const exists = (yield* git
834 .listLocalBranchNames(input.cwd)
835 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
836
837 const target = yield* Effect.gen(function* () {
838 const remoteName = yield* headRemote;
839 yield* git.fetchRemoteTrackingBranch({
840 cwd: input.cwd,
841 remoteName,
842 remoteBranch: pullRequest.headRefName,
843 });
844 return {
845 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
846 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
847 };
848 }).pipe(
849 Effect.catch(() =>
850 Effect.gen(function* () {
851 yield* runGit(input.cwd, "fetchPullRef", [
852 "fetch",
853 "--quiet",
854 "--no-tags",
855 "--",
856 yield* baseRemote,
857 `refs/pull/${pullRequest.number}/head`,
858 ]);
859 const { commitSha } = yield* git.resolveCommit({
860 cwd: input.cwd,
861 revision: "FETCH_HEAD",
862 });
863 return { ref: commitSha, upstream: null };
864 }),
865 ),
866 Effect.mapError(gitFailure),
867 );
868
869 yield* Effect.gen(function* () {
870 if (!exists) {
871 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
872 }
873 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
874 if (exists) {
875 yield* runGit(
876 input.cwd,
877 "sync",
878 input.force === true
879 ? ["reset", "--hard", "--quiet", target.ref]
880 : ["merge", "--ff-only", "--quiet", target.ref],
881 );
882 }
883 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
884 if (target.upstream !== null) {
885 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
886 }
887 }).pipe(Effect.mapError(gitFailure));
888 },
889 );
890
891 const providerError =
892 (
893 operation: string,
894 cwd: string,
895 context?: { readonly reference?: string; readonly repository?: string },
896 ) =>
897 (error: GitHubFailure) =>
898 new SourceControlProviderError({
899 provider: SourceControlProviderKind.make("github"),
900 operation,
901 cwd,
902 ...(context?.reference === undefined
903 ? {}
904 : {
905 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
906 context.reference,
907 ),
908 }),
909 ...(context?.repository === undefined
910 ? {}
911 : {
912 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
913 context.repository,
914 ),
915 }),
916 detail: error.detail,
917 cause: error.cause,
918 });
919
920 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
921 input: { readonly cwd: string; readonly url: URL },
922 endpoint: string,
923 ) {
924 const result = yield* api
925 .rest({
926 host: input.url.host,
927 operation: "resolveLink",
928 path: endpoint,
929 maxResponseBytes: 1_000_000,
930 })
931 .pipe(
932 Effect.timeout("3 seconds"),
933 Effect.mapError(
934 (cause) =>
935 new SourceControlProviderError({
936 provider: SourceControlProviderKind.make("github"),
937 operation: "resolveLink",
938 cwd: input.cwd,
939 detail: "The linked subject could not be read.",
940 cause,
941 }),
942 ),
943 );
944 const subject = yield* decodeLinkSubject(result.body).pipe(
945 Effect.mapError(
946 (cause) =>
947 new SourceControlProviderError({
948 provider: SourceControlProviderKind.make("github"),
949 operation: "resolveLink.decode",
950 cwd: input.cwd,
951 detail: "The linked subject could not be read.",
952 cause,
953 }),
954 ),
955 );
956 return { title: subject.title, body: subject.body ?? null };
957 });
958
959 return SourceControlProvider.SourceControlProvider.of({
960 kind: SourceControlProviderKind.make("github"),
961 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
962 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
963 ),
964 // GitHub matches bare heads; read a full page to disambiguate forks by owner. A default branch
965 // collides with most forks, so its owner-qualified lookup has GitHub filter by owner instead.
966 headBranchProbe: ({ headSelectors, defaultBranchHeadSelector }) => ({
967 headSelectors: defaultBranchHeadSelector
968 ? [defaultBranchHeadSelector]
969 : headSelectors.filter((selector) => !selector.includes(":")),
970 limit: 100,
971 }),
972 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
973 function ({ cwd, treeish }) {
974 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
975 },
976 ),
977 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
978 // gh's pick among the checkout's remotes, led by the one `gh repo set-default` marked
979 // (`gh-resolved`). An HTTPS remote keeps a non-default port in the context's host, and the
980 // mark is then ignored.
981 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
982 function* ({ cwd, context, repository }) {
983 const host = URL.canParse(context.provider.baseUrl)
984 ? new URL(context.provider.baseUrl).host
985 : null;
986 const target = repository?.toLowerCase();
987 const fromEnvironment = parseGitHubRepositorySelector(
988 environment.GH_REPO ?? "",
989 host ?? "",
990 );
991 if (fromEnvironment !== null) {
992 const { host: targetHost, owner, name } = fromEnvironment;
993 return (
994 host !== null &&
995 URL.canParse(`https://${targetHost}`) &&
996 new URL(`https://${targetHost}`).host === host &&
997 `${owner}/${name}`.toLowerCase() === target
998 );
999 }
1000 const { locator } = resolveGitHubRepository({
1001 ...(yield* readRemotes(cwd)),
1002 hostHint: host ?? undefined,
1003 defaultHost: host ?? "github.com",
1004 });
1005 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
1006 },
1007 ),
1008 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
1009 // from this key.
1010 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
1011 cwd,
1012 branch,
1013 baseBranch,
1014 }) {
1015 return git
1016 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
1017 .pipe(
1018 Effect.catch((cause) =>
1019 Effect.logWarning("Could not record the branch base for gh", { cause }),
1020 ),
1021 );
1022 }),
1023 resolveLink: (input) => {
1024 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
1025 if (input.url.host !== "github.com") return undefined;
1026 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
1027 input.url.pathname,
1028 );
1029 if (!match) return undefined;
1030 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
1031 },
1032 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
1033 function (input) {
1034 return (
1035 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
1036 ).pipe(
1037 Effect.flatMap((allowReserve) =>
1038 listByHead({
1039 cwd: input.cwd,
1040 headSelector: input.headSelector,
1041 state: input.state,
1042 limit: input.limit ?? (input.state === "open" ? 1 : 20),
1043 host: contextHost(input.context),
1044 context: input.context,
1045 allowReserve,
1046 }),
1047 ),
1048 Effect.map((records) => records.map(toChangeRequest)),
1049 Effect.mapError(
1050 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
1051 ),
1052 );
1053 },
1054 ),
1055 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
1056 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
1057 Effect.map(toChangeRequest),
1058 Effect.mapError(
1059 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
1060 ),
1061 );
1062 }),
1063 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
1064 function* (input) {
1065 const locator = yield* resolveRepository(input);
1066 const body = yield* fileSystem
1067 .readFileString(input.bodyFile)
1068 .pipe(
1069 Effect.mapError((cause) =>
1070 failure("The pull request description could not be read.", cause),
1071 ),
1072 );
1073 yield* rest({
1074 host: locator.host,
1075 operation: "createPullRequest",
1076 method: "POST",
1077 allowReserve: true,
1078 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
1079 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
1080 body: {
1081 base: input.baseRefName,
1082 head: input.headSelector,
1083 title: input.title,
1084 body,
1085 maintainer_can_modify: true,
1086 },
1087 });
1088 },
1089 (effect, input) =>
1090 effect.pipe(
1091 Effect.mapError(
1092 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1093 ),
1094 ),
1095 ),
1096 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1097 function* (input) {
1098 const fallbackHost = (
1099 input.host ??
1100 (yield* resolveRepository(input).pipe(
1101 Effect.map((locator) => locator.host),
1102 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1103 ))
1104 ).toLowerCase();
1105 const bareName = input.repository.trim().replace(/\.git$/i, "");
1106 const locator =
1107 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1108 (/^[^/\s]+$/.test(bareName)
1109 ? {
1110 host: fallbackHost,
1111 owner: yield* readViewerLogin(fallbackHost),
1112 name: bareName,
1113 }
1114 : null);
1115 if (locator === null) return yield* failure("Repositories are named owner/name.");
1116 return repositoryCloneUrls(yield* readRepository(locator));
1117 },
1118 (effect, input) =>
1119 effect.pipe(
1120 Effect.mapError(
1121 providerError("getRepositoryCloneUrls", input.cwd, {
1122 repository: input.repository,
1123 }),
1124 ),
1125 ),
1126 ),
1127 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1128 function* (input) {
1129 const locator = parseGitHubRepositorySelector(
1130 input.repository,
1131 (environment.GH_HOST ?? "github.com").toLowerCase(),
1132 );
1133 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1134 const owner = locator?.owner ?? viewer;
1135 const name = locator?.name ?? input.repository.trim();
1136 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1137 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1138 const response = yield* rest(
1139 {
1140 host,
1141 operation: "createRepository",
1142 method: "POST",
1143 allowReserve: true,
1144 path:
1145 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1146 body: { name, private: input.visibility === "private" },
1147 },
1148 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1149 );
1150 const decoded = decodeRawRepository(response.body);
1151 if (Result.isFailure(decoded)) {
1152 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1153 }
1154 return repositoryCloneUrls(decoded.success);
1155 },
1156 (effect, input) =>
1157 effect.pipe(
1158 Effect.mapError(
1159 providerError("createRepository", input.cwd, { repository: input.repository }),
1160 ),
1161 ),
1162 ),
1163 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1164 function* (input) {
1165 const locator = yield* resolveRepository({
1166 cwd: input.cwd,
1167 host: contextHost(input.context),
1168 context: input.context,
1169 });
1170 const repository = yield* readRepository(locator);
1171 const branch = repository.default_branch?.trim() ?? "";
1172 return branch.length > 0 ? branch : null;
1173 },
1174 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1175 ),
1176 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1177 function (input) {
1178 return checkoutPullRequest(input).pipe(
1179 Effect.mapError(
1180 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1181 ),
1182 );
1183 },
1184 ),
1185 });
1186});