Fix hosted review selection, conversations and optional job failures

Co-authored-by: Mahedi Hasan Emon <mahedi.emon62@gmail.com>

Co-authored-by: Victor GALISSON <victor.galisson@purecontrol.com>
This commit is contained in:
Brennan Benson
2026-11-08 17:43:52 -08:00
co-authored by Mahedi Hasan Emon Victor GALISSON
parent 651f656c77
commit e55ff64d98
59 changed files with 2419 additions and 425 deletions
+3 -9
View File
@@ -1,13 +1,12 @@
import {
gitLabPipelineToPRCheck,
mapGitLabPipelineJobStatusToCheckStatus,
mapGitLabPipelineJobStatusToConclusion
gitLabPipelineJobOutcome
} from '../../../src/shared/source-control/checks/gitlab/gitlab-pipeline-checks'
import { summarizeProviderChecks } from '../../../src/shared/source-control/checks/provider-check-summary'
import type { ProviderCheckSummary } from '../../../src/shared/github/pull-request-types'
import type { GitLabPipeline } from '../../../src/shared/gitlab-types'
type GitLabPipelineJobLike = { status: string }
type GitLabPipelineJobLike = { status: string; allowFailure?: boolean }
export function buildGitLabCheckSummary(
jobs: GitLabPipelineJobLike[],
@@ -20,10 +19,5 @@ export function buildGitLabCheckSummary(
scope: 'pipeline'
}
}
return summarizeProviderChecks(
jobs.map((job) => ({
status: mapGitLabPipelineJobStatusToCheckStatus(job.status),
conclusion: mapGitLabPipelineJobStatusToConclusion(job.status)
}))
)
return summarizeProviderChecks(jobs.map(gitLabPipelineJobOutcome))
}
@@ -251,6 +251,7 @@ export type DetailPayload =
name: string
stage: string
status: string
allowFailure?: boolean
webUrl?: string | null
duration?: number | null
}>
@@ -74,6 +74,7 @@ export const gitlabWorkItemDetailSchema = z
name: z.string(),
stage: z.string(),
status: z.string(),
allowFailure: salvagedOptional('allowFailure', z.boolean()),
webUrl: prNullableText('webUrl'),
duration: salvagedOptional('duration', z.number().finite().nullable())
})
@@ -53,7 +53,13 @@ const comment = {
url: 'https://example.test/comment'
}
function response(pr: unknown, errors?: unknown): { stdout: string } {
return { stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }) }
return {
stdout: JSON.stringify({ data: { repository: { pullRequest: pr } }, errors }, (_key, value) =>
value && typeof value === 'object' && Array.isArray(value.nodes)
? { pageInfo: { hasNextPage: false, endCursor: null }, ...value }
: value
)
}
}
describe('PR conversation request reuse', () => {
@@ -83,6 +89,7 @@ describe('PR conversation request reuse', () => {
)
ghExecFileAsyncMock
.mockRejectedValueOnce(Object.assign(new Error('GraphQL error'), partial))
.mockResolvedValueOnce({ stdout: 'me' })
.mockResolvedValueOnce({
stdout: JSON.stringify([
{
@@ -96,13 +103,13 @@ describe('PR conversation request reuse', () => {
})
const comments = await getPRComments('/repo', 7, { ...options, noCache: true })
expect(comments.map((c) => c.body)).toEqual(['Conversation', 'Review summary'])
expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([
expect(ghExecFileAsyncMock.mock.calls[2][0]).toEqual([
'api',
'-H',
'Accept: application/vnd.github.full+json',
'repos/acme/widgets/pulls/7/reviews?per_page=100'
])
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2)
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3)
})
it('retains the successful REST source when GraphQL and the other REST source fail', async () => {
@@ -301,4 +308,108 @@ describe('PR conversation request reuse', () => {
})
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1)
})
it('pages independent sources and nested replies without rereading completed sources', async () => {
const thread = {
id: 'T1',
isResolved: true,
line: 4,
startLine: null,
originalLine: 4,
originalStartLine: null,
rootHunk: { nodes: [{ diffHunk: '@@ -1 +1 @@\n-old\n+new' }] },
comments: {
nodes: [{ ...comment, id: 'ROOT', databaseId: 11, path: 'a.ts' }],
pageInfo: { hasNextPage: true, endCursor: 'reply-1' }
}
}
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
if (args.includes('threadId=T1')) {
return {
stdout: JSON.stringify({
data: {
node: {
...thread,
comments: {
nodes: [{ ...comment, id: 'REPLY', databaseId: 12, body: 'Reply', path: 'a.ts' }],
pageInfo: { hasNextPage: false, endCursor: null }
}
}
}
})
}
}
if (args.includes('cursor=comment-1')) {
return response({
comments: { nodes: [{ ...comment, id: 'IC_13', databaseId: 13, body: 'Newest' }] }
})
}
return response({
comments: { nodes: [comment], pageInfo: { hasNextPage: true, endCursor: 'comment-1' } },
reviews: { nodes: [] },
reviewThreads: { nodes: [thread] }
})
})
const result = await getPRComments('/repo', 7, { ...options, noCache: true })
expect(result.map((c) => c.id)).toEqual([10, 13, 11, 12])
expect(result.find((c) => c.id === 11)).toMatchObject({
threadId: 'T1',
isResolved: true,
path: 'a.ts',
line: 4,
diffHunk: '-old\n+new'
})
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(3)
const continuation = ghExecFileAsyncMock.mock.calls[1][0].join(' ')
expect(continuation).not.toContain('reviewThreads(')
expect(continuation).not.toContain('reviews(')
})
it.each(['failure', 'repeated cursor'])(
'rejects an incomplete conversation after %s',
async (mode) => {
const first = response({
comments: { nodes: [comment], pageInfo: { hasNextPage: true, endCursor: 'same' } },
reviews: { nodes: [] },
reviewThreads: { nodes: [] }
})
ghExecFileAsyncMock.mockResolvedValueOnce(first)
if (mode === 'failure') {
ghExecFileAsyncMock.mockRejectedValueOnce(new Error('offline'))
} else {
ghExecFileAsyncMock.mockResolvedValueOnce(first)
}
await expect(getPRComments('/repo', 7, { ...options, noCache: true })).rejects.toThrow(
/pagination|cursor/
)
}
)
it('pages raw REST review rows even when the first 100 bodies are hidden', async () => {
const review = (id: number, body: string) => ({
id,
body,
user: null,
submitted_at: '2026-04-01T00:00:00Z',
html_url: 'https://example.test/review'
})
ghExecFileAsyncMock.mockImplementation(async (args: string[]) => {
if (args.includes('graphql')) {
return response({ comments: { nodes: [] }, reviews: null, reviewThreads: { nodes: [] } })
}
if (args.includes('user')) {
return { stdout: 'me' }
}
return {
stdout: JSON.stringify(
args.at(-1)?.includes('&page=2')
? [review(101, 'Latest summary')]
: Array.from({ length: 100 }, (_, i) => review(i, '<!-- hidden -->'))
)
}
})
await expect(getPRComments('/repo', 7, { ...options, noCache: true })).resolves.toMatchObject([
{ id: 101, body: 'Latest summary' }
])
expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(4)
})
})
@@ -37,6 +37,7 @@ vi.mock('./github-api-repository', async (importOriginal) =>
)
)
import { getFallbackPRListForBranch, getRestPRForBranch } from './client/lookup/pr-branch-lookup'
import { getPRForBranchOutcome } from './client/lookup/pr-for-branch-outcome'
import { resetPRForBranchMocks } from './client-test-harness'
@@ -70,4 +71,56 @@ describe('PR lookup conditional REST reads', () => {
])
expect(noteRateLimitSpendMock.mock.calls).toEqual([['core']])
})
it('revalidates both mixed and active discovery responses before falling back to history', async () => {
const repo = { owner: 'acme', repo: 'widgets', host: 'github.com' }
const old = Array.from({ length: 10 }, (_, i) => ({
number: i + 1,
state: 'closed',
title: 'Old',
head: { ref: 'feature' }
}))
const open = { number: 11, state: 'open', title: 'Active', head: { ref: 'feature' } }
const http = (data: unknown, etag: string) => ({
stdout: `HTTP/2.0 200 OK\nEtag: "${etag}"\r\n\r\n${JSON.stringify(data)}`
})
ghExecFileAsyncMock
.mockResolvedValueOnce(http(old, 'recent'))
.mockResolvedValueOnce(http([open], 'active'))
.mockRejectedValueOnce(
Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' })
)
.mockRejectedValueOnce(
Object.assign(new Error('304'), { stdout: 'HTTP/2.0 304 Not Modified\n\n' })
)
await expect(
getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' })
).resolves.toMatchObject({ number: 11 })
await expect(
getRestPRForBranch(repo, 'acme', 'feature', { cwd: '/repo' })
).resolves.toMatchObject({ number: 11 })
expect(ghExecFileAsyncMock.mock.calls[2][0]).toContain('If-None-Match: "recent"')
expect(ghExecFileAsyncMock.mock.calls[3][0]).toContain('If-None-Match: "active"')
})
it('uses the same saturated-page rule for the CLI fallback', async () => {
ghExecFileAsyncMock
.mockResolvedValueOnce({
stdout: JSON.stringify(
Array.from({ length: 10 }, (_, i) => ({ number: i + 1, state: 'CLOSED' }))
)
})
.mockResolvedValueOnce({ stdout: '[{"number":11,"state":"OPEN"}]' })
await expect(
getFallbackPRListForBranch(
{ owner: 'acme', repo: 'widgets', host: 'github.com' },
'feature',
{ cwd: '/repo' }
)
).resolves.toMatchObject({ number: 11 })
expect(ghExecFileAsyncMock.mock.calls[0][0]).toEqual(
expect.arrayContaining(['--state', 'all', '--limit', '10'])
)
expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual(
expect.arrayContaining(['--state', 'open', '--limit', '1'])
)
})
})
+93 -11
View File
@@ -9,7 +9,12 @@ import { resolveGitHubRepoExecution, type GitHubApiRepository } from '../../gith
import { noteRepositoryRateLimitSpend, repositoryRateLimitGuard } from '../../rate-limit'
import { assertRateLimitBudget } from './../lookup/pr-lookup-rate-limit'
import { REVIEW_THREADS_QUERY } from './pr-review-threads-query'
import { parsePRConversationResponse, parseRestPRComments } from './pr-conversation-response'
import type { parsePRConversationResponse } from './pr-conversation-response'
import { parseRestPRCommentPage } from './pr-conversation-response'
import {
readCompletePRConversation,
IncompletePRConversationError
} from './pr-conversation-pagination'
import { readViewerLogin } from './authenticated-viewer'
/** Combine conversation comments, review summaries and GraphQL threads with resolution metadata. */
async function readPRComments(
@@ -68,31 +73,106 @@ async function readPRComments(
let conversation: ReturnType<typeof parsePRConversationResponse> = { reviewComments: [] }
if (threadsResult) {
try {
conversation = parsePRConversationResponse(threadsResult.stdout)
} catch {
conversation = await readCompletePRConversation(
threadsResult.stdout,
async (query, variables) => {
await assertRateLimitBudget('graphql', ownerRepo, ghOptions)
noteRepositoryRateLimitSpend(ownerRepo, 'graphql', 1, ghOptions)
const args = ['api', 'graphql', '-f', `query=${query}`]
if (!('threadId' in variables)) {
args.push(
'-f',
`owner=${ownerRepo.owner}`,
'-f',
`repo=${ownerRepo.repo}`,
'-F',
`pr=${prNumber}`
)
}
for (const [key, value] of Object.entries(variables)) {
args.push('-f', `${key}=${value}`)
}
try {
return (await ghExecFileAsync(args, ghOptions)).stdout
} catch (error) {
const { stdout } = extractExecError(error)
if (stdout) {
return stdout
}
throw error
}
}
)
} catch (error) {
if (error instanceof IncompletePRConversationError) {
throw error
}
console.warn('Invalid review threads response; falling back to REST')
}
}
const { issueComments, reviewSummaries, reviewComments } = conversation
// REST has no viewerDidAuthor, so conversation comments match the reading account's login instead.
let restViewer: Promise<string | null> | undefined
const readRestSource = async (endpoint: string, reviews: boolean): Promise<PRComment[]> => {
await assertRateLimitBudget('core', ownerRepo, ghOptions).catch((error: unknown) => {
restBudgetFailed = true
throw error
})
const comments: PRComment[] = []
const ids = new Set<number>()
const rawIds = new Set<number>()
let page = 1
try {
noteRepositoryRateLimitSpend(ownerRepo, 'core', reviews ? 1 : 2, ghOptions)
const [{ stdout }, viewerLogin] = await Promise.all([
ghExecFileAsync(['api', '-H', GITHUB_BODY_MEDIA_TYPE, endpoint], ghOptions),
reviews ? null : readViewerLogin(ghOptions)
])
return parseRestPRComments(stdout, reviews, viewerLogin)
while (true) {
if (page > 1) {
await assertRateLimitBudget('core', ownerRepo, ghOptions)
}
const needsViewer = !restViewer
restViewer ??= readViewerLogin(ghOptions)
noteRepositoryRateLimitSpend(ownerRepo, 'core', needsViewer ? 2 : 1, ghOptions)
const [{ stdout }, viewer] = await Promise.all([
ghExecFileAsync(
[
'api',
'-H',
GITHUB_BODY_MEDIA_TYPE,
page === 1 ? endpoint : `${endpoint}&page=${page}`
],
ghOptions
),
restViewer
])
const result = parseRestPRCommentPage(stdout, reviews, viewer)
const advanced = result.rawIds.some((id) => !rawIds.has(id))
for (const id of result.rawIds) {
rawIds.add(id)
}
for (const comment of result.comments) {
if (!ids.has(comment.id)) {
ids.add(comment.id)
comments.push(comment)
}
}
if (!result.hasMore) {
return comments
}
if (!advanced) {
throw new Error('GitHub REST conversation page did not advance')
}
page += 1
}
} catch (error) {
if (page > 1) {
throw new IncompletePRConversationError('GitHub REST conversation pagination failed', {
cause: error
})
}
console.warn('Failed to fetch PR conversation fallback:', extractExecError(error).stderr)
return []
}
}
const [issueResult, reviewsResult] = await Promise.all([
issueComments === undefined
? readRestSource(`${base}/issues/${prNumber}/comments?per_page=100`, false)
@@ -106,8 +186,10 @@ async function readPRComments(
...reviewComments,
...(reviewSummaries ?? reviewsResult ?? [])
]
all.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime())
return all
.map((comment) => ({ comment, time: Date.parse(comment.createdAt) }))
.sort((a, b) => a.time - b.time)
.map(({ comment }) => comment)
}
// Legacy local fallback returns issue-level comments only.
@@ -135,7 +217,7 @@ async function readPRComments(
...(c.viewerDidAuthor === true ? { viewerDidAuthor: true } : {})
}))
} catch (err) {
if (restBudgetFailed) {
if (restBudgetFailed || err instanceof IncompletePRConversationError) {
throw err
}
console.warn('getPRComments failed:', err)
@@ -0,0 +1,111 @@
import {
mapPRConversationSources,
parsePRConversationSources,
parsePRReviewThreadResponse
} from './pr-conversation-response'
import {
reviewConversationQuery,
REVIEW_THREAD_REPLIES_QUERY,
type PRConversationSource
} from './pr-review-threads-query'
export class IncompletePRConversationError extends Error {}
type PageInfo = { hasNextPage: boolean; endCursor: string | null } | undefined
function nextCursor(info: PageInfo, seen: Set<string>): string | null {
if (!info) {
throw new IncompletePRConversationError('Missing GitHub conversation page information')
}
if (!info.hasNextPage) {
return null
}
if (!info.endCursor || seen.has(info.endCursor)) {
throw new IncompletePRConversationError('GitHub conversation cursor did not advance')
}
seen.add(info.endCursor)
return info.endCursor
}
function appendNodes<T extends { id: string } | null>(
target: T[],
nodes: T[],
ids: Set<string>
): void {
for (const node of nodes) {
if (node && !ids.has(node.id)) {
ids.add(node.id)
target.push(node)
}
}
}
/** Complete independent sources once, then each unfinished thread, before normalizing/sorting. */
export async function readCompletePRConversation(
initial: string,
read: (query: string, variables: Record<string, string>) => Promise<string>
): Promise<ReturnType<typeof mapPRConversationSources>> {
const sources = parsePRConversationSources(initial)
try {
const readSource = async (name: PRConversationSource, cursor: string) =>
parsePRConversationSources(await read(reviewConversationQuery(name), { cursor }), name)
await finishSource(
sources.comments,
async (cursor) => (await readSource('comments', cursor)).comments
)
await finishSource(
sources.reviews,
async (cursor) => (await readSource('reviews', cursor)).reviews
)
await finishSource(
sources.reviewThreads,
async (cursor) => (await readSource('reviewThreads', cursor)).reviewThreads
)
for (const thread of sources.reviewThreads?.nodes ?? []) {
if (!thread) {
continue
}
const seen = new Set<string>()
const ids = new Set(thread.comments.nodes.flatMap((node) => (node ? [node.id] : [])))
let cursor = nextCursor(thread.comments.pageInfo, seen)
while (cursor) {
const page = parsePRReviewThreadResponse(
await read(REVIEW_THREAD_REPLIES_QUERY, { threadId: thread.id, cursor })
)
if (page.id !== thread.id) {
throw new Error('Unexpected GitHub review thread')
}
appendNodes(thread.comments.nodes, page.comments.nodes, ids)
cursor = nextCursor(page.comments.pageInfo, seen)
}
}
return mapPRConversationSources(sources)
} catch (cause) {
if (cause instanceof IncompletePRConversationError) {
throw cause
}
throw new IncompletePRConversationError('GitHub conversation pagination failed', { cause })
}
}
async function finishSource<T extends { id: string } | null>(
connection: { nodes: T[]; pageInfo?: Exclude<PageInfo, undefined> } | undefined,
read: (
cursor: string
) => Promise<{ nodes: T[]; pageInfo?: Exclude<PageInfo, undefined> } | undefined>
): Promise<void> {
if (!connection) {
return
}
const seen = new Set<string>()
const ids = new Set(connection.nodes.flatMap((node) => (node ? [node.id] : [])))
let cursor = nextCursor(connection.pageInfo, seen)
while (cursor) {
const page = await read(cursor)
if (!page) {
throw new Error('Incomplete GitHub conversation source')
}
appendNodes(connection.nodes, page.nodes, ids)
cursor = nextCursor(page.pageInfo, seen)
}
}
@@ -30,30 +30,32 @@ const commentSchema = z.object({
)
.nullish()
})
const commentConnection = z.object({ nodes: z.array(commentSchema.nullable()) })
const threadConnection = z.object({
nodes: z.array(
z
.object({
id: z.string(),
isResolved: z.boolean(),
line: z.number().nullable(),
startLine: z.number().nullable(),
originalLine: z.number().nullable(),
originalStartLine: z.number().nullable(),
diffSide: z.string().nullish().catch(undefined),
// Optional so a failed or trimmed field never drops the thread.
rootHunk: z
.object({ nodes: z.array(z.object({ diffHunk: z.string().nullish() }).nullable()) })
.nullish()
.catch(undefined),
comments: z.object({
nodes: z.array(commentSchema.extend({ path: z.string() }).nullable())
})
})
.nullable()
)
const pageInfo = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }).optional()
const commentConnection = z.object({ nodes: z.array(commentSchema.nullable()), pageInfo })
const threadSchema = z.object({
id: z.string(),
isResolved: z.boolean(),
line: z.number().nullable(),
startLine: z.number().nullable(),
originalLine: z.number().nullable(),
originalStartLine: z.number().nullable(),
diffSide: z.string().nullish().catch(undefined),
rootHunk: z
.object({ nodes: z.array(z.object({ diffHunk: z.string().nullish() }).nullable()) })
.nullish()
.catch(undefined),
comments: z.object({
nodes: z.array(commentSchema.extend({ path: z.string() }).nullable()),
pageInfo
})
})
const threadConnection = z.object({ nodes: z.array(threadSchema.nullable()), pageInfo })
export type PRConversationSources = {
comments?: z.infer<typeof commentConnection>
reviews?: z.infer<typeof commentConnection>
reviewThreads?: z.infer<typeof threadConnection>
}
export type PRReviewThread = z.infer<typeof threadSchema>
const envelopeSchema = z.object({
data: z
.object({
@@ -121,11 +123,10 @@ function hasVisibleReviewBody(body: string | null | undefined): boolean {
return reviewMarkdown.parse(body).children.some(hasVisibleNode)
}
export function parsePRConversationResponse(stdout: string): {
issueComments?: PRComment[]
reviewSummaries?: PRComment[]
reviewComments: PRComment[]
} {
export function parsePRConversationSources(
stdout: string,
strictSource?: string
): PRConversationSources {
const envelope = envelopeSchema.parse(JSON.parse(stdout))
const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors)
const pr = envelope.data?.repository?.pullRequest
@@ -136,23 +137,56 @@ export function parsePRConversationResponse(stdout: string): {
!error.path?.length || !error.path.includes('pullRequest') || error.path[2] === source
)
)
if (strictSource && failed(strictSource)) {
throw new Error('Incomplete GitHub conversation source')
}
const comments = commentConnection.safeParse(pr?.comments)
const reviews = commentConnection.safeParse(pr?.reviews)
const threads = threadConnection.safeParse(pr?.reviewThreads)
return {
issueComments:
comments.success && !failed('comments')
? comments.data.nodes.filter(hasDatabaseId).map(mapGraphQLComment)
: undefined,
reviewSummaries:
reviews.success && !failed('reviews')
? reviews.data.nodes
.filter(hasDatabaseId)
.filter((c) => hasVisibleReviewBody(c.body))
.map(mapGraphQLComment)
: undefined,
reviewComments: threads.success
? threads.data.nodes.flatMap((thread) =>
...(comments.success && !failed('comments') ? { comments: comments.data } : {}),
...(reviews.success && !failed('reviews') ? { reviews: reviews.data } : {}),
...(threads.success ? { reviewThreads: threads.data } : {})
}
}
export function parsePRReviewThreadResponse(stdout: string): PRReviewThread {
const envelope = z
.object({ data: z.object({ node: z.unknown() }), errors: envelopeSchema.shape.errors })
.parse(JSON.parse(stdout))
const errors = removeFailedGitHubBodyHtml(envelope.data, envelope.errors)
if (errors?.length) {
throw new Error('Incomplete GitHub review thread replies')
}
return threadSchema.parse(envelope.data.node)
}
export function parsePRConversationResponse(stdout: string): {
issueComments?: PRComment[]
reviewSummaries?: PRComment[]
reviewComments: PRComment[]
} {
return mapPRConversationSources(parsePRConversationSources(stdout))
}
export function mapPRConversationSources(sources: PRConversationSources): {
issueComments?: PRComment[]
reviewSummaries?: PRComment[]
reviewComments: PRComment[]
} {
const { comments, reviews, reviewThreads: threads } = sources
return {
issueComments: comments
? comments.nodes.filter(hasDatabaseId).map(mapGraphQLComment)
: undefined,
reviewSummaries: reviews
? reviews.nodes
.filter(hasDatabaseId)
.filter((c) => hasVisibleReviewBody(c.body))
.map(mapGraphQLComment)
: undefined,
reviewComments: threads
? threads.nodes.flatMap((thread) =>
thread
? thread.comments.nodes.filter(hasDatabaseId).map((c) =>
Object.assign(mapGraphQLComment(c), {
@@ -193,14 +227,13 @@ const restCommentSchema = z.object({
html_url: z.string()
})
export function parseRestPRComments(
export function parseRestPRCommentPage(
stdout: string,
reviews: boolean,
viewerLogin: string | null
): PRComment[] {
return z
.array(restCommentSchema)
.parse(JSON.parse(stdout))
): { comments: PRComment[]; rawIds: number[]; hasMore: boolean } {
const rows = z.array(restCommentSchema).parse(JSON.parse(stdout))
const comments = rows
.filter((c) => !reviews || hasVisibleReviewBody(c.body))
.map((c) => ({
id: c.id,
@@ -213,4 +246,13 @@ export function parseRestPRComments(
isBot: c.user?.type === 'Bot',
...viewerAuthorship(c.user?.login, viewerLogin)
}))
return { comments, rawIds: rows.map((row) => row.id), hasMore: rows.length >= 100 }
}
export function parseRestPRComments(
stdout: string,
reviews: boolean,
viewerLogin: string | null
): PRComment[] {
return parseRestPRCommentPage(stdout, reviews, viewerLogin).comments
}
@@ -1,82 +1,39 @@
// REST review comments omit thread IDs and resolution status; fetch them through GraphQL.
export const REVIEW_THREADS_QUERY = `
query($owner: String!, $repo: String!, $pr: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr) {
reviewThreads(first: 100) {
nodes {
id
isResolved
line
startLine
originalLine
originalStartLine
diffSide
rootHunk: comments(first: 1) {
nodes {
diffHunk
}
}
comments(first: 100) {
nodes {
id
databaseId
author { __typename login avatarUrl(size: 48) }
body
bodyHTML
createdAt
url
viewerDidAuthor
path
reactionGroups {
content
viewerHasReacted
reactors {
totalCount
}
}
}
}
}
}
comments(first: 100) {
nodes {
id
databaseId
author { __typename login avatarUrl(size: 48) }
body
bodyHTML
createdAt
url
viewerDidAuthor
reactionGroups {
content
viewerHasReacted
reactors {
totalCount
}
}
}
}
reviews(first: 100) {
nodes {
id
databaseId
author { __typename login avatarUrl(size: 48) }
body
bodyHTML
createdAt
submittedAt
url
reactionGroups {
content
viewerHasReacted
reactors {
totalCount
}
}
}
}
const PAGE_INFO = 'pageInfo { hasNextPage endCursor }'
const COMMENT_FIELDS = `
id databaseId author { __typename login avatarUrl(size: 48) }
body bodyHTML createdAt url viewerDidAuthor
reactionGroups { content viewerHasReacted reactors { totalCount } }
`
const THREAD_FIELDS = `
id isResolved line startLine originalLine originalStartLine diffSide
rootHunk: comments(first: 1) { nodes { diffHunk } }
comments(first: 100) { ${PAGE_INFO} nodes { ${COMMENT_FIELDS} path } }
`
export type PRConversationSource = 'comments' | 'reviews' | 'reviewThreads'
export function reviewConversationQuery(source?: PRConversationSource): string {
const connection = (name: PRConversationSource): string => {
if (source && name !== source) {
return ''
}
const fields =
name === 'reviewThreads'
? THREAD_FIELDS
: `${COMMENT_FIELDS}${name === 'reviews' ? ' submittedAt' : ''}`
return `${name}(first: 100${source ? ', after: $cursor' : ''}) { ${PAGE_INFO} nodes { ${fields} } }`
}
return `query($owner: String!, $repo: String!, $pr: Int!${source ? ', $cursor: String!' : ''}) {
repository(owner: $owner, name: $repo) { pullRequest(number: $pr) {
${connection('reviewThreads')} ${connection('comments')} ${connection('reviews')}
} }
}`
}
export const REVIEW_THREADS_QUERY = reviewConversationQuery()
export const REVIEW_THREAD_REPLIES_QUERY = `
query($threadId: ID!, $cursor: String!) {
node(id: $threadId) { ... on PullRequestReviewThread {
id isResolved line startLine originalLine originalStartLine diffSide
comments(first: 100, after: $cursor) { ${PAGE_INFO} nodes { ${COMMENT_FIELDS} path } }
} }
}`
@@ -1,3 +1,5 @@
import { assertRateLimitBudget } from './pr-lookup-rate-limit'
import { selectBranchReview } from '../../../source-control/branch-review-selection'
import { ghExecFileAsync } from '../../gh-utils'
import type { OwnerRepo, ghRepoExecOptions } from '../../gh-utils'
import {
@@ -24,12 +26,20 @@ 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.
const BRANCH_PR_LOOKUP_PAGE_SIZE = 10
function preferOpenPullRequest<T extends { state: string }>(list: T[]): T | undefined {
return list.find((pr) => pr.state.toLowerCase() === 'open') ?? list[0]
function parseBranchList<T extends { state: string; number: number }>(stdout: string): T[] {
const parsed: unknown = JSON.parse(stdout)
if (
!Array.isArray(parsed) ||
!parsed.every(
(row) =>
row && typeof row.state === 'string' && Number.isInteger(row.number) && row.number > 0
)
) {
throw new Error('Invalid branch review list')
}
return parsed
}
export async function getRestPRForBranch(
@@ -39,13 +49,20 @@ export async function getRestPRForBranch(
ghOptions: ReturnType<typeof ghRepoExecOptions>
): Promise<PullRequestLookupData | null> {
const head = encodeURIComponent(`${headOwner}:${branchName}`)
const stdout = await revalidateGitHubRestJson(
prRepo,
`repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=all&per_page=${BRANCH_PR_LOOKUP_PAGE_SIZE}`,
ghOptions
)
const list = JSON.parse(stdout) as RestPullRequest[]
const pr = preferOpenPullRequest(list)
const read = async (state: 'all' | 'open', limit: number): Promise<RestPullRequest[]> =>
parseBranchList<RestPullRequest>(
await revalidateGitHubRestJson(
prRepo,
`repos/${prRepo.owner}/${prRepo.repo}/pulls?head=${head}&state=${state}&per_page=${limit}`,
ghOptions
)
)
const pr = await selectBranchReview({
readRecent: () => read('all', BRANCH_PR_LOOKUP_PAGE_SIZE),
readActive: async () => (await read('open', 1))[0] ?? null,
isActive: (row) => row.state.toLowerCase() === 'open',
pageSize: BRANCH_PR_LOOKUP_PAGE_SIZE
})
return pr ? mapRestPullRequest(pr) : null
}
@@ -54,26 +71,34 @@ export async function getFallbackPRListForBranch(
branchName: string,
ghOptions: ReturnType<typeof ghRepoExecOptions>
): Promise<PullRequestLookupData | null> {
noteRepositoryRateLimitSpend(prRepo, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'pr',
'list',
'--repo',
`${prRepo.owner}/${prRepo.repo}`,
'--head',
branchName,
'--state',
'all',
'--limit',
String(BRANCH_PR_LOOKUP_PAGE_SIZE),
'--json',
PR_BRANCH_LIST_JSON_FIELDS
],
{ ...ghOptions, ...githubHostExecOptions(prRepo) }
)
const list = JSON.parse(stdout) as PullRequestLookupData[]
const pr = preferOpenPullRequest(list)
const read = async (state: 'all' | 'open', limit: number): Promise<PullRequestLookupData[]> => {
await assertRateLimitBudget('graphql', prRepo, ghOptions)
noteRepositoryRateLimitSpend(prRepo, 'graphql', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'pr',
'list',
'--repo',
`${prRepo.owner}/${prRepo.repo}`,
'--head',
branchName,
'--state',
state,
'--limit',
String(limit),
'--json',
PR_BRANCH_LIST_JSON_FIELDS
],
{ ...ghOptions, ...githubHostExecOptions(prRepo) }
)
return parseBranchList<PullRequestLookupData>(stdout)
}
const pr = await selectBranchReview({
readRecent: () => read('all', BRANCH_PR_LOOKUP_PAGE_SIZE),
readActive: async () => (await read('open', 1))[0] ?? null,
isActive: (row) => row.state.toLowerCase() === 'open',
pageSize: BRANCH_PR_LOOKUP_PAGE_SIZE
})
// Branch lists paginate PRs, not their nested check contexts.
return pr ? { ...pr, statusCheckRollup: [], checksUnavailable: true } : null
}
@@ -1,3 +1,5 @@
import { readCurrentReviewHead } from '../../../source-control/review-current-head'
import { shouldHideMergedImplicitReview } from '../../../source-control/branch-review-selection'
import type {
GitHubOwnerRepo,
GitHubPRMergeMethodSettings,
@@ -15,9 +17,7 @@ import {
normalizeReviewDecision,
isAutoMergeEnabled
} from './../map/work-item-field-coercion'
import { requireReachableGitRoute } from '../../../providers/execution-host-provider-dispatch'
import { ownerRepoFromPullRequestUrl, sameOwnerRepo } from '../github-exec-scope'
import { getConnectionExecutionHostId } from '../../../../shared/execution-host'
import { githubRepositoryWebHost } from '../../github-repository-host'
export type PullRequestLookupData = {
number: number
@@ -226,11 +226,14 @@ export function shouldHideMergedImplicitPR(
linkedPRNumber: number | null | undefined,
currentHeadOid: string | null
): boolean {
if (!data || !isMergedImplicitPR(data, linkedPRNumber)) {
return false
}
// Preserve historical merged reviews only when their head matches the current checkout.
return !currentHeadOid || data.headRefOid !== currentHeadOid
return data
? shouldHideMergedImplicitReview(
mapPRState(data.state, data.isDraft),
linkedPRNumber,
data.headRefOid,
currentHeadOid
)
: false
}
export async function linkedMergedPRDivergedHeadOid(
@@ -267,15 +270,5 @@ export async function getCurrentHeadOid(
connectionId?: string | null,
localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {}
): Promise<string | null> {
requireReachableGitRoute(getConnectionExecutionHostId(connectionId))
try {
const result = await gitExecFileAsync(['rev-parse', 'HEAD'], {
cwd: repoPath,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}),
...(localGitOptions.admissionTier ? { admissionTier: localGitOptions.admissionTier } : {})
})
return result.stdout.trim() || null
} catch {
return null
}
return readCurrentReviewHead(repoPath, connectionId, localGitOptions, gitExecFileAsync)
}
@@ -1,3 +1,7 @@
import {
readGitReviewBranchSources,
type GitReviewBranchSource
} from '../../../../shared/git/remotes/git-review-branch-source'
import { gitExecFileAsync } from '../../gh-utils'
import { readLocalGitConfigSignature } from '../../local-git-config-signature'
import type { GitAdmissionTier } from '../../../git/command-runner/git-exec-options'
@@ -11,7 +15,6 @@ import {
pruneTrackedUpstreamSnapshotCache,
parseTrackedUpstreamBranch,
getCacheableTrackedUpstreamSnapshot,
canUseCachedTrackedUpstreamBranch,
doesTrackedUpstreamCacheConfigSignatureMatch,
getTrackedUpstreamBranchCacheKey,
type TrackedUpstreamBranch,
@@ -25,87 +28,148 @@ export async function getTrackedUpstreamBranch(
connectionId?: string | null,
localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {}
): Promise<TrackedUpstreamBranch | null> {
const snapshot = await getTrackedUpstreamSnapshot(
repoPath,
branchName,
connectionId,
localGitOptions
)
return snapshot.upstreamsByBranchName.get(branchName) ?? null
}
export async function getReviewBranchSource(
repoPath: string,
branchName: string,
connectionId?: string | null,
localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {},
force = false
): Promise<GitReviewBranchSource> {
const snapshot = await getTrackedUpstreamSnapshot(
repoPath,
branchName,
connectionId,
localGitOptions,
true,
force
)
const source = snapshot.reviewSources?.get(branchName)
if (snapshot.probeFailed || !source || source instanceof Error) {
throw new Error('Cannot establish the branch review source')
}
return source
}
async function getTrackedUpstreamSnapshot(
repoPath: string,
branchName: string,
connectionId?: string | null,
localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {},
includeReviewSources = false,
force = false
): Promise<TrackedUpstreamSnapshotProbeResult> {
const cacheKey = getTrackedUpstreamBranchCacheKey(repoPath, connectionId, localGitOptions)
const now = Date.now()
const serves = (
value: Pick<TrackedUpstreamSnapshotProbeResult, 'upstreamsByBranchName' | 'reviewSources'>
): boolean =>
value.upstreamsByBranchName.has(branchName) &&
(!includeReviewSources || value.reviewSources?.has(branchName) === true)
const cached = trackedUpstreamSnapshotCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
const configSignatureMatches = await doesTrackedUpstreamCacheConfigSignatureMatch(
if (
cached &&
!force &&
cached.expiresAt > Date.now() &&
serves(cached) &&
(await doesTrackedUpstreamCacheConfigSignatureMatch(
cached,
repoPath,
connectionId,
localGitOptions
)
if (
configSignatureMatches &&
cached.upstreamsByBranchName.has(branchName) &&
canUseCachedTrackedUpstreamBranch(cached, branchName)
) {
return cached.upstreamsByBranchName.get(branchName) ?? null
}
trackedUpstreamSnapshotCache.delete(cacheKey)
))
) {
return { ...cached, cacheable: true, probeFailed: false }
}
if (cached) {
trackedUpstreamSnapshotCache.delete(cacheKey)
}
const inFlight = trackedUpstreamSnapshotInFlight.get(cacheKey)
if (inFlight) {
if (inFlight && !force) {
const result = await inFlight
if (result.upstreamsByBranchName.has(branchName)) {
return result.upstreamsByBranchName.get(branchName) ?? null
if (serves(result)) {
return result
}
// A concurrent snapshot can predate branch creation; reprobe instead of fabricating absence.
const retryInFlight = trackedUpstreamSnapshotInFlight.get(cacheKey)
if (retryInFlight) {
const retryResult = await retryInFlight
return retryResult.upstreamsByBranchName.get(branchName) ?? null
const retry = trackedUpstreamSnapshotInFlight.get(cacheKey)
if (retry && retry !== inFlight) {
const fresh = await retry
if (serves(fresh)) {
return fresh
}
}
}
// Share one repo/runtime upstream scan across hundreds of polled branches.
const probeGeneration = beginTrackedUpstreamSnapshotProbe(cacheKey)
const probe = probeTrackedUpstreamSnapshot(repoPath, connectionId, localGitOptions)
const generation = beginTrackedUpstreamSnapshotProbe(cacheKey)
const probe = probeTrackedUpstreamSnapshot(
repoPath,
connectionId,
localGitOptions,
includeReviewSources ? branchName : undefined
)
trackedUpstreamSnapshotInFlight.set(cacheKey, probe)
try {
const result = await probe
if (result.cacheable && trackedUpstreamSnapshotGenerations.get(cacheKey) === probeGeneration) {
if (result.cacheable && trackedUpstreamSnapshotGenerations.get(cacheKey) === generation) {
trackedUpstreamSnapshotCache.set(cacheKey, {
...(result.gitConfigSignature ? { gitConfigSignature: result.gitConfigSignature } : {}),
upstreamsByBranchName: getCacheableTrackedUpstreamSnapshot(result.upstreamsByBranchName),
...(result.reviewSources ? { reviewSources: result.reviewSources } : {}),
expiresAt: Date.now() + TRACKED_UPSTREAM_SNAPSHOT_CACHE_TTL_MS
})
pruneTrackedUpstreamSnapshotCache(Date.now())
}
if (trackedUpstreamSnapshotGenerations.get(cacheKey) !== probeGeneration) {
const fresherCached = trackedUpstreamSnapshotCache.get(cacheKey)
if (fresherCached?.upstreamsByBranchName.has(branchName)) {
return fresherCached.upstreamsByBranchName.get(branchName) ?? null
if (trackedUpstreamSnapshotGenerations.get(cacheKey) !== generation) {
const fresh = trackedUpstreamSnapshotCache.get(cacheKey)
if (fresh && serves(fresh)) {
return { ...fresh, cacheable: true, probeFailed: false }
}
}
return result.upstreamsByBranchName.get(branchName) ?? null
return result
} finally {
if (trackedUpstreamSnapshotInFlight.get(cacheKey) === probe) {
trackedUpstreamSnapshotInFlight.delete(cacheKey)
}
finishTrackedUpstreamSnapshotProbe(cacheKey, probeGeneration)
finishTrackedUpstreamSnapshotProbe(cacheKey, generation)
}
}
export async function probeTrackedUpstreamSnapshot(
repoPath: string,
connectionId?: string | null,
localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {}
localGitOptions: { wslDistro?: string; admissionTier?: GitAdmissionTier } = {},
reviewBranchName?: string
): Promise<TrackedUpstreamSnapshotProbeResult> {
const startingGitConfigSignature = await readLocalGitConfigSignature({
repoPath,
connectionId: connectionId ?? null,
...localGitOptions
})
const { probeFailed, upstreamsByBranchName } = await probeTrackedUpstreamBranches(
let { probeFailed, upstreamsByBranchName } = await probeTrackedUpstreamBranches(
repoPath,
connectionId,
localGitOptions
)
let reviewSources: Map<string, GitReviewBranchSource | Error> | undefined
if (reviewBranchName && !probeFailed) {
try {
requireReachableGitRoute(getConnectionExecutionHostId(connectionId))
if (!upstreamsByBranchName.has(reviewBranchName)) {
upstreamsByBranchName.set(reviewBranchName, null)
}
reviewSources = await readGitReviewBranchSources(
(args) => gitExecFileAsync(args, { cwd: repoPath, ...localGitOptions }),
upstreamsByBranchName.keys()
)
} catch {
probeFailed = true
}
}
const endingGitConfigSignature = await readLocalGitConfigSignature({
repoPath,
connectionId: connectionId ?? null,
@@ -121,7 +185,8 @@ export async function probeTrackedUpstreamSnapshot(
cacheable: !configSignatureChanged && !probeFailed,
probeFailed,
...(gitConfigSignature ? { gitConfigSignature } : {}),
upstreamsByBranchName
upstreamsByBranchName,
...(reviewSources ? { reviewSources } : {})
}
}
@@ -1,3 +1,4 @@
import type { GitReviewBranchSource } from '../../../../shared/git/remotes/git-review-branch-source'
import { splitRemoteBranchName } from '../../../../shared/git/remotes/git-remote-branch-name'
import type { OwnerRepo } from '../../gh-utils'
import { readLocalGitConfigSignature } from '../../local-git-config-signature'
@@ -15,6 +16,7 @@ export type TrackedUpstreamSnapshotCacheEntry = {
expiresAt: number
gitConfigSignature?: string
upstreamsByBranchName: Map<string, TrackedUpstreamBranch | null>
reviewSources?: Map<string, GitReviewBranchSource | Error>
}
export type TrackedUpstreamSnapshotProbeResult = {
@@ -22,6 +24,7 @@ export type TrackedUpstreamSnapshotProbeResult = {
gitConfigSignature?: string
probeFailed: boolean
upstreamsByBranchName: Map<string, TrackedUpstreamBranch | null>
reviewSources?: Map<string, GitReviewBranchSource | Error>
}
export const trackedUpstreamSnapshotCache = new Map<string, TrackedUpstreamSnapshotCacheEntry>()
+1 -19
View File
@@ -1,19 +1 @@
import { createHash } from 'node:crypto'
import type { GitHubRepoExecOptions } from './github-api-repository'
export function githubReadExecutionScope(
options: GitHubRepoExecOptions,
environment: NodeJS.ProcessEnv = options.env ?? process.env
): string {
const { admissionTier: _admissionTier, ...executionOptions } = options
// gh wrappers and credential selection can depend on cwd and the inherited environment.
return createHash('sha256')
.update(
JSON.stringify([
executionOptions,
process.cwd(),
Object.entries(environment).sort(([a], [b]) => a.localeCompare(b, 'en'))
])
)
.digest('hex')
}
export { codeHostReadExecutionScope as githubReadExecutionScope } from '../source-control/code-host-read-execution-scope'
+49 -90
View File
@@ -5,35 +5,18 @@ import { githubHostExecOptions, type GitHubRepoExecOptions } from './github-api-
import { githubRepoIdentityKey } from '../../shared/github/repository-identity-key'
import type { OwnerRepo } from './github-repository-identity'
// Definitive merged-commit membership is immutable; errors expire sooner so later pushes can resolve unknowns.
const MEMBERSHIP_CACHE_MAX_ENTRIES = 200
const MEMBERSHIP_DEFINITIVE_TTL_MS = 6 * 60 * 60 * 1000
const MEMBERSHIP_ERROR_TTL_MS = 5 * 60 * 1000
import {
MergedReviewMembershipMemo,
type MergedReviewCommitMembership
} from '../source-control/merged-review-membership-memo'
const COMMIT_PULLS_PAGE_SIZE = 100
// Full pages through the cap cannot prove absence; keep pathological commit fan-out unknown.
const COMMIT_PULLS_MAX_PAGES = 5
export type MergedPRCommitMembership = 'contained' | 'not-contained' | 'unknown'
const membershipCache = new Map<string, { value: MergedPRCommitMembership; expiresAt: number }>()
function pruneMergedPRCommitMembershipCache(now = Date.now()): void {
for (const [cacheKey, cached] of membershipCache) {
if (cached.expiresAt <= now) {
membershipCache.delete(cacheKey)
}
}
while (membershipCache.size > MEMBERSHIP_CACHE_MAX_ENTRIES) {
const oldestKey = membershipCache.keys().next().value
if (oldestKey === undefined) {
break
}
membershipCache.delete(oldestKey)
}
}
export type MergedPRCommitMembership = MergedReviewCommitMembership
const membershipMemo = new MergedReviewMembershipMemo()
export function resetMergedPRCommitMembershipCacheForTest(): void {
membershipCache.clear()
membershipMemo.clear()
}
/** Check PR-history membership rather than branch-name reuse; failures return unknown. */
@@ -51,76 +34,52 @@ export async function isCommitPartOfMergedPR(args: {
const repo = args.ownerRepo.repo
const ghOptions = { ...args.ghOptions, ...githubHostExecOptions(args.ownerRepo) }
const cacheKey = `${githubReadExecutionScope(ghOptions)}\0${githubRepoIdentityKey(args.ownerRepo)}#${args.prNumber}@${oid}`
const now = Date.now()
pruneMergedPRCommitMembershipCache(now)
const cached = membershipCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
return cached.value
const cached = membershipMemo.peek(cacheKey)
if (cached !== undefined) {
return cached
}
// An unrun probe cannot justify clearing a durable linked PR.
if (repositoryRateLimitGuard(args.ownerRepo, 'core', ghOptions).blocked) {
return 'unknown'
}
try {
// Paginate until found or a short page proves absence; a full final page leaves membership unknown.
for (let page = 1; page <= COMMIT_PULLS_MAX_PAGES; page += 1) {
if (page > 1 && repositoryRateLimitGuard(args.ownerRepo, 'core', ghOptions).blocked) {
membershipCache.set(cacheKey, {
value: 'unknown',
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
})
return 'unknown'
}
noteRepositoryRateLimitSpend(args.ownerRepo, 'core', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'api',
`repos/${owner}/${repo}/commits/${oid}/pulls?per_page=${COMMIT_PULLS_PAGE_SIZE}&page=${page}`
],
ghOptions
)
const parsed = JSON.parse(stdout) as unknown
// Non-array success is unverified, not evidence that a durable link should be cleared.
if (!Array.isArray(parsed)) {
membershipCache.set(cacheKey, {
value: 'unknown',
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
})
return 'unknown'
}
const entries = parsed
const contained = entries.some(
(entry) =>
typeof entry === 'object' &&
entry !== null &&
(entry as { number?: unknown }).number === args.prNumber
)
if (contained) {
membershipCache.set(cacheKey, {
value: 'contained',
expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS
})
return 'contained'
}
if (entries.length < COMMIT_PULLS_PAGE_SIZE) {
membershipCache.set(cacheKey, {
value: 'not-contained',
expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS
})
return 'not-contained'
return membershipMemo.read(cacheKey, async () => {
try {
// Paginate until found or a short page proves absence; a full final page leaves membership unknown.
for (let page = 1; page <= COMMIT_PULLS_MAX_PAGES; page += 1) {
if (page > 1 && repositoryRateLimitGuard(args.ownerRepo, 'core', ghOptions).blocked) {
return 'unknown'
}
noteRepositoryRateLimitSpend(args.ownerRepo, 'core', 1, ghOptions)
const { stdout } = await ghExecFileAsync(
[
'api',
`repos/${owner}/${repo}/commits/${oid}/pulls?per_page=${COMMIT_PULLS_PAGE_SIZE}&page=${page}`
],
ghOptions
)
const parsed = JSON.parse(stdout) as unknown
// Non-array success is unverified, not evidence that a durable link should be cleared.
if (!Array.isArray(parsed)) {
return 'unknown'
}
const entries = parsed
const contained = entries.some(
(entry) =>
typeof entry === 'object' &&
entry !== null &&
(entry as { number?: unknown }).number === args.prNumber
)
if (contained) {
return 'contained'
}
if (entries.length < COMMIT_PULLS_PAGE_SIZE) {
return 'not-contained'
}
}
return 'unknown'
} catch {
// A local commit can become queryable after push; preserve links until verification succeeds.
return 'unknown'
}
membershipCache.set(cacheKey, {
value: 'unknown',
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
})
return 'unknown'
} catch {
// A local commit can become queryable after push; preserve links until verification succeeds.
membershipCache.set(cacheKey, {
value: 'unknown',
expiresAt: now + MEMBERSHIP_ERROR_TTL_MS
})
return 'unknown'
}
})
}
@@ -0,0 +1,93 @@
import { beforeEach, expect, it, vi } from 'vitest'
import type * as GlabApiResponse from './glab-api-response'
const { read, pages } = vi.hoisted(() => ({ read: vi.fn(), pages: vi.fn() }))
vi.mock('./gl-utils', async () => ({
...(await vi.importActual<typeof GlabApiResponse>('./glab-api-response')),
glabExecFileAsync: read,
glabApiWithHeaders: pages,
glabHostnameArgs: () => [],
glabRepoExecOptions: () => ({})
}))
import { createGitLabBranchDiscovery } from './branch-review-discovery'
const args = {
repoPath: '/repo',
project: { host: 'gitlab.com', path: 'g/p' },
sourceProjectId: 1,
localGitOptions: {}
}
const row = (iid: number, state = 'merged', source = 1) => ({
iid,
state,
source_project_id: source,
target_project_id: 2,
source_branch: 'feature',
updated_at: `2026-11-01T00:00:${String(iid % 60).padStart(2, '0')}Z`
})
beforeEach(() => {
read.mockReset()
pages.mockReset()
})
it('prefers an older active MR and probes both active states behind a full recent page', async () => {
read
.mockResolvedValueOnce({
stdout: JSON.stringify(Array.from({ length: 10 }, (_, i) => row(i + 1)))
})
.mockResolvedValueOnce({ stdout: JSON.stringify([row(11, 'opened')]) })
.mockResolvedValueOnce({ stdout: JSON.stringify([row(12, 'locked')]) })
await expect(createGitLabBranchDiscovery(args)('feature')).resolves.toMatchObject({ iid: 12 })
expect(read.mock.calls.map(([a]) => a.at(-1))).toEqual([
expect.stringContaining('source_project_id=1&state=all&per_page=10'),
expect.stringContaining('source_project_id=1&state=opened&per_page=1'),
expect.stringContaining('source_project_id=1&state=locked&per_page=1')
])
})
it.each(['foreign', 'locked'])(
'completes the existing branch-filtered endpoint on legacy %s filtering',
async (mode) => {
read.mockResolvedValueOnce({
stdout: JSON.stringify(
mode === 'foreign'
? [row(1, 'opened', 8)]
: Array.from({ length: 10 }, (_, i) => row(i + 1))
)
})
if (mode === 'locked') {
read
.mockResolvedValueOnce({ stdout: '[]' })
.mockRejectedValueOnce({ stderr: 'HTTP 400: state does not have a valid value: locked' })
}
pages.mockImplementation(async ([endpoint]: string[]) => ({
body: JSON.stringify(
new URL(endpoint, 'https://gitlab.com').searchParams.get('page') === '1'
? Array.from({ length: 100 }, (_, i) => row(i + 1, 'opened', 8))
: [row(101, 'opened')]
),
headers: {
'x-next-page':
new URL(endpoint, 'https://gitlab.com').searchParams.get('page') === '1' ? '2' : ''
}
}))
await expect(createGitLabBranchDiscovery(args)('feature')).resolves.toMatchObject({ iid: 101 })
expect(pages.mock.calls[0][0][0]).toContain('&state=all&per_page=100&page=1')
expect(pages.mock.calls[0][0][0]).not.toContain('source_project_id=')
}
)
it('does not turn an active-probe failure into historical absence', async () => {
read
.mockResolvedValueOnce({
stdout: JSON.stringify(Array.from({ length: 10 }, (_, i) => row(i + 1)))
})
.mockRejectedValueOnce(new Error('offline'))
await expect(createGitLabBranchDiscovery(args)('feature')).rejects.toThrow('offline')
expect(pages).not.toHaveBeenCalled()
})
it('fails a legacy traversal rather than selecting from an incomplete foreign prefix', async () => {
read.mockResolvedValue({ stdout: JSON.stringify([row(1, 'opened', 8)]) })
pages
.mockResolvedValueOnce({
body: JSON.stringify(Array.from({ length: 100 }, (_, i) => row(i + 1, 'opened', 8))),
headers: { 'x-next-page': '2' }
})
.mockRejectedValueOnce(new Error('offline'))
await expect(createGitLabBranchDiscovery(args)('feature')).rejects.toThrow('incomplete')
})
+143
View File
@@ -0,0 +1,143 @@
import { selectBranchReview } from '../source-control/branch-review-selection'
import { extractExecError } from '../git/exec-error'
import { fetchAllGitLabPages } from './gitlab-paginated-list'
import { isUnsupportedReviewListFilter } from './glab-error-classification'
import {
glabExecFileAsync,
glabHostnameArgs,
glabRepoExecOptions,
parseGlabJsonList,
type LocalGitExecOptions,
type ProjectRef
} from './gl-utils'
import { encodedProject } from './project-path-encoding'
export type GitLabBranchReview = {
iid: number
state: string
source_project_id: number
target_project_id: number
source_branch: string
updated_at: string
}
class GitLabReviewFilterUnavailableError extends Error {}
function validateReviews(rows: unknown[], branch: string): GitLabBranchReview[] {
if (
!rows.every((row): row is GitLabBranchReview => {
if (!row || typeof row !== 'object') {
return false
}
const data = row as Record<string, unknown>
return (
typeof data.iid === 'number' &&
Number.isSafeInteger(data.iid) &&
data.iid > 0 &&
typeof data.source_project_id === 'number' &&
Number.isSafeInteger(data.source_project_id) &&
data.source_project_id > 0 &&
typeof data.target_project_id === 'number' &&
Number.isSafeInteger(data.target_project_id) &&
data.target_project_id > 0 &&
typeof data.state === 'string' &&
['opened', 'locked', 'closed', 'merged'].includes(data.state) &&
data.source_branch === branch &&
typeof data.updated_at === 'string' &&
Number.isFinite(Date.parse(data.updated_at))
)
})
) {
throw new Error('Invalid GitLab branch review list')
}
return rows
}
export function isActiveGitLabReview(review: GitLabBranchReview): boolean {
return review.state === 'opened' || review.state === 'locked'
}
/** Compatibility observation lasts for this lookup, including its one qualified alternate name. */
export function createGitLabBranchDiscovery(args: {
repoPath: string
project: ProjectRef
sourceProjectId: number
connectionId?: string | null
localGitOptions: LocalGitExecOptions
}): (branch: string) => Promise<GitLabBranchReview | null> {
let completeTraversal = false
const endpoint = `projects/${encodedProject(args.project.path)}/merge_requests`
const ordered = (branch: string) =>
`source_branch=${encodeURIComponent(branch)}&order_by=updated_at&sort=desc&with_merge_status_recheck=true`
const readComplete = async (branch: string): Promise<GitLabBranchReview | null> => {
const raw = await fetchAllGitLabPages<unknown>(
args.repoPath,
args.project,
`${endpoint}?${ordered(branch)}&state=all`,
args.connectionId,
args.localGitOptions
)
const rows = validateReviews(raw, branch).filter(
(row) => row.source_project_id === args.sourceProjectId
)
return rows.find(isActiveGitLabReview) ?? rows[0] ?? null
}
const read = async (
branch: string,
state: 'all' | 'opened' | 'locked',
limit: number
): Promise<GitLabBranchReview[]> => {
let stdout: string
try {
;({ stdout } = await glabExecFileAsync(
[
'api',
...glabHostnameArgs(args.project, args.connectionId),
`${endpoint}?${ordered(branch)}&source_project_id=${args.sourceProjectId}&state=${state}&per_page=${limit}`
],
glabRepoExecOptions(args.repoPath, args.connectionId, args.localGitOptions)
))
} catch (error) {
const detail = extractExecError(error)
if (isUnsupportedReviewListFilter([detail.stderr, detail.stdout].join('\n'), state)) {
throw new GitLabReviewFilterUnavailableError()
}
throw error
}
const rows = validateReviews(parseGlabJsonList<unknown>(stdout), branch)
if (rows.some((row) => row.source_project_id !== args.sourceProjectId)) {
throw new GitLabReviewFilterUnavailableError()
}
if (state !== 'all' && rows.some((row) => row.state !== state)) {
throw new Error('Invalid GitLab active review list')
}
return rows
}
return async (branch) => {
if (completeTraversal) {
return readComplete(branch)
}
try {
return await selectBranchReview({
readRecent: () => read(branch, 'all', 10),
readActive: async () => {
const opened = (await read(branch, 'opened', 1))[0]
const locked = (await read(branch, 'locked', 1))[0]
return (
[opened, locked]
.filter((row) => row !== undefined)
.sort((a, b) => Date.parse(b.updated_at) - Date.parse(a.updated_at))[0] ?? null
)
},
isActive: isActiveGitLabReview,
pageSize: 10
})
} catch (error) {
if (!(error instanceof GitLabReviewFilterUnavailableError)) {
throw error
}
completeTraversal = true
return readComplete(branch)
}
}
}
+42
View File
@@ -0,0 +1,42 @@
import type { GitReviewBranchSource } from '../../shared/git/remotes/git-review-branch-source'
import { parseGitLabProjectRef, normalizeGitLabHost } from './project-ref-parser'
import { readReviewProjectIdentity } from './review-project-identity'
import type { LocalGitExecOptions, ProjectRef } from './gl-utils'
export async function resolveReviewSourceProject(args: {
repoPath: string
target: ProjectRef
urls: GitReviewBranchSource['urls']
connectionId?: string | null
localGitOptions: LocalGitExecOptions
force?: boolean
}): Promise<{ project: ProjectRef; id: number }> {
let source: { project: ProjectRef; id: number } | undefined
const seen = new Set<string>()
for (const url of args.urls) {
const project = parseGitLabProjectRef(url, [args.target.host])
if (!project || normalizeGitLabHost(project.host) !== normalizeGitLabHost(args.target.host)) {
throw new Error('Review source is not on the target GitLab host')
}
const key = `${project.host}\0${project.path}`
if (seen.has(key)) {
continue
}
seen.add(key)
const identity = await readReviewProjectIdentity(
args.repoPath,
project,
args.connectionId,
args.localGitOptions,
args.force
)
if (source && source.id !== identity.id) {
throw new Error('Review source has multiple projects')
}
source ??= { project, id: identity.id }
}
if (!source) {
throw new Error('Review source is unavailable')
}
return source
}
+134 -5
View File
@@ -11,7 +11,8 @@ const {
resolveIssueSourceMock,
acquireMock,
releaseMock,
gitExecFileAsyncMock
gitExecFileAsyncMock,
reviewSourceMock
} = vi.hoisted(() => ({
glabExecFileAsyncMock: vi.fn(),
glabApiWithHeadersMock: vi.fn(),
@@ -20,7 +21,8 @@ const {
resolveIssueSourceMock: vi.fn(),
acquireMock: vi.fn(),
releaseMock: vi.fn(),
gitExecFileAsyncMock: vi.fn()
gitExecFileAsyncMock: vi.fn(),
reviewSourceMock: vi.fn()
}))
// Why: the #9171 default-branch guard resolves the repo default branch via
@@ -29,6 +31,12 @@ vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
gitExecFileAsync: gitExecFileAsyncMock
}))
vi.mock('../github/client/lookup/tracked-upstream-branch', () => ({
getReviewBranchSource: reviewSourceMock
}))
vi.mock('./branch-review-source', () => ({
resolveReviewSourceProject: async () => ({ id: 1, project: { host: 'gitlab.com', path: 'g/p' } })
}))
vi.mock('./gl-utils', async () => {
const actual = await vi.importActual<typeof GlUtils>('./gl-utils')
@@ -45,13 +53,20 @@ vi.mock('./gl-utils', async () => {
})
import { getMergeRequestForBranch, getMergeRequestForBranchOrThrow } from './client'
import { resetGitLabMrMocks } from './client-mr-test-harness'
import { resetMergedMRCommitMembershipForTest } from './merged-mr-commit-membership'
type MergeRequestDetail = Parameters<typeof mapMRInfo>[0]
function mockBranchLookup(mr: MergeRequestDetail): void {
const identity = {
source_project_id: 1,
target_project_id: 1,
source_branch: 'main',
updated_at: '2026-11-01T00:00:00Z'
}
glabExecFileAsyncMock
.mockResolvedValueOnce({ stdout: JSON.stringify([mr]) })
.mockResolvedValueOnce({ stdout: JSON.stringify(mr) })
.mockResolvedValueOnce({ stdout: JSON.stringify([{ ...identity, ...mr }]) })
.mockResolvedValueOnce({ stdout: JSON.stringify({ ...identity, ...mr }) })
}
describe('gitlab client — MR operations', () => {
@@ -61,6 +76,12 @@ describe('gitlab client — MR operations', () => {
})
beforeEach(() => {
resetMergedMRCommitMembershipForTest()
reviewSourceMock.mockReset().mockImplementation(async (_repo: string, branch: string) => ({
remoteName: 'origin',
urls: ['https://gitlab.com/g/p.git'],
branchName: branch
}))
resetGitLabMrMocks({
glabExecFileAsyncMock,
glabApiWithHeadersMock,
@@ -80,6 +101,10 @@ describe('gitlab client — MR operations', () => {
'reads the failed head pipeline from detail instead of the branch list: %j',
async (pipelineFields) => {
const detail = {
source_project_id: 1,
target_project_id: 1,
source_branch: 'feature/pipeline',
updated_at: '2026-11-01T00:00:00Z',
iid: 5049,
title: 'Pipeline regression',
state: 'opened',
@@ -108,7 +133,17 @@ describe('gitlab client — MR operations', () => {
for (const lookup of [getMergeRequestForBranch, getMergeRequestForBranchOrThrow]) {
glabExecFileAsyncMock
.mockResolvedValueOnce({
stdout: JSON.stringify([{ iid: 6, title: 'Flaky', state: 'opened' }])
stdout: JSON.stringify([
{
iid: 6,
title: 'Flaky',
state: 'opened',
source_project_id: 1,
target_project_id: 1,
source_branch: 'flaky',
updated_at: '2026-11-01T00:00:00Z'
}
])
})
.mockRejectedValueOnce(new Error('glab: 502'))
const result = lookup('/repo', 'flaky')
@@ -125,6 +160,100 @@ describe('gitlab client — MR operations', () => {
expect(releaseMock).toHaveBeenCalledTimes(3)
})
it('uses a qualified tracked name only after complete local absence and excludes the default branch', async () => {
getProjectRefMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' })
reviewSourceMock.mockResolvedValue({
remoteName: 'origin',
urls: ['https://gitlab.com/g/p.git'],
branchName: 'wip',
trackedBranchName: 'renamed',
trackedUrls: ['https://gitlab.com/g/p.git']
})
const mr = {
iid: 8,
title: 'Renamed',
state: 'opened',
source_project_id: 1,
target_project_id: 1,
source_branch: 'renamed',
updated_at: '2026-11-01T00:00:00Z'
}
glabExecFileAsyncMock
.mockResolvedValueOnce({ stdout: '[]' })
.mockResolvedValueOnce({ stdout: JSON.stringify([mr]) })
.mockResolvedValueOnce({ stdout: JSON.stringify(mr) })
await expect(getMergeRequestForBranchOrThrow('/repo', 'wip')).resolves.toMatchObject({
number: 8
})
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(3)
reviewSourceMock.mockResolvedValue({
remoteName: 'origin',
urls: ['https://gitlab.com/g/p.git'],
branchName: 'wip',
trackedBranchName: 'main',
trackedUrls: ['https://gitlab.com/g/p.git']
})
glabExecFileAsyncMock
.mockResolvedValueOnce({ stdout: '[]' })
.mockResolvedValueOnce({ stdout: JSON.stringify([{ ...mr, source_branch: 'main' }]) })
await expect(getMergeRequestForBranchOrThrow('/repo', 'wip')).resolves.toBeNull()
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(5)
})
it.each([10, 100])(
'walks immutable membership once across %s admitted provider refreshes',
async (count) => {
getProjectRefMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' })
const head = 'f'.repeat(40)
const mr = {
iid: 8,
title: 'Merged',
state: 'merged',
sha: 'a'.repeat(40),
source_project_id: 1,
target_project_id: 1,
source_branch: 'feature',
updated_at: '2026-11-01T00:00:00Z'
}
glabExecFileAsyncMock.mockImplementation(async (args: string[]) => ({
stdout:
args.at(-1) === 'user'
? '{"id":1}'
: JSON.stringify(args.at(-1)?.includes('source_branch=') ? [mr] : mr)
}))
glabApiWithHeadersMock.mockImplementation(async (args: string[]) => {
const page = Number(
new URL(args.at(-1) ?? '', 'https://gitlab.com').searchParams.get('page')
)
return {
body: JSON.stringify(
Array.from({ length: 100 }, (_, i) => ({
id: page === 5 && i === 99 ? head : (page * 100 + i).toString(16).padStart(40, '0')
}))
),
headers: { 'x-next-page': page < 5 ? String(page + 1) : '' }
}
})
for (let i = 0; i < count; i++) {
await expect(
getMergeRequestForBranchOrThrow('/repo', 'feature', null, null, {
currentHeadOid: head
})
).resolves.toMatchObject({ number: 8 })
}
expect(glabApiWithHeadersMock).toHaveBeenCalledTimes(5)
expect(
glabExecFileAsyncMock.mock.calls.filter(([args]) => args.at(-1) === 'user')
).toHaveLength(count)
expect(
glabExecFileAsyncMock.mock.calls.filter(([args]) =>
args.at(-1)?.includes('source_branch=')
)
).toHaveLength(count)
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(count * 3)
}
)
it('hides a stale closed MR whose source branch is the repo default branch (#9171)', async () => {
getProjectRefMock.mockResolvedValueOnce({ host: 'gitlab.com', path: 'g/p' })
mockBranchLookup({
+1 -1
View File
@@ -35,7 +35,7 @@ export async function fetchAllGitLabPages<T>(
const { body, headers } = await glabApiWithHeaders(
[
...glabHostnameArgs(projectRef, connectionId),
`${endpoint}?per_page=${PAGE_SIZE}&page=${page}`
`${endpoint}${endpoint.includes('?') ? '&' : '?'}per_page=${PAGE_SIZE}&page=${page}`
],
glabRepoExecOptions(repoPath, connectionId, localGitOptions)
)
@@ -81,3 +81,20 @@ export function classifyJobLogError(stderr: string): ClassifiedError {
export function isMissingJobLogError(stderr: string): boolean {
return classifyGlabError(stderr).type === 'not_found' && !/project\s+not\s+found/i.test(stderr)
}
/** Older servers reject these optimizations; ordinary permission/transport errors are not capabilities. */
export function isUnsupportedReviewListFilter(message: string, state: string): boolean {
const status = /HTTP\s+(\d{3})/i.exec(message)?.[1]
if (status && status !== '400' && status !== '422') {
return false
}
return (
/source_project_id[^\n]*(?:unsupported|unknown|unrecognized|not permitted|not allowed|invalid)/i.test(
message
) ||
(state === 'locked' &&
/\bstate\b[^\n]*(?:does not have a valid value|invalid|unsupported|not (?:an? )?allowed)/i.test(
message
))
)
}
+8 -14
View File
@@ -1,7 +1,4 @@
import {
mapGitLabPipelineJobStatusToCheckStatus,
mapGitLabPipelineJobStatusToConclusion
} from '../../shared/source-control/checks/gitlab/gitlab-pipeline-checks'
import { gitLabPipelineJobOutcome } from '../../shared/source-control/checks/gitlab/gitlab-pipeline-checks'
import type { CheckStatus } from '../../shared/github/pull-request-types'
import type { GitLabIssueInfo, GitLabWorkItem, MRInfo, MRState } from '../../shared/gitlab-types'
@@ -148,7 +145,12 @@ function deriveMergeStateStatus(
}
export function derivePipelineStatus(
rollup: { status?: string }[] | { status?: string } | string | null | undefined
rollup:
| { status?: string; allowFailure?: boolean }[]
| { status?: string }
| string
| null
| undefined
): CheckStatus {
if (!rollup) {
return 'neutral'
@@ -160,15 +162,7 @@ export function derivePipelineStatus(
return classifyPipelineString(rollup.status ?? '')
}
// Share rollup rules so pipeline cards cannot diverge from Checks rows.
const { state } = summarizeProviderChecks(
rollup.map((job) => {
const s = job.status?.toLowerCase() ?? ''
return {
status: mapGitLabPipelineJobStatusToCheckStatus(s),
conclusion: mapGitLabPipelineJobStatusToConclusion(s)
}
})
)
const { state } = summarizeProviderChecks(rollup.map(gitLabPipelineJobOutcome))
// The public status type uses neutral for no check results.
return state === 'none' ? 'neutral' : state
}
+145 -28
View File
@@ -1,3 +1,16 @@
import { getReviewBranchSource } from '../github/client/lookup/tracked-upstream-branch'
import { createGitLabBranchDiscovery } from './branch-review-discovery'
import { resolveReviewSourceProject } from './branch-review-source'
import { forgetReviewProjectIdentity } from './review-project-identity'
import { mergedMRContainsHead } from './merged-mr-commit-membership'
import { readCurrentReviewHead } from '../source-control/review-current-head'
import { shouldHideMergedImplicitReview } from '../source-control/branch-review-selection'
import {
getRemoteHeadBranchName,
getRepoDefaultBranchName
} from '../source-control/repo-default-branch'
import { extractExecError } from '../git/exec-error'
import { classifyGlabError } from './glab-error-classification'
import type { MRInfo } from '../../shared/gitlab-types'
import { derivePipelineStatus, mapMRInfo } from './mappers'
import {
@@ -18,6 +31,11 @@ import {
} from '../source-control/hosted-review-git-options'
import { shouldHideNonOpenReviewOnDefaultBranch } from '../source-control/repo-default-branch'
type BranchReviewOptions = HostedReviewExecutionOptions & {
currentHeadOid?: string | null
userRefresh?: boolean
}
type HostedReviewLocalGitOptions = ReturnType<typeof getHostedReviewLocalGitOptions>
function hostedReviewLocalGitOptionArgs(
@@ -79,7 +97,7 @@ export async function getMergeRequestForBranch(
branch: string,
linkedMRIid?: number | null,
connectionId?: string | null,
options: HostedReviewExecutionOptions = {},
options: BranchReviewOptions = {},
// Strict callers need failures distinguished from confirmed missing reviews.
throwOnFailure = false
): Promise<MRInfo | null> {
@@ -96,7 +114,7 @@ export async function getMergeRequestForBranch(
}
await acquire()
try {
const fetchByIid = async (iid: number): Promise<MRInfo> => {
const fetchByIid = async (iid: number) => {
const { stdout } = await glabExecFileAsync(
[
'api',
@@ -105,40 +123,139 @@ export async function getMergeRequestForBranch(
],
glabRepoExecOptions(repoPath, connectionId, localGitOptions)
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the single-MR endpoint returns the MR fields and its optional pipeline.
const raw = JSON.parse(stdout) as Parameters<typeof mapMRInfo>[0]
const pipelineStatus = derivePipelineStatus(raw.head_pipeline ?? raw.pipeline ?? null)
return mapMRInfo(raw, pipelineStatus)
const raw = JSON.parse(stdout) as Parameters<typeof mapMRInfo>[0] & {
target_project_id?: number
project_id?: number
source_project_id?: number
source_branch?: string
}
return {
raw,
info: mapMRInfo(raw, derivePipelineStatus(raw.head_pipeline ?? raw.pipeline ?? null))
}
}
if (typeof linkedMRIid === 'number') {
return await fetchByIid(linkedMRIid)
return (await fetchByIid(linkedMRIid)).info
}
if (branchName) {
const { stdout } = await glabExecFileAsync(
[
'api',
...glabHostnameArgs(projectRef, connectionId),
// List endpoints need asynchronous merge-status recheck; GitLab may restrict this to Developers.
`projects/${encodedProject(projectRef.path)}/merge_requests?source_branch=${encodeURIComponent(branchName)}&order_by=updated_at&sort=desc&per_page=1&with_merge_status_recheck=true`
],
glabRepoExecOptions(repoPath, connectionId, localGitOptions)
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the branch-list endpoint returns MR summaries; only their identity is used.
const data = JSON.parse(stdout) as Parameters<typeof mapMRInfo>[0][]
if (Array.isArray(data) && data.length > 0) {
// List summaries omit head_pipeline; only detail can supply an authoritative check result.
const info = await fetchByIid(data[0].iid ?? data[0].number ?? 0)
const hideOnDefaultBranch = await shouldHideNonOpenReviewOnDefaultBranch({
state: info.state,
reviewNumber: info.number,
branchName,
const source = await getReviewBranchSource(
repoPath,
branchName,
connectionId,
localGitOptions,
options.userRefresh
)
for (let attempt = 0; attempt < 2; attempt += 1) {
const identityArgs = {
repoPath,
target: projectRef,
urls: source.urls,
connectionId,
localGitOptions,
force: options.userRefresh || attempt > 0
}
const sourceProject = await resolveReviewSourceProject(identityArgs)
try {
const discover = createGitLabBranchDiscovery({
repoPath,
project: projectRef,
sourceProjectId: sourceProject.id,
connectionId,
localGitOptions
})
if (!hideOnDefaultBranch) {
let candidate = await discover(source.branchName)
let usedTrackedName = false
if (!candidate && source.trackedBranchName && source.trackedUrls) {
const trackedSource = await resolveReviewSourceProject({
...identityArgs,
urls: source.trackedUrls
})
if (trackedSource.id === sourceProject.id) {
candidate = await discover(source.trackedBranchName)
usedTrackedName = true
}
}
if (!candidate) {
return null
}
if (usedTrackedName && candidate.source_project_id === candidate.target_project_id) {
const defaultBranch =
source.remoteName === 'origin'
? await getRepoDefaultBranchName(repoPath, connectionId, localGitOptions)
: await getRemoteHeadBranchName(
repoPath,
source.remoteName,
connectionId,
localGitOptions
)
if (candidate.source_branch === defaultBranch) {
return null
}
}
const { info, raw } = await fetchByIid(candidate.iid)
if (
info.number !== candidate.iid ||
raw.source_project_id !== candidate.source_project_id ||
raw.target_project_id !== candidate.target_project_id ||
raw.source_branch !== candidate.source_branch
) {
throw new Error('GitLab merge request identity changed during lookup')
}
if (info.state === 'merged') {
const currentHead =
options.currentHeadOid?.trim() ||
(await readCurrentReviewHead(repoPath, connectionId, localGitOptions))
if (shouldHideMergedImplicitReview(info.state, linkedMRIid, info.headSha, currentHead)) {
if (!currentHead) {
return null
}
const targetProjectId = raw.target_project_id ?? raw.project_id
if (
!Number.isSafeInteger(targetProjectId) ||
!targetProjectId ||
targetProjectId <= 0
) {
throw new Error('Invalid GitLab target project identity')
}
if (
(await mergedMRContainsHead({
repoPath,
project: projectRef,
targetProjectId,
iid: info.number,
headOid: currentHead,
connectionId,
localGitOptions,
userRefresh: options.userRefresh
})) !== 'contained'
) {
return null
}
}
}
if (
!(await shouldHideNonOpenReviewOnDefaultBranch({
state: info.state,
reviewNumber: info.number,
branchName,
repoPath,
connectionId,
localGitOptions
}))
) {
return info
}
return null
} catch (error) {
const detail = extractExecError(error)
if (
attempt > 0 ||
classifyGlabError(
[detail.stderr, detail.stdout, error instanceof Error ? error.message : ''].join('\n')
).type !== 'not_found'
) {
throw error
}
forgetReviewProjectIdentity(repoPath, sourceProject.project, connectionId, localGitOptions)
}
}
return null
@@ -158,7 +275,7 @@ export function getMergeRequestForBranchOrThrow(
branch: string,
linkedMRIid?: number | null,
connectionId?: string | null,
options: HostedReviewExecutionOptions = {}
options: BranchReviewOptions = {}
): Promise<MRInfo | null> {
return getMergeRequestForBranch(repoPath, branch, linkedMRIid, connectionId, options, true)
}
@@ -0,0 +1,82 @@
import { beforeEach, expect, it, vi } from 'vitest'
import type * as GlabApiResponse from './glab-api-response'
const { pages, viewer } = vi.hoisted(() => ({ pages: vi.fn(), viewer: vi.fn() }))
vi.mock('./gl-utils', async () => ({
...(await vi.importActual<typeof GlabApiResponse>('./glab-api-response')),
glabApiWithHeaders: pages,
glabHostnameArgs: () => [],
glabRepoExecOptions: () => ({ cwd: '/repo' })
}))
vi.mock('./gitlab-auth-and-rate-limit', () => ({ readGlabViewer: viewer }))
import {
mergedMRContainsHead,
resetMergedMRCommitMembershipForTest
} from './merged-mr-commit-membership'
const args = {
repoPath: '/repo',
project: { host: 'gitlab.com', path: 'g/p' },
targetProjectId: 1,
iid: 7,
headOid: 'f'.repeat(40),
localGitOptions: {}
}
beforeEach(() => {
resetMergedMRCommitMembershipForTest()
pages.mockReset()
viewer.mockReset().mockResolvedValue({ id: 1 })
})
it.each([10, 100])(
'reuses a complete 500-commit result across %s admitted refreshes and coalesces a cold walk',
async (count) => {
pages.mockImplementation(async ([endpoint]: string[]) => {
const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page'))
return {
body: JSON.stringify(
Array.from({ length: 100 }, (_, i) => ({
id:
page === 5 && i === 99
? args.headOid
: (page * 100 + i).toString(16).padStart(40, '0')
}))
),
headers: { 'x-next-page': page < 5 ? String(page + 1) : '' }
}
})
await expect(
Promise.all([mergedMRContainsHead(args), mergedMRContainsHead(args)])
).resolves.toEqual(['contained', 'contained'])
for (let i = 0; i < count; i++) {
await expect(mergedMRContainsHead(args)).resolves.toBe('contained')
}
expect(pages).toHaveBeenCalledTimes(5)
viewer.mockResolvedValue({ id: 2 })
await mergedMRContainsHead(args)
expect(pages).toHaveBeenCalledTimes(10)
}
)
it('preserves a failed page as unavailable, and a user refresh retries it', async () => {
pages
.mockResolvedValueOnce({
body: JSON.stringify(
Array.from({ length: 100 }, (_, i) => ({ id: i.toString(16).padStart(40, '0') }))
),
headers: { 'x-next-page': '2' }
})
.mockRejectedValueOnce(new Error('offline'))
await expect(mergedMRContainsHead(args)).rejects.toThrow()
await expect(mergedMRContainsHead(args)).rejects.toThrow()
expect(pages).toHaveBeenCalledTimes(2)
pages.mockResolvedValue({
body: JSON.stringify([{ id: args.headOid }]),
headers: { 'x-next-page': '' }
})
await expect(mergedMRContainsHead({ ...args, userRefresh: true })).resolves.toBe('contained')
expect(pages).toHaveBeenCalledTimes(3)
})
it('does a fresh authorized walk without a usable viewer identity', async () => {
viewer.mockRejectedValue(new Error('no viewer'))
pages.mockResolvedValue({ body: '[]', headers: { 'x-next-page': '' } })
await expect(mergedMRContainsHead(args)).resolves.toBe('not-contained')
await expect(mergedMRContainsHead(args)).resolves.toBe('not-contained')
expect(pages).toHaveBeenCalledTimes(2)
})
@@ -0,0 +1,93 @@
import {
MergedReviewMembershipMemo,
type MergedReviewCommitMembership
} from '../source-control/merged-review-membership-memo'
import { codeHostReadExecutionScope } from '../source-control/code-host-read-execution-scope'
import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe'
import { fetchAllGitLabPages } from './gitlab-paginated-list'
import { readGlabViewer } from './gitlab-auth-and-rate-limit'
import {
glabHostnameArgs,
glabRepoExecOptions,
type LocalGitExecOptions,
type ProjectRef
} from './gl-utils'
import { encodedProject } from './project-path-encoding'
const membershipMemo = new MergedReviewMembershipMemo()
const viewers: CoalescedProbes<number | null> = new Map()
export function resetMergedMRCommitMembershipForTest(): void {
membershipMemo.clear()
viewers.clear()
}
export async function mergedMRContainsHead(args: {
repoPath: string
project: ProjectRef
targetProjectId: number
iid: number
headOid: string
connectionId?: string | null
localGitOptions: LocalGitExecOptions
userRefresh?: boolean
}): Promise<MergedReviewCommitMembership> {
const options = glabRepoExecOptions(args.repoPath, args.connectionId, args.localGitOptions)
const scope = codeHostReadExecutionScope({ ...options, connectionId: args.connectionId ?? null })
const viewerKey = `${args.project.host.toLowerCase()}\0${scope}`
const viewer = await runCoalescedProbe(
viewers,
viewerKey,
async () => {
try {
const data = await readGlabViewer(
glabHostnameArgs(args.project, args.connectionId),
options
)
return typeof data.id === 'number' && Number.isSafeInteger(data.id) && data.id > 0
? data.id
: null
} catch {
return null
}
},
Infinity,
{ userRefresh: args.userRefresh }
)
const load = async (): Promise<MergedReviewCommitMembership> => {
const commits = await fetchAllGitLabPages<{ id?: unknown }>(
args.repoPath,
args.project,
`projects/${encodedProject(args.project.path)}/merge_requests/${args.iid}/commits`,
args.connectionId,
args.localGitOptions
)
if (
commits.some(
(commit) => typeof commit.id !== 'string' || !/^[0-9a-f]{40,64}$/i.test(commit.id)
)
) {
throw new Error('Invalid GitLab merge request commits')
}
return commits.some(
(commit) =>
typeof commit.id === 'string' && commit.id.toLowerCase() === args.headOid.toLowerCase()
)
? 'contained'
: 'not-contained'
}
// A missing account identity disables bookkeeping, never the authorized fresh read.
if (viewer === null) {
return load()
}
const key = [
'gitlab',
args.project.host.toLowerCase(),
scope,
viewer,
args.targetProjectId,
args.iid,
args.headOid.toLowerCase()
].join('\0')
return membershipMemo.read(key, load, { refreshFailed: args.userRefresh })
}
+120
View File
@@ -0,0 +1,120 @@
import { beforeEach, expect, it, vi } from 'vitest'
import type * as GlabApiResponse from './glab-api-response'
const { pages, viewer } = vi.hoisted(() => ({ pages: vi.fn(), viewer: vi.fn() }))
vi.mock('./gl-utils', async () => ({
...(await vi.importActual<typeof GlabApiResponse>('./glab-api-response')),
glabApiWithHeaders: pages,
glabHostnameArgs: () => [],
glabRepoExecOptions: () => ({})
}))
vi.mock('./gitlab-auth-and-rate-limit', () => ({ readGlabViewer: viewer }))
import { fetchDiscussionComments } from './mr-discussion-notes'
beforeEach(() => {
pages.mockReset()
viewer.mockReset().mockResolvedValue({ username: 'me' })
})
it.each(['mr', 'issue'] as const)(
'reads newest %s discussions beyond 100 with thread metadata',
async (type) => {
pages.mockImplementation(async ([endpoint]: string[]) => {
const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page'))
return {
body: JSON.stringify(
Array.from({ length: page === 1 ? 100 : 1 }, (_, i) => ({
id: `D${page}-${i}`,
notes: [
{
id: (page - 1) * 100 + i,
body: 'Review',
created_at: page === 1 ? '2026-01-01' : '2026-11-08',
author: { username: 'me' },
resolvable: true,
resolved: true,
position: { new_path: 'a.ts', new_line: 4 }
}
]
}))
),
headers: { 'x-next-page': page === 1 ? '2' : '' }
}
})
const comments = await fetchDiscussionComments(
'/repo',
{ host: 'gitlab.com', path: 'g/p' },
type,
7
)
expect(comments).toHaveLength(101)
expect(comments.at(-1)).toMatchObject({
id: 100,
threadId: 'D2-0',
isResolved: true,
path: 'a.ts',
line: 4,
viewerDidAuthor: true
})
expect(pages).toHaveBeenCalledTimes(2)
expect(viewer).toHaveBeenCalledTimes(1)
}
)
it('never presents a successful prefix after a later discussion page fails', async () => {
pages
.mockResolvedValueOnce({
body: JSON.stringify(Array.from({ length: 100 }, (_, i) => ({ id: String(i) }))),
headers: { 'x-next-page': '2' }
})
.mockRejectedValueOnce(new Error('offline'))
await expect(
fetchDiscussionComments('/repo', { host: 'gitlab.com', path: 'g/p' }, 'mr', 7)
).rejects.toThrow('incomplete')
})
it.each([100, 1000])('measures complete realistic discussions at %s rows', async (count) => {
const body = `## Review\n\nPlease preserve the existing owner across reconnects.\n\n\`\`\`typescript\nconst state = await readOwner()\nreturn state.current\n\`\`\`\n\n${'The next request should retain the confirmed state and report incomplete reads. '.repeat(
20
)}`
let rawBytes = 0
pages.mockImplementation(async ([endpoint]: string[]) => {
const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page'))
const rows = Array.from({ length: Math.min(100, count - (page - 1) * 100) }, (_, i) => ({
id: `discussion-${page}-${i}`,
notes: [
{
id: (page - 1) * 100 + i,
body,
created_at: '2026-11-08T00:00:00Z',
author: { username: 'me', avatar_url: 'https://gitlab.com/avatar.png' },
resolvable: true,
resolved: false,
position: { new_path: 'src/file.ts', new_line: 17 }
}
]
}))
const serialized = JSON.stringify(rows)
rawBytes += Buffer.byteLength(serialized)
return {
body: serialized,
headers: { 'x-next-page': page * 100 < count ? String(page + 1) : '' }
}
})
const before = process.memoryUsage().heapUsed
const start = performance.now()
const result = await fetchDiscussionComments(
'/repo',
{ host: 'gitlab.com', path: 'g/p' },
'mr',
7
)
const normalized = performance.now()
const wireBytes = Buffer.byteLength(JSON.stringify(result))
console.info('gitlab-review-parity-discussions', {
count,
rawBytes,
wireBytes,
readParseSortMs: normalized - start,
serializeMs: performance.now() - normalized,
heapDeltaBytes: process.memoryUsage().heapUsed - before
})
expect(result).toHaveLength(count)
expect(pages).toHaveBeenCalledTimes(count / 100)
})
+9 -11
View File
@@ -1,3 +1,4 @@
import { fetchAllGitLabPages } from './gitlab-paginated-list'
import type { MRComment } from '../../shared/gitlab-types'
import { viewerAuthorship } from '../source-control/comment-viewer-authorship'
import { readGlabViewer } from './gitlab-auth-and-rate-limit'
@@ -5,7 +6,6 @@ import { encodedProject } from './project-path-encoding'
import {
glabHostnameArgs,
glabRepoExecOptions,
glabExecFileAsync,
type LocalGitExecOptions,
type ProjectRef
} from './gl-utils'
@@ -71,15 +71,13 @@ export async function fetchDiscussionComments(
const resource = type === 'mr' ? 'merge_requests' : 'issues'
const hostArgs = glabHostnameArgs(projectRef, connectionId)
const options = glabRepoExecOptions(repoPath, connectionId, localGitOptions)
const [{ stdout }, viewerUsername] = await Promise.all([
glabExecFileAsync(
[
'api',
...hostArgs,
// Bound detail loads to a recent page rather than retaining every historic discussion.
`projects/${encodedProject(projectRef.path)}/${resource}/${iid}/discussions?per_page=100`
],
options
const [discussions, viewerUsername] = await Promise.all([
fetchAllGitLabPages<GitLabRawDiscussion>(
repoPath,
projectRef,
`projects/${encodedProject(projectRef.path)}/${resource}/${iid}/discussions`,
connectionId,
localGitOptions
),
// Notes carry no authorship flag, so ask the reading account who it is.
markViewer
@@ -89,5 +87,5 @@ export async function fetchDiscussionComments(
)
: null
])
return flattenDiscussions(JSON.parse(stdout) as GitLabRawDiscussion[], viewerUsername)
return flattenDiscussions(discussions, viewerUsername)
}
@@ -6,6 +6,8 @@ const { glabApiWithHeadersMock } = vi.hoisted(() => ({ glabApiWithHeadersMock: v
vi.mock('./gl-utils', async () => ({
...(await vi.importActual<typeof GlabApiResponse>('./glab-api-response')),
glabApiWithHeaders: glabApiWithHeadersMock,
acquire: vi.fn(),
release: vi.fn(),
// Serves single-request fetches from the same pipeline, so a reverted fix fails on row counts.
glabExecFileAsync: async (args: string[]) => ({
stdout: (await glabApiWithHeadersMock(args.slice(1))).body
@@ -16,6 +18,7 @@ vi.mock('./gl-utils', async () => ({
import { GitLabIncompletePaginationError } from './gitlab-paginated-list'
import { fetchPipelineJobs } from './pipeline-job-graph'
import { retryJob } from './pipeline-job-mutations'
/** Serves `/jobs` and `/bridges` 100 per page with GitLab's x-next-page header. */
function servePipeline(
@@ -56,6 +59,32 @@ describe('fetchPipelineJobs', () => {
glabApiWithHeadersMock.mockReset()
})
it('preserves optional failure policy through job, bridge and retry responses', async () => {
glabApiWithHeadersMock.mockImplementation(async (args: string[]) => {
const endpoint = args.at(-1) ?? ''
const raw = { id: 19, name: 'test', status: 'failed', allow_failure: true }
return {
body: JSON.stringify(
endpoint.endsWith('/retry')
? raw
: endpoint.includes('/bridges?')
? [{ ...raw, name: 'trigger' }]
: [raw]
),
headers: { 'x-next-page': '' }
}
})
const project = { host: 'gitlab.com', path: 'g/p' }
await expect(fetchPipelineJobs('/repo', project, 7)).resolves.toMatchObject([
{ id: 19, status: 'failed', allowFailure: true },
{ id: 0, name: 'trigger', status: 'failed', allowFailure: true }
])
await expect(retryJob('/repo', 19, undefined, null, project)).resolves.toMatchObject({
ok: true,
job: { id: 19, allowFailure: true }
})
})
it.each([
// One request per started 100-item page on each endpoint.
{ jobs: 130, bridges: 101, requests: 4 },
+4
View File
@@ -16,6 +16,7 @@ type GitLabRawJob = {
name?: string
stage?: string
status?: string
allow_failure?: boolean
web_url?: string
duration?: number | null
started_at?: string | null
@@ -27,6 +28,7 @@ type GitLabRawBridge = {
name?: string
stage?: string
status?: string
allow_failure?: boolean
web_url?: string
duration?: number | null
started_at?: string | null
@@ -46,6 +48,7 @@ function mapPipelineJob(raw: GitLabRawJob, pipelineId: number): GitLabPipelineJo
name: raw.name ?? '',
stage: raw.stage ?? '',
status: raw.status ?? '',
...(typeof raw.allow_failure === 'boolean' ? { allowFailure: raw.allow_failure } : {}),
webUrl: raw.web_url ?? '',
duration: typeof raw.duration === 'number' ? raw.duration : null,
...gitLabRunTimes(raw)
@@ -62,6 +65,7 @@ function mapBridgeAsJob(raw: GitLabRawBridge, pipelineId: number): GitLabPipelin
stage: raw.stage ?? '',
// Bridge status may remain successful while its downstream pipeline is running or failed.
status: childStatus || raw.status || '',
...(typeof raw.allow_failure === 'boolean' ? { allowFailure: raw.allow_failure } : {}),
webUrl: raw.downstream_pipeline?.web_url ?? raw.web_url ?? '',
duration: typeof raw.duration === 'number' ? raw.duration : null,
// The trigger job's own times can end long before the child pipeline it now stands for.
@@ -31,6 +31,7 @@ function mapRetriedPipelineJob(
name?: string
stage?: string
status?: string
allow_failure?: boolean
web_url?: string
duration?: number | null
started_at?: string | null
@@ -44,6 +45,7 @@ function mapRetriedPipelineJob(
name: data.name ?? '',
stage: data.stage ?? '',
status: data.status ?? '',
...(typeof data.allow_failure === 'boolean' ? { allowFailure: data.allow_failure } : {}),
webUrl: data.web_url ?? '',
duration: typeof data.duration === 'number' ? data.duration : null,
...gitLabRunTimes(data)
@@ -0,0 +1,71 @@
import { beforeEach, expect, it, vi } from 'vitest'
const { read, signature } = vi.hoisted(() => ({ read: vi.fn(), signature: vi.fn() }))
vi.mock('./gl-utils', () => ({
glabExecFileAsync: read,
glabHostnameArgs: () => [],
glabRepoExecOptions: (cwd: string) => ({ cwd })
}))
vi.mock('../github/local-git-config-signature', () => ({ readLocalGitConfigSignature: signature }))
import {
readReviewProjectIdentity,
resetReviewProjectIdentitiesForTest
} from './review-project-identity'
const project = { host: 'gitlab.com', path: 'g/p' }
const result = (id: number) => ({
stdout: JSON.stringify({ id, path_with_namespace: 'canonical/p' })
})
beforeEach(() => {
resetReviewProjectIdentitiesForTest()
read.mockReset()
signature.mockReset().mockResolvedValue('config-1')
})
it('coalesces minimal identities, invalidates changed configuration, and does not retain failed reads', async () => {
read.mockResolvedValue(result(1))
await expect(
Promise.all([
readReviewProjectIdentity('/repo', project, null, {}),
readReviewProjectIdentity('/repo', project, null, {})
])
).resolves.toEqual([
{ id: 1, path: 'canonical/p' },
{ id: 1, path: 'canonical/p' }
])
expect(read).toHaveBeenCalledTimes(1)
signature.mockResolvedValue('config-2')
read.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(result(2))
await expect(readReviewProjectIdentity('/repo', project, null, {})).rejects.toThrow('offline')
await expect(readReviewProjectIdentity('/repo', project, null, {})).resolves.toMatchObject({
id: 2
})
expect(read).toHaveBeenCalledTimes(3)
})
it('does not let an older forced-out read overwrite its successor', async () => {
let finish: (value: { stdout: string }) => void = () => {
throw new Error('not started')
}
let started: () => void = () => {
throw new Error('not started')
}
const admitted = new Promise<void>((resolve) => {
started = resolve
})
read
.mockImplementationOnce(() => {
started()
return new Promise<{ stdout: string }>((resolve) => {
finish = resolve
})
})
.mockResolvedValueOnce(result(2))
const old = readReviewProjectIdentity('/repo', project, null, {})
await admitted
await expect(readReviewProjectIdentity('/repo', project, null, {}, true)).resolves.toMatchObject({
id: 2
})
finish(result(1))
await old
await expect(readReviewProjectIdentity('/repo', project, null, {})).resolves.toMatchObject({
id: 2
})
expect(read).toHaveBeenCalledTimes(2)
})
+113
View File
@@ -0,0 +1,113 @@
import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe'
import { codeHostReadExecutionScope } from '../source-control/code-host-read-execution-scope'
import { readLocalGitConfigSignature } from '../github/local-git-config-signature'
import {
glabExecFileAsync,
glabHostnameArgs,
glabRepoExecOptions,
type LocalGitExecOptions,
type ProjectRef
} from './gl-utils'
import { encodedProject } from './project-path-encoding'
import { normalizeGitLabHost } from './project-ref-parser'
type ProjectIdentity = { id: number; path: string }
type CachedIdentity = { value: ProjectIdentity; expiresAt: number; configSignature?: string }
const identities = new Map<string, CachedIdentity>()
const pending: CoalescedProbes<ProjectIdentity> = new Map()
function identityKey(
repoPath: string,
project: ProjectRef,
connectionId: string | null | undefined,
options: LocalGitExecOptions
): string {
return [
normalizeGitLabHost(project.host),
project.path,
connectionId ?? '',
codeHostReadExecutionScope(glabRepoExecOptions(repoPath, connectionId, options))
].join('\0')
}
export function forgetReviewProjectIdentity(
repoPath: string,
project: ProjectRef,
connectionId: string | null | undefined,
options: LocalGitExecOptions
): void {
const key = identityKey(repoPath, project, connectionId, options)
identities.delete(key)
pending.delete(key)
}
export function resetReviewProjectIdentitiesForTest(): void {
identities.clear()
pending.clear()
}
export async function readReviewProjectIdentity(
repoPath: string,
project: ProjectRef,
connectionId: string | null | undefined,
options: LocalGitExecOptions,
force = false
): Promise<ProjectIdentity> {
const key = identityKey(repoPath, project, connectionId, options)
const signature = await readLocalGitConfigSignature({ repoPath, connectionId, ...options })
const cached = identities.get(key)
if (!force && cached && cached.expiresAt > Date.now() && cached.configSignature === signature) {
return cached.value
}
return runCoalescedProbe(
pending,
key,
async (ownsKey) => {
const { stdout } = await glabExecFileAsync(
[
'api',
...glabHostnameArgs(project, connectionId),
`projects/${encodedProject(project.path)}`
],
glabRepoExecOptions(repoPath, connectionId, options)
)
const data: unknown = JSON.parse(stdout)
if (
!data ||
typeof data !== 'object' ||
!('id' in data) ||
typeof data.id !== 'number' ||
!Number.isSafeInteger(data.id) ||
data.id <= 0 ||
!('path_with_namespace' in data) ||
typeof data.path_with_namespace !== 'string' ||
!data.path_with_namespace
) {
throw new Error('Invalid GitLab source project identity')
}
const value = { id: data.id, path: data.path_with_namespace }
if (ownsKey()) {
identities.set(key, {
value,
configSignature: signature,
expiresAt: Date.now() + 5 * 60_000
})
for (const [entryKey, entry] of identities) {
if (entry.expiresAt <= Date.now()) {
identities.delete(entryKey)
}
}
while (identities.size > 512) {
const oldest = identities.keys().next().value
if (oldest === undefined) {
break
}
identities.delete(oldest)
}
}
return value
},
Infinity,
{ userRefresh: force }
)
}
+26
View File
@@ -261,4 +261,30 @@ describe('getWorkItemDetails', () => {
])
}
)
it.each(['mr', 'issue'] as const)(
'returns unavailable for a late %s discussion failure',
async (type) => {
glabExecFileAsyncMock.mockImplementation(async (args: string[]) => {
const endpoint = args.at(-1) ?? ''
if (endpoint.includes('/discussions')) {
if (endpoint.includes('page=2')) {
throw new Error('offline')
}
return {
stdout: JSON.stringify(
Array.from({ length: 100 }, (_, i) => ({
id: String(i),
notes: [{ id: i, body: 'Existing note' }]
}))
)
}
}
if (endpoint === 'user') {
return { stdout: '{"username":"me"}' }
}
return { stdout: JSON.stringify({ iid: 12, title: 'Item', state: 'opened' }) }
})
await expect(getWorkItemDetails('/repo', 12, type)).resolves.toBeNull()
}
)
})
@@ -0,0 +1,29 @@
export async function selectBranchReview<T>(input: {
readRecent: () => Promise<T[]>
readActive: () => Promise<T | null>
isActive: (review: T) => boolean
pageSize: number
}): Promise<T | null> {
const recent = await input.readRecent()
const active = recent.find(input.isActive)
if (active) {
return active
}
// A full mixed-state page cannot prove that no older active review exists.
return recent.length < input.pageSize
? (recent[0] ?? null)
: ((await input.readActive()) ?? recent[0] ?? null)
}
export function shouldHideMergedImplicitReview(
state: string,
linkedNumber: number | null | undefined,
reviewHead: string | null | undefined,
currentHead: string | null
): boolean {
return (
typeof linkedNumber !== 'number' &&
state.toLowerCase() === 'merged' &&
(!currentHead || reviewHead !== currentHead)
)
}
@@ -0,0 +1,18 @@
import { createHash } from 'node:crypto'
export function codeHostReadExecutionScope<T extends object>(
options: T & { env?: NodeJS.ProcessEnv; admissionTier?: unknown },
environment: NodeJS.ProcessEnv = options.env ?? process.env
): string {
const { admissionTier: _admissionTier, ...executionOptions } = options
// gh wrappers and credential selection can depend on cwd and the inherited environment.
return createHash('sha256')
.update(
JSON.stringify([
executionOptions,
process.cwd(),
Object.entries(environment).sort(([a], [b]) => a.localeCompare(b, 'en'))
])
)
.digest('hex')
}
+4 -4
View File
@@ -57,8 +57,8 @@ export type ForgeReviewForBranchInput = ForgeProviderRepositoryContext & {
branch: string
linkedReviewNumber?: number | null
fallbackReviewNumber?: number | null
// GitHub-only merged-at-head visibility; other providers ignore this inspected HEAD.
githubCurrentHeadOid?: string | null
// The inspected checkout HEAD scopes implicit merged-review visibility.
currentHeadOid?: string | null
userRefresh?: boolean
}
@@ -109,7 +109,7 @@ const gitLabForgeProvider = {
input.branch,
input.linkedReviewNumber ?? null,
forgeConnectionId(input),
...hostedReviewExecutionArgs(input)
{ ...input, currentHeadOid: input.currentHeadOid }
)
return mr ? mapGitLabReview(mr) : null
},
@@ -178,7 +178,7 @@ const gitHubForgeProvider = {
...executionArgs[0],
...(input.userRefresh === true ? { userRefresh: true } : {}),
...(fallbackReviewNumber !== null ? { acceptMergedFallbackPR: true } : {}),
currentHeadOid: input.githubCurrentHeadOid ?? null
currentHeadOid: input.currentHeadOid ?? null
}
)
return unwrapGitHubPRForBranchOutcome(outcome)
+1 -1
View File
@@ -138,7 +138,7 @@ export async function readHostedReviewForBranch(
...(providerOptions.localGitExecOptions
? { localGitExecOptions: providerOptions.localGitExecOptions }
: {}),
githubCurrentHeadOid: headOid,
currentHeadOid: headOid,
...(input.userRefresh === true ? { userRefresh: true } : {}),
...reviewLinkForProvider(input, provider.id)
})
@@ -0,0 +1,92 @@
import { runCoalescedProbe, type CoalescedProbes } from '../git/remotes/coalesced-probe'
export type MergedReviewCommitMembership = 'contained' | 'not-contained' | 'unknown'
type Receipt = { value: MergedReviewCommitMembership; expiresAt: number; failed?: boolean }
export class MergedReviewMembershipUnavailableError extends Error {
constructor() {
super('Could not verify merged review commit membership')
}
}
/** Each provider owns a partition; one provider cannot evict another's immutable verdicts. */
export class MergedReviewMembershipMemo {
private readonly receipts = new Map<string, Receipt>()
private readonly pending: CoalescedProbes<MergedReviewCommitMembership> = new Map()
clear(): void {
this.receipts.clear()
this.pending.clear()
}
peek(key: string): MergedReviewCommitMembership | undefined {
this.prune()
const receipt = this.receipts.get(key)
if (receipt?.failed) {
throw new MergedReviewMembershipUnavailableError()
}
return receipt?.value
}
async read(
key: string,
load: () => Promise<MergedReviewCommitMembership>,
options: { refreshFailed?: boolean; bypass?: boolean } = {}
): Promise<MergedReviewCommitMembership> {
this.prune()
const cached = this.receipts.get(key)
if (cached && !options.bypass && !(options.refreshFailed && cached.failed)) {
if (cached.failed) {
throw new MergedReviewMembershipUnavailableError()
}
return cached.value
}
return runCoalescedProbe(
this.pending,
key,
async (ownsKey) => {
try {
const value = await load()
if (ownsKey()) {
this.receipts.set(key, {
value,
expiresAt: Date.now() + (value === 'unknown' ? 5 * 60_000 : 6 * 60 * 60_000)
})
this.prune()
}
return value
} catch {
if (ownsKey()) {
this.receipts.set(key, {
value: 'unknown',
failed: true,
expiresAt: Date.now() + 5 * 60_000
})
this.prune()
}
throw new MergedReviewMembershipUnavailableError()
}
},
// A slow live walk stays shared; elapsed time alone must not multiply it.
Infinity,
{ userRefresh: options.bypass || options.refreshFailed }
)
}
private prune(): void {
const now = Date.now()
for (const [key, receipt] of this.receipts) {
if (receipt.expiresAt <= now) {
this.receipts.delete(key)
}
}
while (this.receipts.size > 200) {
const key = this.receipts.keys().next().value
if (key === undefined) {
break
}
this.receipts.delete(key)
}
}
}
@@ -0,0 +1,23 @@
import { gitExecFileAsync } from '../git/runner'
import { requireReachableGitRoute } from '../providers/execution-host-provider-dispatch'
import { getConnectionExecutionHostId } from '../../shared/execution-host'
import type { HostedReviewLocalGitOptions } from './hosted-review-git-options'
export async function readCurrentReviewHead(
repoPath: string,
connectionId?: string | null,
options: HostedReviewLocalGitOptions = {},
runGit = gitExecFileAsync
): Promise<string | null> {
requireReachableGitRoute(getConnectionExecutionHostId(connectionId))
try {
const result = await runGit(['rev-parse', 'HEAD'], {
cwd: repoPath,
...(options.wslDistro ? { wslDistro: options.wslDistro } : {}),
...(options.admissionTier ? { admissionTier: options.admissionTier } : {})
})
return result.stdout.trim() || null
} catch {
return null
}
}
@@ -36,11 +36,15 @@ function formatCheckTimestamp(
}
type CheckStatusLike = {
gitlabAllowedFailure?: boolean
status: PRCheckDetail['status'] | (string & {}) | null | undefined
conclusion: PRCheckDetail['conclusion'] | (string & {}) | null | undefined
}
function getCheckStatusLabel(check: CheckStatusLike, t: Translate = translate): string {
if (check.gitlabAllowedFailure === true && check.conclusion === 'neutral') {
return t('checks.gitlabAllowedFailure', 'Allowed to fail')
}
const conclusion = check.conclusion ?? 'pending'
switch (conclusion) {
case 'success':
@@ -3,11 +3,11 @@ import { ChevronDown, CircleDashed } from 'lucide-react'
import { cn } from '@/lib/utils'
import {
CHECK_COLOR,
CHECK_ICON
CHECK_ICON,
checkPresentationKey
} from '@/components/right-sidebar/checks-panel/presentation/check-presentation'
import type { CheckDetailsLoadState } from '@/components/github-checks-tab-state'
import type { PRCheckDetail } from '../../../../../shared/github/check-types'
import { getCheckConclusion } from '@/components/pr-check-counts'
import { getCheckDetailsKey, getCheckStatusLabel } from '@/components/github/pr-check-presentation'
import { ChecksTabCheckDetails } from './checks-tab-check-details'
import { useTranslate } from '@/i18n/use-translate'
@@ -57,7 +57,7 @@ export function ChecksTabCheckRow({
onRetry: (check: PRCheckDetail, key: string) => void
}): React.JSX.Element {
const t = useTranslate()
const conclusion = getCheckConclusion(check)
const conclusion = checkPresentationKey(check)
const Icon = CHECK_ICON[conclusion] ?? CircleDashed
const color = CHECK_COLOR[conclusion] ?? 'text-muted-foreground'
const statusLabel = getCheckStatusLabel(check, t)
@@ -8,6 +8,9 @@ import type {
} from '../../../../shared/github/check-types'
export function getCheckStatusLabel(check: PRCheckDetail, t: Translate = translate): string {
if (check.gitlabAllowedFailure === true && check.conclusion === 'neutral') {
return t('checks.gitlabAllowedFailure', 'Allowed to fail')
}
const conclusion = getCheckConclusion(check)
if (conclusion === 'success') {
return t('auto.components.github.prCheckPresentation.successful', 'Successful')
@@ -1,5 +1,5 @@
import React from 'react'
import { ExternalLink, LoaderCircle } from 'lucide-react'
import { AlertTriangle, ExternalLink, LoaderCircle } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import CommentMarkdown from '@/components/sidebar/CommentMarkdown'
@@ -42,6 +42,7 @@ export function jobStatusTone(status: string): string {
case 'waiting_for_resource':
case 'scheduled':
return 'bg-sky-500/15 text-sky-700 dark:text-sky-300'
case 'warning':
case 'manual':
return 'bg-amber-500/15 text-amber-700 dark:text-amber-300'
case 'canceled':
@@ -204,12 +205,14 @@ export function PipelineJobRow({
onRetry: (job: GitLabPipelineJob) => void
}): React.JSX.Element {
const t = useTranslate()
const canRetry = ['failed', 'canceled', 'cancelled'].includes(job.status)
const allowedFailure = job.status === 'failed' && job.allowFailure === true
const canRetry = job.id > 0 && ['failed', 'canceled', 'cancelled'].includes(job.status)
return (
<div className="rounded-md">
<div className="grid w-full grid-cols-[minmax(0,2fr)_minmax(0,1fr)_80px_64px_96px] items-center gap-3 px-3 py-2 text-left text-sm hover:bg-muted/40">
<div className="grid w-full grid-cols-[minmax(0,2fr)_minmax(0,1fr)_max-content_64px_96px] items-center gap-3 px-3 py-2 text-left text-sm hover:bg-muted/40">
<button
type="button"
disabled={job.id <= 0}
onClick={() => onToggleTrace(job)}
className="min-w-0 truncate text-left font-medium"
>
@@ -218,11 +221,12 @@ export function PipelineJobRow({
<span className="min-w-0 truncate text-xs text-muted-foreground">{job.stage}</span>
<span
className={cn(
'rounded-full px-2 py-0.5 text-center text-[10px] font-medium uppercase tracking-wide',
jobStatusTone(job.status)
'flex items-center gap-1 rounded-full px-2 py-0.5 text-center text-[10px] font-medium uppercase tracking-wide',
jobStatusTone(allowedFailure ? 'warning' : job.status)
)}
>
{job.status}
{allowedFailure ? <AlertTriangle className="size-3 shrink-0" /> : null}
{allowedFailure ? t('checks.gitlabAllowedFailure', 'Allowed to fail') : job.status}
</span>
<span className="text-right text-[11px] text-muted-foreground">
{typeof job.duration === 'number'
@@ -9,10 +9,18 @@ import {
GitPullRequest
} from 'lucide-react'
import type { PRInfo } from '../../../../../../shared/github/pull-request-types'
import type { PRCheckDetail } from '../../../../../../shared/github/check-types'
export const PullRequestIcon = GitPullRequest
export function checkPresentationKey(check: PRCheckDetail): string {
return check.gitlabAllowedFailure === true && check.conclusion === 'neutral'
? 'gitlabAllowedFailure'
: (check.conclusion ?? 'pending')
}
export const CHECK_ICON: Record<string, React.ComponentType<{ className?: string }>> = {
gitlabAllowedFailure: AlertTriangle,
success: CircleCheck,
failure: CircleX,
pending: LoaderCircle,
@@ -25,6 +33,7 @@ export const CHECK_ICON: Record<string, React.ComponentType<{ className?: string
}
export const CHECK_COLOR: Record<string, string> = {
gitlabAllowedFailure: 'text-amber-500',
success: 'text-emerald-500',
failure: 'text-rose-500',
pending: 'text-amber-500',
@@ -13,7 +13,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { cn } from '@/lib/utils'
import { observeOffscreenAnimation } from '@/lib/offscreen-animation-pause'
import { useTranslate } from '@/i18n/use-translate'
import { CHECK_COLOR, CHECK_ICON } from './check-presentation'
import { CHECK_COLOR, CHECK_ICON, checkPresentationKey } from './check-presentation'
import { CheckRunDetails } from './check-run-details'
import { CheckRunTime } from './check-run-time'
import { getCheckStatusLabel } from '@/components/github/pr-check-presentation'
@@ -249,7 +249,7 @@ export function ChecksList(props: ChecksListProps): React.JSX.Element {
// The icon already shows the state, so its word lives in the icon's tooltip and accessible name, not beside it.
function CheckStatusIcon({ check }: { check: PRCheckDetail }): React.JSX.Element {
const t = useTranslate()
const conclusion = getCheckConclusion(check)
const conclusion = checkPresentationKey(check)
const Icon = CHECK_ICON[conclusion] ?? CircleDashed
const label = getCheckStatusLabel(check, t)
return (
+3
View File
@@ -23567,5 +23567,8 @@
"branchName": "Branch-Name",
"invalidBranchName": "Dieser Branchname ist ungültig. Wähle einen anderen Namen.",
"createBranchFailed": "Orca konnte den Branch nicht erstellen. Prüfe dieses Repository im Terminal und versuche es erneut."
},
"checks": {
"gitlabAllowedFailure": "Fehlschlag erlaubt"
}
}
+1
View File
@@ -24321,6 +24321,7 @@
}
},
"checks": {
"gitlabAllowedFailure": "Allowed to fail",
"rerunUnsuccessful": "Rerun unsuccessful"
},
"gitGraph": {
+3
View File
@@ -23975,5 +23975,8 @@
"branchName": "Nom de la branche",
"invalidBranchName": "Ce nom de branche n’est pas valide. Choisissez un autre nom.",
"createBranchFailed": "Orca n’a pas pu créer la branche. Vérifiez ce dépôt dans un terminal, puis réessayez."
},
"checks": {
"gitlabAllowedFailure": "Échec autorisé"
}
}
@@ -0,0 +1,26 @@
import { expect, it, vi } from 'vitest'
const { jobTrace } = vi.hoisted(() => ({ jobTrace: vi.fn() }))
vi.mock('./gitlab-owner-api', () => ({
JOB_TRACE_TIMEOUT_MS: 30000,
gitLabApiFor: () => ({ jobTrace })
}))
import { loadGitLabJobLogDetails } from './gitlab-job-trace-client'
it('loads the real job log for an optional failure and keeps manual jobs off the trace API', async () => {
jobTrace.mockResolvedValue({ ok: true, trace: 'Compiler failed: missing module' })
const check = {
name: 'test',
status: 'completed',
conclusion: 'neutral',
url: null,
gitlabJobId: 7,
gitlabAllowedFailure: true
} as const
const details = await loadGitLabJobLogDetails({ repoPath: '/repo', check })
expect(jobTrace).toHaveBeenCalledWith(expect.objectContaining({ jobId: 7, logExcerpt: true }))
expect(details?.jobs[0]).toMatchObject({ id: 7, logTail: 'Compiler failed: missing module' })
await loadGitLabJobLogDetails({
repoPath: '/repo',
check: { ...check, gitlabAllowedFailure: undefined }
})
expect(jobTrace).toHaveBeenCalledTimes(1)
})
@@ -1,6 +1,10 @@
type GitCommandRunner = (args: string[]) => Promise<{ stdout: string }>
type GitConfigSnapshot = Map<string, string[]>
export type GitConfigSnapshot = Map<string, string[]>
export async function readGitConfigSnapshot(runGit: GitCommandRunner): Promise<GitConfigSnapshot> {
return parseGitConfigListSnapshot((await runGit(['config', '--list', '-z'])).stdout)
}
// Mirror config --get exit 1 for absent keys; empty success changes caller behavior.
export class GitConfigSnapshotKeyNotFoundError extends Error {
@@ -54,9 +58,9 @@ export function createGitConfigSnapshotRunner(runGit: GitCommandRunner): GitComm
if (!snapshotPromise) {
// Publish the shared promise before any await so parallel resolvers coalesce.
try {
snapshotPromise = runGit(['config', '--list', '-z'])
.then(({ stdout }) => {
snapshot = parseGitConfigListSnapshot(stdout)
snapshotPromise = readGitConfigSnapshot(runGit)
.then((loaded) => {
snapshot = loaded
return snapshot
})
.catch(() => {
@@ -0,0 +1,63 @@
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { expect, it } from 'vitest'
import { readGitReviewBranchSources } from './git-review-branch-source'
const exec = promisify(execFile)
it('resolves real Git tracking, triangular publication, local tracking and explicit branch mappings', async () => {
const repo = await mkdtemp(path.join(tmpdir(), 'gitlab-review-parity-1108-'))
const git = (args: string[]) =>
exec('git', args, {
cwd: repo,
env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' }
})
try {
await git(['init', '--quiet'])
for (const [key, value] of [
['remote.origin.url', 'https://gitlab.com/team/repo.git'],
['remote.fork.url', 'https://gitlab.com/me/repo.git'],
['branch.feature.remote', 'origin'],
['branch.feature.merge', 'refs/heads/main'],
['branch.wip.remote', 'origin'],
['branch.wip.merge', 'refs/heads/renamed'],
['branch.dot.remote', '.'],
['branch.dot.merge', 'refs/heads/main']
]) {
await git(['config', key, value])
}
const snapshot = () => readGitReviewBranchSources(git, ['feature', 'wip', 'dot'])
expect((await snapshot()).get('feature')).toMatchObject({
branchName: 'feature',
trackedBranchName: 'main',
urls: ['https://gitlab.com/team/repo.git']
})
expect((await snapshot()).get('wip')).toMatchObject({
branchName: 'wip',
trackedBranchName: 'renamed'
})
expect((await snapshot()).get('dot')).toEqual({
remoteName: 'origin',
branchName: 'dot',
urls: ['https://gitlab.com/team/repo.git']
})
await git(['config', 'remote.pushDefault', 'fork'])
expect((await snapshot()).get('feature')).toEqual({
remoteName: 'fork',
branchName: 'feature',
urls: ['https://gitlab.com/me/repo.git']
})
await git(['config', 'branch.feature.pushRemote', 'origin'])
await git(['config', 'remote.origin.push', 'refs/heads/feature:refs/heads/published'])
expect((await snapshot()).get('feature')).toEqual({
remoteName: 'origin',
branchName: 'published',
urls: ['https://gitlab.com/team/repo.git']
})
await git(['config', '--add', 'remote.origin.push', 'refs/heads/feature:refs/heads/other'])
expect((await snapshot()).get('feature')).toBeInstanceOf(Error)
} finally {
await rm(repo, { recursive: true, force: true })
}
})
@@ -0,0 +1,181 @@
import {
readGitConfigSnapshot,
type GitConfigSnapshot
} from '../commands/git-config-snapshot-runner'
import { gitRefTargetsBranchOnRemote } from './git-remote-branch-name'
import { parseGitRemoteVerboseLine } from './git-remote-url-index'
export type GitReviewBranchSource = {
remoteName: string
urls: string[]
branchName: string
trackedBranchName?: string
trackedUrls?: string[]
}
type GitExec = (args: string[]) => Promise<{ stdout: string }>
function mappedPushBranch(spec: string, branch: string): string | null {
const clean = spec.replace(/^\+/, '')
if (clean === ':') {
return branch
}
const [source, destination = source] = clean.split(':')
if (!source) {
return null
}
const normalized =
source === 'HEAD'
? `refs/heads/${branch}`
: source.startsWith('refs/')
? source
: `refs/heads/${source}`
const fullBranch = `refs/heads/${branch}`
const star = normalized.indexOf('*')
let target = destination
if (star !== -1) {
const prefix = normalized.slice(0, star)
const suffix = normalized.slice(star + 1)
if (!fullBranch.startsWith(prefix) || !fullBranch.endsWith(suffix)) {
return null
}
target = destination.replace(
'*',
fullBranch.slice(prefix.length, fullBranch.length - suffix.length)
)
} else if (normalized !== fullBranch) {
return null
}
if (
!target ||
target === 'HEAD' ||
(target.startsWith('refs/') && !target.startsWith('refs/heads/'))
) {
throw new Error('Review push destination is not a branch')
}
return target.replace(/^refs\/heads\//, '')
}
/** One repository snapshot supplies all branches, rather than probing configuration per lookup. */
export async function readGitReviewBranchSources(
runGit: GitExec,
branchNames: Iterable<string>
): Promise<Map<string, GitReviewBranchSource | Error>> {
const config = await readGitConfigSnapshot(runGit)
const { stdout } = await runGit(['remote', '-v'])
const remotes = new Map<string, { fetch: string[]; push: string[] }>()
for (const line of stdout.split(/\r?\n/)) {
const entry = parseGitRemoteVerboseLine(line)
if (!entry) {
continue
}
const urls = remotes.get(entry.name) ?? { fetch: [], push: [] }
urls[entry.direction].push(entry.url)
remotes.set(entry.name, urls)
}
const get = (key: string): string | undefined => config.get(key)?.at(-1)?.trim() || undefined
const remoteIdentities = new Map<string, string>()
for (const [name, urls] of remotes) {
for (const url of [...urls.fetch, ...(config.get(`remote.${name}.url`) ?? [])]) {
if (!remoteIdentities.has(url)) {
remoteIdentities.set(url, name)
}
}
}
const normalizeRemote = (remote: string): string => remoteIdentities.get(remote) ?? remote
const expandedUrls = new Map<string, string[]>()
const urlsFor = (remote: string): string[] => {
const cached = expandedUrls.get(remote)
if (cached) {
return cached
}
const known = remotes.get(remote)
const urls = known?.push.length ? known.push : known?.fetch
const result =
urls ??
(/^[a-z][a-z0-9+.-]*:\/\//i.test(remote) || /^[^\s/:]+@[^:]+:.+/.test(remote)
? [rewritePushUrl(config, remote)]
: [])
if (result.length === 0) {
throw new Error('Review source remote is unavailable')
}
expandedUrls.set(remote, result)
return result
}
const sources = new Map<string, GitReviewBranchSource | Error>()
for (const branch of branchNames) {
try {
const trackedRemoteValue = get(`branch.${branch}.remote`)
const trackedRemote = trackedRemoteValue ? normalizeRemote(trackedRemoteValue) : undefined
const explicitRemote = get(`branch.${branch}.pushremote`) ?? get('remote.pushdefault')
let remote = normalizeRemote(explicitRemote ?? trackedRemote ?? 'origin')
const localTracking = remote === '.' && !explicitRemote
if (localTracking) {
remote = 'origin'
}
if (remote === '.') {
throw new Error('Review publish remote is local')
}
const specs = config.get(`remote.${remote}.push`) ?? []
let branchName = branch
let trackedBranchName: string | undefined
if (specs.length) {
const destinations = new Set(
specs.map((spec) => mappedPushBranch(spec, branch)).filter((value) => value !== null)
)
if (destinations.size !== 1) {
throw new Error('Review push destination is ambiguous')
}
branchName = destinations.values().next().value!
} else if (!localTracking && remote === trackedRemote) {
const merge = get(`branch.${branch}.merge`)
const tracked = merge?.startsWith('refs/heads/')
? merge.slice('refs/heads/'.length)
: undefined
if (
tracked &&
tracked !== branch &&
!gitRefTargetsBranchOnRemote(get(`branch.${branch}.base`), remote, tracked)
) {
trackedBranchName = tracked
}
if (get('push.default') === 'upstream' && !tracked) {
throw new Error('Review upstream is unavailable')
}
} else if (get('push.default') === 'upstream' && explicitRemote && remote !== trackedRemote) {
throw new Error('Review upstream belongs to another remote')
}
sources.set(branch, {
remoteName: remote,
urls: urlsFor(remote),
branchName,
...(trackedBranchName
? { trackedBranchName, trackedUrls: remotes.get(remote)?.fetch ?? [remote] }
: {})
})
} catch {
sources.set(branch, new Error('Cannot establish a unique hosted review source'))
}
}
return sources
}
function rewritePushUrl(config: GitConfigSnapshot, url: string): string {
for (const suffix of ['.pushinsteadof', '.insteadof']) {
let match: { prefix: string; base: string } | undefined
for (const [key, values] of config) {
if (!key.startsWith('url.') || !key.endsWith(suffix)) {
continue
}
for (const prefix of values) {
if (url.startsWith(prefix) && (!match || prefix.length > match.prefix.length)) {
match = { prefix, base: key.slice(4, -suffix.length) }
}
}
}
if (match) {
return match.base + url.slice(match.prefix.length)
}
}
return url
}
+1
View File
@@ -23,6 +23,7 @@ export type PRCheckDetail = {
workflowRunId?: number
// GitLab trace retrieval requires numeric job id, so carry it through the Checks row.
gitlabJobId?: number
gitlabAllowedFailure?: boolean
}
export type PRCheckAnnotation = {
+1
View File
@@ -250,6 +250,7 @@ export type GitLabPipelineJob = {
stage: string
/** Raw GitLab job status — 'success' / 'failed' / 'running' / 'pending' / 'canceled' / 'skipped' / 'manual' / 'created' / 'preparing'. */
status: string
allowFailure?: boolean
webUrl: string
/** Duration in seconds. null when the job hasn't finished. */
duration: number | null
@@ -0,0 +1,51 @@
import { expect, it } from 'vitest'
import { gitLabPipelineJobsToPRChecks } from './gitlab-pipeline-checks'
import { summarizeProviderChecks } from '../provider-check-summary'
import { gitLabJobCanHaveTrace } from './gitlab-job-trace-check-details'
it('counts only optional failed jobs as passing while preserving required and unfinished outcomes', () => {
const jobs = [
{ status: 'failed', allowFailure: true },
{ status: 'failed', allowFailure: false },
{ status: 'running', allowFailure: true },
{ status: 'manual', allowFailure: true },
{ status: 'skipped', allowFailure: true },
{ status: 'canceled', allowFailure: true }
].map((job, i) => ({
...job,
id: i + 1,
name: `job-${i}`,
stage: 'test',
webUrl: '',
duration: null
}))
const checks = gitLabPipelineJobsToPRChecks(jobs)
expect(checks[0]).toMatchObject({
status: 'completed',
conclusion: 'neutral',
gitlabAllowedFailure: true,
gitlabJobId: 1
})
expect(checks.slice(1).every((c) => c.gitlabAllowedFailure === undefined)).toBe(true)
expect(summarizeProviderChecks(checks)).toEqual({
state: 'failure',
total: 6,
passed: 2,
failed: 2,
pending: 1,
neutral: 1,
cancelled: 1
})
expect(summarizeProviderChecks([checks[0]])).toMatchObject({
state: 'success',
passed: 1,
failed: 0
})
expect(
summarizeProviderChecks([
{ status: 'completed', conclusion: 'neutral' },
{ status: 'completed', conclusion: 'skipped' }
])
).toMatchObject({ passed: 1, neutral: 1 })
expect(gitLabJobCanHaveTrace(checks[0])).toBe(true)
expect(gitLabJobCanHaveTrace(checks[3])).toBe(false)
})
@@ -11,7 +11,11 @@ export function gitLabJobCanHaveTrace(check: PRCheckDetail): boolean {
if (check.status === 'queued') {
return false
}
return check.conclusion !== 'neutral' && check.conclusion !== 'skipped'
return (
(check.conclusion !== 'neutral' ||
(check.gitlabAllowedFailure === true && check.status === 'completed')) &&
check.conclusion !== 'skipped'
)
}
/** Adapt GitLab’s flat trace into one job logTail in the existing provider-neutral check-details shape. */
@@ -107,11 +107,23 @@ export function getGitLabPipelineNotLatestCommitSha(
return pipeline.sha.toLowerCase() === mrHeadSha.toLowerCase() ? undefined : pipeline.sha
}
export function gitLabPipelineJobOutcome(job: {
status?: string
allowFailure?: boolean
}): Pick<PRCheckDetail, 'status' | 'conclusion' | 'gitlabAllowedFailure'> {
const status = job.status ?? ''
const allowedFailure = status.toLowerCase() === 'failed' && job.allowFailure === true
return {
status: mapGitLabPipelineJobStatusToCheckStatus(status),
conclusion: allowedFailure ? 'neutral' : mapGitLabPipelineJobStatusToConclusion(status),
...(allowedFailure ? { gitlabAllowedFailure: true } : {})
}
}
export function gitLabPipelineJobsToPRChecks(jobs: GitLabPipelineJob[]): PRCheckDetail[] {
return jobs.map((job) => ({
name: job.stage ? `${job.stage}: ${job.name}` : job.name,
status: mapGitLabPipelineJobStatusToCheckStatus(job.status),
conclusion: mapGitLabPipelineJobStatusToConclusion(job.status),
...gitLabPipelineJobOutcome(job),
url: job.webUrl || null,
...checkRunTimes(job.startedAt, job.finishedAt),
// Truthiness, not != null: the runtime RPC schema requires a positive int.
@@ -5,6 +5,9 @@ export function getCheckConclusion(check: PRCheckDetail): NonNullable<PRCheckDet
}
export function getCheckStatusLabel(check: PRCheckDetail): string {
if (check.gitlabAllowedFailure === true && check.conclusion === 'neutral') {
return 'Allowed to fail'
}
const conclusion = getCheckConclusion(check)
if (conclusion === 'success') {
return 'Successful'
@@ -2,7 +2,11 @@ import type { CheckStatus, ProviderCheckSummary } from '../../github/pull-reques
export type CheckOutcome = 'passed' | 'failed' | 'pending' | 'neutral'
export type CheckOutcomeInput = { status?: string | null; conclusion?: string | null }
export type CheckOutcomeInput = {
status?: string | null
conclusion?: string | null
gitlabAllowedFailure?: boolean
}
// Skipped means not applicable; count it passing everywhere so desktop/mobile agree on the same PR.
const PASSED_CONCLUSIONS = new Set(['success', 'skipped'])
@@ -24,6 +28,9 @@ export function classifyCheckOutcome(check: CheckOutcomeInput): CheckOutcome {
if (FAILED_CONCLUSIONS.has(conclusion)) {
return 'failed'
}
if (check.gitlabAllowedFailure === true && conclusion === 'neutral' && status === 'completed') {
return 'passed'
}
if (PASSED_CONCLUSIONS.has(conclusion)) {
return 'passed'
}