Keep partial check details from replacing complete PR status (#38514)

* Keep PR check status tied to complete observations

* Correct checks presentation types and count import

* Preserve localized empty states and declared runtime support

* Correct discovery fixture stack types

* Omit empty failed-check subtitles

* Preserve check identity through refresh and row publication

* Withhold row identity for malformed check errors

* Limit local capability wakes to local task sources

* Correct PR check regression fixtures

* Preserve browser APIs in PR check regression fixture

* Settle PR check adoption after failed detail reads

* Use the parsed PR check detail type during refresh

* Preserve PR metadata across checks discovery and committed query lifetimes

* Keep complete checks proof separate from legacy publication policy

* Keep PR lookup fixtures independent from complete checks collection

* Keep complete-check fixtures within lint contracts

* test: align PR recordings with source check discovery
This commit is contained in:
Brennan Benson
2026-11-05 10:39:54 -08:00
committed by GitHub
parent 384b445585
commit dd1784f55b
128 changed files with 26893 additions and 19460 deletions
@@ -0,0 +1,26 @@
import type { GitHubApiRepository } from '../../github-api-repository'
import type { GhExecOptions } from '../github-exec-scope'
import { assertRateLimitBudget } from '../lookup/pr-lookup-rate-limit'
import { readGraphQLPRCheckRollup } from './pr-check-rollup'
import { readRestPRCheckRollup } from './rest-pr-check-pages'
export async function readCompletePRCheckObservation(
repository: GitHubApiRepository,
number: number,
headSha: string | undefined,
options: GhExecOptions
): Promise<unknown[] | undefined> {
if (!headSha) {
return undefined
}
try {
await assertRateLimitBudget('graphql', repository, options)
return await readGraphQLPRCheckRollup(repository, number, headSha, options)
} catch {
try {
return await readRestPRCheckRollup(repository, headSha, options)
} catch {
return undefined
}
}
}
+53 -72
View File
@@ -1,3 +1,4 @@
import { normalizePRCheckHeadSha } from '../../../../shared/github/pr-check-head'
import {
withGitHubRepoExecution,
githubRepoContext,
@@ -14,21 +15,21 @@ import { mapCheckStatus, mapCheckConclusion } from '../../mappers'
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
import type { GhExecOptions } from './../github-exec-scope'
import { assertRateLimitBudget } from './../lookup/pr-lookup-rate-limit'
import {
PR_CHECKS_ROLLUP_QUERY,
type GraphQLPRChecksResponse,
type RestCheckRun,
type RestCommitStatus,
type RestCheckSuite
} from './pr-checks-graphql-query'
import { PR_CHECKS_ROLLUP_QUERY, type GraphQLPRChecksResponse } from './pr-checks-graphql-query'
import {
mapRestCheckRun,
mapRestCommitStatus,
mapGraphQLPRChecksResponse,
getPendingApprovalCheckSuiteName,
getPendingApprovalCheckSuiteUrl
getPendingApprovalCheckSuiteUrl,
isPendingApprovalSuiteWithoutRuns
} from './pr-checks-response-mapping'
import { parseActionsRunId } from './check-detail-field-mapping'
import {
readRestPRCheckRuns,
readRestPRCommitStatuses,
readRestPRCheckSuites
} from './rest-pr-check-pages'
export async function getPRChecksViaRestFallback(
ownerRepo: GitHubApiRepository,
headSha: string | undefined,
@@ -38,82 +39,63 @@ export async function getPRChecksViaRestFallback(
if (!headSha) {
return null
}
try {
await assertRateLimitBudget('core', ownerRepo, ghOptions)
} catch (err) {
console.warn('getPRChecks skipped REST fallback, falling back to gh pr checks:', err)
return null
}
await acquire()
try {
const cacheArgs = noCache ? [] : ['--cache', '60s']
const encodedHeadSha = encodeURIComponent(headSha)
const { stdout } = await ghExecFileAsync(
[
'api',
...cacheArgs,
`repos/${ownerRepo.owner}/${ownerRepo.repo}/commits/${encodedHeadSha}/check-runs?per_page=100`
],
ghOptions
const runs = await readRestPRCheckRuns(ownerRepo, headSha, ghOptions, Boolean(noCache))
const checks = runs.map((run) =>
mapRestCheckRun({
...run,
name: run.name ?? '',
html_url: run.html_url ?? '',
details_url: run.details_url ?? null
})
)
noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions)
const checkRunData = JSON.parse(stdout) as {
check_runs?: RestCheckRun[]
}
const checkRuns = (checkRunData.check_runs ?? []).map(mapRestCheckRun)
const checkRunNames = new Set(checkRuns.map((check) => check.name))
let legacyStatuses: PRCheckDetail[] = []
const checkRunNames = new Set(checks.map((check) => check.name))
try {
const statusResult = await ghExecFileAsync(
[
'api',
...cacheArgs,
`repos/${ownerRepo.owner}/${ownerRepo.repo}/commits/${encodedHeadSha}/status?per_page=100`
],
ghOptions
const statuses = await readRestPRCommitStatuses(
ownerRepo,
headSha,
ghOptions,
Boolean(noCache)
)
checks.push(
...statuses
.map(mapRestCommitStatus)
.filter(
(check): check is PRCheckDetail => check !== null && !checkRunNames.has(check.name)
)
)
noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions)
const statusData = JSON.parse(statusResult.stdout) as {
statuses?: RestCommitStatus[]
}
legacyStatuses = (statusData.statuses ?? [])
.map(mapRestCommitStatus)
.filter((check): check is PRCheckDetail => check !== null && !checkRunNames.has(check.name))
} catch (err) {
// Keep richer check-run rows when best-effort legacy-status enrichment fails.
// Detail rows remain useful when best-effort enrichment fails.
console.warn('getPRChecks REST status fallback failed:', err)
}
let pendingApprovalChecks: PRCheckDetail[] = []
try {
const suitesResult = await ghExecFileAsync(
[
'api',
...cacheArgs,
`repos/${ownerRepo.owner}/${ownerRepo.repo}/commits/${encodedHeadSha}/check-suites?per_page=100`
],
ghOptions
const suites = await readRestPRCheckSuites(ownerRepo, headSha, ghOptions, Boolean(noCache))
const represented = new Set(
runs.flatMap((run) => (run.check_suite ? [run.check_suite.id] : []))
)
checks.push(
...suites
.filter((suite) =>
isPendingApprovalSuiteWithoutRuns(
suite.conclusion,
suite.id !== undefined && represented.has(suite.id)
)
)
.map((suite, index) => ({
name: getPendingApprovalCheckSuiteName(suite, headSha, index),
status: 'completed' as const,
conclusion: 'action_required' as const,
url: getPendingApprovalCheckSuiteUrl(ownerRepo, headSha, suite.id)
}))
)
noteRepositoryRateLimitSpend(ownerRepo, 'core', 1, ghOptions)
const suitesData = JSON.parse(suitesResult.stdout) as {
check_suites?: RestCheckSuite[]
}
pendingApprovalChecks = (suitesData.check_suites ?? [])
.filter((suite) => suite.conclusion?.toLowerCase() === 'action_required')
.map((suite, index) => ({
name: getPendingApprovalCheckSuiteName(suite, headSha, index),
status: 'completed' as const,
conclusion: 'action_required' as const,
url: getPendingApprovalCheckSuiteUrl(ownerRepo, headSha, suite.id)
}))
} catch (err) {
console.warn('getPRChecks REST check-suite fallback failed:', err)
}
const checks = [...checkRuns, ...legacyStatuses, ...pendingApprovalChecks]
return checks.length > 0 ? checks : null
const observedHeadSha = normalizePRCheckHeadSha(headSha)
return checks.length > 0
? checks.map((check) => (observedHeadSha ? { ...check, observedHeadSha } : check))
: null
} catch (err) {
console.warn('getPRChecks via REST fallback failed, falling back to gh pr checks:', err)
return null
@@ -132,7 +114,6 @@ async function readPRChecks(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRCheckDetail[]> {
void headSha
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
prRepo,
@@ -0,0 +1,223 @@
import { z } from 'zod'
import { ghExecFileAsync } from '../../gh-utils'
import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository'
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
import type { GhExecOptions } from '../github-exec-scope'
import { isPendingApprovalSuiteWithoutRuns } from './pr-checks-response-mapping'
type ConnectionKind = 'contexts' | 'suites'
export function prCheckRollupFields(kind?: ConnectionKind): string {
return `commits(last: 1) { nodes { commit {
oid
${
kind !== 'suites'
? `statusCheckRollup { contexts(first: 100, after: $checksCursor) {
nodes { __typename ... on CheckRun { status conclusion checkSuite { databaseId } }
... on StatusContext { state } }
pageInfo { hasNextPage endCursor }
} }`
: ''
}
${
kind !== 'contexts'
? `checkSuites(first: 100, after: $suitesCursor) {
nodes { databaseId conclusion }
pageInfo { hasNextPage endCursor }
}`
: ''
}
} } }`
}
const checkConclusion = z.enum([
'ACTION_REQUIRED',
'CANCELLED',
'FAILURE',
'NEUTRAL',
'SKIPPED',
'STALE',
'STARTUP_FAILURE',
'SUCCESS',
'TIMED_OUT'
])
const contextSchema = z.discriminatedUnion('__typename', [
z.object({
__typename: z.literal('CheckRun'),
status: z.enum(['COMPLETED', 'IN_PROGRESS', 'QUEUED', 'REQUESTED', 'WAITING', 'PENDING']),
conclusion: checkConclusion.nullable(),
checkSuite: z.object({ databaseId: z.number() })
}),
z.object({
__typename: z.literal('StatusContext'),
state: z.enum(['ERROR', 'EXPECTED', 'FAILURE', 'PENDING', 'SUCCESS'])
})
])
const connectionSchema = z.object({
nodes: z.array(contextSchema),
pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() })
})
export const prCheckRollupCommitsSchema = z.object({
nodes: z
.array(
z.object({
commit: z.object({
oid: z.string().min(1),
statusCheckRollup: z.object({ contexts: connectionSchema }).nullable().optional(),
checkSuites: z
.object({
nodes: z.array(
z.object({ databaseId: z.number(), conclusion: checkConclusion.nullable() })
),
pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() })
})
.optional()
})
})
)
.max(1)
})
type CheckCommits = z.infer<typeof prCheckRollupCommitsSchema>
type CheckPage = { number: number; headRefOid: string; commits: CheckCommits }
const pageSchema = z.object({
data: z.object({
repository: z.object({
pullRequest: z.object({
number: z.number(),
headRefOid: z.string(),
commits: prCheckRollupCommitsSchema
})
})
}),
errors: z.array(z.unknown()).optional()
})
export async function collectPRCheckRollup(
first: CheckPage,
readPage: (kind: ConnectionKind, cursor: string) => Promise<CheckPage>
): Promise<unknown[]> {
const initial = first.commits.nodes[0]?.commit
if (
!initial ||
initial.oid !== first.headRefOid ||
!initial.checkSuites ||
initial.statusCheckRollup === undefined
) {
throw new Error('Incomplete PR checks observation')
}
const collect = async (kind: ConnectionKind) => {
const connection = (commit: typeof initial) =>
kind === 'contexts' ? commit.statusCheckRollup?.contexts : commit.checkSuites
let page = connection(initial)
const nodes: Record<string, unknown>[] = [...(page?.nodes ?? [])]
const cursors = new Set<string>()
while (page?.pageInfo.hasNextPage) {
const cursor = page.pageInfo.endCursor
if (!cursor || cursors.has(cursor)) {
throw new Error('Incomplete PR checks continuation')
}
cursors.add(cursor)
const next = await readPage(kind, cursor)
const commit = next.commits.nodes[0]?.commit
if (
next.number !== first.number ||
next.headRefOid !== first.headRefOid ||
!commit ||
commit.oid !== initial.oid
) {
throw new Error('PR head changed during checks observation')
}
page = connection(commit)
if (!page) {
throw new Error('Missing PR checks continuation')
}
nodes.push(...page.nodes)
}
return nodes
}
const contexts = await collect('contexts')
const suites = await collect('suites')
const representedSuites = new Set(
contexts.flatMap((context) => {
const suite = context.checkSuite
return context.__typename === 'CheckRun' &&
typeof suite === 'object' &&
suite !== null &&
'databaseId' in suite &&
typeof suite.databaseId === 'number'
? [suite.databaseId]
: []
})
)
return [
...contexts,
...suites
.filter((suite) =>
isPendingApprovalSuiteWithoutRuns(
suite.conclusion,
typeof suite.databaseId === 'number' && representedSuites.has(suite.databaseId)
)
)
.map(() => ({ status: 'COMPLETED', conclusion: 'ACTION_REQUIRED' }))
]
}
export function createPRCheckRollupPageReader(
repository: GitHubApiRepository,
number: number,
options: GhExecOptions
): (kind?: ConnectionKind, cursor?: string) => Promise<CheckPage> {
return async (kind, cursor) => {
const cursors = [
...(kind !== 'suites' ? ['$checksCursor: String'] : []),
...(kind !== 'contexts' ? ['$suitesCursor: String'] : [])
].join(', ')
const query = `query($owner: String!, $repo: String!, $number: Int!,
${cursors}) {
repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
number headRefOid ${prCheckRollupFields(kind)}
} }
}`
const args = [
'api',
'graphql',
'-f',
`query=${query}`,
'-f',
`owner=${repository.owner}`,
'-f',
`repo=${repository.repo}`,
'-F',
`number=${number}`
]
if (cursor) {
args.push('-f', `${kind === 'suites' ? 'suitesCursor' : 'checksCursor'}=${cursor}`)
}
noteRepositoryRateLimitSpend(repository, 'graphql', 1, options)
const { stdout } = await ghExecFileAsync(args, {
...options,
...githubHostExecOptions(repository)
})
const page = pageSchema.parse(JSON.parse(stdout))
if (page.errors?.length) {
throw new Error('Incomplete PR checks response')
}
return page.data.repository.pullRequest
}
}
export async function readGraphQLPRCheckRollup(
repository: GitHubApiRepository,
number: number,
headSha: string,
options: GhExecOptions
): Promise<unknown[]> {
const readPage = createPRCheckRollupPageReader(repository, number, options)
const first = await readPage()
if (first.number !== number || first.headRefOid !== headSha) {
throw new Error('PR head changed before checks observation')
}
return collectPRCheckRollup(first, readPage)
}
@@ -6,6 +6,7 @@ query($owner: String!, $repo: String!, $pr: Int!) {
commits(last: 1) {
nodes {
commit {
oid
statusCheckRollup {
contexts(first: 100) {
nodes {
@@ -53,6 +54,8 @@ query($owner: String!, $repo: String!, $pr: Int!) {
`
export type GraphQLPRChecksResponse = {
errors?: unknown[]
data?: {
repository?: {
pullRequest?: {
@@ -66,6 +69,8 @@ export type GraphQLPRChecksResponse = {
}
export type GraphQLPRChecksCommit = {
oid?: string | null
statusCheckRollup?: {
contexts?: {
nodes?: GraphQLStatusCheckContext[] | null
@@ -1,3 +1,4 @@
import { normalizePRCheckHeadSha } from '../../../../shared/github/pr-check-head'
import type { PRCheckDetail } from '../../../../shared/github/check-types'
import { githubRepositoryWebHost, type GitHubApiRepository } from '../../github-api-repository'
import {
@@ -107,6 +108,12 @@ export function mapGraphQLPendingApprovalCheckSuite(
}
}
export function isPendingApprovalSuiteWithoutRuns(conclusion: unknown, hasRuns: boolean): boolean {
return (
typeof conclusion === 'string' && conclusion.toLowerCase() === 'action_required' && !hasRuns
)
}
export function mapGraphQLPRChecksResponse(
ownerRepo: GitHubApiRepository,
response: GraphQLPRChecksResponse
@@ -137,16 +144,28 @@ export function mapGraphQLPRChecksResponse(
.map(mapGraphQLStatusContext)
.filter((check): check is PRCheckDetail => check !== null && !checkRunNames.has(check.name))
const pendingApprovalChecks = (commit.checkSuites?.nodes ?? [])
.filter((suite) => suite.conclusion?.toLowerCase() === 'action_required')
.filter((suite) => {
const suiteId = nullableNumber(suite.databaseId)
return suiteId === null || !checkSuiteIdsWithRuns.has(suiteId)
return isPendingApprovalSuiteWithoutRuns(
suite.conclusion,
suiteId !== null && checkSuiteIdsWithRuns.has(suiteId)
)
})
.map((suite, index) =>
mapGraphQLPendingApprovalCheckSuite(ownerRepo, suite, pullRequest.headRefOid, index)
)
return [...checkRuns, ...legacyStatuses, ...pendingApprovalChecks]
const observedHeadSha = normalizePRCheckHeadSha(commit.oid)
const provedHead =
observedHeadSha &&
observedHeadSha === normalizePRCheckHeadSha(pullRequest.headRefOid) &&
(response.errors === undefined ||
(Array.isArray(response.errors) && response.errors.length === 0))
? observedHeadSha
: undefined
return [...checkRuns, ...legacyStatuses, ...pendingApprovalChecks].map((check) =>
provedHead ? { ...check, observedHeadSha: provedHead } : check
)
}
export function getPendingApprovalCheckSuiteName(
@@ -0,0 +1,135 @@
import { z } from 'zod'
import { ghExecFileAsync } from '../../gh-utils'
import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository'
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
import type { GhExecOptions } from '../github-exec-scope'
import { assertRateLimitBudget } from '../lookup/pr-lookup-rate-limit'
import { isPendingApprovalSuiteWithoutRuns } from './pr-checks-response-mapping'
const checkRunSchema = z.object({
id: z.number().optional(),
name: z.string().optional(),
status: z.string(),
conclusion: z.string().nullable(),
html_url: z.string().nullish(),
details_url: z.string().nullish(),
check_suite: z.object({ id: z.number() }).nullish()
})
const commitStatusSchema = z.object({
context: z.string().optional(),
state: z.string(),
target_url: z.string().nullish()
})
const checkSuiteSchema = z.object({
id: z.number().optional(),
status: z.string().nullable(),
conclusion: z.string().nullable(),
app: z.object({ name: z.string().nullish(), slug: z.string().nullish() }).nullish()
})
async function readPages<T>(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
endpoint: string,
field: string,
row: z.ZodType<T>,
noCache: boolean
): Promise<T[]> {
const schema = z.looseObject({
total_count: z.number().int().nonnegative()
})
const rows: T[] = []
let total: number | undefined
for (let page = 1; ; page++) {
await assertRateLimitBudget('core', repository, options)
const path = `repos/${repository.owner}/${repository.repo}/commits/${encodeURIComponent(headSha)}/${endpoint}?per_page=100&page=${page}`
const { stdout } = await ghExecFileAsync(
['api', ...(noCache ? [] : ['--cache', '60s']), path],
{ ...options, ...githubHostExecOptions(repository) }
)
noteRepositoryRateLimitSpend(repository, 'core', 1, options)
const result = schema.parse(JSON.parse(stdout))
const count = result.total_count
const pageRows = z.array(row).parse(result[field])
if (total !== undefined && total !== count) {
throw new Error('PR checks changed during REST pagination')
}
total = count
rows.push(...pageRows)
if (rows.length > total || (pageRows.length === 0 && rows.length < total)) {
throw new Error('Incomplete REST PR checks response')
}
if (rows.length === total) {
return rows
}
}
}
export function readRestPRCheckRuns(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache = true
) {
return readPages(
repository,
headSha,
options,
'check-runs',
'check_runs',
checkRunSchema,
noCache
)
}
export function readRestPRCommitStatuses(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache = true
) {
return readPages(repository, headSha, options, 'status', 'statuses', commitStatusSchema, noCache)
}
export function readRestPRCheckSuites(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions,
noCache = true
) {
return readPages(
repository,
headSha,
options,
'check-suites',
'check_suites',
checkSuiteSchema,
noCache
)
}
export async function readRestPRCheckRollup(
repository: GitHubApiRepository,
headSha: string,
options: GhExecOptions
): Promise<unknown[]> {
const runs = await readRestPRCheckRuns(repository, headSha, options)
const statuses = await readRestPRCommitStatuses(repository, headSha, options)
const suites = await readRestPRCheckSuites(repository, headSha, options)
const representedSuites = new Set(
runs.flatMap((run) => (run.check_suite ? [run.check_suite.id] : []))
)
return [
...runs.map((run) => ({ status: run.status, conclusion: run.conclusion })),
...statuses,
...suites
.filter((suite) =>
isPendingApprovalSuiteWithoutRuns(
suite.conclusion,
suite.id !== undefined && representedSuites.has(suite.id)
)
)
.map(() => ({ status: 'COMPLETED', conclusion: 'ACTION_REQUIRED' }))
]
}
@@ -17,6 +17,26 @@ import {
type MainWorkItem
} from './../map/work-item-field-coercion'
import { mapIssueWorkItem, mapPullRequestWorkItem } from './../map/work-item'
import { readCompletePRCheckObservation } from '../check/complete-pr-check-observation'
import { summarizePRCheckRollup } from '../../../../shared/source-control/checks/pr-check-status'
import { ownerRepoFromPullRequestUrl } from '../github-exec-scope'
async function withCompletePRChecks(
item: MainWorkItem,
repository: GitHubApiRepository | null,
number: number,
options: GhExecOptions
): Promise<MainWorkItem> {
const source = repository ?? ownerRepoFromPullRequestUrl(item.url)
const rollup =
source && item.number === number
? await readCompletePRCheckObservation(source, number, item.headSha, options)
: undefined
return {
...item,
checksSummary: rollup === undefined ? undefined : summarizePRCheckRollup(rollup)
}
}
export async function fetchIssueWorkItem(
repoPath: string,
ownerRepo: GitHubApiRepository | null,
@@ -142,7 +162,12 @@ export async function fetchPullRequestWorkItem(
ghOptions
)
const item = JSON.parse(stdout) as Record<string, unknown>
const mapped = mapPullRequestWorkItem(item, ownerRepo)
const mapped = await withCompletePRChecks(
mapPullRequestWorkItem(item, ownerRepo),
ownerRepo,
number,
ghOptions
)
// Best-effort merge metadata must not trigger a REST fallback that drops latestReviews.
const baseRefName = typeof item.baseRefName === 'string' ? item.baseRefName : undefined
try {
@@ -170,9 +195,11 @@ export async function fetchPullRequestWorkItem(
['api', `repos/${ownerRepo.owner}/${ownerRepo.repo}/pulls/${number}`],
ghOptions
)
const mapped = mapPullRequestWorkItem(
JSON.parse(stdout) as Record<string, unknown>,
ownerRepo
const mapped = await withCompletePRChecks(
mapPullRequestWorkItem(JSON.parse(stdout) as Record<string, unknown>, ownerRepo),
ownerRepo,
number,
ghOptions
)
const reviewFields = await fetchPullRequestReviewFields(number, ownerRepo, ghOptions)
return { ...mapped, ...reviewFields }
@@ -188,7 +215,12 @@ export async function fetchPullRequestWorkItem(
['pr', 'view', String(number), '--json', WORK_ITEM_PR_DETAIL_JSON_FIELDS],
ghOptions
)
return mapPullRequestWorkItem(JSON.parse(stdout) as Record<string, unknown>)
return withCompletePRChecks(
mapPullRequestWorkItem(JSON.parse(stdout) as Record<string, unknown>),
null,
number,
ghOptions
)
}
export async function fetchPullRequestWorkItemFromCandidates(
@@ -9,17 +9,19 @@ import type { GhExecOptions } from './../github-exec-scope'
import { isNoPullRequestError } from './../gh-error-predicates'
import {
PR_LOOKUP_JSON_FIELDS,
normalizePullRequestLookupData,
PR_BRANCH_LIST_JSON_FIELDS,
mapRestPullRequest,
normalizePullRequestLookupData,
pullRequestMatchesHeadRepository,
type PullRequestLookupData,
type PullRequestLookupPolicy,
type RestPullRequest
} from './pull-request-lookup-data'
import { getPRByNumber } from './pr-number-lookup'
import { hydratePullRequestLookupData } from './pull-request-lookup-hydration'
import { revalidateGitHubRestJson } from '../../github-rest-revalidation'
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
import { ownerRepoFromPullRequestUrl } from '../github-exec-scope'
// Why: GitHub lists a branch's PRs newest first, so with a page of one a closed PR opened after
// the live one wins. Fetch a page and prefer the open PR; fall back to the newest one.
@@ -72,7 +74,7 @@ export async function getFallbackPRListForBranch(
const list = JSON.parse(stdout) as PullRequestLookupData[]
const pr = preferOpenPullRequest(list)
// Branch lists paginate PRs, not their nested check contexts.
return pr ? { ...pr, checksUnavailable: true } : null
return pr ? { ...pr, statusCheckRollup: [], checksUnavailable: true } : null
}
export async function hydrateBranchLookupWithExactPR(
@@ -189,13 +191,20 @@ export async function lookupPRByBranchName(args: {
args.ghOptions
)
const parsedData: PullRequestLookupData = JSON.parse(stdout)
const lookup = {
data: normalizePullRequestLookupData({
...parsedData,
checksUnavailable: false
}),
dataRepo: null
}
const repository = ownerRepoFromPullRequestUrl(parsedData.url)
const data = repository
? await hydratePullRequestLookupData(
repository,
{ ...parsedData, checksUnavailable: true },
args.ghOptions,
args.executionScope
)
: {
...normalizePullRequestLookupData(parsedData),
statusCheckRollup: [],
checksUnavailable: true
}
const lookup = { data, dataRepo: null }
return !args.policy || (await args.policy.accepts(lookup.data, null))
? lookup
: { data: null, dataRepo: null }
@@ -1,3 +1,4 @@
import { classifyPRRefreshError } from '../../pr-refresh-error-classification'
import { ghExecFileAsync } from '../../gh-utils'
import type { OwnerRepo, ghRepoExecOptions } from '../../gh-utils'
import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository'
@@ -8,8 +9,8 @@ import {
} from './../gh-error-predicates'
import {
PR_LOOKUP_JSON_FIELDS,
mapRestPullRequest,
normalizePullRequestLookupData,
mapRestPullRequest,
type PullRequestLookupData,
type PullRequestLookupPolicy,
type RestPullRequest
@@ -18,6 +19,7 @@ import { hydratePullRequestLookupData } from './pull-request-lookup-hydration'
import { isGitObjectId, isUsableRestStackMetadata } from './rest-stack-metadata-validation'
import { revalidateGitHubRestJson } from '../../github-rest-revalidation'
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
import { ownerRepoFromPullRequestUrl, sameOwnerRepo } from '../github-exec-scope'
import { readPullRequestSidebarQuery } from './pull-request-sidebar-query'
export async function getRestPRByNumber(
ownerRepo: GitHubApiRepository,
@@ -61,22 +63,59 @@ export async function getPRByNumber(
options: { includeStackSummary?: boolean } = {}
): Promise<PullRequestLookupData | null> {
try {
const sidebarData =
options.includeStackSummary && knownPullRequestData === undefined
? await readPullRequestSidebarQuery(ownerRepo, number, ghOptions)
: undefined
let sidebarData: Awaited<ReturnType<typeof readPullRequestSidebarQuery>>
try {
sidebarData =
options.includeStackSummary || knownPullRequestData !== undefined
? await readPullRequestSidebarQuery(ownerRepo, number, ghOptions)
: undefined
} catch (error) {
if (
!knownPullRequestData ||
['repo_unavailable', 'permission', 'rate_limited', 'auth'].includes(
classifyPRRefreshError(error)
)
) {
throw error
}
// Optional combined reads retain the exact metadata recovery path.
sidebarData = undefined
}
if (sidebarData === null) {
return null
}
if (sidebarData) {
const { stack, ...prData } = sidebarData
const known = knownPullRequestData
const sameIdentity =
known &&
known.number === number &&
sameOwnerRepo(ownerRepoFromPullRequestUrl(known.url), ownerRepo) &&
known.headRepositoryOwner?.login?.toLowerCase() ===
prData.headRepositoryOwner?.login?.toLowerCase() &&
known.headRepository?.name?.toLowerCase() === prData.headRepository?.name?.toLowerCase()
const compatibleStack =
sameIdentity &&
known.headRefOid === prData.headRefOid &&
known.baseRefOid === prData.baseRefOid &&
stack &&
known.stack?.number === stack.number &&
known.stack.position === stack.position &&
known.stack.baseRefName === stack.baseRefName
? { ...known.stack, ...stack }
: stack
const hydrated = await hydratePullRequestLookupData(
ownerRepo,
prData,
{
...prData,
...(sameIdentity && known.headDefaultBranchName
? { headDefaultBranchName: known.headDefaultBranchName }
: {})
},
ghOptions,
executionScope
)
return { ...hydrated, ...(stack ? { stack } : {}) }
return { ...hydrated, ...(compatibleStack ? { stack: compatibleStack } : {}) }
}
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
@@ -97,7 +136,7 @@ export async function getPRByNumber(
{
...knownPullRequestData,
...exactData,
checksUnavailable: false,
checksUnavailable: true,
...(knownPullRequestData?.stack ? { stack: knownPullRequestData.stack } : {})
},
ghOptions,
@@ -114,7 +153,12 @@ export async function getPRByNumber(
? await getRestPRByNumber(ownerRepo, number, ghOptions)
: knownPullRequestData
return restData
? hydratePullRequestLookupData(ownerRepo, restData, ghOptions, executionScope)
? hydratePullRequestLookupData(
ownerRepo,
{ ...restData, checksUnavailable: true },
ghOptions,
executionScope
)
: null
} catch (restErr) {
if (isNotFoundGhError(restErr)) {
@@ -171,13 +215,20 @@ export async function lookupPRByNumber(args: {
args.ghOptions
)
const parsedData: PullRequestLookupData = JSON.parse(stdout)
const lookup = {
data: normalizePullRequestLookupData({
...parsedData,
checksUnavailable: false
}),
dataRepo: null
}
const repository = ownerRepoFromPullRequestUrl(parsedData.url)
const data = repository
? await hydratePullRequestLookupData(
repository,
{ ...parsedData, checksUnavailable: true },
args.ghOptions,
args.executionScope
)
: {
...normalizePullRequestLookupData(parsedData),
statusCheckRollup: [],
checksUnavailable: true
}
const lookup = { data, dataRepo: null }
return !args.policy || (await args.policy.accepts(lookup.data, null))
? lookup
: { data: null, dataRepo: null }
@@ -40,7 +40,10 @@ export function assemblePRRefreshFoundOutcome(args: {
title: data.title,
state: mapPRState(data.state, data.isDraft),
url: data.url,
checksStatus: checksSummary.state === 'none' ? 'neutral' : checksSummary.state,
checksStatus:
data.checksUnavailable !== false || checksSummary.state === 'none'
? 'neutral'
: checksSummary.state,
...(data.checksUnavailable === false ? { checksSummary } : {}),
updatedAt: data.updatedAt,
mergeable,
@@ -81,10 +81,10 @@ export type RestPullRequest = {
}
export const PR_LOOKUP_JSON_FIELDS =
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,reviewDecision,mergeStateStatus,autoMergeRequest,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository'
'number,title,state,url,updatedAt,isDraft,mergeable,reviewDecision,mergeStateStatus,autoMergeRequest,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository'
export const PR_BRANCH_LIST_JSON_FIELDS =
'number,title,state,url,statusCheckRollup,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository'
'number,title,state,url,updatedAt,isDraft,mergeable,baseRefName,headRefName,baseRefOid,headRefOid,headRepositoryOwner,headRepository,isCrossRepository'
export type GitHubPRBranchLookupOptions = HostedReviewExecutionOptions & {
userRefresh?: boolean
@@ -6,6 +6,7 @@ import {
normalizePullRequestLookupData,
type PullRequestLookupData
} from './pull-request-lookup-data'
import { readCompletePRCheckObservation } from '../check/complete-pr-check-observation'
export async function hydratePullRequestLookupData(
ownerRepo: OwnerRepo,
data: PullRequestLookupData,
@@ -13,6 +14,10 @@ export async function hydratePullRequestLookupData(
executionScope: string
): Promise<PullRequestLookupData> {
const normalized = normalizePullRequestLookupData(data)
const checks =
data.checksUnavailable === false
? data.statusCheckRollup
: await readCompletePRCheckObservation(ownerRepo, data.number, data.headRefOid, ghOptions)
const hasRichMergeFields =
'reviewDecision' in data || 'mergeStateStatus' in data || 'autoMergeRequest' in data
const mergeMetadata =
@@ -26,6 +31,8 @@ export async function hydratePullRequestLookupData(
: undefined
return {
...normalized,
statusCheckRollup: checks ?? [],
checksUnavailable: checks === undefined,
...(mergeMetadata ? { mergeQueueRequired: mergeMetadata.mergeQueueRequired } : {}),
...(mergeMetadata ? { autoMergeAllowed: mergeMetadata.autoMergeAllowed } : {}),
...(mergeMetadata?.mergeMethodSettings
@@ -5,26 +5,16 @@ import { githubHostExecOptions, type GitHubApiRepository } from '../../github-ap
import { noteRepositoryRateLimitSpend } from '../../rate-limit'
import type { GhExecOptions } from '../github-exec-scope'
import type { PullRequestLookupData } from './pull-request-lookup-data'
import {
collectPRCheckRollup,
createPRCheckRollupPageReader,
prCheckRollupCommitsSchema,
prCheckRollupFields
} from '../check/pr-check-rollup'
const CHECKS_FIELDS = `commits(last: 1) {
nodes {
commit {
oid
statusCheckRollup {
contexts(first: 100, after: $checksCursor) {
nodes {
__typename
... on CheckRun { status conclusion }
... on StatusContext { state }
}
pageInfo { hasNextPage endCursor }
}
}
}
}
}`
const CHECKS_FIELDS = prCheckRollupFields()
const SIDEBAR_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $checksCursor: String) {
const SIDEBAR_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $checksCursor: String, $suitesCursor: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
number title state url updatedAt isDraft mergeable reviewDecision mergeStateStatus
@@ -39,31 +29,6 @@ const SIDEBAR_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $ch
}
}`
const CHECKS_QUERY = `query($owner: String!, $repo: String!, $number: Int!, $checksCursor: String) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) { number ${CHECKS_FIELDS} }
}
}`
const commitsSchema = z.object({
nodes: z
.array(
z.object({
commit: z.object({
oid: z.string(),
statusCheckRollup: z
.object({
contexts: z.object({
nodes: z.array(z.record(z.string(), z.unknown()).nullable()),
pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() })
})
})
.nullable()
})
})
)
.max(1)
})
const errorsSchema = z
.array(
z.object({
@@ -91,7 +56,7 @@ const pullRequestSchema = z.object({
isCrossRepository: z.boolean().optional(),
headRepositoryOwner: z.object({ login: z.string() }).nullable(),
headRepository: z.object({ name: z.string() }).nullable(),
commits: commitsSchema,
commits: z.unknown(),
stack: z.unknown().optional(),
stackEntry: z.unknown().optional()
})
@@ -109,14 +74,6 @@ const missingEnvelopeSchema = z.object({
data: z.object({ repository: z.object({ pullRequest: z.null() }) }),
errors: errorsSchema
})
const checksEnvelopeSchema = z.object({
data: z.object({
repository: z.object({
pullRequest: z.object({ number: z.number(), commits: commitsSchema })
})
}),
errors: errorsSchema
})
async function readQuery(
repository: GitHubApiRepository,
@@ -188,13 +145,16 @@ export async function readPullRequestSidebarQuery(
return undefined
}
const envelope = parsed.data
const stackErrors = envelope.errors ?? []
const errors = envelope.errors ?? []
const stackErrors = errors.filter(
({ path }) => path?.[2] === 'stack' || path?.[2] === 'stackEntry'
)
if (
stackErrors.some(
errors.some(
({ path }) =>
path?.[0] !== 'repository' ||
path[1] !== 'pullRequest' ||
(path[2] !== 'stack' && path[2] !== 'stackEntry')
(path[2] !== 'stack' && path[2] !== 'stackEntry' && path[2] !== 'commits')
)
) {
if (response.failure) {
@@ -206,37 +166,21 @@ export async function readPullRequestSidebarQuery(
if (pr.number !== number) {
return undefined
}
let contexts = pr.commits.nodes[0]?.commit.statusCheckRollup?.contexts
const statusCheckRollup = contexts?.nodes.flatMap((node) => (node ? [node] : [])) ?? []
const cursors = new Set<string>()
while (contexts?.pageInfo.hasNextPage) {
const cursor = contexts.pageInfo.endCursor
if (!cursor || cursors.has(cursor)) {
return undefined
let statusCheckRollup: unknown[] | undefined
try {
if (!pr.headRefOid || errors.some(({ path }) => path?.[2] === 'commits')) {
throw new Error('Missing PR head')
}
cursors.add(cursor)
const page = await readQuery(repository, number, options, CHECKS_QUERY, cursor)
if (page.failure) {
throw page.failure.error
}
const parsedPage = checksEnvelopeSchema.safeParse(page.payload)
if (!parsedPage.success) {
return undefined
}
const next = parsedPage.data
if (
next.errors?.length ||
next.data.repository.pullRequest.number !== number ||
next.data.repository.pullRequest.commits.nodes[0]?.commit.oid !==
pr.commits.nodes[0]?.commit.oid
) {
return undefined
}
contexts = next.data.repository.pullRequest.commits.nodes[0]?.commit.statusCheckRollup?.contexts
if (!contexts) {
return undefined
}
statusCheckRollup.push(...contexts.nodes.flatMap((node) => (node ? [node] : [])))
statusCheckRollup = await collectPRCheckRollup(
{
number: pr.number,
headRefOid: pr.headRefOid,
commits: prCheckRollupCommitsSchema.parse(pr.commits)
},
createPRCheckRollupPageReader(repository, number, options)
)
} catch {
// Metadata remains usable when complete checks need REST recovery.
}
const stack = stackSchema.safeParse(pr.stack)
const entry = stackEntrySchema.safeParse(pr.stackEntry)
@@ -248,8 +192,8 @@ export async function readPullRequestSidebarQuery(
...metadata,
baseRefOid: pr.baseRefOid ?? undefined,
headRefOid: pr.headRefOid ?? undefined,
statusCheckRollup,
checksUnavailable: false,
statusCheckRollup: statusCheckRollup ?? [],
checksUnavailable: statusCheckRollup === undefined,
stackMetadataChecked,
stack:
stackMetadataChecked && validStack
@@ -12,7 +12,7 @@ export const WORK_ITEM_PR_LIST_JSON_FIELDS =
// Keep first-paint reviewers in list payloads; defer costly checks, review decisions and merge metadata.
export const WORK_ITEM_PR_DETAIL_JSON_FIELDS =
'number,title,state,url,labels,updatedAt,author,isDraft,headRefName,baseRefName,headRefOid,headRepositoryOwner,additions,deletions,changedFiles,reviewDecision,reviewRequests,latestReviews,assignees,statusCheckRollup,mergeable,mergeStateStatus,autoMergeRequest,maintainerCanModify'
'number,title,state,url,labels,updatedAt,author,isDraft,headRefName,baseRefName,headRefOid,headRepositoryOwner,additions,deletions,changedFiles,reviewDecision,reviewRequests,latestReviews,assignees,mergeable,mergeStateStatus,autoMergeRequest,maintainerCanModify'
/** Preserve API-provided avatars with logins; dotcom login-based URLs do not identify Enterprise avatars. */
export function authorFieldsFromUnknown(