Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

run.ts

506 lines14.7 KB

1/**
2 * Orchestrate one AI review job: skip, review, optional polish push, comment, label.
3 */
4​
5import { spawn } from 'node:child_process'
6import { homedir } from 'node:os'
7import { readFile } from 'node:fs/promises'
8import { join, resolve } from 'node:path'
9import process from 'node:process'
10import { fileURLToPath } from 'node:url'
11import { chat } from '@tanstack/ai'
12import {
13 GROK_CLI_INSTALL_COMMAND,
14 grokBuildText,
15} from '@tanstack/ai-grok-build'
16import {
17 createSecrets,
18 defineSandbox,
19 defineWorkspace,
20 localSource,
21 withSandbox,
22} from '@tanstack/ai-sandbox'
23import { localProcessSandbox } from '@tanstack/ai-sandbox-local-process'
24import {
25 loadConfig,
26 isRosterMaintainer,
27} from '../../scripts/maintainer/config.ts'
28import { resolveToken } from '../../scripts/maintainer/env.ts'
29import { createGitHubClient } from '../../scripts/maintainer/github.ts'
30import type { GitHubClient } from '../../scripts/maintainer/github.ts'
31import type { ToolsetConfig } from '../../scripts/maintainer/types.ts'
32import {
33 buildReviewComment,
34 isBotReviewComment,
35 upsertReviewComment,
36} from './comments.ts'
37import {
38 isAiReviewLabelEvent,
39 isPullRequestLabeledEvent,
40 parseReviewEvent,
41} from './event.ts'
42import { createReviewStreamLogger } from './log.ts'
43import { commitAll, headRemoteUrl, pushHead } from './git.ts'
44import type { GitRunner } from './git.ts'
45import { setReviewState } from './labels.ts'
46import { fetchPullRequest, fetchPullRequestDiff } from './pr.ts'
47import { approveWaitingWorkflows, setSecureLabel } from './secure.ts'
48import { scanPullSecurity } from './security.ts'
49import { shouldSkip } from './skip.ts'
50import { createReviewTools } from './tools.ts'
51import { parseVerdict, reviewLabelFor, reviewVerdictSchema } from './verdict.ts'
52​
53function isRecord(value: unknown): value is Record<string, unknown> {
54 return typeof value === 'object' && value !== null && !Array.isArray(value)
56​
57function readIssueCommentBody(event: unknown) {
58 if (!isRecord(event) || !isRecord(event.comment)) return ''
59 return typeof event.comment.body === 'string' ? event.comment.body : ''
61​
62function firstToken(body: string) {
63 const trimmed = body.trim()
64 if (trimmed.length === 0) return ''
65 const [token] = trimmed.split(/\s+/)
66 return token ?? ''
68​
69function formatFinding(
70 issue: ReturnType<typeof parseVerdict>['issues'][number],
71) {
72 return `[${issue.severity}] ${issue.file}:${issue.line} ${issue.description}`
74​
75function pushNoteFor(input: {
76 pushLanded: boolean
77 verdict: ReturnType<typeof parseVerdict>['verdict']
78 maintainerCanModify: boolean
79}) {
80 if (input.pushLanded) {
81 return 'Pushed polish commit to the PR branch.'
82 }
83 if (input.verdict === 'polish' && !input.maintainerCanModify) {
84 return 'Did not push: fork has maintainer edits off.'
85 }
86 return 'Did not push.'
88​
89/**
90 * Read `**Head SHA:** <sha>` from a bot review comment body.
91 *
92 * @param body comment markdown
93 */
94export function parseHeadShaFromComment(body: string) {
95 const match = /\*\*Head SHA:\*\*\s+(\S+)/.exec(body)
96 return match?.[1] ?? null
98​
99function parseListedComment(value: unknown) {
100 if (!isRecord(value) || typeof value.body !== 'string') return null
101 const user = isRecord(value.user) ? value.user : null
102 const userLogin =
103 user !== null && typeof user.login === 'string' ? user.login : null
104 return { body: value.body, userLogin }
106​
107async function fetchAlreadyReviewedSha(
108 client: GitHubClient,
109 repo: string,
110 issueNumber: number,
111 machineUserLogin: string,
112) {
113 const list = await client.rest(
114 'GET',
115 `/repos/${repo}/issues/${issueNumber}/comments`,
116 )
117 if (!Array.isArray(list)) return null
118 const comments = []
119 for (const item of list) {
120 const comment = parseListedComment(item)
121 if (comment !== null) comments.push(comment)
122 }
123 const existing = comments.find((comment) =>
124 isBotReviewComment(comment, machineUserLogin),
125 )
126 if (existing === undefined) return null
127 return parseHeadShaFromComment(existing.body)
129​
130type ReviewInput = {
131 pr: Awaited<ReturnType<typeof fetchPullRequest>>
132 diff: string
133 worktreeRoot: string
134 client: GitHubClient
135 repo: string
137​
138/**
139 * Production Grok review step for `runReviewJob`.
140 *
141 * `grokBuildText` streams tools first, then a `structured-output.complete`
142 * event. Do not call this from unit tests.
143 */
144export function createGrokReview() {
145 return async (input: ReviewInput) => {
146 const xaiKey = process.env.XAI_API_KEY
147 const sandbox = defineSandbox({
148 id: 'ai-review',
149 provider: localProcessSandbox({
150 dir: input.worktreeRoot,
151 removeOnDestroy: false,
152 }),
153 workspace: defineWorkspace({
154 source: localSource(input.worktreeRoot),
155 setup: ({ serial }) => serial(GROK_CLI_INSTALL_COMMAND),
156 ...(xaiKey !== undefined && xaiKey.length > 0
157 ? { secrets: createSecrets({ XAI_API_KEY: xaiKey }) }
158 : {}),
159 }),
160 lifecycle: { reuse: 'none', destroyOnComplete: false },
161 })
162 const stream = chat({
163 adapter: grokBuildText('grok-4.6', {
164 authMode: 'api-key',
165 protocol: 'streaming-json',
166 cwd: input.worktreeRoot,
167 grokExecutable: join(homedir(), '.grok', 'bin', 'grok'),
168 }),
169 stream: true,
170 tools: createReviewTools({ worktreeRoot: input.worktreeRoot }),
171 outputSchema: reviewVerdictSchema,
172 middleware: [withSandbox(sandbox)],
173 threadId: `ai-review-${input.pr.number}`,
174 messages: [
175 {
176 role: 'user',
177 content: [
178 'Review this pull request.',
179 'Read the changed source files before you choose a verdict.',
180 'If it is a bug fix and does not fix the claimed root cause, verdict is reject.',
181 'If it is useful and needs listed bug or suggestion edits, apply those with edit_file, then verdict polish.',
182 'If it is useful and clean, verdict is ready.',
183 'Nits stay in issues. Do not edit files for nits.',
184 'Never edit .github/workflows.',
185 '',
186 `Pull request #${input.pr.number}: ${input.pr.title}`,
187 input.pr.htmlUrl,
188 input.pr.body ?? '',
189 '',
190 'Diff:',
191 input.diff,
192 ].join('\n'),
193 },
194 ],
195 })
196 let object: unknown
197 const log = createReviewStreamLogger()
198 for await (const chunk of stream) {
199 log.chunk(chunk)
200 if (
201 chunk.type === 'CUSTOM' &&
202 chunk.name === 'structured-output.complete' &&
203 isRecord(chunk.value) &&
204 'object' in chunk.value
205 ) {
206 object = chunk.value.object
207 }
208 }
209 log.flush()
210 if (object === undefined) {
211 throw new Error('chat() did not emit structured-output.complete')
212 }
213 const verdict = parseVerdict(object)
214 console.log('ai-review verdict', JSON.stringify(verdict, null, 2))
215 return verdict
216 }
218​
219/**
220 * Run one PR review: skip, review, optional polish push, comment, label.
221 *
222 * @param opts GitHub client, event, worktree, injected review step, and git runner
223 */
224export async function runReviewJob(opts: {
225 client: GitHubClient
226 repo: string
227 token: string
228 config: ToolsetConfig
229 eventName: string
230 event: unknown
231 worktreeRoot: string
232 machineUserLogin: string
233 gitRunner: GitRunner
234 review: (input: ReviewInput) => Promise<ReturnType<typeof parseVerdict>>
235 alreadyReviewedSha: string | null
236 headCommitAuthorLogin: string | null
237}) {
238 const parsed = parseReviewEvent({
239 eventName: opts.eventName,
240 event: opts.event,
241 })
242​
243 if (opts.eventName === 'issue_comment') {
244 if (firstToken(readIssueCommentBody(opts.event)) !== '/ai-review') {
245 return { skipped: true as const, reason: 'not-command' }
246 }
247 if (!isRosterMaintainer(parsed.commentAuthor, opts.config)) {
248 return { skipped: true as const, reason: 'not-maintainer' }
249 }
250 }
251​
252 if (
253 opts.eventName === 'pull_request' &&
254 isPullRequestLabeledEvent(opts.event) &&
255 !isAiReviewLabelEvent(opts.event)
256 ) {
257 return { skipped: true as const, reason: 'not-label' }
258 }
259​
260 if (isAiReviewLabelEvent(opts.event)) {
261 if (!isRosterMaintainer(parsed.commentAuthor, opts.config)) {
262 return { skipped: true as const, reason: 'not-maintainer' }
263 }
264 }
265​
266 const pr = await fetchPullRequest(opts.client, opts.repo, parsed.prNumber)
267 const skip = shouldSkip({
268 mode: parsed.mode,
269 isDraft: pr.isDraft,
270 authorLogin: pr.authorLogin,
271 headCommitAuthorLogin: opts.headCommitAuthorLogin,
272 headSha: pr.headSha,
273 alreadyReviewedSha: opts.alreadyReviewedSha,
274 machineUserLogin: opts.machineUserLogin,
275 config: opts.config,
276 })
277 if (skip.skip) {
278 return { skipped: true as const, reason: skip.reason }
279 }
280​
281 const diff = await fetchPullRequestDiff(
282 opts.client,
283 opts.repo,
284 parsed.prNumber,
285 )
286 const verdict = await opts.review({
287 pr,
288 diff,
289 worktreeRoot: opts.worktreeRoot,
290 client: opts.client,
291 repo: opts.repo,
292 })
293​
294 let pushLanded = false
295 const canPushPolish = verdict.verdict === 'polish' && pr.maintainerCanModify
296 if (canPushPolish) {
297 const commit = await commitAll(
298 opts.worktreeRoot,
299 `ai-review: apply review polish for #${pr.number}`,
300 opts.gitRunner,
301 {
302 name: opts.machineUserLogin,
303 email: `${opts.machineUserLogin}@users.noreply.github.com`,
304 },
305 )
306 if (commit.committed) {
307 await pushHead(opts.worktreeRoot, opts.gitRunner, {
308 remoteUrl: headRemoteUrl({
309 isFork: pr.headRepo !== opts.repo,
310 originRepo: opts.repo,
311 headRepo: pr.headRepo,
312 token: opts.token,
313 }),
314 ref: pr.headRef,
315 })
316 }
317 pushLanded = commit.committed
318 }
319​
320 const label = reviewLabelFor(verdict.verdict, pushLanded)
321 const security = scanPullSecurity(pr.files)
322 let approvedRuns = 0
323 let approveError: string | null = null
324 if (label === 'ai-ready' && security.ok) {
325 try {
326 approvedRuns = await approveWaitingWorkflows(
327 opts.client,
328 opts.repo,
329 pr.headSha,
330 )
331 } catch (error) {
332 approveError = error instanceof Error ? error.message : String(error)
333 }
334 }
335 const markSecure =
336 label === 'ai-ready' && security.ok && approveError === null
337 await setReviewState(opts.client, opts.repo, pr.number, label)
338 await setSecureLabel(opts.client, opts.repo, pr.number, markSecure)
339 const findings = []
340 for (const issue of verdict.issues) {
341 findings.push(formatFinding(issue))
342 }
343 const body = buildReviewComment({
344 verdict: verdict.verdict,
345 headSha: pr.headSha,
346 findings,
347 pushNote: pushNoteFor({
348 pushLanded,
349 verdict: verdict.verdict,
350 maintainerCanModify: pr.maintainerCanModify,
351 }),
352 label,
353 securityNote: securityNoteFor({
354 markSecure,
355 reasons: security.reasons,
356 approvedRuns,
357 approveError,
358 }),
359 })
360 await upsertReviewComment(
361 opts.client,
362 opts.repo,
363 pr.number,
364 body,
365 opts.machineUserLogin,
366 )
367 return { skipped: false as const, verdict, label, pushLanded }
369​
370function securityNoteFor(input: {
371 markSecure: boolean
372 reasons: Array<string>
373 approvedRuns: number
374 approveError: string | null
375}) {
376 if (input.reasons.length > 0) {
377 return `blocked. Did not approve workflows.\n${input.reasons.map((reason) => `- ${reason}`).join('\n')}`
378 }
379 if (input.approveError !== null) {
380 return `clean. Did not add label \`secure\`. Could not approve workflows: ${input.approveError}`
381 }
382 if (!input.markSecure) {
383 return 'Did not mark secure. Verdict is not ai-ready.'
384 }
385 if (input.approvedRuns === 0) {
386 return 'clean. Added label `secure`. No waiting workflow runs.'
387 }
388 return `clean. Added label \`secure\`. Approved ${String(input.approvedRuns)} waiting workflow runs.`
390​
391function createProcessGitRunner(): GitRunner {
392 return (args, cwd) =>
393 new Promise((resolveResult, reject) => {
394 const child = spawn('git', args, { cwd })
395 let stdout = ''
396 let stderr = ''
397 child.stdout.on('data', (chunk: Buffer | string) => {
398 stdout += String(chunk)
399 })
400 child.stderr.on('data', (chunk: Buffer | string) => {
401 stderr += String(chunk)
402 })
403 child.on('error', reject)
404 child.on('close', (code) => {
405 resolveResult({ stdout, stderr, code: code ?? 1 })
406 })
407 })
409​
410async function resolveReviewToken() {
411 const fromEnv = process.env.AI_REVIEW_TOKEN
412 if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv
413 try {
414 return await resolveToken()
415 } catch {
416 throw new Error('missing AI_REVIEW_TOKEN or XAI_API_KEY')
417 }
419​
420function requireEnv(name: string) {
421 const value = process.env[name]
422 if (value === undefined || value.length === 0) {
423 throw new Error(`missing ${name}`)
424 }
425 return value
427​
428function isExecutedDirectly() {
429 const entry = process.argv[1]
430 if (entry === undefined) return false
431 return fileURLToPath(import.meta.url) === resolve(entry)
433​
434/**
435 * Production entry. Fills `runReviewJob` opts from env.
436 *
437 * Needs `AI_REVIEW_TOKEN` (or a resolvable GitHub token) and `XAI_API_KEY`.
438 */
439export async function main() {
440 const token = await resolveReviewToken()
441 requireEnv('XAI_API_KEY')
442 const eventName = process.env.GITHUB_EVENT_NAME
443 const eventPath = process.env.GITHUB_EVENT_PATH
444 const repo = process.env.GITHUB_REPOSITORY
445 if (
446 eventName === undefined ||
447 eventName.length === 0 ||
448 eventPath === undefined ||
449 eventPath.length === 0 ||
450 repo === undefined ||
451 repo.length === 0
452 ) {
453 throw new Error(
454 'missing GITHUB_EVENT_NAME, GITHUB_EVENT_PATH, or GITHUB_REPOSITORY',
455 )
456 }
457 const eventText = await readFile(eventPath, 'utf8')
458 const event: unknown = JSON.parse(eventText)
459 const config = await loadConfig()
460 const worktreeRoot =
461 process.env.AI_REVIEW_WORKTREE ??
462 process.env.GITHUB_WORKSPACE ??
463 process.cwd()
464 const machineUserLogin =
465 process.env.AI_REVIEW_MACHINE_USER ?? 'tanstack-ai-bot'
466 const headCommitAuthor = process.env.AI_REVIEW_HEAD_COMMIT_AUTHOR
467 const client = createGitHubClient({ token })
468 const parsed = parseReviewEvent({ eventName, event })
469 const alreadyReviewedSha = await fetchAlreadyReviewedSha(
470 client,
471 repo,
472 parsed.prNumber,
473 machineUserLogin,
474 )
475 const result = await runReviewJob({
476 client,
477 repo,
478 token,
479 config,
480 eventName,
481 event,
482 worktreeRoot,
483 machineUserLogin,
484 gitRunner: createProcessGitRunner(),
485 review: createGrokReview(),
486 alreadyReviewedSha,
487 headCommitAuthorLogin:
488 headCommitAuthor === undefined || headCommitAuthor.length === 0
489 ? null
490 : headCommitAuthor,
491 })
492 if (result.skipped) {
493 console.log(`ai-review skipped: ${result.reason}`)
494 return
495 }
496 console.log(
497 `ai-review done label=${result.label} push=${String(result.pushLanded)}`,
498 )
500​
501if (isExecutedDirectly()) {
502 main().catch((error) => {
503 console.error(error)
504 process.exitCode = 1
505 })