feat(server): source control, media and discovery use GitHub's API instead of gh #16321
Mergedjuliusmarmingemerged 9 commits into
t3code/github-api-pr-cli fromrefs/pull/16321/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge changed the title
- @@ -929,8 +782,16 @@782+ readonly allowReserve: boolean;783+ }) {784+ const locator = yield* resolveRepository({ cwd: input.cwd, host: input.rateLimitHost });785+ const limit = Math.min(Math.max(Math.trunc(input.limit), 1), 100);786+ // `owner:branch` names a fork's branch. GitHub filters on the branch name only, so the787+ // owner is matched on the rows it returns.788+ const ownerMatch = /^([^:/\s]+):(.+)$/u.exec(input.headSelector.trim());789+ const headRefName = ownerMatch?.[2] ?? input.headSelector.trim();790+ const rows = yield* Effect.request(929791 new PullRequestsByHeadRead({930792 cwd: input.cwd,931- host,932- owner: repository.owner,933- name: repository.name,934- headRefName: input.headSelector,793+ ...locator,794+ headRefName,935795 state: input.state,936- limit: Math.min(Math.max(Math.trunc(input.limit), 1), 100),796+ limit: ownerMatch ? OWNER_HEAD_SCAN_LIMIT : limit,797+ allowReserve: input.allowReserve,@@ -525,8 +533,13 @@525- const host = input.host.toLowerCase();526- const repositories = new Map<string, { readonly owner: string; readonly name: string }>();527- for (const line of input.remotes.split("\n")) {528- const match = /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim());529- if (!match) continue;530- const [remoteHost, owner, name, ...rest] = normalizeGitRemoteUrl(match[2]!).split("/");531- if (remoteHost !== host || !owner || !name || rest.length > 0) return null;532- repositories.set(match[1]!, { owner, name });533+export function parsePullRequestReference(534+ reference: string,535+):536+ | { readonly kind: "number"; readonly number: number }537+ | { readonly kind: "url"; readonly locator: GitHubRepositoryLocator; readonly number: number }538+ | { readonly kind: "branch"; readonly headSelector: string } {539+ const trimmed = reference.trim();540+ const numbered = /^#?([1-9]\d*)$/.exec(trimmed);541+ if (numbered) return { kind: "number", number: Number(numbered[1]) };542+ if (/^https?:\/\//i.test(trimmed)) {543+ try {544+ const url = new URL(trimmed);545+ const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)(?:\/.*)?$/.exec(url.pathname);@@ -146,4 +113,4 @@146113 requestHeaders: Record<string, string | undefined>,147114 ) {148115 // Both media hosts are served by github.com's account, which is the host `gh` stores it under.149- const token = yield* githubToken({ cwd: asset.cwd, host: "github.com" });116+ const token = yield* githubToken;apps/server/src/sourceControl/GitHubCli.ts lines 1078 to 1040OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1073 +1021,20 @@1073- execute({1021+ Effect.mapError(gitFailure(input.cwd)),1022+ );1023+1024+ yield* Effect.gen(function* () {1025+ if (!exists) yield* runGit(input.cwd, "branch", ["branch", localBranch, target.ref]);1026+ if (target.upstream !== null) {1027+ yield* git.setBranchUpstream({ cwd: input.cwd, branch: localBranch, ...target.upstream });1028+ }1029+ yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));1030+ if (exists) {1031+ yield* runGit(1032+ input.cwd,1033+ "sync",1034+ input.force === true1035+ ? ["reset", "--hard", "--quiet", target.ref]1036+ : ["merge", "--ff-only", "--quiet", target.ref],1037+ );1038+ }1039+ }).pipe(Effect.mapError(gitFailure(input.cwd)));1040+ });@@ -1064,6 +997,15 @@1064- ...(input.rateLimitHost === undefined ? {} : { rateLimitHost: input.rateLimitHost }),1065- args: ["repo", "view", "--json", "defaultBranchRef", "--jq", ".defaultBranchRef.name"],1066- }).pipe(1067- Effect.map((value) => {1068- const trimmed = value.stdout.trim();1069- return trimmed.length > 0 ? trimmed : null;997+ remoteName,998+ remoteBranch: pullRequest.headRefName,999+ });1000+ return {1001+ ref: `refs/remotes/${remoteName}/${pullRequest.headRefName}`,1002+ upstream: { remoteName, remoteBranch: pullRequest.headRefName },1003+ };1004+ }).pipe(1005+ Effect.catch(() =>1006+ Effect.gen(function* () {1007+ yield* runGit(input.cwd, "fetchPullRef", [1008+ "fetch",1009+ "--quiet",1010+ "--no-tags",1011+ yield* baseRemote,
- @@ -1076,0 +1058,21 @@1058+ Effect.gen(function* () {1059+ const fallbackHost = (yield* resolveRepository({ cwd: input.cwd }).pipe(1060+ Effect.map((locator) => locator.host),1061+ Effect.orElseSucceed(() => globalThis.process.env.GH_HOST ?? "github.com"),1062+ )).toLowerCase();1063+ const locator = parseGitHubRepositorySelector(input.repository, fallbackHost);1064+ if (locator === null) {1065+ return yield* commandFailure(input.cwd, "Repositories are named owner/name.");1066+ }1067+ return repositoryCloneUrls(yield* readRepository(input.cwd, locator));1068+ }),1069+ createRepository: (input) =>1070+ Effect.gen(function* () {1071+ const locator = parseGitHubRepositorySelector(1072+ input.repository,1073+ (globalThis.process.env.GH_HOST ?? "github.com").toLowerCase(),1074+ );1075+ const viewer = locator === null ? null : yield* readViewerLogin(input.cwd, locator.host);1076+ const owner = locator?.owner ?? viewer;1077+ const name = locator?.name ?? input.repository.trim();1078+ const host = locator?.host ?? "github.com";@@ -113,0 +133,21 @@133+ * GitHub is usable with a token from the environment or with `gh` to hand one over. An134+ * environment token is checked against the API, since `gh auth status` may not know it.135+ */136+export const makeDiscovery = Effect.gen(function* () {137+ const api = yield* GitHubApi.GitHubApi;138+ const process = yield* VcsProcess.VcsProcess;139+ return {140+ type: "managed-cli",141+ kind: discovery.kind,142+ label: discovery.label,143+ installHint: discovery.installHint,144+ probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {145+ const cli = yield* probeSourceControlProvider({ cwd, process, spec: discovery });146+ const variable = environmentTokenVariable();147+ if (variable === null) return cli;148+ const viewer = yield* api149+ .rest({ host: "github.com", operation: "discovery", path: "user" })150+ .pipe(Effect.result);151+ const login = Result.isSuccess(viewer)152+ ? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login153+ : undefined;
- @@ -1046,0 +892,21 @@892+ const headNameWithOwner = pullRequest.headRepositoryNameWithOwner ?? null;893+ const isCrossRepository =894+ pullRequest.isCrossRepository ??895+ (headNameWithOwner !== null && headNameWithOwner.toLowerCase() !== baseNameWithOwner);896+ const headOwner =897+ pullRequest.headRepositoryOwnerLogin ?? headNameWithOwner?.split("/")[0] ?? null;898+899+ const remotes = yield* gitRead(input.cwd, ["remote", "-v"]).pipe(900+ Effect.map((result) => (result.exitCode === 0 ? result.stdout : "")),901+ Effect.mapError(gitFailure(input.cwd)),902+ );903+ const remoteFor = (nameWithOwner: string) =>904+ remotes905+ .split("\n")906+ .map((line) => /^(\S+)\s+(\S+)\s+\(fetch\)$/u.exec(line.trim()))907+ .find(908+ (match) =>909+ match !== null &&910+ normalizeGitRemoteUrl(match[2]!).split("/").slice(1).join("/") ===911+ nameWithOwner.toLowerCase(),912+ )?.[1] ?? null;
- @@ -665,9 +566,12 @@665- ),666- ),667- );668- },669- {670- capacity: 32,671- timeToLive: (exit) => (Exit.isSuccess(exit) ? exit.value : Duration.minutes(1)),672- },673- );566+ const gitRead = (cwd: string, args: ReadonlyArray<string>) =>567+ process.run({568+ operation: "GitHubCli.resolveRepository",569+ command: "git",570+ args,571+ cwd,572+ allowNonZeroExit: true,573+ timeoutMs: 5_000,574+ });575+576+ const commandFailure = (cwd: string, detail: string) =>577+ new GitHubCliCommandError({ command: "gh", cwd, cause: new Error(detail) });
- @@ -129,14 +74,15 @@129- return `GitHub CLI failed in execute: ${this.detail}`;74+ return "Pull request not found. Check the PR number or URL and try again.";13075 }13176 }1327713378 export class GitHubCliCommandError extends Schema.TaggedError<GitHubCliCommandError>()(13479 "GitHubCliCommandError",13580 { ...gitHubCliFailureFields, httpStatus: Schema.optional(Schema.Int) },13681 ) {137- get detail(): string {138- return "GitHub CLI command failed.";139- }140-14182 override get message(): string {142- return `GitHub CLI failed in execute: ${this.detail}`;83+ // GitHub's own reason ("A pull request already exists…") or the failed step's, when known.84+ const reason =85+ this.cause instanceof Error && this.cause.message.trim() !== ""86+ ? this.cause.message.trim()87+ : null;88+ return reason === null ? "GitHub request failed." : reason;@@ -245 +149,20 @@245- }149+/** Maps a GitHub API failure onto the errors callers of this service already handle. */150+function fromGitHubApiError(cwd: string, error: GitHubApi.GitHubApiError): GitHubCliError {151+ const context = { command: "gh" as const, cwd, cause: error };152+ switch (error._tag) {153+ case "GitHubCliMissingError":154+ return new GitHubCliUnavailableError(context);155+ case "GitHubNotSignedInError":156+ case "GitHubApiAuthenticationError":157+ return new GitHubCliAuthenticationError(context);158+ case "GitHubCliFailedError":159+ return new GitHubCliCommandError(context);160+ case "GitHubApiRateLimitError":161+ return new GitHubCliRateLimitError({162+ ...context,163+ ...(error.retryAt === undefined ? {} : { retryAt: error.retryAt }),164+ });165+ case "SourceControlRateLimitPausedError":166+ return new GitHubCliRateLimitError({ ...context, retryAt: error.retryAt });167+ case "GitHubApiNotFoundError":168+ return new GitHubPullRequestNotFoundError(context);@@ -716,14 +555,7 @@716- credential?.credentialFingerprint ?? (yield* SourceControlRateLimit.CredentialScope),717- ),718- Effect.catchTags({719- SourceControlRateLimitPausedError: (cause) =>720- Effect.fail(721- new GitHubCliRateLimitError({722- command: "gh",723- cwd: input.cwd,724- retryAt: cause.retryAt,725- cause,726- }),727- ),728- }),729- );555+ readonly host?: string | undefined;556+ }) {557+ const envRepository = environment.GH_REPO?.trim();558+ const defaultHost = (input.host ?? environment.GH_HOST ?? "github.com").toLowerCase();559+ if (envRepository) {560+ const locator = parseGitHubRepositorySelector(envRepository, defaultHost);561+ if (locator !== null) return locator;
juliusmarminge merged this649418f
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
4007410· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.