fix(github): honor the saved project account for PR requests (#35023)

* fix(github): resolve project accounts at the request boundary

* fix(github): retain account identity through request settlement

* fix: isolate GitHub leaf caches by held execution identity

* fix: use canonical options type for merged review membership
This commit is contained in:
Brennan Benson
2026-10-30 12:39:59 -07:00
committed by GitHub
parent bd82832a53
commit eca40bc3bf
32 changed files with 2748 additions and 1316 deletions
+21 -12
View File
@@ -1,3 +1,8 @@
import {
withGitHubRepoExecution,
githubRepoContext,
ghRepoExecOptions
} from '../../github-repository-identity'
import { runCoalescedProbe, type CoalescedProbes } from '../../../git/coalesced-probe'
import { githubReadExecutionScope } from '../../github-read-execution-scope'
import type { PRCheckDetail } from '../../../../shared/github/check-types'
@@ -241,16 +246,20 @@ export function getPRChecks(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<PRCheckDetail[]> {
const key = JSON.stringify([
repoPath,
prNumber,
headSha ?? null,
prRepo ?? null,
Boolean(options?.noCache),
connectionId ?? null,
githubReadExecutionScope(localGitOptions)
])
return runCoalescedProbe(checksReads, key, () =>
readPRChecks(repoPath, prNumber, headSha, prRepo, options, connectionId, localGitOptions)
)
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
const key = JSON.stringify([
repoPath,
prNumber,
headSha ?? null,
prRepo ?? null,
Boolean(options?.noCache),
connectionId ?? null,
githubReadExecutionScope(
ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions))
)
])
return runCoalescedProbe(checksReads, key, () =>
readPRChecks(repoPath, prNumber, headSha, prRepo, options, connectionId, localGitOptions)
)
})
}
+80 -77
View File
@@ -1,3 +1,4 @@
import { withGitHubRepoExecution } from '../../github-repository-identity'
import type { GitHubRerunPRChecksResult } from '../../../../shared/github/check-types'
import { ghExecFileAsync, acquire, release, type LocalGitExecOptions } from '../../gh-utils'
// Keep real error parsing available when tests mock gh-utils.
@@ -18,85 +19,87 @@ export async function rerunPRChecks(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<GitHubRerunPRChecksResult> {
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
options.prRepo,
connectionId,
localGitOptions
)
if (!ownerRepo) {
return codeHostFailure('github.repoUnresolved')
}
const checks = await getPRChecks(
repoPath,
prNumber,
options.headSha,
ownerRepo,
{ noCache: true },
connectionId,
localGitOptions
)
const candidates = options.failedOnly
? checks.filter((check) =>
['failure', 'cancelled', 'timed_out'].includes(check.conclusion ?? '')
)
: checks
const workflowRunIds = new Set(
candidates
.map((check) => check.workflowRunId ?? parseActionsRunId(check.url))
.filter((id): id is number => typeof id === 'number')
)
const checkRunIds = new Set(
candidates
.filter((check) => !check.workflowRunId && !parseActionsRunId(check.url))
.map((check) => check.checkRunId)
.filter((id): id is number => typeof id === 'number')
)
if (workflowRunIds.size === 0 && checkRunIds.size === 0) {
return codeHostFailure(
options.failedOnly ? 'github.noFailedChecks' : 'github.noRerunnableChecks'
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
const { ownerRepo, ghOptions } = await resolveGitHubRepoExecution(
repoPath,
options.prRepo,
connectionId,
localGitOptions
)
}
if (!ownerRepo) {
return codeHostFailure('github.repoUnresolved')
}
let count = 0
await acquire()
try {
for (const runId of workflowRunIds) {
const endpoint = options.failedOnly
? `repos/${ownerRepo.owner}/${ownerRepo.repo}/actions/runs/${runId}/rerun-failed-jobs`
: `repos/${ownerRepo.owner}/${ownerRepo.repo}/actions/runs/${runId}/rerun`
await ghExecFileAsync(['api', '-X', 'POST', endpoint], {
...ghOptions,
env: { ...process.env, GH_PROMPT_DISABLED: '1' }
})
count += 1
}
for (const checkRunId of checkRunIds) {
await ghExecFileAsync(
[
'api',
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/check-runs/${checkRunId}/rerequest`
],
{ ...ghOptions, env: { ...process.env, GH_PROMPT_DISABLED: '1' } }
const checks = await getPRChecks(
repoPath,
prNumber,
options.headSha,
ownerRepo,
{ noCache: true },
connectionId,
localGitOptions
)
const candidates = options.failedOnly
? checks.filter((check) =>
['failure', 'cancelled', 'timed_out'].includes(check.conclusion ?? '')
)
: checks
const workflowRunIds = new Set(
candidates
.map((check) => check.workflowRunId ?? parseActionsRunId(check.url))
.filter((id): id is number => typeof id === 'number')
)
const checkRunIds = new Set(
candidates
.filter((check) => !check.workflowRunId && !parseActionsRunId(check.url))
.map((check) => check.checkRunId)
.filter((id): id is number => typeof id === 'number')
)
if (workflowRunIds.size === 0 && checkRunIds.size === 0) {
return codeHostFailure(
options.failedOnly ? 'github.noFailedChecks' : 'github.noRerunnableChecks'
)
count += 1
}
return { ok: true, count }
} catch (err) {
const { stderr } = extractExecError(err)
const classified = classifyRerunChecksError(stderr)
// Rerun POSTs are not idempotent; report partial success before the user retries.
return count > 0
? {
ok: false,
error: `${classified.message} (${count} rerun${count === 1 ? '' : 's'} already started)`
}
: classifiedFailure(classified)
} finally {
release()
}
let count = 0
await acquire()
try {
for (const runId of workflowRunIds) {
const endpoint = options.failedOnly
? `repos/${ownerRepo.owner}/${ownerRepo.repo}/actions/runs/${runId}/rerun-failed-jobs`
: `repos/${ownerRepo.owner}/${ownerRepo.repo}/actions/runs/${runId}/rerun`
await ghExecFileAsync(['api', '-X', 'POST', endpoint], {
...ghOptions,
env: { ...process.env, GH_PROMPT_DISABLED: '1' }
})
count += 1
}
for (const checkRunId of checkRunIds) {
await ghExecFileAsync(
[
'api',
'-X',
'POST',
`repos/${ownerRepo.owner}/${ownerRepo.repo}/check-runs/${checkRunId}/rerequest`
],
{ ...ghOptions, env: { ...process.env, GH_PROMPT_DISABLED: '1' } }
)
count += 1
}
return { ok: true, count }
} catch (err) {
const { stderr } = extractExecError(err)
const classified = classifyRerunChecksError(stderr)
// Rerun POSTs are not idempotent; report partial success before the user retries.
return count > 0
? {
ok: false,
error: `${classified.message} (${count} rerun${count === 1 ? '' : 's'} already started)`
}
: classifiedFailure(classified)
} finally {
release()
}
})
}
@@ -25,6 +25,7 @@ import {
import { getOriginGitHubApiRepository, githubHostExecOptions } from '../../github-api-repository'
import { classifyCreatePRError, parseCreatePRPayload } from './create-pr-error-classification'
import { findOpenPRByHeadBase, readPullRequestTemplate } from './pull-request-template'
import { withGitHubRepoExecution } from '../../github-repository-identity'
export async function createGitHubPullRequest(
repoPath: string,
input: CreateHostedReviewInput,
@@ -43,131 +44,137 @@ export async function createGitHubPullRequest(
// `gh` runs on this client whatever the host; only the git reads under it are routed.
const connectionId = hostedReviewSshConnectionId(executionHostId)
// The unqualified head branch belongs to origin; retain its resolved host.
const ownerRepo = await getOriginGitHubApiRepository(
return withGitHubRepoExecution(
repoPath,
connectionId,
getHostedReviewLocalGitOptions(options)
)
if (!ownerRepo) {
return {
ok: false,
code: 'unsupported_provider',
error: 'Creating pull requests requires a GitHub remote.',
reason: 'unsupported_provider'
}
}
// The runner qualifies --repo using options.host.
const repoArg = `${ownerRepo.owner}/${ownerRepo.repo}`
const base = normalizeHostedReviewBaseRef(input.base)
const head = input.head ? normalizeHostedReviewHeadRef(input.head) || undefined : undefined
const title = input.title.trim()
if (!base || !title) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: base branch and title are required.'
}
}
if (head && head.toLowerCase() === base.toLowerCase()) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: choose a different base branch before creating a pull request.',
reason: 'same_base_branch'
}
}
const tempDir = await mkdtemp(join(tmpdir(), 'orca-pr-body-'))
await acquire()
const bodyPath = join(tempDir, 'body.md')
try {
const body =
input.useTemplate && !input.body?.trim()
? await readPullRequestTemplate(repoPath, connectionId)
: (input.body ?? '')
await writeFile(bodyPath, body, 'utf8')
const createArgs = [
'pr',
'create',
'--repo',
repoArg,
'--base',
base,
'--title',
title,
'--body-file',
bodyPath
]
if (head) {
createArgs.push('--head', head)
}
if (input.draft) {
createArgs.push('--draft')
}
try {
const localGitOptions = getHostedReviewLocalGitOptions(options)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const { stdout } = await ghExecFileAsync(createArgs, {
...ghRepoExecOptions(context),
...(connectionId ? {} : localGitOptions),
...githubHostExecOptions(ownerRepo),
timeout: 60_000,
idempotent: false
})
const created = parseCreatePRPayload(stdout)
if (created) {
return { ok: true, ...created }
}
const found = head
? await findOpenPRByHeadBase({
repoPath,
repo: ownerRepo,
head,
base,
connectionId,
options
}).catch(() => null)
: null
if (found) {
return { ok: true, ...found }
}
return {
ok: false,
code: 'unknown_completion',
error: 'PR creation may have completed. Refreshing branch review state...',
reason: 'creation_unconfirmed'
}
} catch (error) {
const classified = classifyCreatePRError(error)
if (
!classified.ok &&
(classified.code === 'already_exists' || classified.code === 'unknown_completion') &&
head
) {
const existing = await findOpenPRByHeadBase({
repoPath,
repo: ownerRepo,
head,
base,
connectionId,
options
}).catch(() => null)
if (existing) {
return {
ok: false,
code: 'already_exists',
error: 'A pull request already exists for this branch.',
reason: 'existing_review',
existingReview: existing
}
getHostedReviewLocalGitOptions(options),
async () => {
// The unqualified head branch belongs to origin; retain its resolved host.
const ownerRepo = await getOriginGitHubApiRepository(
repoPath,
connectionId,
getHostedReviewLocalGitOptions(options)
)
if (!ownerRepo) {
return {
ok: false,
code: 'unsupported_provider',
error: 'Creating pull requests requires a GitHub remote.',
reason: 'unsupported_provider'
}
}
return classified
// The runner qualifies --repo using options.host.
const repoArg = `${ownerRepo.owner}/${ownerRepo.repo}`
const base = normalizeHostedReviewBaseRef(input.base)
const head = input.head ? normalizeHostedReviewHeadRef(input.head) || undefined : undefined
const title = input.title.trim()
if (!base || !title) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: base branch and title are required.'
}
}
if (head && head.toLowerCase() === base.toLowerCase()) {
return {
ok: false,
code: 'validation',
error: 'Create PR failed: choose a different base branch before creating a pull request.',
reason: 'same_base_branch'
}
}
const tempDir = await mkdtemp(join(tmpdir(), 'orca-pr-body-'))
await acquire()
const bodyPath = join(tempDir, 'body.md')
try {
const body =
input.useTemplate && !input.body?.trim()
? await readPullRequestTemplate(repoPath, connectionId)
: (input.body ?? '')
await writeFile(bodyPath, body, 'utf8')
const createArgs = [
'pr',
'create',
'--repo',
repoArg,
'--base',
base,
'--title',
title,
'--body-file',
bodyPath
]
if (head) {
createArgs.push('--head', head)
}
if (input.draft) {
createArgs.push('--draft')
}
try {
const localGitOptions = getHostedReviewLocalGitOptions(options)
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const { stdout } = await ghExecFileAsync(createArgs, {
...ghRepoExecOptions(context),
...githubHostExecOptions(ownerRepo),
timeout: 60_000,
idempotent: false
})
const created = parseCreatePRPayload(stdout)
if (created) {
return { ok: true, ...created }
}
const found = head
? await findOpenPRByHeadBase({
repoPath,
repo: ownerRepo,
head,
base,
connectionId,
options
}).catch(() => null)
: null
if (found) {
return { ok: true, ...found }
}
return {
ok: false,
code: 'unknown_completion',
error: 'PR creation may have completed. Refreshing branch review state...',
reason: 'creation_unconfirmed'
}
} catch (error) {
const classified = classifyCreatePRError(error)
if (
!classified.ok &&
(classified.code === 'already_exists' || classified.code === 'unknown_completion') &&
head
) {
const existing = await findOpenPRByHeadBase({
repoPath,
repo: ownerRepo,
head,
base,
connectionId,
options
}).catch(() => null)
if (existing) {
return {
ok: false,
code: 'already_exists',
error: 'A pull request already exists for this branch.',
reason: 'existing_review',
existingReview: existing
}
}
}
return classified
}
} finally {
await rm(tempDir, { recursive: true, force: true }).catch(() => undefined)
release()
}
}
} finally {
await rm(tempDir, { recursive: true, force: true }).catch(() => undefined)
release()
}
)
}
@@ -35,7 +35,6 @@ export async function findOpenPRByHeadBase(args: {
],
{
...ghRepoExecOptions(context),
...(args.connectionId ? {} : localGitOptions),
...githubHostExecOptions(args.repo)
}
)
@@ -154,10 +154,7 @@ async function readRepositoryMergeMetadata(
args.push('-f', `branch=${branchName}`)
args.push('-f', `qualified=refs/heads/${branchName}`)
}
const { stdout } = await ghExecFileAsync(args, {
...ghOptions,
...githubHostExecOptions(ownerRepo)
})
const { stdout } = await ghExecFileAsync(args, ghOptions)
const parsed = JSON.parse(stdout) as {
data?: {
repository?: {
+127 -122
View File
@@ -1,3 +1,4 @@
import { withGitHubRepoExecution } from '../../github-repository-identity'
import type { IssueSourcePreference } from '../../../../shared/repo-types'
import { acquire, release, classifyGhError, type LocalGitExecOptions } from '../../gh-utils'
import {
@@ -52,40 +53,79 @@ export async function getWorkItemWithRepository(
preference?: IssueSourcePreference,
includeIssueDetails = false
): Promise<WorkItemRepositoryLookup> {
await acquire()
try {
// Number-based issue lookup must honor the same selected source as its list.
if (type === 'issue') {
const { source } = await resolveIssueGitHubApiRepositorySource(
repoPath,
preference,
connectionId,
localGitOptions
)
// Explicit origin cannot fall back to ambient gh repository discovery.
if (!source && preference === 'origin') {
return { item: null, repository: null }
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
await acquire()
try {
// Number-based issue lookup must honor the same selected source as its list.
if (type === 'issue') {
const { source } = await resolveIssueGitHubApiRepositorySource(
repoPath,
preference,
connectionId,
localGitOptions
)
// Explicit origin cannot fall back to ambient gh repository discovery.
if (!source && preference === 'origin') {
return { item: null, repository: null }
}
const issueDetails =
includeIssueDetails && source
? await getIssueDetailsViaGraphQL(
repoPath,
number,
source,
connectionId,
localGitOptions,
true
)
: undefined
return {
item:
issueDetails?.item ??
(await fetchIssueWorkItem(repoPath, source, number, connectionId, localGitOptions)),
repository: source,
...(includeIssueDetails ? { issueDetails } : {})
}
}
const issueDetails =
includeIssueDetails && source
? await getIssueDetailsViaGraphQL(
repoPath,
number,
source,
connectionId,
localGitOptions,
true
)
: undefined
return {
item:
issueDetails?.item ??
(await fetchIssueWorkItem(repoPath, source, number, connectionId, localGitOptions)),
repository: source,
...(includeIssueDetails ? { issueDetails } : {})
if (type === 'pr') {
return {
item: await fetchPullRequestWorkItemFromCandidates(
repoPath,
number,
connectionId,
localGitOptions,
preference
),
repository: null
}
}
try {
const { source } = await resolveIssueGitHubApiRepositorySource(
repoPath,
preference,
connectionId,
localGitOptions
)
if (source || preference !== 'origin') {
const issue = await fetchIssueWorkItem(
repoPath,
source,
number,
connectionId,
localGitOptions
)
if (issue) {
return { item: issue, repository: source }
}
}
} catch (err) {
// Only genuine issue 404s permit trying a same-number PR; preserve transient failures.
const stderr = err instanceof Error ? err.message : String(err)
if (classifyGhError(stderr).type !== 'not_found') {
throw err
}
}
}
if (type === 'pr') {
return {
item: await fetchPullRequestWorkItemFromCandidates(
repoPath,
@@ -96,49 +136,12 @@ export async function getWorkItemWithRepository(
),
repository: null
}
} catch {
return { item: null, repository: null }
} finally {
release()
}
try {
const { source } = await resolveIssueGitHubApiRepositorySource(
repoPath,
preference,
connectionId,
localGitOptions
)
if (source || preference !== 'origin') {
const issue = await fetchIssueWorkItem(
repoPath,
source,
number,
connectionId,
localGitOptions
)
if (issue) {
return { item: issue, repository: source }
}
}
} catch (err) {
// Only genuine issue 404s permit trying a same-number PR; preserve transient failures.
const stderr = err instanceof Error ? err.message : String(err)
if (classifyGhError(stderr).type !== 'not_found') {
throw err
}
}
return {
item: await fetchPullRequestWorkItemFromCandidates(
repoPath,
number,
connectionId,
localGitOptions,
preference
),
repository: null
}
} catch {
return { item: null, repository: null }
} finally {
release()
}
})
}
export async function getWorkItemByOwnerRepo(
@@ -150,57 +153,59 @@ export async function getWorkItemByOwnerRepo(
localGitOptions: LocalGitExecOptions = {},
options: { preview?: boolean } = {}
): Promise<MainWorkItem | null> {
const requestedHost = ownerRepo.host?.trim().toLowerCase()
const requestedRepository = requestedHost
? { ...ownerRepo, host: requestedHost }
: await resolveGitHubApiRepository(repoPath, ownerRepo, connectionId, localGitOptions)
if (!requestedRepository) {
return null
}
const { candidates } = await resolveGitHubApiRepositoryCandidates(
repoPath,
connectionId,
localGitOptions
)
const requestedKey = githubRepoIdentityKey(requestedRepository)
const matchedRepository = candidates.find(
(candidate) => githubRepoIdentityKey(candidate) === requestedKey
)
// Pasted hosts must match configured remotes before receiving credentials.
if (!matchedRepository) {
return null
}
await acquire()
try {
if (options.preview) {
return await fetchWorkItemPreview(
repoPath,
matchedRepository,
number,
type,
connectionId,
localGitOptions
)
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
const requestedHost = ownerRepo.host?.trim().toLowerCase()
const requestedRepository = requestedHost
? { ...ownerRepo, host: requestedHost }
: await resolveGitHubApiRepository(repoPath, ownerRepo, connectionId, localGitOptions)
if (!requestedRepository) {
return null
}
if (type === 'issue') {
return await fetchIssueWorkItem(
repoPath,
matchedRepository,
number,
connectionId,
localGitOptions
)
}
return await fetchPullRequestWorkItem(
const { candidates } = await resolveGitHubApiRepositoryCandidates(
repoPath,
matchedRepository,
number,
connectionId,
localGitOptions
)
} catch {
return null
} finally {
release()
}
const requestedKey = githubRepoIdentityKey(requestedRepository)
const matchedRepository = candidates.find(
(candidate) => githubRepoIdentityKey(candidate) === requestedKey
)
// Pasted hosts must match configured remotes before receiving credentials.
if (!matchedRepository) {
return null
}
await acquire()
try {
if (options.preview) {
return await fetchWorkItemPreview(
repoPath,
matchedRepository,
number,
type,
connectionId,
localGitOptions
)
}
if (type === 'issue') {
return await fetchIssueWorkItem(
repoPath,
matchedRepository,
number,
connectionId,
localGitOptions
)
}
return await fetchPullRequestWorkItem(
repoPath,
matchedRepository,
number,
connectionId,
localGitOptions
)
} catch {
return null
} finally {
release()
}
})
}
+88 -85
View File
@@ -1,3 +1,4 @@
import { withGitHubRepoExecution } from '../../github-repository-identity'
import type { IssueSourcePreference } from '../../../../shared/repo-types'
import { isGitHubWorkItemsQueryTooLarge } from '../../../../shared/github/work-items-query-bounds'
import { parseTaskQuery, type ParsedTaskQuery } from '../../../../shared/task-query'
@@ -114,99 +115,101 @@ export async function countWorkItems(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): Promise<number> {
const trimmedQuery = query?.trim() ?? ''
if (isGitHubWorkItemsQueryTooLarge(trimmedQuery)) {
return 0
}
const [issueResolved, prResolved] = await Promise.all([
resolveIssueGitHubApiRepositorySource(repoPath, preference, connectionId, localGitOptions),
resolvePrWorkItemSource(repoPath, preference, connectionId, localGitOptions)
])
const issueOwnerRepo = issueResolved.source
const prOwnerRepo = prResolved.source
const ownerRepo = prOwnerRepo ?? issueOwnerRepo
if (!ownerRepo) {
return 0
}
const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null
const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery()
const ghOptions = {
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
// Decorative counts must stop at the search budget floor.
if (spendsSharedGitHubComQuota(ownerRepo, ghOptions)) {
await getRateLimit()
}
if (
!usesGraphqlWorkItemSearch(ownerRepo, ghOptions) &&
repositoryRateLimitGuard(ownerRepo, 'search', ghOptions).blocked
) {
return 0
}
await acquire()
try {
if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) {
return await countWorkItemsForQuery(
repoPath,
ownerRepo,
effectiveQuery,
connectionId,
localGitOptions
)
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
const trimmedQuery = query?.trim() ?? ''
if (isGitHubWorkItemsQueryTooLarge(trimmedQuery)) {
return 0
}
const [issueResolved, prResolved] = await Promise.all([
resolveIssueGitHubApiRepositorySource(repoPath, preference, connectionId, localGitOptions),
resolvePrWorkItemSource(repoPath, preference, connectionId, localGitOptions)
])
const issueOwnerRepo = issueResolved.source
const prOwnerRepo = prResolved.source
const ownerRepo = prOwnerRepo ?? issueOwnerRepo
if (!ownerRepo) {
return 0
}
const counts: Promise<number>[] = []
// PR-only filters cannot match issues; avoid spending a search call on that half.
const hasPrOnlyFilter =
effectiveQuery.draft ||
effectiveQuery.reviewRequested !== null ||
effectiveQuery.reviewedBy !== null
const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null
const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery()
const ghOptions = {
...ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)),
...githubHostExecOptions(ownerRepo)
}
// Decorative counts must stop at the search budget floor.
if (spendsSharedGitHubComQuota(ownerRepo, ghOptions)) {
await getRateLimit()
}
if (
effectiveQuery.scope !== 'pr' &&
effectiveQuery.state !== 'merged' &&
!hasPrOnlyFilter &&
issueOwnerRepo
!usesGraphqlWorkItemSearch(ownerRepo, ghOptions) &&
repositoryRateLimitGuard(ownerRepo, 'search', ghOptions).blocked
) {
counts.push(
countWorkItemsForQuery(
return 0
}
await acquire()
try {
if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) {
return await countWorkItemsForQuery(
repoPath,
issueOwnerRepo,
{ ...effectiveQuery, scope: 'issue' },
ownerRepo,
effectiveQuery,
connectionId,
localGitOptions
)
)
}
if (effectiveQuery.scope !== 'issue' && prOwnerRepo) {
counts.push(
countWorkItemsForQuery(
repoPath,
prOwnerRepo,
{ ...effectiveQuery, scope: 'pr' },
connectionId,
localGitOptions
)
)
}
// Preserve counts from successful sources when another search fails.
const results = await Promise.allSettled(counts)
let total = 0
for (const r of results) {
if (r.status === 'fulfilled') {
total += r.value
} else {
console.warn('countWorkItems partial failure:', r.reason)
}
const counts: Promise<number>[] = []
// PR-only filters cannot match issues; avoid spending a search call on that half.
const hasPrOnlyFilter =
effectiveQuery.draft ||
effectiveQuery.reviewRequested !== null ||
effectiveQuery.reviewedBy !== null
if (
effectiveQuery.scope !== 'pr' &&
effectiveQuery.state !== 'merged' &&
!hasPrOnlyFilter &&
issueOwnerRepo
) {
counts.push(
countWorkItemsForQuery(
repoPath,
issueOwnerRepo,
{ ...effectiveQuery, scope: 'issue' },
connectionId,
localGitOptions
)
)
}
if (effectiveQuery.scope !== 'issue' && prOwnerRepo) {
counts.push(
countWorkItemsForQuery(
repoPath,
prOwnerRepo,
{ ...effectiveQuery, scope: 'pr' },
connectionId,
localGitOptions
)
)
}
// Preserve counts from successful sources when another search fails.
const results = await Promise.allSettled(counts)
let total = 0
for (const r of results) {
if (r.status === 'fulfilled') {
total += r.value
} else {
console.warn('countWorkItems partial failure:', r.reason)
}
}
return total
} catch (err) {
console.warn('countWorkItems failed:', err)
return 0
} finally {
release()
}
return total
} catch (err) {
console.warn('countWorkItems failed:', err)
return 0
} finally {
release()
}
})
}
+70 -67
View File
@@ -1,3 +1,4 @@
import { withGitHubRepoExecution } from '../../github-repository-identity'
import type { ListWorkItemsResult } from '../../../../shared/github/work-item-types'
import type { IssueSourcePreference } from '../../../../shared/repo-types'
import { isGitHubWorkItemsQueryTooLarge } from '../../../../shared/github/work-items-query-bounds'
@@ -18,75 +19,77 @@ export async function listWorkItems(
noCache?: boolean,
localGitOptions: LocalGitExecOptions = {}
): Promise<ListWorkItemsResult<MainWorkItem>> {
const trimmedQuery = query?.trim() ?? ''
const requestedPage = normalizeWorkItemPage(page)
if (isGitHubWorkItemsQueryTooLarge(trimmedQuery)) {
return {
items: [],
sources: {
issues: null,
prs: null,
originCandidate: null,
upstreamCandidate: null
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
const trimmedQuery = query?.trim() ?? ''
const requestedPage = normalizeWorkItemPage(page)
if (isGitHubWorkItemsQueryTooLarge(trimmedQuery)) {
return {
items: [],
sources: {
issues: null,
prs: null,
originCandidate: null,
upstreamCandidate: null
}
}
}
}
const [issueResolved, prResolved] = await Promise.all([
resolveIssueGitHubApiRepositorySource(repoPath, preference, connectionId, localGitOptions),
resolvePrWorkItemSource(repoPath, preference, connectionId, localGitOptions)
])
const issueOwnerRepo = issueResolved.source
const prOwnerRepo = prResolved.source
const ineligible =
!issueOwnerRepo &&
!prOwnerRepo &&
(await isTaskRepositoryIneligible(repoPath, 'github', connectionId, localGitOptions))
await acquire()
try {
// Preserve fetch failures for IPC; an empty fallback would hide per-repo outages.
const partial = !trimmedQuery
? await listRecentWorkItems(
repoPath,
issueOwnerRepo,
prOwnerRepo,
limit,
requestedPage,
connectionId,
noCache,
localGitOptions
)
: await listQueriedWorkItems(
repoPath,
issueOwnerRepo,
prOwnerRepo,
parseTaskQuery(trimmedQuery),
limit,
requestedPage,
connectionId,
localGitOptions,
noCache
)
const [issueResolved, prResolved] = await Promise.all([
resolveIssueGitHubApiRepositorySource(repoPath, preference, connectionId, localGitOptions),
resolvePrWorkItemSource(repoPath, preference, connectionId, localGitOptions)
])
const issueOwnerRepo = issueResolved.source
const prOwnerRepo = prResolved.source
const ineligible =
!issueOwnerRepo &&
!prOwnerRepo &&
(await isTaskRepositoryIneligible(repoPath, 'github', connectionId, localGitOptions))
await acquire()
try {
// Preserve fetch failures for IPC; an empty fallback would hide per-repo outages.
const partial = !trimmedQuery
? await listRecentWorkItems(
repoPath,
issueOwnerRepo,
prOwnerRepo,
limit,
requestedPage,
connectionId,
noCache,
localGitOptions
)
: await listQueriedWorkItems(
repoPath,
issueOwnerRepo,
prOwnerRepo,
parseTaskQuery(trimmedQuery),
limit,
requestedPage,
connectionId,
localGitOptions,
noCache
)
const errors =
partial.issuesError || partial.prsError
? {
...(partial.issuesError ? { issues: partial.issuesError } : {}),
...(partial.prsError ? { prs: partial.prsError } : {})
}
: undefined
return {
items: partial.items,
sources: {
issues: issueOwnerRepo,
prs: prOwnerRepo,
originCandidate: prResolved.originCandidate,
upstreamCandidate: prResolved.upstreamCandidate,
...(ineligible ? { ineligible: true as const } : {})
},
...(errors ? { errors } : {}),
...(issueResolved.fellBack ? { issueSourceFellBack: true } : {})
const errors =
partial.issuesError || partial.prsError
? {
...(partial.issuesError ? { issues: partial.issuesError } : {}),
...(partial.prsError ? { prs: partial.prsError } : {})
}
: undefined
return {
items: partial.items,
sources: {
issues: issueOwnerRepo,
prs: prOwnerRepo,
originCandidate: prResolved.originCandidate,
upstreamCandidate: prResolved.upstreamCandidate,
...(ineligible ? { ineligible: true as const } : {})
},
...(errors ? { errors } : {}),
...(issueResolved.fellBack ? { issueSourceFellBack: true } : {})
}
} finally {
release()
}
} finally {
release()
}
})
}
@@ -1,3 +1,4 @@
import { withGitHubRepoExecution } from '../../github-repository-identity'
import { getRepoExecutionHostId } from '../../../../shared/execution-host'
import {
hostedReviewRepoScope,
@@ -21,51 +22,62 @@ export async function getPRForBranchOutcome(
fallbackPRNumber?: number | null,
options: GitHubPRBranchLookupOptions = {}
): Promise<PRRefreshOutcome> {
const branchName = branch.replace(/^refs\/heads\//, '')
// Detached HEAD cannot discover by branch, but explicit PR numbers remain safe.
if (!branchName && typeof linkedPRNumber !== 'number' && typeof fallbackPRNumber !== 'number') {
return { kind: 'no-pr', fetchedAt: Date.now() }
}
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const localGitOptions = localGitArgs[0] ?? {}
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const executionScope = githubPRStackExecutionScope(connectionId, localGitOptions)
const key = JSON.stringify([
executionScope,
return withGitHubRepoExecution(
repoPath,
scopeGeneration(hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId }))),
branchName,
linkedPRNumber ?? null,
fallbackPRNumber ?? null,
options.acceptMergedFallbackPR ?? false,
options.currentHeadOid ?? null,
githubReadExecutionScope(ghOptions)
])
return runCoalescedProbe(
reads,
key,
async () => {
await acquire()
try {
return await resolvePRForBranchOutcome({
repoPath,
branchName,
linkedPRNumber,
connectionId,
fallbackPRNumber,
options,
localGitOptions,
ghOptions,
executionScope
})
} catch (err) {
return prRefreshUpstreamError(err)
} finally {
release()
connectionId,
hostedReviewLocalGitOptionArgs(options)[0] ?? {},
async (): Promise<PRRefreshOutcome> => {
const branchName = branch.replace(/^refs\/heads\//, '')
// Detached HEAD cannot discover by branch, but explicit PR numbers remain safe.
if (
!branchName &&
typeof linkedPRNumber !== 'number' &&
typeof fallbackPRNumber !== 'number'
) {
return { kind: 'no-pr', fetchedAt: Date.now() }
}
},
2 * 60_000
const localGitArgs = hostedReviewLocalGitOptionArgs(options)
const localGitOptions = localGitArgs[0] ?? {}
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const executionScope = githubPRStackExecutionScope(connectionId, localGitOptions)
const key = JSON.stringify([
executionScope,
repoPath,
scopeGeneration(hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId }))),
branchName,
linkedPRNumber ?? null,
fallbackPRNumber ?? null,
options.acceptMergedFallbackPR ?? false,
options.currentHeadOid ?? null,
githubReadExecutionScope(ghOptions)
])
return runCoalescedProbe(
reads,
key,
async () => {
await acquire()
try {
return await resolvePRForBranchOutcome({
repoPath,
branchName,
linkedPRNumber,
connectionId,
fallbackPRNumber,
options,
localGitOptions,
ghOptions,
executionScope
})
} catch (err) {
return prRefreshUpstreamError(err)
} finally {
release()
}
},
2 * 60_000
)
}
)
}
@@ -1,6 +1,7 @@
import type { GitHubPRStack } from '../../../../shared/github/pull-request-types'
import type { ghRepoExecOptions } from '../../gh-utils'
import type { GitHubApiRepository } from '../../github-api-repository'
import { githubHostExecOptions, type GitHubApiRepository } from '../../github-api-repository'
import { githubReadExecutionScope } from '../../github-read-execution-scope'
import { githubRepoIdentityKey } from '../../../../shared/github/repository-identity-key'
import { getRestPRByNumber } from './pr-number-lookup'
export const PR_STACK_SUMMARY_CACHE_TTL_MS = 60_000
@@ -42,7 +43,8 @@ export async function getCachedGitHubPRStackSummary(
ghOptions: ReturnType<typeof ghRepoExecOptions>,
executionScope: string
): Promise<GitHubPRStack | undefined> {
const key = `${executionScope}\0${githubRepoIdentityKey(ownerRepo)}#${number}`
const execution = { ...ghOptions, ...githubHostExecOptions(ownerRepo) }
const key = `${executionScope}\0${githubReadExecutionScope(execution)}\0${githubRepoIdentityKey(ownerRepo)}#${number}`
const now = Date.now()
prunePRStackSummaryCache(now)
const cached = prStackSummaryCache.get(key)
@@ -56,7 +58,7 @@ export async function getCachedGitHubPRStackSummary(
if (existing) {
return existing
}
const request = getRestPRByNumber(ownerRepo, number, ghOptions).then((pr) => pr.stack)
const request = getRestPRByNumber(ownerRepo, number, execution).then((pr) => pr.stack)
prStackSummaryInFlight.set(key, request)
try {
const value = await request
@@ -1,3 +1,4 @@
import { withGitHubRepoExecution } from '../../github-repository-identity'
import type { IssueSourcePreference } from '../../../../shared/repo-types'
import type { GitPushTarget } from '../../../../shared/worktree/types'
import {
@@ -53,99 +54,101 @@ export async function getPullRequestPushTarget(
localGitOptions: LocalGitExecOptions = {},
preference?: IssueSourcePreference
): Promise<PullRequestPushTarget | null> {
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const candidates = await resolvePullRequestLookupCandidates(
repoPath,
preference,
connectionId,
localGitOptions
)
if (candidates.length === 0) {
return null
}
await acquire()
try {
let prStdout = ''
let matchedRepository: GitHubApiRepository | null = null
for (const candidate of candidates) {
try {
const { stdout } = await ghExecFileAsync(
['api', `repos/${candidate.owner}/${candidate.repo}/pulls/${prNumber}`],
{ ...ghOptions, ...githubHostExecOptions(candidate) }
)
prStdout = stdout
matchedRepository = candidate
break
} catch (error) {
// Fork origin may differ from the upstream PR namespace; exhaust candidate repositories.
if (isNotFoundGhError(error)) {
continue
}
throw error
}
}
if (!prStdout || !matchedRepository) {
return null
}
const origin = await getGitHubApiRepositoryForRemote(
return withGitHubRepoExecution(repoPath, connectionId, localGitOptions, async () => {
const context = githubRepoContext(repoPath, connectionId, localGitOptions)
const ghOptions = ghRepoExecOptions(context)
const candidates = await resolvePullRequestLookupCandidates(
repoPath,
'origin',
preference,
connectionId,
localGitOptions
)
const pr = JSON.parse(prStdout) as {
maintainer_can_modify?: boolean
head?: {
ref?: string
repo?: {
full_name?: string
clone_url?: string
ssh_url?: string
owner?: { login?: string }
name?: string
} | null
}
}
const headRepo = pr.head?.repo
const branchName = pr.head?.ref?.trim()
const owner = headRepo?.owner?.login?.trim()
const repo = headRepo?.name?.trim() ?? headRepo?.full_name?.split('/')[1]?.trim()
const cloneUrl = headRepo?.clone_url?.trim()
const sshUrl = headRepo?.ssh_url?.trim()
const maintainerCanModify =
typeof pr.maintainer_can_modify === 'boolean' ? pr.maintainer_can_modify : undefined
if (!owner || !repo || !branchName || !cloneUrl || !sshUrl) {
if (candidates.length === 0) {
return null
}
if (
origin &&
githubRepoIdentityKey(origin) ===
githubRepoIdentityKey({ owner, repo, host: matchedRepository.host })
) {
await acquire()
try {
let prStdout = ''
let matchedRepository: GitHubApiRepository | null = null
for (const candidate of candidates) {
try {
const { stdout } = await ghExecFileAsync(
['api', `repos/${candidate.owner}/${candidate.repo}/pulls/${prNumber}`],
{ ...ghOptions, ...githubHostExecOptions(candidate) }
)
prStdout = stdout
matchedRepository = candidate
break
} catch (error) {
// Fork origin may differ from the upstream PR namespace; exhaust candidate repositories.
if (isNotFoundGhError(error)) {
continue
}
throw error
}
}
if (!prStdout || !matchedRepository) {
return null
}
const origin = await getGitHubApiRepositoryForRemote(
repoPath,
'origin',
connectionId,
localGitOptions
)
const pr = JSON.parse(prStdout) as {
maintainer_can_modify?: boolean
head?: {
ref?: string
repo?: {
full_name?: string
clone_url?: string
ssh_url?: string
owner?: { login?: string }
name?: string
} | null
}
}
const headRepo = pr.head?.repo
const branchName = pr.head?.ref?.trim()
const owner = headRepo?.owner?.login?.trim()
const repo = headRepo?.name?.trim() ?? headRepo?.full_name?.split('/')[1]?.trim()
const cloneUrl = headRepo?.clone_url?.trim()
const sshUrl = headRepo?.ssh_url?.trim()
const maintainerCanModify =
typeof pr.maintainer_can_modify === 'boolean' ? pr.maintainer_can_modify : undefined
if (!owner || !repo || !branchName || !cloneUrl || !sshUrl) {
return null
}
if (
origin &&
githubRepoIdentityKey(origin) ===
githubRepoIdentityKey({ owner, repo, host: matchedRepository.host })
) {
return {
pushTarget: { remoteName: 'origin', branchName },
...(maintainerCanModify !== undefined ? { maintainerCanModify } : {})
}
}
let originUrl: string | null = null
try {
const rawOriginUrl = await getRemoteUrlForRepo(context, 'origin')
originUrl = rawOriginUrl?.trim() || null
} catch {
originUrl = null
}
return {
pushTarget: { remoteName: 'origin', branchName },
pushTarget: {
remoteName: sanitizeRemoteName(owner, repo),
branchName,
remoteUrl: pickPushRemoteUrl({ originUrl, cloneUrl, sshUrl })
},
...(maintainerCanModify !== undefined ? { maintainerCanModify } : {})
}
} finally {
release()
}
let originUrl: string | null = null
try {
const rawOriginUrl = await getRemoteUrlForRepo(context, 'origin')
originUrl = rawOriginUrl?.trim() || null
} catch {
originUrl = null
}
return {
pushTarget: {
remoteName: sanitizeRemoteName(owner, repo),
branchName,
remoteUrl: pickPushRemoteUrl({ originUrl, cloneUrl, sshUrl })
},
...(maintainerCanModify !== undefined ? { maintainerCanModify } : {})
}
} finally {
release()
}
})
}