Open History to see the last commit
1import type { GitHubClient } from '../../scripts/maintainer/github.ts'
2import { fetchPullRequest } from './pr.ts'
3
4/**
5 * Resolve any trigger to `{ parsed, pr }`. A `workflow_run` is resolved through
6 * authenticated run and pull request metadata, never the event payload.
7 */
8export async function resolveReviewEvent(input: {
9 eventName: string
10 event: unknown
11 client: GitHubClient
12 repo: string
13}) {
14 if (input.eventName !== 'workflow_run') {
15 const parsed = parseReviewEvent(input)
16 const pr = await fetchPullRequest(input.client, input.repo, parsed.prNumber)
17 return { parsed, pr }
18 }
19 const eventRun = isRecord(input.event) ? input.event.workflow_run : undefined
20 const id = parsePrNumber(isRecord(eventRun) ? eventRun.id : undefined)
21 if (id === null) throw new Error('workflow_run is missing a valid run ID')
22 const run = await input.client.rest(
23 'GET',
24 `/repos/${input.repo}/actions/runs/${id}`,
25 )
26 const workflow = await input.client.rest(
27 'GET',
28 `/repos/${input.repo}/actions/workflows/ai-review-signal.yml`,
29 )
30 if (
31 !isRecord(run) ||
32 !isRecord(workflow) ||
33 run.id !== id ||
34 typeof workflow.id !== 'number' ||
35 run.workflow_id !== workflow.id ||
36 workflow.path !== '.github/workflows/ai-review-signal.yml' ||
37 run.event !== 'pull_request' ||
38 run.status !== 'completed' ||
39 run.conclusion !== 'success' ||
40 !isRecord(run.repository) ||
41 run.repository.full_name !== input.repo ||
42 !isRecord(run.head_repository) ||
43 typeof run.head_repository.full_name !== 'string' ||
44 !isRecord(run.head_repository.owner) ||
45 typeof run.head_repository.owner.login !== 'string' ||
46 typeof run.head_branch !== 'string' ||
47 typeof run.head_sha !== 'string' ||
48 !/^[0-9a-f]{40}$/i.test(run.head_sha)
49 ) {
50 throw new Error('workflow_run does not match the trusted signal workflow')
51 }
52 // The base repo's /commits/{sha}/pulls returns [] for a fork head, so list
53 // by head instead. One head branch has at most one open PR into main.
54 const head = encodeURIComponent(
55 `${run.head_repository.owner.login}:${run.head_branch}`,
56 )
57 const batch = await input.client.rest(
58 'GET',
59 `/repos/${input.repo}/pulls?state=open&base=main&head=${head}&per_page=100`,
60 )
61 if (!Array.isArray(batch))
62 throw new Error('Invalid workflow_run pull request list')
63 const candidates = new Set<number>()
64 for (const candidate of batch) {
65 if (
66 !isRecord(candidate) ||
67 !isRecord(candidate.head) ||
68 !isRecord(candidate.base) ||
69 !isRecord(candidate.head.repo) ||
70 !isRecord(candidate.base.repo)
71 )
72 throw new Error('Malformed workflow_run pull request')
73 const number = parsePrNumber(candidate.number)
74 if (
75 number !== null &&
76 candidate.state === 'open' &&
77 candidate.base.ref === 'main' &&
78 candidate.base.repo.full_name === input.repo &&
79 candidate.head.sha === run.head_sha &&
80 candidate.head.ref === run.head_branch &&
81 candidate.head.repo.full_name === run.head_repository.full_name
82 )
83 candidates.add(number)
84 }
85 if (candidates.size !== 1)
86 throw new Error('workflow_run has no unique current pull request')
87 const prNumber = [...candidates][0]
88 if (prNumber === undefined)
89 throw new Error('Missing workflow_run pull request')
90 const pr = await fetchPullRequest(input.client, input.repo, prNumber)
91 if (
92 pr.state !== 'open' ||
93 pr.baseRepo !== input.repo ||
94 pr.baseRef !== 'main' ||
95 pr.headSha !== run.head_sha ||
96 pr.headRef !== run.head_branch ||
97 pr.headRepo !== run.head_repository.full_name
98 )
99 throw new Error('workflow_run pull request changed')
100 return {
101 parsed: {
102 prNumber,
103 mode: 'auto',
104 commentAuthor: null,
105 eventName: 'workflow_run',
106 } satisfies ReviewEvent,
107 pr,
108 }
109}
110
111export type ReviewEvent = {
112 prNumber: number
113 mode: 'auto' | 'manual'
114 commentAuthor: string | null
115 eventName: 'workflow_run' | 'workflow_dispatch' | 'issue_comment'
116}
117
118function isRecord(value: unknown): value is Record<string, unknown> {
119 return typeof value === 'object' && value !== null && !Array.isArray(value)
120}
121
122function parsePrNumber(value: unknown) {
123 if (typeof value === 'number' && Number.isInteger(value) && value > 0) {
124 return value
125 }
126 if (typeof value !== 'string' || value.length === 0) {
127 return null
128 }
129 const parsed = Number(value)
130 if (!Number.isInteger(parsed) || parsed <= 0) {
131 return null
132 }
133 return parsed
134}
135
136function readCommentAuthor(event: unknown) {
137 const comment = isRecord(event) ? event.comment : undefined
138 const user = isRecord(comment) ? comment.user : undefined
139 if (!isRecord(user) || typeof user.login !== 'string') {
140 return null
141 }
142 return user.login
143}
144
145/**
146 * Parse a GitHub Actions event into the PR number and auto vs manual mode.
147 *
148 * Always throws for `workflow_run`. Use `resolveReviewEvent`.
149 * Also throws if `eventName` is unknown, `workflow_dispatch` has no valid
150 * `inputs.pr_number`, or `issue_comment` is not on a pull request.
151 */
152export function parseReviewEvent(input: { eventName: string; event: unknown }) {
153 switch (input.eventName) {
154 case 'workflow_run':
155 throw new Error('workflow_run requires authenticated resolution')
156 case 'workflow_dispatch': {
157 const inputs = isRecord(input.event) ? input.event.inputs : undefined
158 const prNumber = parsePrNumber(
159 isRecord(inputs) ? inputs.pr_number : undefined,
160 )
161 if (prNumber === null) {
162 throw new Error('workflow_dispatch is missing a valid inputs.pr_number')
163 }
164 return {
165 prNumber,
166 mode: 'manual',
167 commentAuthor: null,
168 eventName: 'workflow_dispatch',
169 } satisfies ReviewEvent
170 }
171 case 'issue_comment': {
172 const issue = isRecord(input.event) ? input.event.issue : undefined
173 const isPrComment =
174 isRecord(issue) &&
175 issue.pull_request !== undefined &&
176 issue.pull_request !== null
177 if (!isPrComment) {
178 throw new Error('issue_comment is not on a pull request')
179 }
180 const prNumber = parsePrNumber(issue.number)
181 if (prNumber === null) {
182 throw new Error('issue_comment is missing issue.number')
183 }
184 return {
185 prNumber,
186 mode: 'manual',
187 commentAuthor: readCommentAuthor(input.event),
188 eventName: 'issue_comment',
189 } satisfies ReviewEvent
190 }
191 default:
192 throw new Error(`Unknown GitHub event: ${input.eventName}`)
193 }
194}