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
397type PullRequestListState = "open" | "closed" | "merged" | "all";
398
399const GRAPHQL_STATES: Record<
400 PullRequestListState,
401 NonNullable<PullRequestsByHead.Variables["states"]>
402> = {
403 open: ["OPEN"],
404 closed: ["CLOSED"],
405 merged: ["MERGED"],
406 all: ["OPEN", "CLOSED", "MERGED"],
407};
408/** 50 lookups keeps responses near 0.5s at the same one-point cost as 100. */
409const HEAD_LOOKUPS_PER_DOCUMENT = 50;
410/** Git reads stagger background lookups by ~300ms; gather batches before spending quota. */
411const HEAD_LOOKUP_BATCH_WINDOW = "50 millis";
412const BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW = "500 millis";
413/** For heads matching 100 PRs each, 50 lookups approached GitHub's ~10s limit; 25 took ~7s. */
414const BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT = 25;
415const HEAD_LOOKUP_MAX_RESPONSE_BYTES = 16_000_000;
416const OWNER_HEAD_SCAN_LIMIT = 100;
417
418function trimmed(value: string): string | null {
419 const text = value.trim();
420 return text.length > 0 ? text : null;
421}
422
423/** Null isolates unusable PRs from the rest of a listing. */
424function toPullRequestRecord(node: PullRequestNode): NormalizedGitHubPullRequestRecord | null {
425 const title = trimmed(node.title);
426 const url = trimmed(node.url);
427 const baseRefName = trimmed(node.baseRefName);
428 const headRefName = trimmed(node.headRefName);
429 const updatedAt = DateTime.make(node.updatedAt);
430 if (node.number < 1 || !title || !url || !baseRefName || !headRefName) return null;
431 if (Option.isNone(updatedAt)) return null;
432 return normalizeGitHubPullRequestRecord({
433 ...node,
434 title,
435 url,
436 baseRefName,
437 headRefName,
438 updatedAt: Option.some(DateTime.toUtc(updatedAt.value)),
439 });
440}
441
442export function pullRequestCheckoutBranchName(input: {
443 readonly headRefName: string;
444 readonly headOwner: string | null;
445 readonly isCrossRepository: boolean;
446 readonly defaultBranch: string | null;
447}): string {
448 return input.isCrossRepository &&
449 input.headOwner !== null &&
450 input.defaultBranch !== null &&
451 input.headRefName === input.defaultBranch
452 ? `${input.headOwner}/${input.headRefName}`
453 : input.headRefName;
454}
455
456const contextHost = (context: SourceControlProvider.SourceControlProviderContext | undefined) =>
457 context === undefined ? undefined : new URL(context.provider.baseUrl).host;
458
459export const make = Effect.gen(function* () {
460 const api = yield* GitHubRest.GitHubRest;
461 const sourceControlHost = yield* SourceControlHost.SourceControlHost;
462 const process = sourceControlHost.process;
463 const environment = yield* HostProcess.Environment;
464 const git = sourceControlHost.git;
465 const fileSystem = yield* FileSystem.FileSystem;
466
467 const gitRead = (cwd: string, args: ReadonlyArray<string>) =>
468 process.run({
469 operation: "GitHubSourceControlProvider.resolveRepository",
470 command: "git",
471 args,
472 cwd,
473 allowNonZeroExit: true,
474 timeoutMs: 5_000,
475 });
476
477 const resolveRepository = Effect.fn("GitHubSourceControlProvider.resolveRepository")(
478 function* (input: {
479 readonly cwd: string;
480 readonly host?: string | undefined;
481 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
482 }) {
483 const envRepository = environment.GH_REPO?.trim();
484 const hostHint = input.host ?? contextHost(input.context);
485 const defaultHost = (hostHint ?? environment.GH_HOST ?? "github.com").toLowerCase();
486 if (envRepository) {
487 const locator = parseGitHubRepositorySelector(envRepository, defaultHost);
488 if (locator !== null) return locator;
489 }
490 const [remotes, resolved] = yield* Effect.all([
491 gitRead(input.cwd, ["remote", "-v"]),
492 gitRead(input.cwd, ["config", "--get-regexp", "^remote\\..*\\.gh-resolved$"]),
493 ]).pipe(Effect.orElseSucceed(() => [null, null] as const));
494 const { host, locator } = resolveGitHubRepository({
495 remotes: remotes?.exitCode === 0 ? remotes.stdout : "",
496 resolved: resolved?.exitCode === 0 ? resolved.stdout : "",
497 hostHint,
498 defaultHost,
499 });
500 if (locator !== null) return locator;
501 if (input.context) {
502 const remote = normalizeGitRemoteUrl(input.context.remoteUrl);
503 const fallback = parseGitHubRepositorySelector(
504 `${host}/${remote.slice(remote.indexOf("/") + 1)}`,
505 host,
506 );
507 if (fallback !== null) return fallback;
508 }
509 return yield* failure(
510 `No GitHub repository on ${host} was found among this checkout's git remotes.`,
511 );
512 },
513 );
514
515 const client = yield* GraphQLClient.make(
516 GraphQLGroup.make(LenientPullRequestsByHead, PullRequestByNumber).middleware(
517 GitHubGraphQlClient.GitHubGraphQlAuth,
518 ),
519 ).pipe(Effect.provide(GitHubGraphQlClient.layer));
520
521 const graphqlRead = <A, E, R>(
522 target: GitHubGraphQlClient.GitHubGraphQlTarget["Service"],
523 decodeDetail: string,
524 effect: Effect.Effect<A, E, R>,
525 ) =>
526 effect.pipe(
527 GitHubGraphQlClient.call(target),
528 Effect.mapError((error) =>
529 GraphQLClientError.isGraphQLClientError(error)
530 ? failure(decodeDetail, error)
531 : fromGitHubApiError(error as GitHubRequestPolicy.GitHubApiError),
532 ),
533 );
534
535 const rest = (input: GitHubRest.GitHubRestInput, notFoundDetail?: string) =>
536 api.rest(input).pipe(Effect.mapError((error) => fromGitHubApiError(error, notFoundDetail)));
537
538 // Batch by host/credential; isolate missing repositories and interactive/background reserves.
539 const headResolver = GraphQLResolver.aliased(client.PullRequestsByHead, {
540 batchKey: GitHubGraphQlClient.batchKey,
541 }).pipe(RequestResolver.batchN(HEAD_LOOKUPS_PER_DOCUMENT));
542 const interactiveHeadResolver = headResolver.pipe(
543 RequestResolver.setDelay(HEAD_LOOKUP_BATCH_WINDOW),
544 );
545 const backgroundHeadResolver = headResolver.pipe(
546 RequestResolver.batchN(BACKGROUND_HEAD_LOOKUPS_PER_DOCUMENT),
547 RequestResolver.setDelay(BACKGROUND_HEAD_LOOKUP_BATCH_WINDOW),
548 );
549
550 const listByHead = Effect.fn("GitHubSourceControlProvider.listByHead")(function* (input: {
551 readonly cwd: string;
552 readonly headSelector: string;
553 readonly state: PullRequestListState;
554 readonly limit: number;
555 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
556 readonly host?: string | undefined;
557 readonly allowReserve: boolean;
558 }) {
559 const locator = yield* resolveRepository(input);
560 const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);
561 const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());
562 const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();
563 const result = yield* graphqlRead(
564 {
565 host: locator.host,
566 operation: "listPullRequestsByHead",
567 allowReserve: input.allowReserve,
568 // 50 default-branch lookups can each match 100 fork PRs and exceed the usual cap.
569 maxResponseBytes: HEAD_LOOKUP_MAX_RESPONSE_BYTES,
570 },
571 "GitHub returned an invalid change request list.",
572 GraphQLResolver.request(
573 {
574 owner: locator.owner,
575 name: locator.name,
576 head: headRefName,
577 states: GRAPHQL_STATES[input.state],
578 first: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,
579 },
580 input.allowReserve ? interactiveHeadResolver : backgroundHeadResolver,
581 ),
582 );
583 if (result.repository === null) return yield* notFound("The repository could not be read.");
584 const rows = (result.repository.pullRequests.nodes ?? []).flatMap((entry) => {
585 const node = Option.getOrNull(decodePullRequestNode(entry));
586 const record = node === null ? null : toPullRequestRecord(node);
587 return record === null ? [] : [record];
588 });
589 if (!ownerMatch) return rows;
590 const headOwner = ownerMatch[1]!.toLowerCase();
591 return rows
592 .filter((row) => row.headRepositoryOwnerLogin?.toLowerCase() === headOwner)
593 .slice(0, limit);
594 });
595
596 const readPullRequest = Effect.fn("GitHubSourceControlProvider.readPullRequest")(
597 function* (input: {
598 readonly cwd: string;
599 readonly reference: string;
600 readonly context?: SourceControlProvider.SourceControlProviderContext | undefined;
601 readonly host?: string | undefined;
602 }) {
603 const parsed = parsePullRequestReference(input.reference);
604 if (parsed.kind === "branch") {
605 // `gh pr view <branch>` prefers an open pull request, then the newest of any state.
606 const lookup = (state: PullRequestListState) =>
607 listByHead({
608 cwd: input.cwd,
609 headSelector: parsed.headSelector,
610 state,
611 limit: 1,
612 host: input.host,
613 context: input.context,
614 allowReserve: true,
615 });
616 const [open] = yield* lookup("open");
617 const found = open ?? (yield* lookup("all"))[0];
618 if (found === undefined) return yield* notFound("No pull request has this head branch.");
619 return found;
620 }
621 const locator = parsed.kind === "url" ? parsed.locator : yield* resolveRepository(input);
622 const decodeDetail = "GitHub returned an invalid pull request.";
623 const result = yield* graphqlRead(
624 { host: locator.host, operation: "getPullRequest", allowReserve: true },
625 decodeDetail,
626 client.PullRequestByNumber({
627 owner: locator.owner,
628 name: locator.name,
629 number: parsed.number,
630 }),
631 );
632 const node = result.repository?.pullRequest;
633 if (node == null) return yield* notFound("The pull request does not exist.");
634 const record = toPullRequestRecord(node);
635 if (record === null)
636 return yield* failure(decodeDetail, new Error("Malformed pull request."));
637 return record;
638 },
639 );
640
641 const readRepository = Effect.fn("GitHubSourceControlProvider.readRepository")(function* (
642 locator: GitHubRepositoryLocator,
643 ) {
644 const response = yield* rest(
645 {
646 host: locator.host,
647 operation: "getRepository",
648 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}`,
649 allowReserve: true,
650 },
651 REPOSITORY_NOT_FOUND,
652 );
653 const decoded = decodeRawRepository(response.body);
654 if (Result.isFailure(decoded)) {
655 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
656 }
657 return decoded.success;
658 });
659
660 const readViewerLogin = Effect.fn("GitHubSourceControlProvider.readViewerLogin")(function* (
661 host: string,
662 ) {
663 const response = yield* rest({
664 host,
665 operation: "getViewer",
666 path: "user",
667 allowReserve: true,
668 });
669 const decoded = decodeViewerLogin(response.body);
670 if (Result.isFailure(decoded)) {
671 return yield* failure("GitHub request failed.", decoded.failure);
672 }
673 return decoded.success.login;
674 });
675
676 // Keep paths, argv and stderr in cause; expose only a fixed checkout error to clients.
677 const gitFailure = (cause: unknown) =>
678 failure("The pull request could not be checked out with git.", cause);
679
680 const runGit = (cwd: string, operation: string, args: ReadonlyArray<string>) =>
681 git.execute({
682 operation: `GitHubSourceControlProvider.checkoutPullRequest.${operation}`,
683 cwd,
684 args,
685 });
686
687 const checkoutPullRequest = Effect.fn("GitHubSourceControlProvider.checkoutPullRequest")(
688 function* (input: {
689 readonly cwd: string;
690 readonly reference: string;
691 readonly force?: boolean;
692 readonly context?: SourceControlProvider.SourceControlProviderContext;
693 }) {
694 const reference = parsePullRequestReference(input.reference);
695 const pullRequest = yield* readPullRequest(input);
696 const base = reference.kind === "url" ? reference.locator : yield* resolveRepository(input);
697 const baseNameWithOwner = `${base.owner}/${base.name}`.toLowerCase();
698 const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;
699 const isCrossRepository =
700 pullRequest.isCrossRepository ??
701 (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);
702 const headOwner =
703 pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;
704
705 const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(
706 Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),
707 Effect.mapError(gitFailure),
708 );
709 const remoteFor = (nameWithOwner: string) =>
710 parseFetchRemotes(remotes).find(
711 (remote) =>
712 (gitHubApiHostForRemote(remote.url) ??
713 normalizeGitRemoteUrl(remote.url).split("/")[0]) === base.host &&
714 normalizeGitRemoteUrl(remote.url).split("/").slice(1).join("/") ===
715 nameWithOwner.toLowerCase(),
716 )?.name ?? null;
717 const baseRemote = Effect.suspend(() => {
718 const known = remoteFor(baseNameWithOwner);
719 return known === null ? git.resolvePrimaryRemoteName(input.cwd) : Effect.succeed(known);
720 });
721 // Avoid resetting the default branch; prefix colliding forks and fail if it is unknown.
722 const defaultBranch = isCrossRepository
723 ? yield* readRepository(base).pipe(
724 Effect.map((repository) => repository.default_branch ?? null),
725 )
726 : null;
727 const localBranch = pullRequestCheckoutBranchName({
728 headRefName: pullRequest.headRefName,
729 headOwner,
730 isCrossRepository,
731 defaultBranch,
732 });
733
734 const headRemote = Effect.gen(function* () {
735 if (!isCrossRepository) return yield* baseRemote;
736 if (headNameWithOwner === null) return yield* failure("The fork is gone.");
737 const known = remoteFor(headNameWithOwner);
738 if (known !== null) return known;
739 const [owner, name] = headNameWithOwner.split("/");
740 const fork = yield* readRepository({ host: base.host, owner: owner!, name: name! });
741 const originUrl = yield* git.readConfigValue(input.cwd, "remote.origin.url");
742 return yield* git.ensureRemote({
743 cwd: input.cwd,
744 preferredName: headOwner ?? "fork",
745 url: originUrl !== null && isSshRemoteUrl(originUrl) ? fork.ssh_url : fork.html_url,
746 });
747 });
748
749 const exists = (yield* git
750 .listLocalBranchNames(input.cwd)
751 .pipe(Effect.mapError(gitFailure))).includes(localBranch);
752
753 const target = yield* Effect.gen(function* () {
754 const remoteName = yield* headRemote;
755 yield* git.fetchRemoteTrackingBranch({
756 cwd: input.cwd,
757 remoteName,
758 remoteBranch: pullRequest.headRefName,
759 });
760 return {
761 ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,
762 upstream: { remoteName, remoteBranch: pullRequest.headRefName },
763 };
764 }).pipe(
765 Effect.catch(() =>
766 Effect.gen(function* () {
767 yield* runGit(input.cwd, "fetchPullRef", [
768 "fetch",
769 "--quiet",
770 "--no-tags",
771 "--",
772 yield* baseRemote,
773 `refs/pull/${pullRequest.number}/head`,
774 ]);
775 const { commitSha } = yield* git.resolveCommit({
776 cwd: input.cwd,
777 revision: "FETCH_HEAD",
778 });
779 return { ref: commitSha, upstream: null };
780 }),
781 ),
782 Effect.mapError(gitFailure),
783 );
784
785 yield* Effect.gen(function* () {
786 if (!exists) {
787 yield* git.createBranch({ cwd: input.cwd, branch: localBranch, startPoint: target.ref });
788 }
789 yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
790 if (exists) {
791 yield* runGit(
792 input.cwd,
793 "sync",
794 input.force === true
795 ? ["reset", "--hard", "--quiet", target.ref]
796 : ["merge", "--ff-only", "--quiet", target.ref],
797 );
798 }
799 // Set tracking after sync succeeds so a failed checkout preserves the existing upstream.
800 if (target.upstream !== null) {
801 yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });
802 }
803 }).pipe(Effect.mapError(gitFailure));
804 },
805 );
806
807 const providerError =
808 (
809 operation: string,
810 cwd: string,
811 context?: { readonly reference?: string; readonly repository?: string },
812 ) =>
813 (error: GitHubFailure) =>
814 new SourceControlProviderError({
815 provider: SourceControlProviderKind.make("github"),
816 operation,
817 cwd,
818 ...(context?.reference === undefined
819 ? {}
820 : {
821 reference: SourceControlProvider.transportSafeSourceControlErrorValue(
822 context.reference,
823 ),
824 }),
825 ...(context?.repository === undefined
826 ? {}
827 : {
828 repository: SourceControlProvider.transportSafeSourceControlErrorValue(
829 context.repository,
830 ),
831 }),
832 detail: error.detail,
833 cause: error.cause,
834 });
835
836 const readLinkSubject = Effect.fn("GitHubSourceControlProvider.readLinkSubject")(function* (
837 input: { readonly cwd: string; readonly url: URL },
838 endpoint: string,
839 ) {
840 const result = yield* api
841 .rest({
842 host: input.url.host,
843 operation: "resolveLink",
844 path: endpoint,
845 maxResponseBytes: 1_000_000,
846 })
847 .pipe(
848 Effect.timeout("3 seconds"),
849 Effect.mapError(
850 (cause) =>
851 new SourceControlProviderError({
852 provider: SourceControlProviderKind.make("github"),
853 operation: "resolveLink",
854 cwd: input.cwd,
855 detail: "The linked subject could not be read.",
856 cause,
857 }),
858 ),
859 );
860 const subject = yield* decodeLinkSubject(result.body).pipe(
861 Effect.mapError(
862 (cause) =>
863 new SourceControlProviderError({
864 provider: SourceControlProviderKind.make("github"),
865 operation: "resolveLink.decode",
866 cwd: input.cwd,
867 detail: "The linked subject could not be read.",
868 cause,
869 }),
870 ),
871 );
872 return { title: subject.title, body: subject.body ?? null };
873 });
874
875 return SourceControlProvider.SourceControlProvider.of({
876 kind: SourceControlProviderKind.make("github"),
877 resolveRemoteWebHost: Effect.fn("GitHubSourceControlProvider.resolveRemoteWebHost")(
878 ({ context }) => Effect.succeed(gitHubApiHostForRemote(context.remoteUrl)),
879 ),
880 // GitHub matches bare heads; read a full page to disambiguate forks by owner.
881 headBranchProbe: ({ headSelectors }) => ({
882 headSelectors: headSelectors.filter((selector) => !selector.includes(":")),
883 limit: 100,
884 }),
885 readChangeRequestTemplate: Effect.fn("GitHubSourceControlProvider.readChangeRequestTemplate")(
886 function ({ cwd, treeish }) {
887 return GitHubChangeRequestTemplate.detect(cwd, treeish, git.execute);
888 },
889 ),
890 // `createChangeRequest` targets what `resolveRepository` picks: GH_REPO when it parses, else
891 // the remote `gh repo set-default` marked (`gh-resolved`). An HTTPS remote keeps a
892 // non-default port in the context's host, and the mark is then ignored.
893 createsChangeRequestsIn: Effect.fn("GitHubSourceControlProvider.createsChangeRequestsIn")(
894 function* ({ cwd, context, repository }) {
895 const host = URL.canParse(context.provider.baseUrl)
896 ? new URL(context.provider.baseUrl).host
897 : null;
898 const target = repository?.toLowerCase();
899 const fromEnvironment = parseGitHubRepositorySelector(
900 environment.GH_REPO ?? "",
901 host ?? "",
902 );
903 if (fromEnvironment !== null) {
904 const { host: targetHost, owner, name } = fromEnvironment;
905 return (
906 host !== null &&
907 URL.canParse(`https://${targetHost}`) &&
908 new URL(`https://${targetHost}`).host === host &&
909 `${owner}/${name}`.toLowerCase() === target
910 );
911 }
912 const mark = yield* git
913 .readConfigValue(cwd, `remote.${context.remoteName}.gh-resolved`)
914 .pipe(Effect.orElseSucceed(() => null));
915 const { locator } = resolveGitHubRepository({
916 remotes: `${context.remoteName}\t${context.remoteUrl} (fetch)`,
917 resolved: mark === null ? "" : `remote.${context.remoteName}.gh-resolved ${mark}`,
918 hostHint: host ?? undefined,
919 defaultHost: host ?? "github.com",
920 });
921 return locator === null || `${locator.owner}/${locator.name}`.toLowerCase() === target;
922 },
923 ),
924 // `gh pr create` run in the checkout, as an agent in a T3 worktree often does, takes its base
925 // from this key.
926 recordBranchBase: Effect.fn("GitHubSourceControlProvider.recordBranchBase")(function ({
927 cwd,
928 branch,
929 baseBranch,
930 }) {
931 return git
932 .writeConfigValue({ cwd, key: `branch.${branch}.gh-merge-base`, value: baseBranch })
933 .pipe(
934 Effect.catch((cause) =>
935 Effect.logWarning("Could not record the branch base for gh", { cause }),
936 ),
937 );
938 }),
939 resolveLink: (input) => {
940 // Automatic enrichment must not send ambient CLI credentials to a host from message text.
941 if (input.url.host !== "github.com") return undefined;
942 const match = /^\/([\w.-]+)\/([\w.-]+)\/(?:pull|issues)\/([1-9]\d*)(?:\/.*)?$/.exec(
943 input.url.pathname,
944 );
945 if (!match) return undefined;
946 return readLinkSubject(input, `repos/${match[1]}/${match[2]}/issues/${match[3]}`);
947 },
948 listChangeRequests: Effect.fn("GitHubSourceControlProvider.listChangeRequests")(
949 function (input) {
950 return (
951 input.state === "open" ? Effect.succeed(true) : SourceControlRateLimit.Interactive
952 ).pipe(
953 Effect.flatMap((allowReserve) =>
954 listByHead({
955 cwd: input.cwd,
956 headSelector: input.headSelector,
957 state: input.state,
958 limit: input.limit ?? (input.state === "open" ? 1 : 20),
959 host: contextHost(input.context),
960 context: input.context,
961 allowReserve,
962 }),
963 ),
964 Effect.map((records) => records.map(toChangeRequest)),
965 Effect.mapError(
966 providerError("listChangeRequests", input.cwd, { reference: input.headSelector }),
967 ),
968 );
969 },
970 ),
971 getChangeRequest: Effect.fn("GitHubSourceControlProvider.getChangeRequest")(function (input) {
972 return readPullRequest({ ...input, host: contextHost(input.context) }).pipe(
973 Effect.map(toChangeRequest),
974 Effect.mapError(
975 providerError("getChangeRequest", input.cwd, { reference: input.reference }),
976 ),
977 );
978 }),
979 createChangeRequest: Effect.fn("GitHubSourceControlProvider.createChangeRequest")(
980 function* (input) {
981 const locator = yield* resolveRepository(input);
982 const body = yield* fileSystem
983 .readFileString(input.bodyFile)
984 .pipe(
985 Effect.mapError((cause) =>
986 failure("The pull request description could not be read.", cause),
987 ),
988 );
989 yield* rest({
990 host: locator.host,
991 operation: "createPullRequest",
992 method: "POST",
993 allowReserve: true,
994 path: `repos/${encodeURIComponent(locator.owner)}/${encodeURIComponent(locator.name)}/pulls`,
995 // Explicitly allow maintainer edits to match gh; the API default is undocumented.
996 body: {
997 base: input.baseRefName,
998 head: input.headSelector,
999 title: input.title,
1000 body,
1001 maintainer_can_modify: true,
1002 },
1003 });
1004 },
1005 (effect, input) =>
1006 effect.pipe(
1007 Effect.mapError(
1008 providerError("createChangeRequest", input.cwd, { reference: input.headSelector }),
1009 ),
1010 ),
1011 ),
1012 getRepositoryCloneUrls: Effect.fn("GitHubSourceControlProvider.getRepositoryCloneUrls")(
1013 function* (input) {
1014 const fallbackHost = (
1015 input.host ??
1016 (yield* resolveRepository(input).pipe(
1017 Effect.map((locator) => locator.host),
1018 Effect.orElseSucceed(() => environment.GH_HOST ?? "github.com"),
1019 ))
1020 ).toLowerCase();
1021 const bareName = input.repository.trim().replace(/\.git$/i, "");
1022 const locator =
1023 parseGitHubRepositorySelector(input.repository, fallbackHost) ??
1024 (/^[^/\s]+$/.test(bareName)
1025 ? {
1026 host: fallbackHost,
1027 owner: yield* readViewerLogin(fallbackHost),
1028 name: bareName,
1029 }
1030 : null);
1031 if (locator === null) return yield* failure("Repositories are named owner/name.");
1032 return repositoryCloneUrls(yield* readRepository(locator));
1033 },
1034 (effect, input) =>
1035 effect.pipe(
1036 Effect.mapError(
1037 providerError("getRepositoryCloneUrls", input.cwd, {
1038 repository: input.repository,
1039 }),
1040 ),
1041 ),
1042 ),
1043 createRepository: Effect.fn("GitHubSourceControlProvider.createRepository")(
1044 function* (input) {
1045 const locator = parseGitHubRepositorySelector(
1046 input.repository,
1047 (environment.GH_HOST ?? "github.com").toLowerCase(),
1048 );
1049 const viewer = locator === null ? null : yield* readViewerLogin(locator.host);
1050 const owner = locator?.owner ?? viewer;
1051 const name = locator?.name ?? input.repository.trim();
1052 const host = locator?.host ?? (environment.GH_HOST?.trim().toLowerCase() || "github.com");
1053 const isViewer = viewer !== null && owner?.toLowerCase() === viewer.toLowerCase();
1054 const response = yield* rest(
1055 {
1056 host,
1057 operation: "createRepository",
1058 method: "POST",
1059 allowReserve: true,
1060 path:
1061 isViewer || owner === null ? "user/repos" : `orgs/${encodeURIComponent(owner)}/repos`,
1062 body: { name, private: input.visibility === "private" },
1063 },
1064 `No organization named ${owner ?? "that"} that this account can create repositories in.`,
1065 );
1066 const decoded = decodeRawRepository(response.body);
1067 if (Result.isFailure(decoded)) {
1068 return yield* failure("GitHub returned an invalid repository.", decoded.failure);
1069 }
1070 return repositoryCloneUrls(decoded.success);
1071 },
1072 (effect, input) =>
1073 effect.pipe(
1074 Effect.mapError(
1075 providerError("createRepository", input.cwd, { repository: input.repository }),
1076 ),
1077 ),
1078 ),
1079 getDefaultBranch: Effect.fn("GitHubSourceControlProvider.getDefaultBranch")(
1080 function* (input) {
1081 const locator = yield* resolveRepository({
1082 cwd: input.cwd,
1083 host: contextHost(input.context),
1084 context: input.context,
1085 });
1086 const repository = yield* readRepository(locator);
1087 const branch = repository.default_branch?.trim() ?? "";
1088 return branch.length > 0 ? branch : null;
1089 },
1090 (effect, input) => effect.pipe(Effect.mapError(providerError("getDefaultBranch", input.cwd))),
1091 ),
1092 checkoutChangeRequest: Effect.fn("GitHubSourceControlProvider.checkoutChangeRequest")(
1093 function (input) {
1094 return checkoutPullRequest(input).pipe(
1095 Effect.mapError(
1096 providerError("checkoutChangeRequest", input.cwd, { reference: input.reference }),
1097 ),
1098 );
1099 },
1100 ),
1101 });
1102});