feat(server): pull requests talk to GitHub's API instead of the gh CLI (#16320)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-06 13:14:13 -07:00
1 parent 1564aaa5d2
commit adc3c9327a
15 files changed
+2871 -2597

No files matched your search

+50 -67
View File
@@ -1,18 +1,21 @@
// Run with: node apps/server/scripts/measure-pr-preview.ts owner/repo 123 456
// Numbers form a session with shared repository-permission caches. Browser and
// service caches are excluded. Uses real GitHub reads, without a server or database.
// CLI-generated GraphQL
// queries are replayed with rateLimit.cost, outside the timed section, to measure
// their cost without confusing other applications' traffic with this process's.
// Every GraphQL read carries `rateLimit`, so its cost is read off its own answer.
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Console from "effect/Console";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { FetchHttpClient } from "effect/http";
import * as GitHubPullRequestCli from "../src/pullRequest/GitHubPullRequestCli.ts";
import * as GitHubPullRequestProvider from "../src/pullRequest/GitHubPullRequestProvider.ts";
import * as GitHubCli from "../src/sourceControl/GitHubCli.ts";
import * as GitHubApi from "../src/sourceControl/GitHubApi.ts";
import * as GitHubCredentials from "../src/sourceControl/GitHubCredentials.ts";
import * as GitHubGraphQlBudget from "../src/sourceControl/githubGraphQlBudget.ts";
import * as SourceControlRateLimit from "../src/sourceControl/SourceControlRateLimit.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
const [repository, ...numbers] = process.argv.slice(2);
@@ -20,77 +23,58 @@ if (!repository || numbers.length === 0 || numbers.some((number) => !/^\d+$/.tes
throw new Error("Usage: node apps/server/scripts/measure-pr-preview.ts owner/repo number...");
}
type Read = { graphqlRequests: number; restRequests: number; cost: number; debug: string };
type Read = { graphqlRequests: number; restRequests: number; cost: number };
const reads: Read[] = [];
const layerMeasuredProcess = Layer.effect(
VcsProcess.VcsProcess,
const decodeCost = Schema.decodeUnknownOption(
Schema.fromJsonString(
Schema.Struct({
data: Schema.Struct({ rateLimit: Schema.Struct({ cost: Schema.Number }) }),
}),
),
);
const measuredApi = Layer.effect(
GitHubApi.GitHubApi,
Effect.gen(function* () {
const vcs = yield* VcsProcess.VcsProcess;
return VcsProcess.VcsProcess.of({
run: (input) =>
vcs.run({ ...input, env: { ...input.env, GH_DEBUG: input.env?.GH_DEBUG ?? "api" } }).pipe(
Effect.tap((output) =>
Effect.sync(() => {
const graphqlRequests = [...output.stderr.matchAll(/^> POST \/graphql /gm)].length;
const requests = [...output.stderr.matchAll(/^> (?:GET|POST) /gm)].length;
const cost = /"rateLimit"\s*:\s*\{[^}]*"cost"\s*:\s*(\d+)/.exec(output.stdout)?.[1];
const api = yield* GitHubApi.make;
return GitHubApi.GitHubApi.of({
...api,
graphql: (input) =>
api.graphql(input).pipe(
Effect.tap((body) =>
Effect.sync(() =>
reads.push({
graphqlRequests,
restRequests: requests - graphqlRequests,
cost: Number(cost ?? 0),
debug: output.stderr,
});
}),
graphqlRequests: 1,
restRequests: 0,
cost: Option.match(decodeCost(body), {
onNone: () => 0,
onSome: (decoded) => decoded.data.rateLimit.cost,
}),
}),
),
),
),
rest: (input) =>
api
.rest(input)
.pipe(
Effect.tap(() =>
Effect.sync(() => reads.push({ graphqlRequests: 0, restRequests: 1, cost: 0 })),
),
),
});
}),
).pipe(Layer.provide(VcsProcess.layer), Layer.provide(NodeServices.layer));
const layerServices = GitHubPullRequestCli.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provideMerge(layerMeasuredProcess),
).pipe(
Layer.provide(GitHubCredentials.layer),
Layer.provide(GitHubGraphQlBudget.layer),
Layer.provide(SourceControlRateLimit.layer),
Layer.provide(FetchHttpClient.layer),
Layer.provide(VcsProcess.layer),
Layer.provide(NodeServices.layer),
);
const decodeJson = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown));
const services = GitHubPullRequestCli.layer.pipe(Layer.provideMerge(measuredApi));
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const graphqlCost = Effect.fn("measurePrPreview.graphqlCost")(function* (read: Read) {
// The REST quota probe synthesizes rateLimit.cost for budget admission.
// It does not spend GraphQL points.
if (!read.graphqlRequests) return 0;
if (read.cost) return read.cost;
const vcs = yield* VcsProcess.VcsProcess;
let cost = 0;
let found = 0;
for (const match of read.debug.matchAll(
/GraphQL query:\n([\s\S]*?)\nGraphQL variables: (\{[^\n]*\})/g,
)) {
const query = match[1]!.replace(/(\bquery\b[^{]*\{)/, "$1 rateLimit { cost }");
const output = yield* vcs.run({
operation: "measurePrPreview.cost",
command: "gh",
cwd: process.cwd(),
args: [
"api",
"graphql",
"--hostname",
"github.com",
"--input",
"-",
"--jq",
".data.rateLimit.cost",
],
stdin: encodeJson({ query, variables: decodeJson(match[2]!) }),
env: { GH_DEBUG: "" },
});
cost += Number(output.stdout.trim());
found++;
}
if (found !== read.graphqlRequests)
throw new Error("Could not account for every GraphQL request");
return cost;
});
for (const mode of ["detail", "preview"] as const) {
// Start each side cold, then retain the caches shared across PRs in one session.
@@ -108,8 +92,7 @@ for (const mode of ["detail", "preview"] as const) {
: provider.getChangeRequestPreview!(input);
const elapsedMs = Math.round(performance.now() - start);
const measured = [...reads];
const costs = yield* Effect.forEach(measured, graphqlCost);
const points = costs.reduce((total, cost) => total + cost, 0);
const points = measured.reduce((total, read) => total + read.cost, 0);
return {
repository,
number,
@@ -123,7 +106,7 @@ for (const mode of ["detail", "preview"] as const) {
}),
);
}),
).pipe(Effect.provide(layerServices)),
).pipe(Effect.provide(services)),
);
for (const row of rows) await Effect.runPromise(Console.log(encodeJson(row)));
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -6,7 +6,7 @@ import * as Result from "effect/Result";
import type { PullRequestReaction } from "@t3tools/contracts";
import { decodePullRequestDetailJson } from "./gitHubPullRequestJson.ts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";
import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";
import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";
@@ -331,7 +331,7 @@ describe("gitHubViewerPermissions", () => {
number: 7,
})
.pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, {
Effect.provideService(GitHubApi.PinnedGitHubCredential, {
host: "github.com",
token: Redacted.make("credential"),
credentialFingerprint: fingerprint,
@@ -378,7 +378,7 @@ describe("gitHubViewerPermissions", () => {
commits: [],
}).pipe(
Effect.flatMap((detail) =>
GitHubCli.PinnedGitHubCredential.pipe(
GitHubApi.PinnedGitHubCredential.pipe(
Effect.map((credential) => ({
...detail,
viewerAccess: {
@@ -672,10 +672,9 @@ it.effect("propagates workflow discovery rate limits", () =>
getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),
listWorkflowRunsRequiringApproval: () =>
Effect.fail(
new GitHubCli.GitHubCliRateLimitError({
command: "gh",
cwd: "/w",
cause: new Error("rate limited"),
new GitHubApi.GitHubApiRateLimitError({
host: "github.com",
operation: "listWorkflowRunsRequiringApproval",
}),
),
getViewerAccess: () =>
@@ -101,22 +101,28 @@ export function gitHubViewerPermissions(access: GitHubViewerAccess): PullRequest
};
}
/** The CLI tags that mean the tool itself is unusable, rather than one request failing. */
/** The tags that mean GitHub is out of reach for this account, rather than one request failing. */
export function gitHubProviderFailure(
error: GitHubPullRequestCli.GitHubPullRequestCliError,
): PullRequestProviderFailure {
if (error._tag === "GitHubCliUnavailableError") return { reason: "missing-tool" };
if (error._tag === "GitHubCliAuthenticationError") return { reason: "unauthenticated" };
if (error._tag === "GitHubCliRateLimitError")
return {
reason: "rate-limited",
...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
};
if (error._tag === "SourceControlRateLimitPausedError") {
return { reason: "rate-limited", retryAt: error.retryAt };
switch (error._tag) {
case "GitHubCliMissingError":
return { reason: "missing-tool" };
case "GitHubNotSignedInError":
case "GitHubApiAuthenticationError":
return { reason: "unauthenticated" };
case "GitHubApiRateLimitError":
return {
reason: "rate-limited",
...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),
};
case "SourceControlRateLimitPausedError":
return { reason: "rate-limited", retryAt: error.retryAt };
case "GitHubApiNotFoundError":
return { reason: "not-found" };
default:
return { reason: "failed" };
}
if (error._tag === "GitHubPullRequestNotFoundError") return { reason: "not-found" };
return { reason: "failed" };
}
/**
@@ -196,7 +202,7 @@ export const make = Effect.gen(function* () {
provider: "github",
operation,
...gitHubProviderFailure(error),
detail: error.detail,
detail: error.message,
cause: error,
});
@@ -224,7 +230,7 @@ export const make = Effect.gen(function* () {
.pipe(
Effect.matchEffect({
onFailure: (error) =>
error._tag === "GitHubCliRateLimitError" ||
error._tag === "GitHubApiRateLimitError" ||
error._tag === "SourceControlRateLimitPausedError"
? Effect.fail(error)
: Effect.succeed({
@@ -2,7 +2,7 @@ import { assert, it } from "@effect/vitest";
import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import { azureDevOpsProviderFailure } from "./AzureDevOpsPullRequestProvider.ts";
@@ -15,7 +15,7 @@ const cause = new Error("redacted provider failure");
it("classifies rate limits from every pull-request provider", () => {
assert.deepStrictEqual(
gitHubProviderFailure(
new GitHubCli.GitHubCliRateLimitError({ command: "gh", cwd: "/repo", cause }),
new GitHubApi.GitHubApiRateLimitError({ host: "github.com", operation: "execute" }),
),
{ reason: "rate-limited" },
);
@@ -5,8 +5,10 @@ import type { SourceControlProviderKind } from "@t3tools/contracts";
import * as AzureDevOpsCli from "../sourceControl/AzureDevOpsCli.ts";
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import * as GitHubCredentials from "../sourceControl/GitHubCredentials.ts";
import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";
import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";
import * as GitLabCli from "../sourceControl/GitLabCli.ts";
import * as ForgejoCli from "../sourceControl/ForgejoCli.ts";
import * as ForgejoPullRequestProvider from "./ForgejoPullRequestProvider.ts";
@@ -60,8 +62,14 @@ export const make = Effect.map(
export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe(
Layer.provide(
GitHubPullRequestCli.layer.pipe(
Layer.provide(GitHubCli.layer),
Layer.provide(GitHubGraphQlBudget.layer),
Layer.provide(
GitHubApi.layer.pipe(
Layer.provide(GitHubCredentials.layer),
// The same layers GitHubCli merges, so both share one budget and one pause per host.
Layer.provide(GitHubGraphQlBudget.layer),
Layer.provide(SourceControlRateLimit.layer),
),
),
),
),
Layer.provide(GitLabPullRequestCli.layer.pipe(Layer.provide(GitLabCli.layer))),
@@ -4,11 +4,10 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Redacted from "effect/Redacted";
import { ChildProcessSpawner } from "effect/process";
import type { PullRequestCheck } from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import { makeChecksRevalidator } from "./gitHubConditionalChecks.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import { KnownWorkflowRuns, makeChecksRevalidator } from "./gitHubConditionalChecks.ts";
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
@@ -27,31 +26,46 @@ it.effect(
let changed = "";
let reads = 0;
const requests: string[] = [];
const known: Array<unknown> = [];
const revalidate = yield* makeChecksRevalidator.pipe(
Effect.provide(
Layer.mock(GitHubCli.GitHubCli)({
execute: ({ args }) =>
Layer.mock(GitHubApi.GitHubApi)({
rest: ({ path, ifNoneMatch }) =>
Effect.sync(() => {
const endpoint = args[1]!;
requests.push(endpoint);
const head = endpoint.endsWith("/pulls/1");
requests.push(path);
const head = path.endsWith("/pulls/1");
const modified =
!args.includes("-H") || (endpoint.includes(changed) && changed !== "");
const next = endpoint.includes("check-runs") && endpoint.endsWith("page=1");
ifNoneMatch === undefined || (path.includes(changed) && changed !== "");
const next = path.includes("check-runs") && path.endsWith("page=1");
const runs = path.includes("/actions/runs");
return {
exitCode: ChildProcessSpawner.ExitCode(modified ? 0 : 1),
stdout: modified
? `HTTP/2.0 200 OK\r\nEtag: "${sha}-${changed}"\r\n${next ? 'Link: <https://api.github.com/next>; rel="next"\r\n' : ""}\r\n${head ? encodeJson({ head: { sha }, base: { repo: { id: 1 } }, headRepositoryId: 2 }) : ""}`
: "HTTP/2.0 304 Not Modified\r\n\r\n",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
status: modified ? 200 : 304,
headers: modified
? {
etag: `"${sha}-${changed}"`,
...(next ? { link: '<https://api.github.com/next>; rel="next"' } : {}),
}
: {},
body: !modified
? ""
: head
? encodeJson({ head: { sha, repo: { id: 2 } }, base: { repo: { id: 1 } } })
: runs
? encodeJson({
workflow_runs: [
{ id: 9, status: "completed", conclusion: "action_required" },
],
})
: "{}",
truncated: false,
invalidUtf8: false,
};
}),
}),
),
);
const read = Effect.sync(() => {
const read = Effect.gen(function* () {
known.push(yield* KnownWorkflowRuns);
reads++;
return {
state: "open" as const,
@@ -64,10 +78,15 @@ it.effect(
});
const poll = (identity = credential) =>
revalidate(reference, read).pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, identity),
Effect.provideService(GitHubApi.PinnedGitHubCredential, identity),
);
yield* poll();
expect(reads).toBe(1);
// The fork's runs were just confirmed, so the read is handed them instead of listing them.
expect(known[0]).toEqual({
headSha: sha,
runs: [{ id: 9, status: "completed", conclusion: "action_required" }],
});
requests.length = 0;
yield* poll();
expect(reads).toBe(1);
@@ -113,27 +132,32 @@ it.effect("does not retain failed or incomplete reads, and supports hosts withou
let reads = 0;
const revalidate = yield* makeChecksRevalidator.pipe(
Effect.provide(
Layer.mock(GitHubCli.GitHubCli)({
execute: ({ args }) =>
Layer.mock(GitHubApi.GitHubApi)({
rest: ({ path, ifNoneMatch }) =>
unavailable
? Effect.fail(
new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: "/repo",
cause: undefined,
httpStatus: 502,
new GitHubApi.GitHubApiResponseError({
host: "github.com",
operation: "revalidateChecks",
status: 502,
}),
)
: Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(0),
stdout:
args.includes("-H") && etags
? "HTTP/2.0 304 Not Modified\n\n"
: `HTTP/2.0 200 OK\n${etags ? 'Etag: "one"\n' : ""}\n${args[1]!.endsWith("/pulls/1") ? encodeJson({ head: { sha }, base: { repo: { id: 1 } }, headRepositoryId: 1 }) : ""}`,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}),
: Effect.succeed(
ifNoneMatch !== undefined && etags
? { status: 304, headers: {}, body: "", truncated: false, invalidUtf8: false }
: {
status: 200,
headers: etags ? { etag: '"one"' } : {},
body: path.endsWith("/pulls/1")
? encodeJson({
head: { sha, repo: { id: 1 } },
base: { repo: { id: 1 } },
})
: "{}",
truncated: false,
invalidUtf8: false,
},
),
}),
),
);
@@ -141,7 +165,11 @@ it.effect("does not retain failed or incomplete reads, and supports hosts withou
reads++;
return fail
? Effect.fail(
new GitHubCli.GitHubCliCommandError({ command: "gh", cwd: "/repo", cause: undefined }),
new GitHubApi.GitHubApiResponseError({
host: "github.com",
operation: "read",
status: 500,
}),
)
: Effect.succeed({
state: "open" as const,
@@ -152,7 +180,7 @@ it.effect("does not retain failed or incomplete reads, and supports hosts withou
});
const poll = () =>
revalidate(reference, read).pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, credential),
Effect.provideService(GitHubApi.PinnedGitHubCredential, credential),
);
yield* poll().pipe(Effect.flip);
fail = false;
@@ -190,15 +218,13 @@ it.effect("falls back when REST checks are unavailable without retrying unsuppor
let reads = 0;
const revalidate = yield* makeChecksRevalidator.pipe(
Effect.provide(
Layer.mock(GitHubCli.GitHubCli)({
execute: () => {
Layer.mock(GitHubApi.GitHubApi)({
rest: () => {
probes++;
return Effect.fail(
new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: "/repo",
cause: undefined,
httpStatus: 404,
new GitHubApi.GitHubApiNotFoundError({
host: "github.com",
operation: "revalidateChecks",
}),
);
},
@@ -211,7 +237,7 @@ it.effect("falls back when REST checks are unavailable without retrying unsuppor
});
for (let tick = 0; tick < 2; tick++)
yield* revalidate(reference, read).pipe(
Effect.provideService(GitHubCli.PinnedGitHubCredential, credential),
Effect.provideService(GitHubApi.PinnedGitHubCredential, credential),
);
expect(probes).toBe(1);
expect(reads).toBe(2);
@@ -1,32 +1,63 @@
import * as Clock from "effect/Clock";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import { PositiveInt, type PullRequestChecks } from "@t3tools/contracts";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import type { GitHubPullRequestDetail } from "./gitHubPullRequestJson.ts";
import type { GitHubPullRequestCliError } from "./GitHubPullRequestCli.ts";
import type { ProviderRepositoryRef } from "./PullRequestProvider.ts";
const decodeHeadSchema = Schema.Struct({
head: Schema.Struct({ sha: Schema.String.check(Schema.isPattern(/^[a-f0-9]{40,64}$/)) }),
const HeadSchema = Schema.Struct({
head: Schema.Struct({
sha: Schema.String.check(Schema.isPattern(/^[a-f0-9]{40,64}$/)),
// Null once the fork a pull request came from has been deleted.
repo: Schema.NullOr(Schema.Struct({ id: PositiveInt })),
}),
base: Schema.Struct({ repo: Schema.Struct({ id: PositiveInt }) }),
headRepositoryId: Schema.NullOr(PositiveInt),
});
const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(decodeHeadSchema));
const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(HeadSchema));
type Validator = { etag: string | undefined; next: boolean };
const WorkflowRunSchema = Schema.Struct({
id: Schema.Int,
name: Schema.optional(Schema.NullOr(Schema.String)),
html_url: Schema.optional(Schema.NullOr(Schema.String)),
status: Schema.optional(Schema.NullOr(Schema.String)),
conclusion: Schema.optional(Schema.NullOr(Schema.String)),
head_branch: Schema.optional(Schema.NullOr(Schema.String)),
});
const decodeWorkflowRuns = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Struct({ workflow_runs: Schema.Array(WorkflowRunSchema) })),
);
export type KnownWorkflowRun = typeof WorkflowRunSchema.Type;
/**
* Every `pull_request` workflow run of one head, as the revalidator just confirmed them against
* GitHub. A read running under it filters these rather than asking for the runs again.
*/
export const KnownWorkflowRuns = Context.Reference<{
readonly headSha: string;
readonly runs: ReadonlyArray<KnownWorkflowRun>;
} | null>("t3/pullRequest/KnownWorkflowRuns", { defaultValue: () => null });
type Validator = { etag: string | undefined; next: boolean; body: string };
/** A host that answers these with one of them has no conditional REST for it at all. */
const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
export const makeChecksRevalidator = Effect.gen(function* () {
const github = yield* GitHubCli.GitHubCli;
const api = yield* GitHubApi.GitHubApi;
const entries = yield* Cache.makeWith(
(_key: string) =>
Effect.sync(() => ({
gate: Semaphore.makeUnsafe(1),
validators: new Map<string, Validator>(),
head: null as Schema.Schema.Type<typeof decodeHeadSchema> | null,
head: null as typeof HeadSchema.Type | null,
value: null as PullRequestChecks | null,
readAt: 0,
supported: true,
@@ -43,71 +74,64 @@ export const makeChecksRevalidator = Effect.gen(function* () {
>,
) =>
Effect.gen(function* () {
const credential = yield* GitHubCli.PinnedGitHubCredential;
const credential = yield* GitHubApi.PinnedGitHubCredential;
if (credential === null) return yield* read;
const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`;
const entry = yield* Cache.get(entries, key);
return yield* entry.gate.withPermit(
Effect.gen(function* () {
if (!entry.supported) return yield* read;
const fail = () =>
new GitHubCli.GitHubCliCommandError({
command: "gh",
cwd: input.cwd,
cause: new Error("GitHub returned an invalid conditional checks response."),
const fail = (status: number) =>
new GitHubApi.GitHubApiResponseError({
host: input.host,
operation: "revalidateChecks",
status,
});
/** Whether the endpoint has a next page, or null where the host cannot say. */
const get = (endpoint: string, head = false) =>
Effect.gen(function* () {
const previous = entry.validators.get(endpoint);
const result = yield* github
.execute({
cwd: input.cwd,
args: [
"api",
endpoint,
"--hostname",
input.host,
"--include",
...(head
? [
"--jq",
"{head:{sha:.head.sha},base:{repo:{id:.base.repo.id}},headRepositoryId:.head.repo.id}",
]
: ["--silent"]),
...(previous?.etag ? ["-H", `If-None-Match: ${previous.etag}`] : []),
],
acceptNotModified: true,
const response = yield* api
.rest({
host: input.host,
operation: "revalidateChecks",
path: endpoint,
...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
})
.pipe(
Effect.catchTags({
GitHubCliCommandError: (error) =>
GitHubApiNotFoundError: () =>
Effect.sync(() => {
entry.supported = ![404, 405, 501].includes(error.httpStatus ?? 0);
entry.supported = false;
return null;
}),
GitHubApiResponseError: (error) =>
Effect.sync(() => {
entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
return null;
}),
}),
);
if (result === null) {
if (response === null) {
entry.value = null;
return null;
}
if (result.stdoutTruncated || result.stdoutInvalidUtf8) return yield* fail();
const split = result.stdout.search(/\r?\n\r?\n/);
const headers = split < 0 ? result.stdout : result.stdout.slice(0, split);
const status = /^HTTP\/\S+ (\d+)/.exec(headers)?.[1];
if (status === "304" && previous) return previous.next;
if (status !== "200") return yield* fail();
if (response.status === 304 && previous) return previous.next;
if (response.status !== 200 || response.truncated) {
return yield* fail(response.status);
}
entry.value = null;
if (head) {
const decoded = yield* decodeHead(result.stdout.slice(split).trim()).pipe(
Effect.mapError(fail),
const decoded = yield* decodeHead(response.body).pipe(
Effect.mapError(() => fail(response.status)),
);
if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
entry.head = decoded;
}
const validator = {
etag: /^etag:\s*(.+)$/im.exec(headers)?.[1]?.trim(),
next: /^link:.*rel="next"/im.test(headers),
etag: response.headers["etag"]?.trim(),
next: /rel="next"/.test(response.headers["link"] ?? ""),
body: response.body,
};
entry.validators.set(endpoint, validator);
return validator.next;
@@ -115,27 +139,44 @@ export const makeChecksRevalidator = Effect.gen(function* () {
const root = `repos/${input.repository}`;
if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
const head = entry.head;
if (head === null) return yield* fail();
if (head === null) return yield* fail(200);
const runsEndpoint =
head.head.repo?.id !== head.base.repo.id
? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`
: null;
const endpoints = [
`${root}/commits/${head.head.sha}/check-runs?filter=all`,
`${root}/commits/${head.head.sha}/status`,
...(head.headRepositoryId !== head.base.repo.id
? [`${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`]
: []),
...(runsEndpoint === null ? [] : [runsEndpoint]),
];
const runPages: Array<string> = [];
for (const endpoint of endpoints) {
for (let page = 1; ; page++) {
if (page > 100) return yield* fail();
const next = yield* get(
`${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
);
if (page > 100) return yield* fail(200);
const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`;
const next = yield* get(paged);
if (next === null) return yield* read;
if (endpoint === runsEndpoint) runPages.push(paged);
if (!next) break;
}
}
const now = yield* Clock.currentTimeMillis;
if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
const fresh = yield* read;
// Every page of the head's runs was just confirmed current, so the read filters them
// rather than listing the runs a second time.
const pages = runPages.map((endpoint) =>
decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
);
const known =
runsEndpoint !== null && pages.every(Option.isSome)
? {
headSha: head.head.sha,
runs: pages.flatMap((page) =>
Option.isSome(page) ? page.value.workflow_runs : [],
),
}
: null;
const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
const value = {
state: fresh.state,
checks: fresh.checks,
@@ -6,10 +6,10 @@ import {
buildPullRequestWatchFingerprintsGraphQlQuery,
decodePullRequestSummariesJson,
decodePullRequestWatchFingerprintsJson,
buildReviewSubmissionJson,
buildReviewSubmission,
buildPullRequestStackMembershipsGraphQlQuery,
decodePullRequestStackMembershipsJson,
buildReviewerRequestJson,
buildReviewerRequest,
buildSetFilesViewedGraphQlMutation,
decodeBaseComparisonJson,
decodePullRequestActivityJson,
@@ -25,26 +25,50 @@ import {
decodeReviewThreadCommentsJson,
decodeReviewThreadsJson,
decodeViewerPermissionsJson,
decodeWorkflowRunApprovalsJson,
decodeWorkflowRunsJson,
reviewThreadConversation,
REVIEW_THREADS_GRAPHQL_QUERY,
pullRequestCoreGraphQlQuery,
pullRequestSearchGraphQlQuery,
} from "./gitHubPullRequestJson.ts";
/**
* Rows as a repository's own GraphQL list answers them. Entries may use flat shapes for brevity:
* `reviewRequests` and `latestReviews` as arrays, and `checks` as the rollup state.
*/
function listJson(entries: ReadonlyArray<Record<string, unknown>>): string {
return JSON.stringify(
entries.map((entry) => ({
number: 1,
title: "Add the pull requests page",
url: "https://github.com/pingdotgg/t3code/pull/1",
headRefName: "feat/page",
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
...entry,
})),
);
return JSON.stringify({
data: {
repository: {
pullRequests: {
pageInfo: { hasNextPage: false },
nodes: entries.map(({ reviewRequests, latestReviews, checks, ...entry }) => ({
number: 1,
title: "Add the pull requests page",
url: "https://github.com/pingdotgg/t3code/pull/1",
headRefName: "feat/page",
baseRefName: "main",
createdAt: "2026-07-01T00:00:00Z",
updatedAt: "2026-07-02T00:00:00Z",
...(reviewRequests === undefined
? {}
: {
reviewRequests: {
nodes: (reviewRequests as ReadonlyArray<unknown>).map((requestedReviewer) => ({
requestedReviewer,
})),
},
}),
...(latestReviews === undefined ? {} : { latestReviews: { nodes: latestReviews } }),
...(checks === undefined
? {}
: { commits: { nodes: [{ commit: { statusCheckRollup: { state: checks } } }] } }),
...entry,
})),
},
},
},
});
}
function expectSuccess<A>(result: Result.Result<A, unknown>): A {
@@ -136,38 +160,15 @@ describe("pull request list decoding", () => {
]);
});
it("rolls the head commit's checks up to the one word a row has space for", () => {
it("rolls the head commit's rollup up to the one word a row has space for", () => {
const batch = expectSuccess(
decodePullRequestListJson(
listJson([
// A failure outranks a run still going, and a completed run has to be read through its
// conclusion rather than its status.
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "build", status: "IN_PROGRESS" },
{ name: "test", status: "COMPLETED", conclusion: "FAILURE" },
],
},
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "build", status: "QUEUED" },
],
},
{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" }] },
// A commit status reports one `state` and no `status` at all.
{ statusCheckRollup: [{ context: "ci/legacy", state: "ERROR" }] },
// Neither a pass, a failure nor a wait is no verdict rather than a green tick.
{ statusCheckRollup: [{ name: "lint", status: "COMPLETED", conclusion: "SKIPPED" }] },
// Cancelled reads as failing here and in the detail header, so the two never flap.
{
statusCheckRollup: [
{ name: "lint", status: "COMPLETED", conclusion: "SUCCESS" },
{ name: "test", status: "COMPLETED", conclusion: "CANCELLED" },
],
},
{ statusCheckRollup: [] },
{ checks: "FAILURE" },
{ checks: "PENDING" },
{ checks: "SUCCESS" },
{ checks: "ERROR" },
{ checks: "EXPECTED" },
{},
]),
),
@@ -177,16 +178,15 @@ describe("pull request list decoding", () => {
"pending",
"passing",
"failing",
null,
"failing",
null,
"pending",
null,
]);
});
it("skips malformed entries but still counts them, so paging does not stop early", () => {
const raw = `[${listJson([{}]).slice(1, -1)},{"number":"not-a-number"}]`;
const batch = expectSuccess(decodePullRequestListJson(raw));
const batch = expectSuccess(
decodePullRequestListJson(listJson([{}, { number: "not-a-number" }])),
);
expect(batch.items).toHaveLength(1);
expect(batch.rawCount).toBe(2);
});
@@ -279,6 +279,43 @@ describe("pull request detail decoding", () => {
],
});
/** The same conversation as the GraphQL activity query answers it. */
const activityJson = (raw: Record<string, unknown>) =>
JSON.stringify({
data: {
repository: {
pullRequest: {
comments: { nodes: raw["comments"] ?? [] },
reviews: { nodes: raw["reviews"] ?? [] },
commits: {
nodes: ((raw["commits"] ?? []) as ReadonlyArray<Record<string, unknown>>).map(
({ authors, ...commit }) => ({
commit: {
...commit,
authors: {
nodes: ((authors ?? []) as ReadonlyArray<Record<string, unknown>>).map(
({ login, ...author }) => ({
...author,
...(login === undefined ? {} : { user: { login } }),
}),
),
},
},
}),
),
},
},
},
},
});
const activity = (raw: Record<string, unknown>) =>
Result.map(decodePullRequestActivityJson(activityJson(raw)), (page) => ({
comments: page.remarks.toSorted((left, right) =>
left.createdAt.localeCompare(right.createdAt),
),
commits: page.commits ?? [],
}));
it("maps check-run status and commit-status state onto one vocabulary", () => {
const detail = expectSuccess(decodePullRequestDetailJson(detailJson));
expect(detail.checks.map((check) => [check.name, check.status])).toEqual([
@@ -333,13 +370,15 @@ describe("pull request detail decoding", () => {
it("decodes workflow runs that can be approved", () => {
expect(
expectSuccess(
decodeWorkflowRunApprovalsJson(
JSON.stringify([
{ databaseId: 10, workflowName: "contributor tests", url: "https://example.com/10" },
{ databaseId: 11, workflowName: null, url: null },
]),
decodeWorkflowRunsJson(
JSON.stringify({
workflow_runs: [
{ id: 10, name: "contributor tests", html_url: "https://example.com/10" },
{ id: 11, name: null, html_url: null },
],
}),
),
),
).runs,
).toEqual([
{ id: 10, name: "contributor tests", url: "https://example.com/10" },
{ id: 11, name: "Workflow run 11", url: null },
@@ -398,14 +437,14 @@ describe("pull request detail decoding", () => {
});
it("merges reviews with comments in time order and keeps a bodyless approval", () => {
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
const detail = expectSuccess(activity(JSON.parse(detailJson) as Record<string, unknown>));
// r2 approved without writing anything, which is still the event worth seeing.
expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]);
expect(detail.comments.at(-1)?.reviewState).toBe("APPROVED");
});
it("keeps every attributed commit author, including an unlinked signature", () => {
const detail = expectSuccess(decodePullRequestActivityJson(detailJson));
const detail = expectSuccess(activity(JSON.parse(detailJson) as Record<string, unknown>));
expect(detail.commits[0]?.authors).toEqual([
{ login: "octocat", name: "Octo Cat", avatarUrl: null },
{ login: "Pair Author", name: "Pair Author", avatarUrl: null },
@@ -415,22 +454,20 @@ describe("pull request detail decoding", () => {
it("drops the bodyless review GitHub opens to hold line comments", () => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const detail = expectSuccess(
decodePullRequestActivityJson(
JSON.stringify({
...raw,
reviews: [
// What a reviewer leaving inline comments produces: a container with a state but
// nothing to read. Its comments come from the review threads instead.
{ id: "r4", body: "", state: "COMMENTED", submittedAt: "2026-07-07T00:00:00Z" },
{
id: "r5",
body: "Looks good.",
state: "COMMENTED",
submittedAt: "2026-07-08T00:00:00Z",
},
],
}),
),
activity({
...raw,
reviews: [
// What a reviewer leaving inline comments produces: a container with a state but
// nothing to read. Its comments come from the review threads instead.
{ id: "r4", body: "", state: "COMMENTED", submittedAt: "2026-07-07T00:00:00Z" },
{
id: "r5",
body: "Looks good.",
state: "COMMENTED",
submittedAt: "2026-07-08T00:00:00Z",
},
],
}),
);
expect(detail.comments.map((comment) => comment.id)).toEqual(["c1", "r5"]);
@@ -441,12 +478,10 @@ describe("pull request detail decoding", () => {
(state) => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const detail = expectSuccess(
decodePullRequestActivityJson(
JSON.stringify({
...raw,
reviews: [{ id: "r6", body: "", state, submittedAt: "2026-07-07T00:00:00Z" }],
}),
),
activity({
...raw,
reviews: [{ id: "r6", body: "", state, submittedAt: "2026-07-07T00:00:00Z" }],
}),
);
expect(detail.comments.map((comment) => comment.id)).toContain("r6");
@@ -456,12 +491,10 @@ describe("pull request detail decoding", () => {
it("drops a review that carries neither a body nor a state", () => {
const raw = JSON.parse(detailJson) as Record<string, unknown>;
const detail = expectSuccess(
decodePullRequestActivityJson(
JSON.stringify({
...raw,
reviews: [{ id: "r3", body: " ", submittedAt: "2026-07-07T00:00:00Z" }],
}),
),
activity({
...raw,
reviews: [{ id: "r3", body: " ", submittedAt: "2026-07-07T00:00:00Z" }],
}),
);
expect(detail.comments.map((comment) => comment.id)).toEqual(["c1"]);
});
@@ -1432,18 +1465,16 @@ describe("reviewer candidate decoding", () => {
describe("reviewer request payload", () => {
it("sends people and teams in the two lists GitHub keeps them in", () => {
expect(
JSON.parse(
buildReviewerRequestJson([
{ id: "octocat", kind: "user" },
{ id: "reviewers", kind: "team" },
{ id: "hubot", kind: "user" },
]),
),
buildReviewerRequest([
{ id: "octocat", kind: "user" },
{ id: "reviewers", kind: "team" },
{ id: "hubot", kind: "user" },
]),
).toEqual({ reviewers: ["octocat", "hubot"], team_reviewers: ["reviewers"] });
});
it("sends both lists even where one of them is empty, which is what GitHub reads", () => {
expect(JSON.parse(buildReviewerRequestJson([{ id: "octocat", kind: "user" }]))).toEqual({
expect(buildReviewerRequest([{ id: "octocat", kind: "user" }])).toEqual({
reviewers: ["octocat"],
team_reviewers: [],
});
@@ -1452,24 +1483,22 @@ describe("reviewer request payload", () => {
describe("review submission payload", () => {
it("sends the verdict, the summary and every line comment in one body", () => {
const payload = JSON.parse(
buildReviewSubmissionJson({
verdict: "request-changes",
body: "Two things.",
comments: [
{
path: "src/a.ts",
position: { kind: "added", newLine: 12 },
body: "rename this",
},
{
path: "src/b.ts",
position: { kind: "deleted", oldLine: 3 },
body: "why remove?",
},
],
}),
) as Record<string, unknown>;
const payload = buildReviewSubmission({
verdict: "request-changes",
body: "Two things.",
comments: [
{
path: "src/a.ts",
position: { kind: "added", newLine: 12 },
body: "rename this",
},
{
path: "src/b.ts",
position: { kind: "deleted", oldLine: 3 },
body: "why remove?",
},
],
});
expect(payload).toEqual({
event: "REQUEST_CHANGES",
body: "Two things.",
@@ -1481,9 +1510,11 @@ describe("review submission payload", () => {
});
it("sends an approval with no words and no comments", () => {
expect(
JSON.parse(buildReviewSubmissionJson({ verdict: "approve", body: "", comments: [] })),
).toEqual({ event: "APPROVE", body: "", comments: [] });
expect(buildReviewSubmission({ verdict: "approve", body: "", comments: [] })).toEqual({
event: "APPROVE",
body: "",
comments: [],
});
});
});
@@ -155,6 +155,9 @@ const RawSearchItemSchema = Schema.Struct({
latestReviews: Schema.optional(
Schema.NullOr(Schema.Struct({ nodes: Schema.Array(Schema.NullOr(RawLatestReviewSchema)) })),
),
/** Asked for by the per-repository listing, and left out of the cross-repository search. */
additions: Schema.optional(Schema.Int),
deletions: Schema.optional(Schema.Int),
createdAt: Schema.String,
updatedAt: Schema.String,
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
@@ -167,7 +170,14 @@ const RawSearchItemSchema = Schema.Struct({
Schema.Array(
Schema.NullOr(
Schema.Struct({
requestedReviewer: Schema.optional(Schema.NullOr(RawActorSchema)),
requestedReviewer: Schema.optional(
Schema.NullOr(
Schema.Struct({
...RawActorSchema.fields,
slug: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
),
}),
),
),
@@ -215,14 +225,27 @@ const RawSearchItemSchema = Schema.Struct({
),
});
const RawRowConnectionSchema = Schema.Struct({
pageInfo: Schema.optional(
Schema.NullOr(
Schema.Struct({
hasNextPage: Schema.Boolean,
endCursor: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
),
// Row by row: a node that is not a pull request — or one field GitHub changes — is skipped
// rather than blanking every repository at once.
nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
});
const RawSearchSchema = Schema.Struct({
data: Schema.Struct({ search: RawRowConnectionSchema }),
});
const RawRepositoryPullRequestsSchema = Schema.Struct({
data: Schema.Struct({
search: Schema.Struct({
pageInfo: Schema.optional(Schema.NullOr(Schema.Struct({ hasNextPage: Schema.Boolean }))),
// Row by row, like the listing's own: a node that is not a pull request — or one field
// GitHub changes — is skipped rather than blanking every repository at once.
nodes: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))),
}),
repository: Schema.NullOr(Schema.Struct({ pullRequests: RawRowConnectionSchema })),
}),
});
@@ -414,31 +437,103 @@ const RawDetailSchema = Schema.Struct({
),
});
const RawWorkflowRunApprovalSchema = Schema.Struct({
databaseId: Schema.Int,
workflowName: Schema.optional(Schema.NullOr(Schema.String)),
url: Schema.optional(Schema.NullOr(Schema.String)),
/** `GET /repos/{owner}/{repo}/actions/runs`, one page of it. */
const RawWorkflowRunsSchema = Schema.Struct({
workflow_runs: Schema.Array(
Schema.Struct({
id: Schema.Int,
name: Schema.optional(Schema.NullOr(Schema.String)),
html_url: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
});
const RawPullRequestHeadSchema = Schema.Struct({
number: Schema.Int,
headRefOid: Schema.String,
isCrossRepository: Schema.optional(Schema.Boolean),
headRepositoryOwner: Schema.optional(Schema.NullOr(Schema.Struct({ login: Schema.String }))),
const RawPullRequestHeadsSchema = Schema.Struct({
data: Schema.Struct({
repository: Schema.NullOr(
Schema.Struct({
pullRequests: Schema.Struct({
pageInfo: Schema.optional(RawPageInfoSchemaFields()),
nodes: Schema.Array(
Schema.Struct({
number: Schema.Int,
headRefOid: Schema.String,
isCrossRepository: Schema.optional(Schema.Boolean),
headRepositoryOwner: Schema.optional(
Schema.NullOr(Schema.Struct({ login: Schema.String })),
),
}),
),
}),
}),
),
}),
});
const RawActivityConnection = <S extends Schema.Top>(node: S) =>
Schema.optional(
Schema.NullOr(
Schema.Struct({
pageInfo: Schema.optional(RawPageInfoSchemaFields()),
nodes: Schema.Array(node),
}),
),
);
const RawActivitySchema = Schema.Struct({
author: Schema.optional(Schema.NullOr(RawActorSchema)),
comments: Schema.optional(Schema.Array(RawCommentSchema)),
reviews: Schema.optional(Schema.Array(RawReviewSchema)),
commits: Schema.optional(Schema.Array(RawCommitSchema)),
data: Schema.Struct({
repository: Schema.Struct({
pullRequest: Schema.Struct({
author: Schema.optional(Schema.NullOr(RawActorSchema)),
comments: RawActivityConnection(RawCommentSchema),
reviews: RawActivityConnection(RawReviewSchema),
commits: Schema.optional(
Schema.NullOr(
Schema.Struct({
nodes: Schema.Array(
Schema.Struct({
commit: Schema.Struct({
oid: Schema.String,
messageHeadline: Schema.optional(Schema.String),
committedDate: Schema.String,
authors: Schema.optional(
Schema.NullOr(
Schema.Struct({
nodes: Schema.Array(
Schema.Struct({
email: Schema.optional(Schema.NullOr(Schema.String)),
name: Schema.optional(Schema.NullOr(Schema.String)),
user: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.optional(Schema.NullOr(Schema.String)),
}),
),
),
}),
),
}),
),
),
}),
}),
),
}),
),
),
}),
}),
}),
});
/** Where a connection carries on from, which is what every paged read below follows. */
const RawPageInfoSchema = Schema.Struct({
hasNextPage: Schema.optional(Schema.Boolean),
endCursor: Schema.optional(Schema.NullOr(Schema.String)),
});
function RawPageInfoSchemaFields() {
return Schema.Struct({
hasNextPage: Schema.optional(Schema.Boolean),
endCursor: Schema.optional(Schema.NullOr(Schema.String)),
});
}
const RawPageInfoSchema = RawPageInfoSchemaFields();
/**
* What GitHub says the viewer may do with a pull request. Both are optional so that an install
@@ -707,19 +802,25 @@ export function decodeActorAvatarsJson(
return Result.succeed(avatarsByLogin);
}
export const PULL_REQUEST_LIST_JSON_FIELDS =
"number,title,url,author,headRefName,baseRefName,state,isDraft,mergeable,reviewDecision,additions,deletions,createdAt,updatedAt,mergedAt,reviewRequests,latestReviews,labels,statusCheckRollup";
export const PULL_REQUEST_DETAIL_JSON_FIELDS = `${PULL_REQUEST_LIST_JSON_FIELDS},body,changedFiles,closedAt,isCrossRepository,headRepositoryOwner,headRefOid,autoMergeRequest`;
/**
* Pull refs let the comparison share the detail read without first resolving a fork branch.
* `isRequired` is asked for on github.com only: an older Enterprise server may not know it, and
* an unknown field fails the whole read.
*/
export const pullRequestCoreGraphQlQuery = (host: string) => {
function checkContextNodesSelection(host: string): string {
const required =
host.toLowerCase() === "github.com" ? " isRequired(pullRequestNumber: $number)" : "";
return `nodes {
__typename
... on StatusContext { context state targetUrl createdAt description${required} }
... on CheckRun {
name status conclusion startedAt completedAt detailsUrl${required}
checkSuite { workflowRun { workflow { name } } }
}
}`;
}
export const pullRequestCoreGraphQlQuery = (host: string) => {
return `query($owner: String!, $name: String!, $number: Int!, $headRef: String!) {
repository(owner: $owner, name: $name) {
mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed viewerPermission
@@ -738,14 +839,7 @@ export const pullRequestCoreGraphQlQuery = (host: string) => {
labels(first: 100) { nodes { name color } }
commits(last: 1) {
nodes { commit { statusCheckRollup { contexts(first: 100) {
nodes {
__typename
... on StatusContext { context state targetUrl createdAt description${required} }
... on CheckRun {
name status conclusion startedAt completedAt detailsUrl${required}
checkSuite { workflowRun { workflow { name } } }
}
}
${checkContextNodesSelection(host)}
pageInfo { hasNextPage }
} } } }
}
@@ -791,7 +885,29 @@ export function decodePullRequestPreviewJson(
}));
}
export const PULL_REQUEST_ACTIVITY_JSON_FIELDS = "author,comments,reviews,commits";
/**
* The conversation a pull request carries outside its review threads: who opened it, its issue
* comments, its reviews and its newest commits. The two remark connections page independently, so
* each is switched on only while it has more to give; the first read asks for everything.
*/
export const PULL_REQUEST_ACTIVITY_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $head: Boolean!, $withComments: Boolean!, $commentsAfter: String, $withReviews: Boolean!, $reviewsAfter: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
author @include(if: $head) { __typename login avatarUrl ... on User { name } }
commits(last: 100) @include(if: $head) {
nodes { commit { oid messageHeadline committedDate authors(first: 10) { nodes { name email user { login } } } } }
}
comments(first: 100, after: $commentsAfter) @include(if: $withComments) {
pageInfo { hasNextPage endCursor }
nodes { id body createdAt lastEditedAt url author { __typename login avatarUrl ... on User { name } } }
}
reviews(first: 100, after: $reviewsAfter) @include(if: $withReviews) {
pageInfo { hasNextPage endCursor }
nodes { id body state submittedAt lastEditedAt url author { __typename login avatarUrl ... on User { name } } }
}
}
}
}`;
/** GitHub's own ceiling on a connection page, which is what both thread reads ask for. */
const GRAPHQL_PAGE_SIZE = 100;
@@ -818,13 +934,45 @@ export const PULL_REQUEST_SEARCH_MAX_ROWS = GRAPHQL_PAGE_SIZE;
* than twenty labels shows twenty, and one that has asked more than twenty people for a review
* is already past what a row can say.
*/
export function pullRequestSearchGraphQlQuery(rows: number, includeStacks = false): string {
return `query($q: String!) {
search(query: $q, type: ISSUE, first: ${Math.min(Math.max(Math.trunc(rows), 1), PULL_REQUEST_SEARCH_MAX_ROWS)}) {
pageInfo { hasNextPage }
export function pullRequestSearchGraphQlQuery(
rows: number,
includeStacks = false,
includeStats = false,
): string {
return `query($q: String!, $after: String) {
search(query: $q, type: ISSUE, first: ${pageRows(rows)}, after: $after) {
pageInfo { hasNextPage endCursor }
nodes {
... on PullRequest {
${includeStacks ? "stack { number size baseRefName } stackEntry { position }" : ""}
${pullRequestRowSelection(includeStacks, includeStats)}
}
}
}
}`;
}
/**
* A repository's pull requests without search, newest created first: the order `gh pr list` lists
* in when it does not search, for a repository GitHub's search index does not cover.
*/
export function pullRequestListGraphQlQuery(rows: number, includeStacks = false): string {
return `query($owner: String!, $name: String!, $states: [PullRequestState!], $after: String) {
repository(owner: $owner, name: $name) {
pullRequests(first: ${pageRows(rows)}, after: $after, states: $states, orderBy: { field: CREATED_AT, direction: DESC }) {
pageInfo { hasNextPage endCursor }
nodes { ${pullRequestRowSelection(includeStacks, true)} }
}
}
}`;
}
function pageRows(rows: number): number {
return Math.min(Math.max(Math.trunc(rows), 1), PULL_REQUEST_SEARCH_MAX_ROWS);
}
/** One listing row, the same whether it came from a search or from a repository's own list. */
function pullRequestRowSelection(includeStacks: boolean, includeStats: boolean): string {
return `${includeStacks ? "stack { number size baseRefName } stackEntry { position }" : ""}
number
title
url
@@ -836,17 +984,14 @@ export function pullRequestSearchGraphQlQuery(rows: number, includeStacks = fals
mergeable
reviewDecision
latestReviews(first: 20) { nodes { state author { login } } }
${includeStats ? "additions deletions" : ""}
createdAt
updatedAt
mergedAt
repository { nameWithOwner }
reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } } } }
reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } ... on Team { slug } } } }
labels(first: 20) { nodes { name color } }
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
}
}
}
}`;
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }`;
}
/**
@@ -1094,24 +1239,6 @@ export const UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION = `mutation($commentId: ID!,
}
}`;
/**
* A GraphQL request as `gh api graphql --input -` takes it. Variables travel in the document
* rather than as `-f name=value` flags, so a reader's own words never reach argv.
*/
const GraphQlRequestSchema = Schema.Struct({
query: Schema.String,
variables: Schema.Record(Schema.String, Schema.String),
});
const encodeGraphQlRequest = Schema.encodeSync(Schema.fromJsonString(GraphQlRequestSchema));
export function encodeGraphQlRequestJson(input: {
readonly query: string;
readonly variables: Readonly<Record<string, string>>;
}): string {
return encodeGraphQlRequest({ query: input.query, variables: { ...input.variables } });
}
/** The body of `POST /repos/{owner}/{repo}/pulls/{number}/reviews`, which sends a review whole. */
const ReviewSubmissionSchema = Schema.Struct({
event: Schema.Literals(["COMMENT", "APPROVE", "REQUEST_CHANGES"]),
@@ -1126,8 +1253,6 @@ const ReviewSubmissionSchema = Schema.Struct({
),
});
const encodeReviewSubmission = Schema.encodeSync(Schema.fromJsonString(ReviewSubmissionSchema));
const REVIEW_EVENTS: Record<PullRequestReviewVerdict, "COMMENT" | "APPROVE" | "REQUEST_CHANGES"> = {
comment: "COMMENT",
approve: "APPROVE",
@@ -1166,12 +1291,12 @@ function gitHubReviewPosition(position: PullRequestReviewPosition): {
}
/** The whole review as one request body, which is how GitHub keeps it invisible until sent. */
export function buildReviewSubmissionJson(input: {
export function buildReviewSubmission(input: {
readonly verdict: PullRequestReviewVerdict;
readonly body: string;
readonly comments: ReadonlyArray<PullRequestReviewCommentDraft>;
}): string {
return encodeReviewSubmission({
}): typeof ReviewSubmissionSchema.Type {
return {
event: REVIEW_EVENTS[input.verdict],
body: input.body,
comments: input.comments.map((comment) => ({
@@ -1179,7 +1304,7 @@ export function buildReviewSubmissionJson(input: {
...gitHubReviewPosition(comment.position),
body: comment.body,
})),
});
};
}
export interface GitHubPullRequestListItem {
@@ -1644,23 +1769,15 @@ function toDetail(raw: Schema.Schema.Type<typeof RawDetailSchema>): GitHubPullRe
};
}
function toActivity(raw: Schema.Schema.Type<typeof RawActivitySchema>): GitHubPullRequestActivity {
return {
author: toActor(raw.author),
comments: toComments(raw),
commits: toCommits(raw.commits),
};
}
const decodeUnknownList = decodeJsonResult(Schema.Array(Schema.Unknown));
const decodeListEntry = Schema.decodeUnknownExit(RawListItemSchema);
const decodeSearch = decodeJsonResult(RawSearchSchema);
const decodeSearchItem = Schema.decodeUnknownExit(RawSearchItemSchema);
const decodeStats = decodeJsonResult(RawStatsSchema);
const decodeDetail = decodeJsonResult(RawDetailSchema);
const decodeWorkflowRunApprovals = decodeJsonResult(Schema.Array(RawWorkflowRunApprovalSchema));
const decodePullRequestHeads = decodeJsonResult(Schema.Array(RawPullRequestHeadSchema));
const decodeWorkflowRuns = decodeJsonResult(RawWorkflowRunsSchema);
const decodePullRequestHeads = decodeJsonResult(RawPullRequestHeadsSchema);
const decodeActivity = decodeJsonResult(RawActivitySchema);
const decodeRepositoryPullRequests = decodeJsonResult(RawRepositoryPullRequestsSchema);
const decodeFileEntry = Schema.decodeUnknownExit(RawPullRequestFileSchema);
const decodeReviewThreads = decodeJsonResult(RawReviewThreadsSchema);
const decodeReviewThreadComments = decodeJsonResult(RawReviewThreadCommentsSchema);
@@ -1669,27 +1786,78 @@ type DecodeFailure = Cause.Cause<Schema.SchemaError>;
export interface GitHubPullRequestListBatch {
readonly items: ReadonlyArray<GitHubPullRequestListItem>;
/** Rows gh returned, counted before decoding, so a skipped row cannot hide a next page. */
/** Rows GitHub returned, counted before decoding, so a skipped row cannot hide a next page. */
readonly rawCount: number;
/** Where the next page starts, or null once GitHub has handed over every row. */
readonly endCursor: string | null;
}
/** Malformed entries are skipped rather than failing the batch: one unexpected pull request
* must not blank the whole list. */
/**
* One page of a repository's own pull request list. Malformed rows are skipped rather than
* failing the page: one unexpected pull request must not blank the whole list. A repository the
* viewer cannot see answers as an empty page, which is what `gh pr list` printed for it too.
*/
export function decodePullRequestListJson(
raw: string,
): Result.Result<GitHubPullRequestListBatch, DecodeFailure> {
const decoded = decodeUnknownList(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const decoded = decodeRepositoryPullRequests(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
const connection = decoded.success.data.repository?.pullRequests;
const nodes = connection?.nodes ?? [];
const items: GitHubPullRequestListItem[] = [];
for (const entry of decoded.success) {
const item = decodeListEntry(entry);
if (Exit.isSuccess(item)) {
items.push(toListItem(item.value));
}
for (const entry of nodes) {
const row = toRow(entry);
if (row !== null) items.push(row.item);
}
return Result.succeed({ items, rawCount: decoded.success.length });
return Result.succeed({
items,
rawCount: nodes.length,
endCursor:
connection?.pageInfo?.hasNextPage === true ? trimmed(connection.pageInfo.endCursor) : null,
});
}
/**
* A row as GraphQL answers it: reviewers and labels arrive as connections, and the checks as
* GitHub's one-word rollup rather than the whole check list. Null for a node that is not a pull
* request, or one whose fields no longer decode.
*/
function toRow(
entry: unknown,
): { readonly item: GitHubPullRequestListItem; readonly repository: string | null } | null {
const decodedNode = decodeSearchItem(entry);
if (!Exit.isSuccess(decodedNode)) return null;
const node = decodedNode.value;
const stack = toStackMembership(node);
const reviewRequests = (node.reviewRequests?.nodes ?? []).flatMap(
(request): ReadonlyArray<{ readonly login?: string; readonly slug?: string }> => {
const reviewer = request?.requestedReviewer;
const login = trimmed(reviewer?.login);
if (login !== null) return [{ login }];
const slug = trimmed(reviewer?.slug);
return slug === null ? [] : [{ slug }];
},
);
return {
item: {
...toListItem({
...node,
latestReviews: (node.latestReviews?.nodes ?? []).flatMap((review) =>
review === null ? [] : [review],
),
reviewRequests,
labels: (node.labels?.nodes ?? []).flatMap((label) => (label === null ? [] : [label])),
// The rollup arrives as one enum. Dressed as a single check here so it is read the same
// way the detail's checks are.
statusCheckRollup: (node.commits?.nodes ?? []).flatMap((commitNode) => {
const state = trimmed(commitNode?.commit?.statusCheckRollup?.state);
return state === null ? [] : [{ state }];
}),
}),
...(stack === undefined ? {} : { stack }),
},
repository: trimmed(node.repository?.nameWithOwner),
};
}
export interface GitHubPullRequestSearchItem extends GitHubPullRequestListItem {
@@ -1703,12 +1871,12 @@ export interface GitHubPullRequestSearchBatch {
readonly rawCount: number;
/** More rows than this slice asked for, which is truncation for every repository in it. */
readonly hasNextPage: boolean;
/** Where the next page of the same search starts. */
readonly endCursor: string | null;
}
/**
* A search answers with the same pull request the listing does, one connection deeper: reviewers
* and labels arrive as connections, and the row names the repository it came from. Flattened to
* the shape `gh pr list --json` hands over so both reads decode into one type.
* A search answers with the same row a repository's list does, each naming its repository.
*
* Rows that are not pull requests decode as empty and are skipped, the way a malformed listing
* row is — `is:pr` already excludes them, and one surprise must not blank a whole host.
@@ -1720,41 +1888,19 @@ export function decodePullRequestSearchJson(
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
const nodes = decoded.success.data.search.nodes ?? [];
const search = decoded.success.data.search;
const nodes = search.nodes ?? [];
const items: GitHubPullRequestSearchItem[] = [];
for (const entry of nodes) {
const decodedNode = decodeSearchItem(entry);
if (!Exit.isSuccess(decodedNode)) continue;
const node = decodedNode.value;
const repository = trimmed(node.repository?.nameWithOwner);
if (repository === null) continue;
const stack = toStackMembership(node);
items.push({
...toListItem({
...node,
latestReviews: (node.latestReviews?.nodes ?? []).flatMap((review) =>
review === null ? [] : [review],
),
reviewRequests: (node.reviewRequests?.nodes ?? []).flatMap((request) => {
const login = trimmed(request?.requestedReviewer?.login);
return login === null ? [] : [{ login }];
}),
labels: (node.labels?.nodes ?? []).flatMap((label) => (label === null ? [] : [label])),
// The search asks for the verdict rather than the checks behind it, so it arrives as one
// enum. Dressed as a single check here so the rollup is read the same way on both paths.
statusCheckRollup: (node.commits?.nodes ?? []).flatMap((commitNode) => {
const state = trimmed(commitNode?.commit?.statusCheckRollup?.state);
return state === null ? [] : [{ state }];
}),
}),
...(stack === undefined ? {} : { stack }),
repository,
});
const row = toRow(entry);
if (row === null || row.repository === null) continue;
items.push({ ...row.item, repository: row.repository });
}
return Result.succeed({
items,
rawCount: nodes.length,
hasNextPage: decoded.success.data.search.pageInfo?.hasNextPage ?? false,
hasNextPage: search.pageInfo?.hasNextPage ?? false,
endCursor: search.pageInfo?.hasNextPage === true ? trimmed(search.pageInfo.endCursor) : null,
});
}
@@ -1900,6 +2046,13 @@ export function buildPullRequestSummariesGraphQlQuery(
return `query PullRequestSummaries {\n${selections.join("\n")}\n}`;
}
/** One pull request's summary, aliased the way the batch is so the same decoder reads it. */
export function pullRequestSummaryGraphQlQuery(includeStacks = false): string {
return `query($owner: String!, $name: String!, $number: Int!) {
s0: repository(owner: $owner, name: $name) { pullRequest(number: $number) { ${PULL_REQUEST_SUMMARY_SELECTION}${includeStacks ? ` ${STACK_MEMBERSHIP_SELECTION}` : ""} } }
}`;
}
const RawSummarySchema = Schema.Struct({
...RawSearchItemSchema.fields,
changedFiles: Schema.optional(Schema.NullOr(Schema.Int)),
@@ -2147,11 +2300,7 @@ export function decodePullRequestCoreJson(
requestedReviewer === null ? [] : [requestedReviewer],
),
labels: pr.labels.nodes,
statusCheckRollup:
contexts?.nodes.map((check) => ({
...check,
workflowName: check.checkSuite?.workflowRun?.workflow?.name ?? null,
})) ?? [],
statusCheckRollup: toCheckContexts(contexts?.nodes ?? []),
}),
viewerAccess: {
canWrite: toCanWrite(repository.viewerPermission),
@@ -2183,27 +2332,50 @@ export function decodePullRequestDetailJson(
: Result.fail(decoded.failure);
}
export function decodeWorkflowRunApprovalsJson(
raw: string,
): Result.Result<ReadonlyArray<GitHubWorkflowRunApproval>, DecodeFailure> {
const decoded = decodeWorkflowRunApprovals(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
return Result.succeed(
decoded.success.map((run) => ({
id: run.databaseId,
name: trimmed(run.workflowName) ?? `Workflow run ${run.databaseId}`,
url: trimmed(run.url),
})),
);
export interface GitHubWorkflowRunPage {
readonly runs: ReadonlyArray<GitHubWorkflowRunApproval>;
/** Runs on the page, counted before decoding, which is what decides whether to page on. */
readonly rawCount: number;
}
export function decodePullRequestHeadsJson(
/** One page of `actions/runs`. */
export function decodeWorkflowRunsJson(
raw: string,
): Result.Result<ReadonlyArray<GitHubPullRequestHead>, DecodeFailure> {
): Result.Result<GitHubWorkflowRunPage, DecodeFailure> {
const decoded = decodeWorkflowRuns(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
return Result.succeed({
runs: decoded.success.workflow_runs.map((run) => ({
id: run.id,
name: trimmed(run.name) ?? `Workflow run ${run.id}`,
url: trimmed(run.html_url),
})),
rawCount: decoded.success.workflow_runs.length,
});
}
/** Open pull requests whose head branch has one name, from whichever repository it lives in. */
export const PULL_REQUEST_HEADS_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $head: String!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequests(first: 100, after: $after, states: [OPEN], headRefName: $head) {
pageInfo { hasNextPage endCursor }
nodes { number headRefOid isCrossRepository headRepositoryOwner { login } }
}
}
}`;
export function decodePullRequestHeadsJson(raw: string): Result.Result<
{
readonly heads: ReadonlyArray<GitHubPullRequestHead>;
readonly nextCursor: string | null;
},
DecodeFailure
> {
const decoded = decodePullRequestHeads(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
return Result.succeed(
decoded.success.map((pullRequest) => ({
const connection = decoded.success.data.repository?.pullRequests;
return Result.succeed({
heads: (connection?.nodes ?? []).map((pullRequest) => ({
number: pullRequest.number,
headSha: pullRequest.headRefOid,
...(typeof pullRequest.isCrossRepository === "boolean"
@@ -2211,16 +2383,145 @@ export function decodePullRequestHeadsJson(
: {}),
headRepositoryOwner: trimmed(pullRequest.headRepositoryOwner?.login),
})),
);
nextCursor: nextCursorOf(connection?.pageInfo),
});
}
export interface GitHubPullRequestActivityPage {
/** Only on the first page, which is the one that asks for them. */
readonly author?: PullRequestActor | null;
readonly commits?: ReadonlyArray<PullRequestCommit>;
/** Issue comments and reviews, each list unsorted. */
readonly remarks: ReadonlyArray<PullRequestComment>;
readonly nextCommentsCursor: string | null;
readonly nextReviewsCursor: string | null;
}
/** One page of `PULL_REQUEST_ACTIVITY_GRAPHQL_QUERY`. */
export function decodePullRequestActivityJson(
raw: string,
): Result.Result<GitHubPullRequestActivity, DecodeFailure> {
): Result.Result<GitHubPullRequestActivityPage, DecodeFailure> {
const decoded = decodeActivity(raw);
return Result.isSuccess(decoded)
? Result.succeed(toActivity(decoded.success))
: Result.fail(decoded.failure);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
const pr = decoded.success.data.repository.pullRequest;
return Result.succeed({
...(pr.author === undefined ? {} : { author: toActor(pr.author) }),
...(pr.commits === undefined
? {}
: {
commits: toCommits(
(pr.commits?.nodes ?? []).map(({ commit }) => ({
...commit,
authors: (commit.authors?.nodes ?? []).map((author) => ({
...author,
login: author.user?.login ?? null,
})),
})),
),
}),
remarks: toComments({
comments: pr.comments?.nodes ?? [],
reviews: pr.reviews?.nodes ?? [],
}),
nextCommentsCursor: nextCursorOf(pr.comments?.pageInfo),
nextReviewsCursor: nextCursorOf(pr.reviews?.pageInfo),
});
}
/** Every check context of the head commit, a page at a time, for a rollup past one page. */
export const pullRequestCheckContextsGraphQlQuery = (host: string) =>
`query($owner: String!, $name: String!, $number: Int!, $after: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
headRefOid
commits(last: 1) {
nodes { commit { statusCheckRollup { contexts(first: 100, after: $after) {
${checkContextNodesSelection(host)}
pageInfo { hasNextPage endCursor }
} } } }
}
}
}
}`;
const RawCheckContextNodeSchema = Schema.Struct({
...RawCheckSchema.fields,
checkSuite: Schema.optional(
Schema.NullOr(
Schema.Struct({
workflowRun: Schema.NullOr(
Schema.Struct({ workflow: Schema.NullOr(Schema.Struct({ name: Schema.String })) }),
),
}),
),
),
});
const decodeCheckContexts = decodeJsonResult(
Schema.Struct({
data: Schema.Struct({
repository: Schema.Struct({
pullRequest: Schema.Struct({
headRefOid: Schema.String,
commits: Schema.Struct({
nodes: Schema.Array(
Schema.Struct({
commit: Schema.Struct({
statusCheckRollup: Schema.NullOr(
Schema.Struct({
contexts: Schema.Struct({
nodes: Schema.Array(RawCheckContextNodeSchema),
pageInfo: RawPageInfoSchema,
}),
}),
),
}),
}),
),
}),
}),
}),
}),
}),
);
/** A check context as the rollup reports it; opaque outside this module. */
export type GitHubCheckContext = Schema.Schema.Type<typeof RawCheckSchema>;
function toCheckContexts(
nodes: ReadonlyArray<Schema.Schema.Type<typeof RawCheckContextNodeSchema>>,
): ReadonlyArray<GitHubCheckContext> {
return nodes.map((check) => ({
...check,
workflowName: check.checkSuite?.workflowRun?.workflow?.name ?? null,
}));
}
export function decodePullRequestCheckContextsJson(raw: string): Result.Result<
{
readonly headSha: string;
readonly contexts: ReadonlyArray<GitHubCheckContext>;
readonly nextCursor: string | null;
},
DecodeFailure
> {
const decoded = decodeCheckContexts(raw);
if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);
const pr = decoded.success.data.repository.pullRequest;
const contexts = pr.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
return Result.succeed({
headSha: pr.headRefOid,
contexts: toCheckContexts(contexts?.nodes ?? []),
nextCursor: nextCursorOf(contexts?.pageInfo),
});
}
/** The checks and their one-word verdict, from every context of the head commit. */
export function pullRequestChecksFromContexts(contexts: ReadonlyArray<GitHubCheckContext>): {
readonly checks: ReadonlyArray<PullRequestCheck>;
readonly checksState: PullRequestChecksState | null;
} {
return { checks: toChecks(contexts), checksState: rollupChecksState(contexts) };
}
export interface GitHubReviewThreadComments {
@@ -2778,17 +3079,15 @@ const ReviewerRequestSchema = Schema.Struct({
team_reviewers: Schema.Array(Schema.String),
});
const encodeReviewerRequest = Schema.encodeSync(Schema.fromJsonString(ReviewerRequestSchema));
export function buildReviewerRequestJson(
export function buildReviewerRequest(
reviewers: ReadonlyArray<{ readonly id: string; readonly kind: PullRequestReviewerKind }>,
): string {
return encodeReviewerRequest({
): typeof ReviewerRequestSchema.Type {
return {
reviewers: reviewers.flatMap((reviewer) => (reviewer.kind === "user" ? [reviewer.id] : [])),
team_reviewers: reviewers.flatMap((reviewer) =>
reviewer.kind === "team" ? [reviewer.id] : [],
),
});
};
}
export const LABEL_CANDIDATES_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
@@ -2876,12 +3175,10 @@ export function decodeLabelCandidatesJson(
}
/** The body of `POST /repos/{owner}/{repo}/issues/{number}/labels`, which adds to what is there. */
const LabelRequestSchema = Schema.Struct({ labels: Schema.Array(Schema.String) });
const encodeLabelRequest = Schema.encodeSync(Schema.fromJsonString(LabelRequestSchema));
export function buildLabelRequestJson(labels: ReadonlyArray<string>): string {
return encodeLabelRequest({ labels });
export function buildLabelRequest(labels: ReadonlyArray<string>): {
readonly labels: ReadonlyArray<string>;
} {
return { labels };
}
/**
@@ -2965,14 +3262,28 @@ export interface GitHubPullRequestFilesPatch {
export function decodePullRequestFilesJson(
raw: string,
): Result.Result<GitHubPullRequestFilesPatch, DecodeFailure> {
const decoded = decodeUnknownList(raw);
if (!Result.isSuccess(decoded)) {
return Result.fail(decoded.failure);
}
return Result.map(decodeUnknownList(raw), toFilesPatch);
}
/**
* The files of one commit, which the commit endpoint lists and pages the same way, only wrapped
* in an object. An empty commit carries no `files` at all, which is a commit with nothing in it.
*/
export function decodeCommitFilesJson(
raw: string,
): Result.Result<GitHubPullRequestFilesPatch, DecodeFailure> {
return Result.map(decodeCommitFiles(raw), (commit) => toFilesPatch(commit.files ?? []));
}
const decodeCommitFiles = decodeJsonResult(
Schema.Struct({ files: Schema.optional(Schema.NullOr(Schema.Array(Schema.Unknown))) }),
);
function toFilesPatch(entries: ReadonlyArray<unknown>): GitHubPullRequestFilesPatch {
const sections: string[] = [];
const omittedFileStats: PullRequestOmittedFileStat[] = [];
let truncated = false;
for (const entry of decoded.success) {
for (const entry of entries) {
const file = decodeFileEntry(entry);
if (Exit.isFailure(file)) continue;
const value = file.value;
@@ -3009,12 +3320,12 @@ export function decodePullRequestFilesJson(
].join("\n");
sections.push(hunks.length === 0 ? `${header}\n` : `${header}\n${hunks.replace(/\n?$/, "\n")}`);
}
return Result.succeed({
return {
patch: sections.join(""),
truncated,
rawCount: decoded.success.length,
rawCount: entries.length,
omittedFileStats,
});
};
}
/**
@@ -2,15 +2,62 @@ import { expect, it } from "@effect/vitest";
import * as Layer from "effect/Layer";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/process";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import { runGitHubStackAction as runStackAction } from "./githubStackActions.ts";
const runGitHubStackAction = (
execute: GitHubCli.GitHubCli["Service"]["execute"],
input: Parameters<typeof runStackAction>[0],
) => runStackAction(input).pipe(Effect.provide(Layer.mock(GitHubCli.GitHubCli)({ execute })));
/**
* One request as the fake saw it, flattened to words: the path or document, then each variable
* or body field as `name=value`, so an assertion reads as "this request carried that value".
*/
type Call = ReadonlyArray<string>;
type Send = (
call: Call,
kind: "graphql" | "rest",
) => Effect.Effect<string, GitHubApi.GitHubApiError>;
const runGitHubStackAction = (send: Send, input: Parameters<typeof runStackAction>[0]) =>
runStackAction(input).pipe(
Effect.provide(
Layer.mock(GitHubApi.GitHubApi)({
graphql: (request) => {
// GitHub refuses a document that declares a variable it never uses.
const declared = [...request.query.matchAll(/\$(\w+)\s*:/g)].map((match) => match[1]!);
const unused = declared.filter(
(name) => !new RegExp(`\\$${name}(?!\\w)(?!\\s*:)`).test(request.query),
);
if (unused.length > 0) {
return Effect.die(new Error(`Variables declared but not used: ${unused.join(", ")}`));
}
return send(words(request.query, request.variables), "graphql");
},
rest: (request) =>
send(words(request.path, request.body), "rest").pipe(
Effect.map((body) => ({
status: 200,
headers: {},
body,
truncated: false,
invalidUtf8: false,
})),
),
}),
),
);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
function words(head: string, fields: unknown): Call {
return [
head,
...Object.entries((fields ?? {}) as Record<string, unknown>).map(
([key, value]) => `${key}=${typeof value === "string" ? value : encodeJson(value)}`,
),
];
}
const isMutation = (call: Call) => call[0]!.startsWith("mutation");
const stack = [
{
@@ -71,21 +118,13 @@ const rebased = {
const rebaseResponses = [branch(2, "bbb"), rebased, branch(3, "ccc", 1, ["rebased-sha"]), rebased];
function fake(responses: readonly unknown[]) {
const calls: ReadonlyArray<string>[] = [];
const execute: GitHubCli.GitHubCli["Service"]["execute"] = (request) =>
const calls: Call[] = [];
const execute: Send = (call) =>
Effect.sync(() => {
calls.push(request.args);
calls.push(call);
const value = responses[calls.length - 1];
if (value === undefined) throw new Error("Unexpected GitHub request");
return {
exitCode: ChildProcessSpawner.ExitCode(0),
// @effect-diagnostics-next-line preferSchemaOverJson:off
stdout: JSON.stringify(value),
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
stdoutInvalidUtf8: false,
};
return encodeJson(value);
});
return { execute, calls };
}
@@ -215,29 +254,25 @@ it.effect("rebases unmerged layers bottom to top without local git commands", ()
Effect.gen(function* () {
const api = fake([stack, access, ...rebaseResponses]);
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
const mutations = api.calls.filter((args) =>
args.some((arg) => arg.startsWith("query=mutation")),
);
const mutations = api.calls.filter(isMutation);
expect(mutations).toHaveLength(2);
expect(mutations[0]).toContain("id=PR_2");
expect(mutations[0]).toContain("sha=bbb");
expect(mutations[1]).toContain("id=PR_3");
expect(mutations[1]).toContain("sha=ccc");
expect(api.calls.every((args) => args[0] === "api")).toBe(true);
}),
);
it.effect("does not update later layers after a rebase failure", () =>
Effect.gen(function* () {
const api = fake([stack, access, branch(2, "bbb")]);
const execute: typeof api.execute = (request) =>
!request.args.some((arg) => arg.startsWith("query=mutation"))
? api.execute(request)
const execute: Send = (call, kind) =>
!isMutation(call)
? api.execute(call, kind)
: Effect.fail(
new GitHubCli.GitHubCliAuthenticationError({
command: "gh",
cwd: "/repo",
cause: new Error("denied"),
new GitHubApi.GitHubApiAuthenticationError({
host: "github.com",
operation: "runGitHubStackAction",
}),
);
const result = yield* runGitHubStackAction(execute, { ...input, action: "update-branch" }).pipe(
@@ -272,7 +307,6 @@ it.effect("refuses the entire rebase before mutation when a later fork denies wr
failure: { _tag: "GitHubStackPermissionError" },
});
expect(api.calls).toHaveLength(2);
expect(api.calls.every((args) => args[0] === "api")).toBe(true);
}),
);
@@ -333,9 +367,7 @@ it.effect("skips current layers without submitting a rebase mutation", () =>
Effect.gen(function* () {
const api = fake([stack, access, branch(2, "bbb", 0), branch(3, "ccc", 0, ["bbb"])]);
yield* runGitHubStackAction(api.execute, { ...input, action: "update-branch" });
expect(api.calls.some((args) => args.some((arg) => arg.startsWith("query=mutation")))).toBe(
false,
);
expect(api.calls.some((args) => isMutation(args))).toBe(false);
}),
);
@@ -380,9 +412,7 @@ it.effect("reports partial progress when a later head changes during the rebase"
if (result._tag === "Failure") {
expect(result.failure.message).toContain("Earlier updates remain on GitHub");
}
expect(
api.calls.filter((args) => args.some((arg) => arg.startsWith("query=mutation"))),
).toHaveLength(1);
expect(api.calls.filter((args) => isMutation(args))).toHaveLength(1);
}),
);
@@ -403,11 +433,7 @@ it.effect.each([false, true])("rejects a push to a processed layer, rebased=%s",
_tag: "Failure",
failure: { _tag: "GitHubStackChangedError", number: 2, completed: 1 },
});
expect(api.calls.at(-1)?.some((arg) => arg.includes('processed:nodes(ids:["PR_2"])'))).toBe(
true,
);
expect(
api.calls.filter((args) => args.some((arg) => arg.startsWith("query=mutation"))),
).toHaveLength(rebasedParent ? 1 : 0);
expect(api.calls.at(-1)?.includes('ids=["PR_2"]')).toBe(true);
expect(api.calls.filter((args) => isMutation(args))).toHaveLength(rebasedParent ? 1 : 0);
}),
);
+57 -120
View File
@@ -8,7 +8,7 @@ import * as Clock from "effect/Clock";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
import * as GitHubApi from "../sourceControl/GitHubApi.ts";
import { decodePullRequestStacksJson } from "./gitHubPullRequestJson.ts";
const stackErrorIdentity = {
@@ -21,10 +21,6 @@ export class GitHubStackChangedError extends Schema.TaggedError<GitHubStackChang
"GitHubStackChangedError",
{ ...stackErrorIdentity, completed: Schema.Int },
) {
get detail(): string {
return this.message;
}
override get message(): string {
return this.completed > 0
? `The stack changed at PR #${this.number} after ${this.completed} layers. Earlier updates remain on GitHub. Refresh it before trying again.`
@@ -36,10 +32,6 @@ export class GitHubStackUnsupportedError extends Schema.TaggedError<GitHubStackU
"GitHubStackUnsupportedError",
stackErrorIdentity,
) {
get detail(): string {
return this.message;
}
override get message(): string {
return "This operation is not supported for this stack.";
}
@@ -49,10 +41,6 @@ export class GitHubStackResponseInvalidError extends Schema.TaggedError<GitHubSt
"GitHubStackResponseInvalidError",
{ ...stackErrorIdentity, cause: Schema.optional(Schema.Defect()) },
) {
get detail(): string {
return this.message;
}
override get message(): string {
return "GitHub returned an unreadable stack operation response.";
}
@@ -62,10 +50,6 @@ export class GitHubStackMergeRejectedError extends Schema.TaggedError<GitHubStac
"GitHubStackMergeRejectedError",
{ ...stackErrorIdentity, cause: Schema.Defect() },
) {
get detail(): string {
return this.message;
}
override get message(): string {
return "GitHub refused the stack merge. Check the stack's branch rules and merge requirements.";
}
@@ -75,10 +59,6 @@ export class GitHubStackMergePendingError extends Schema.TaggedError<GitHubStack
"GitHubStackMergePendingError",
stackErrorIdentity,
) {
get detail(): string {
return this.message;
}
override get message(): string {
return "The merge is still running on GitHub. Check its status there before submitting another request.";
}
@@ -88,10 +68,6 @@ export class GitHubStackPermissionError extends Schema.TaggedError<GitHubStackPe
"GitHubStackPermissionError",
stackErrorIdentity,
) {
get detail(): string {
return this.message;
}
override get message(): string {
return "You cannot update every branch in this stack. Check write access and fork maintainer permissions before retrying.";
}
@@ -101,10 +77,6 @@ export class GitHubStackRebaseFailedError extends Schema.TaggedError<GitHubStack
"GitHubStackRebaseFailedError",
{ ...stackErrorIdentity, completed: Schema.Int, cause: Schema.Defect() },
) {
get detail(): string {
return this.message;
}
override get message(): string {
return `Stack rebase stopped at PR #${this.number} after ${this.completed} layers. Earlier updates remain on GitHub; resolve the failing layer before retrying.`;
}
@@ -179,8 +151,6 @@ const decodeRebaseResponse = Schema.decodeEffect(
),
);
const encodeNodeIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String)));
const decodeMergeResponse = Schema.decodeEffect(Schema.fromJsonString(MergeResponse));
/** Remote-only updates: a stack rebase never switches or rewrites the environment's checkout. */
@@ -194,7 +164,7 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
action: PullRequestAction;
mergeMethod?: PullRequestMergeMethod;
}) {
const github = yield* GitHubCli.GitHubCli;
const api = yield* GitHubApi.GitHubApi;
const identity = {
repository: input.repository,
number: input.number,
@@ -203,11 +173,12 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
if (input.action !== "merge" && input.action !== "update-branch")
return yield* new GitHubStackUnsupportedError({ ...identity });
const endpoint = `repos/${input.repository}`;
const read = yield* github.execute({
cwd: input.cwd,
args: ["api", "--hostname", input.host, `${endpoint}/stacks?pull_request=${input.number}`],
const read = yield* api.rest({
host: input.host,
operation: "runGitHubStackAction",
path: `${endpoint}/stacks?pull_request=${input.number}`,
});
const decoded = decodePullRequestStacksJson(read.stdout);
const decoded = decodePullRequestStacksJson(read.body);
if (Result.isFailure(decoded))
return yield* new GitHubStackResponseInvalidError({ ...identity, cause: decoded.failure });
const stack = decoded.success;
@@ -243,27 +214,19 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
return yield* new GitHubStackUnsupportedError({ ...identity });
if (input.action === "update-branch") {
const [owner, name] = input.repository.split("/");
const permissions = yield* github.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
"graphql",
"-f",
`owner=${owner}`,
"-f",
`name=${name}`,
"-f",
`query=query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${open
.map(
(layer) =>
`pr${layer.number}:pullRequest(number:${layer.number}){headRepository{viewerPermission} maintainerCanModify}`,
)
.join(" ")}}}`,
],
const permissions = yield* api.graphql({
host: input.host,
operation: "runGitHubStackAction",
allowReserve: true,
variables: { owner, name },
query: `query($owner:String!,$name:String!){repository(owner:$owner,name:$name){${open
.map(
(layer) =>
`pr${layer.number}:pullRequest(number:${layer.number}){headRepository{viewerPermission} maintainerCanModify}`,
)
.join(" ")}}}`,
});
const access = yield* decodeBranchAccess(permissions.stdout).pipe(
const access = yield* decodeBranchAccess(permissions).pipe(
Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })),
);
// viewerCanUpdateBranch is false for an already-current layer, even if rebasing its parent
@@ -282,35 +245,27 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
const processed: Array<{ id: string; number: number; headSha: string }> = [];
for (const [index, layer] of open.entries()) {
yield* Effect.gen(function* () {
const read = yield* github.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
"graphql",
"-f",
`owner=${owner}`,
"-f",
`name=${name}`,
"-F",
`number=${layer.number}`,
"-f",
`sha=${layer.headSha}`,
"-f",
`query=query($owner:String!,$name:String!,$number:Int!,$sha:String!){${
processed.length === 0
? ""
: `processed:nodes(ids:${encodeNodeIds(processed.map((head) => head.id))}){... on PullRequest{headRefOid}}`
} repository(owner:$owner,name:$name){pullRequest(number:$number){id headRefOid baseRef{compare(headRef:$sha){behindBy}}}}}`,
],
const read = yield* api.graphql({
host: input.host,
operation: "runGitHubStackAction",
allowReserve: true,
variables: {
owner,
name,
number: layer.number,
sha: layer.headSha,
ids: processed.map((head) => head.id),
},
// GitHub rejects a declared variable the document never uses, so `$ids` is always
// selected; an empty list asks for nothing.
query: `query($owner:String!,$name:String!,$number:Int!,$sha:String!,$ids:[ID!]!){processed:nodes(ids:$ids){... on PullRequest{headRefOid}} repository(owner:$owner,name:$name){pullRequest(number:$number){id headRefOid baseRef{compare(headRef:$sha){behindBy}}}}}`,
});
const {
data: {
processed: observed,
repository: { pullRequest: pr },
},
} = yield* decodeRebaseBranch(read.stdout);
} = yield* decodeRebaseBranch(read);
// A push to an earlier layer must not silently become the next layer's new base.
const changed = processed.find(
(head, index) => observed?.[index]?.headRefOid !== head.headSha,
@@ -332,22 +287,14 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
return;
}
// Pass the reviewed revision to GitHub, including when a push races this read.
const updated = yield* github.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
"graphql",
"-f",
`id=${pr.id}`,
"-f",
`sha=${layer.headSha}`,
"-f",
"query=mutation($id:ID!,$sha:GitObjectID!){updatePullRequestBranch(input:{pullRequestId:$id,expectedHeadOid:$sha,updateMethod:REBASE}){pullRequest{headRefOid}}}",
],
const updated = yield* api.graphql({
host: input.host,
operation: "runGitHubStackAction",
variables: { id: pr.id, sha: layer.headSha },
query:
"mutation($id:ID!,$sha:GitObjectID!){updatePullRequestBranch(input:{pullRequestId:$id,expectedHeadOid:$sha,updateMethod:REBASE}){pullRequest{headRefOid}}}",
});
const response = yield* decodeRebaseResponse(updated.stdout);
const response = yield* decodeRebaseResponse(updated);
processed.push({
id: pr.id,
number: layer.number,
@@ -374,24 +321,18 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
decodeMergeResponse(raw).pipe(
Effect.mapError((cause) => new GitHubStackResponseInvalidError({ ...identity, cause })),
);
const request = yield* github.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
"--method",
"PUT",
`${endpoint}/pulls/${input.number}/merge-async`,
"-f",
`merge_method=${input.mergeMethod ?? "merge"}`,
"-f",
"merge_action=default",
"-f",
`sha=${target.headSha}`,
],
const request = yield* api.rest({
host: input.host,
operation: "runGitHubStackAction",
method: "PUT",
path: `${endpoint}/pulls/${input.number}/merge-async`,
body: {
merge_method: input.mergeMethod ?? "merge",
merge_action: "default",
sha: target.headSha,
},
});
let result = yield* decode(request.stdout);
let result = yield* decode(request.body);
const deadline = (yield* Clock.currentTimeMillis) + 5 * 60_000;
for (
let attempt = 0;
@@ -401,16 +342,12 @@ export const runGitHubStackAction = Effect.fn("runGitHubStackAction")(function*
const uuid = result.details.uuid;
if (!uuid) return yield* new GitHubStackResponseInvalidError({ ...identity });
yield* Effect.sleep(Math.min(1_000 * 2 ** attempt, 10_000));
const poll = yield* github.execute({
cwd: input.cwd,
args: [
"api",
"--hostname",
input.host,
`${endpoint}/pulls/${input.number}/merge-async/${encodeURIComponent(uuid)}`,
],
const poll = yield* api.rest({
host: input.host,
operation: "runGitHubStackAction",
path: `${endpoint}/pulls/${input.number}/merge-async/${encodeURIComponent(uuid)}`,
});
result = yield* decode(poll.stdout);
result = yield* decode(poll.body);
}
if (result.status === "pending") return yield* new GitHubStackMergePendingError({ ...identity });
if (result.status === "failed")
+8 -2
View File
@@ -117,6 +117,8 @@ export interface GitHubRestResponse {
readonly headers: Readonly<Record<string, string | undefined>>;
readonly body: string;
readonly truncated: boolean;
/** The body was not valid UTF-8, which a raw file read takes to mean binary. */
readonly invalidUtf8: boolean;
}
export interface GitHubRestInput {
@@ -131,6 +133,8 @@ export interface GitHubRestInput {
/** Revalidates a cached answer. A 304 is returned rather than failed, and is free. */
readonly ifNoneMatch?: string;
readonly maxResponseBytes?: number;
/** Defaults to 30 seconds; a whole pull request's patch may need longer. */
readonly timeout?: Duration.Input;
/** Overrides `AllowGitHubReserve` for this one request. */
readonly allowReserve?: boolean;
}
@@ -381,11 +385,11 @@ export const make = Effect.gen(function* () {
readonly operation: string;
readonly request: HttpClientRequest.HttpClientRequest;
readonly maxResponseBytes: number;
readonly timeout?: Duration.Input | undefined;
readonly allowReserve: boolean;
readonly acceptNotModified: boolean;
/** Reads the body for GraphQL `errors`, which GitHub sends with HTTP 200. */
readonly graphql?: boolean;
readonly timeout?: Duration.Duration | undefined;
}) {
const host = normalizeHost(input.host);
// Only the path: a query string can carry a SHA or a branch, and never needs to be in a trace.
@@ -435,7 +439,7 @@ export const make = Effect.gen(function* () {
// 204, 304 and many refusals carry no body at all, which is an empty answer.
Effect.catchIf(
(error) => error.reason._tag === "EmptyBodyError",
() => Effect.succeed({ text: "", truncated: false }),
() => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
),
);
return { response, collected };
@@ -468,6 +472,7 @@ export const make = Effect.gen(function* () {
headers,
body: collected.text,
truncated: collected.truncated,
invalidUtf8: collected.invalidUtf8,
}),
),
RateLimited: () =>
@@ -526,6 +531,7 @@ export const make = Effect.gen(function* () {
operation: input.operation,
request,
maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
timeout: input.timeout,
allowReserve: input.allowReserve ?? interactive,
acceptNotModified: input.ifNoneMatch !== undefined,
}),
+1 -4
View File
@@ -38,10 +38,7 @@ const DEFAULT_TIMEOUT_MS = 30_000;
/** Server-local credential scope; never put its value in RPC payloads or cache keys. */
export const PinnedGitHubCredential = GitHubApi.PinnedGitHubCredential;
export const AllowGitHubReserve = Context.Reference<boolean>(
"t3/sourceControl/AllowGitHubReserve",
{ defaultValue: () => false },
);
export const AllowGitHubReserve = GitHubApi.AllowGitHubReserve;
function commandHosts(args: ReadonlyArray<string>): Array<string | null> {
const hosts: Array<string | null> = [];