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

run.ts

710 lines20.9 KB

1/**
2 * Orchestrate one AI review job: authorize the trigger, resolve the PR, clear
3 * stale labels, audit the snapshot, skip check, review, validate the generated
4 * diff, optional polish push, recheck identity, approve workflows, label, comment.
5 */
6​
7import { spawn } from 'node:child_process'
8import { readFile } from 'node:fs/promises'
9import { resolve } from 'node:path'
10import process from 'node:process'
11import { fileURLToPath } from 'node:url'
12import { chat } from '@tanstack/ai'
13import {
14 GROK_CLI_INSTALL_COMMAND,
15 grokBuildText,
16} from '@tanstack/ai-grok-build'
17import {
18 createSecrets,
19 defineSandbox,
20 defineWorkspace,
21 githubRepo,
22 withSandbox,
23} from '@tanstack/ai-sandbox'
24import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
25import {
26 loadConfig,
27 isRosterMaintainer,
28} from '../../scripts/maintainer/config.ts'
29import { resolveToken } from '../../scripts/maintainer/env.ts'
30import { createGitHubClient } from '../../scripts/maintainer/github.ts'
31import type { GitHubClient } from '../../scripts/maintainer/github.ts'
32import type { ToolsetConfig } from '../../scripts/maintainer/types.ts'
33import {
34 buildBlockedComment,
35 buildReviewComment,
36 isBotReviewComment,
37 upsertReviewComment,
38} from './comments.ts'
39import { parseReviewEvent, resolveReviewEvent } from './event.ts'
40import { createReviewStreamLogger } from './log.ts'
41import {
42 GitCommandError,
43 applyPatch,
44 commitAll,
45 headRemoteUrl,
46 preparePullWorktree,
47 pushHead,
48 readPullSnapshot,
49} from './git.ts'
50import type { GitRunner } from './git.ts'
51import { setReviewState } from './labels.ts'
52import { fetchPullRequest } from './pr.ts'
53import { approveWaitingWorkflows, setSecureLabel } from './secure.ts'
54import { auditPullSecurity, scanGeneratedDiff } from './security.ts'
55import { shouldSkip } from './skip.ts'
56import { parseVerdict, reviewLabelFor, reviewVerdictSchema } from './verdict.ts'
57​
58function isRecord(value: unknown): value is Record<string, unknown> {
59 return typeof value === 'object' && value !== null && !Array.isArray(value)
61​
62function readIssueCommentBody(event: unknown) {
63 if (!isRecord(event) || !isRecord(event.comment)) return ''
64 return typeof event.comment.body === 'string' ? event.comment.body : ''
66​
67function readGeneratedDiff(chunk: unknown) {
68 if (
69 !isRecord(chunk) ||
70 chunk.type !== 'CUSTOM' ||
71 chunk.name !== 'file.changed' ||
72 !isRecord(chunk.value) ||
73 typeof chunk.value.diff !== 'string'
74 ) {
75 return null
76 }
77 return chunk.value.diff
79​
80function firstToken(body: string) {
81 const trimmed = body.trim()
82 if (trimmed.length === 0) return ''
83 const [token] = trimmed.split(/\s+/)
84 return token ?? ''
86​
87function formatFinding(
88 issue: ReturnType<typeof parseVerdict>['issues'][number],
89) {
90 return `[${issue.severity}] ${issue.file}:${issue.line} ${issue.description}`
92​
93function pushNoteFor(input: {
94 pushLanded: boolean
95 verdict: ReturnType<typeof parseVerdict>['verdict']
96 maintainerCanModify: boolean
97}) {
98 if (input.pushLanded) {
99 return 'Pushed polish commit to the PR branch.'
100 }
101 if (input.verdict === 'polish' && !input.maintainerCanModify) {
102 return 'Did not push: fork has maintainer edits off.'
103 }
104 return 'Did not push.'
106​
107/**
108 * Read `**Head SHA:** <sha>` from a bot review comment body.
109 *
110 * @param body comment markdown
111 */
112export function parseHeadShaFromComment(body: string) {
113 const match = /\*\*Head SHA:\*\*\s+(\S+)/.exec(body)
114 return match?.[1] ?? null
116​
117function parseListedComment(value: unknown) {
118 if (!isRecord(value) || typeof value.body !== 'string') return null
119 const user = isRecord(value.user) ? value.user : null
120 const userLogin =
121 user !== null && typeof user.login === 'string' ? user.login : null
122 return { body: value.body, userLogin }
124​
125async function fetchAlreadyReviewedSha(
126 client: GitHubClient,
127 repo: string,
128 issueNumber: number,
129 machineUserLogin: string,
130) {
131 const list = await client.rest(
132 'GET',
133 `/repos/${repo}/issues/${issueNumber}/comments?per_page=100`,
134 )
135 if (!Array.isArray(list)) return null
136 const comments = []
137 for (const item of list) {
138 const comment = parseListedComment(item)
139 if (comment !== null) comments.push(comment)
140 }
141 const existing = comments.find((comment) =>
142 isBotReviewComment(comment, machineUserLogin),
143 )
144 if (existing === undefined) return null
145 return parseHeadShaFromComment(existing.body)
147​
148type ReviewInput = {
149 pr: Awaited<ReturnType<typeof fetchPullRequest>>
150 diff: string
152​
153type ReviewOutput = ReturnType<typeof parseVerdict> & {
154 generatedDiff?: string
156​
157function matchesPullIdentity(
158 pr: ReviewInput['pr'],
159 current: ReviewInput['pr'],
160 expectedSha: string,
161) {
162 return (
163 current.number === pr.number &&
164 current.state === 'open' &&
165 current.baseRepo === pr.baseRepo &&
166 current.baseSha === pr.baseSha &&
167 current.baseRef === pr.baseRef &&
168 current.headRepo === pr.headRepo &&
169 current.headRef === pr.headRef &&
170 current.headSha === expectedSha
171 )
173​
174/**
175 * Production Grok review step for `runReviewJob`.
176 *
177 * `grokBuildText` streams tools first, then a `structured-output.complete`
178 * event. Do not call this from unit tests.
179 */
180export function createGrokReview() {
181 return async (input: ReviewInput) => {
182 const xaiKey = process.env.XAI_API_KEY
183 const sandbox = defineSandbox({
184 id: 'ai-review',
185 provider: dockerSandbox({
186 image:
187 'node:24-bookworm@sha256:be23f54a88d34e8824c741b19b91064094f92c1c97b194144bfc8b50d67258e2',
188 hostGateway: false,
189 }),
190 workspace: defineWorkspace({
191 source: githubRepo({
192 repo: input.pr.headRepo,
193 ref: input.pr.headRef,
194 depth: 1,
195 }),
196 setup: ({ serial }) => {
197 serial(`test "$(git rev-parse HEAD)" = '${input.pr.headSha}'`)
198 serial(GROK_CLI_INSTALL_COMMAND)
199 },
200 // Grok CLI child commands can read this key. Network access can expose it.
201 ...(xaiKey !== undefined && xaiKey.length > 0
202 ? { secrets: createSecrets({ XAI_API_KEY: xaiKey }) }
203 : {}),
204 }),
205 lifecycle: {
206 reuse: 'none',
207 snapshot: 'none',
208 destroyOnComplete: true,
209 },
210 })
211 const stream = chat({
212 adapter: grokBuildText('grok-4.6', {
213 authMode: 'api-key',
214 protocol: 'streaming-json',
215 cwd: '/workspace',
216 }),
217 stream: true,
218 outputSchema: reviewVerdictSchema,
219 middleware: [withSandbox(sandbox)],
220 threadId: `ai-review-${input.pr.number}`,
221 messages: [
222 {
223 role: 'user',
224 content: [
225 'Review this pull request.',
226 'Read the changed source files before you choose a verdict.',
227 'If it is a bug fix and does not fix the claimed root cause, verdict is reject.',
228 'If it is useful and needs listed bug or suggestion edits, edit the source files, then verdict polish.',
229 'If it is useful and clean, verdict is ready.',
230 'Nits stay in issues. Do not edit files for nits.',
231 'Never edit .github/workflows.',
232 '',
233 `Pull request #${input.pr.number}: ${input.pr.title}`,
234 input.pr.htmlUrl,
235 input.pr.body ?? '',
236 '',
237 'Diff:',
238 input.diff,
239 ].join('\n'),
240 },
241 ],
242 })
243 let object: unknown
244 let generatedDiff = ''
245 const log = createReviewStreamLogger()
246 for await (const chunk of stream) {
247 log.chunk(chunk)
248 if (
249 chunk.type === 'CUSTOM' &&
250 chunk.name === 'structured-output.complete' &&
251 isRecord(chunk.value) &&
252 'object' in chunk.value
253 ) {
254 object = chunk.value.object
255 }
256 const changed = readGeneratedDiff(chunk)
257 if (changed !== null) generatedDiff = changed
258 }
259 log.flush()
260 if (object === undefined) {
261 throw new Error('chat() did not emit structured-output.complete')
262 }
263 const verdict = parseVerdict(object)
264 console.log('ai-review verdict', JSON.stringify(verdict, null, 2))
265 return { ...verdict, generatedDiff }
266 }
268​
269/**
270 * Run one PR review: skip, review, optional polish push, comment, label.
271 *
272 * @param opts GitHub client, event, worktree, injected review step, and git runner
273 */
274export async function runReviewJob(opts: {
275 client: GitHubClient
276 repo: string
277 token: string
278 config: ToolsetConfig
279 eventName: string
280 event: unknown
281 worktreeRoot: string
282 repoRoot: string
283 machineUserLogin: string
284 gitRunner: GitRunner
285 review: (input: ReviewInput) => Promise<ReviewOutput>
286 prepareWorktree: (input: {
287 number: number
288 headSha: string
289 worktreeRoot: string
290 }) => Promise<void>
291 alreadyReviewedSha?: string | null
292 headCommitAuthorLogin?: string | null
293 /** Values the sandbox could read. Defaults to `XAI_API_KEY`. */
294 sandboxSecrets?: Array<string>
295}) {
296 const intent =
297 opts.eventName === 'workflow_run'
298 ? null
299 : parseReviewEvent({ eventName: opts.eventName, event: opts.event })
300​
301 if (opts.eventName === 'issue_comment') {
302 if (firstToken(readIssueCommentBody(opts.event)) !== '/ai-review') {
303 return { skipped: true as const, reason: 'not-command' }
304 }
305 if (!isRosterMaintainer(intent?.commentAuthor ?? null, opts.config)) {
306 return { skipped: true as const, reason: 'not-maintainer' }
307 }
308 }
309​
310 const { parsed, pr } = await resolveReviewEvent({
311 eventName: opts.eventName,
312 event: opts.event,
313 client: opts.client,
314 repo: opts.repo,
315 })
316 const alreadyReviewedSha =
317 opts.alreadyReviewedSha === undefined
318 ? await fetchAlreadyReviewedSha(
319 opts.client,
320 opts.repo,
321 pr.number,
322 opts.machineUserLogin,
323 )
324 : opts.alreadyReviewedSha
325 let headCommitAuthorLogin = opts.headCommitAuthorLogin
326 if (headCommitAuthorLogin === undefined) {
327 const commit = await opts.client.rest(
328 'GET',
329 `/repos/${opts.repo}/commits/${pr.headSha}`,
330 )
331 const author = isRecord(commit) ? commit.author : undefined
332 headCommitAuthorLogin =
333 isRecord(author) && typeof author.login === 'string' ? author.login : null
334 }
335 const skip = shouldSkip({
336 mode: parsed.mode,
337 isDraft: pr.isDraft,
338 authorLogin: pr.authorLogin,
339 headCommitAuthorLogin,
340 headSha: pr.headSha,
341 alreadyReviewedSha,
342 machineUserLogin: opts.machineUserLogin,
343 config: opts.config,
344 })
345 const alreadyReviewed =
346 skip.skip &&
347 !pr.isDraft &&
348 pr.headSha === alreadyReviewedSha &&
349 pr.baseRef === 'main'
350 if (alreadyReviewed) {
351 return { skipped: true as const, reason: skip.reason }
352 }
353 const staleLabels = ['secure', 'ai-ready']
354 for (const label of staleLabels) {
355 try {
356 await opts.client.rest(
357 'DELETE',
358 `/repos/${opts.repo}/issues/${pr.number}/labels/${label}`,
359 )
360 } catch (error) {
361 const missingLabel =
362 error instanceof Error && error.message.includes('HTTP 404:')
363 if (!missingLabel) throw error
364 }
365 }
366 if (
367 pr.baseRef !== 'main' ||
368 pr.baseRepo !== opts.repo ||
369 pr.state !== 'open'
370 ) {
371 return { skipped: true as const, reason: 'not-main' }
372 }
373 // A block must show on the PR. workflow_run jobs are not PR checks, so a
374 // silent skip looks the same as a review that never ran. The head SHA in the
375 // comment also stops a paid repeat of the same blocked commit.
376 async function blocked(reasons: Array<string>) {
377 if (!skip.skip) {
378 await upsertReviewComment(
379 opts.client,
380 opts.repo,
381 pr.number,
382 buildBlockedComment({ headSha: pr.headSha, reasons }),
383 opts.machineUserLogin,
384 )
385 }
386 return {
387 skipped: true as const,
388 reason: 'security-blocked',
389 security: { ok: false as const, reasons },
390 }
391 }
392 let snapshot
393 try {
394 snapshot = await readPullSnapshot(opts.repoRoot, pr, opts.gitRunner)
395 } catch (error) {
396 // A failed fetch is a broken runner or token, not a verdict on the PR.
397 if (error instanceof GitCommandError && error.args[0] === 'fetch')
398 throw error
399 return await blocked([
400 error instanceof Error ? error.message : String(error),
401 ])
402 }
403 const security = auditPullSecurity(snapshot)
404 if (!security.ok) return await blocked(security.reasons)
405 if (skip.skip) {
406 return { skipped: true as const, reason: skip.reason }
407 }
408​
409 const diff = snapshot.diff
410 const review = await opts.review({
411 pr,
412 diff,
413 })
414 const verdict = parseVerdict(review)
415 const generatedDiff = review.generatedDiff ?? ''
416 const sandboxSecrets = opts.sandboxSecrets ?? [process.env.XAI_API_KEY ?? '']
417 const generatedSecurity = scanGeneratedDiff(generatedDiff, sandboxSecrets)
418 if (!generatedSecurity.ok) return await blocked(generatedSecurity.reasons)
419 if (generatedDiff.length > 0 && verdict.verdict !== 'polish') {
420 return await blocked(['generated diff requires a polish verdict'])
421 }
422 // The verdict text goes into a public comment. The sandbox can read the key.
423 const verdictText = JSON.stringify(verdict)
424 if (
425 sandboxSecrets.some(
426 (secret) => secret.length > 0 && verdictText.includes(secret),
427 )
428 ) {
429 return await blocked(['review text contains a sandbox secret'])
430 }
431​
432 let pushLanded = false
433 let reviewedSha = pr.headSha
434 const canPushPolish =
435 verdict.verdict === 'polish' &&
436 pr.maintainerCanModify &&
437 generatedDiff.length > 0
438 if (canPushPolish) {
439 const beforePolish = await fetchPullRequest(
440 opts.client,
441 opts.repo,
442 pr.number,
443 )
444 if (
445 !matchesPullIdentity(pr, beforePolish, pr.headSha) ||
446 !beforePolish.maintainerCanModify
447 ) {
448 return { skipped: true as const, reason: 'head-changed' }
449 }
450 await opts.prepareWorktree({
451 number: pr.number,
452 headSha: pr.headSha,
453 worktreeRoot: opts.worktreeRoot,
454 })
455 await applyPatch(opts.worktreeRoot, generatedDiff, opts.gitRunner)
456 const commit = await commitAll(
457 opts.worktreeRoot,
458 `ai-review: apply review polish for #${pr.number}`,
459 opts.gitRunner,
460 {
461 name: opts.machineUserLogin,
462 email: `${opts.machineUserLogin}@users.noreply.github.com`,
463 },
464 )
465 if (commit.committed) {
466 const head = await opts.gitRunner(
467 ['rev-parse', 'HEAD'],
468 opts.worktreeRoot,
469 )
470 reviewedSha = head.stdout.trim()
471 if (head.code !== 0 || !/^[0-9a-f]{40}$/i.test(reviewedSha)) {
472 throw new Error('could not read the polish commit SHA')
473 }
474 const beforePush = await fetchPullRequest(
475 opts.client,
476 opts.repo,
477 pr.number,
478 )
479 if (
480 !matchesPullIdentity(pr, beforePush, pr.headSha) ||
481 !beforePush.maintainerCanModify
482 ) {
483 return { skipped: true as const, reason: 'head-changed' }
484 }
485 await pushHead(opts.worktreeRoot, opts.gitRunner, {
486 remoteUrl: headRemoteUrl({
487 isFork: pr.headRepo !== opts.repo,
488 originRepo: opts.repo,
489 headRepo: pr.headRepo,
490 token: opts.token,
491 }),
492 ref: pr.headRef,
493 expectedSha: pr.headSha,
494 })
495 }
496 pushLanded = commit.committed
497 }
498​
499 const currentPr = await fetchPullRequest(opts.client, opts.repo, pr.number)
500 // GitHub can still report the old head just after our push. Accept that
501 // read, or the polish commit lands with no comment and no label.
502 const staleReadAfterPush =
503 pushLanded && matchesPullIdentity(pr, currentPr, pr.headSha)
504 if (!matchesPullIdentity(pr, currentPr, reviewedSha) && !staleReadAfterPush) {
505 return { skipped: true as const, reason: 'head-changed' }
506 }
507 const label = reviewLabelFor(verdict.verdict, pushLanded)
508 let approvedRuns = 0
509 let approveError: string | null = null
510 if (label === 'ai-ready' && security.ok) {
511 try {
512 approvedRuns = await approveWaitingWorkflows(
513 opts.client,
514 opts.repo,
515 reviewedSha,
516 )
517 } catch (error) {
518 approveError = error instanceof Error ? error.message : String(error)
519 }
520 }
521 const markSecure =
522 label === 'ai-ready' && security.ok && approveError === null
523 await setReviewState(opts.client, opts.repo, pr.number, label)
524 await setSecureLabel(opts.client, opts.repo, pr.number, markSecure)
525 const findings = []
526 for (const issue of verdict.issues) {
527 findings.push(formatFinding(issue))
528 }
529 const body = buildReviewComment({
530 verdict: verdict.verdict,
531 headSha: reviewedSha,
532 findings,
533 pushNote: pushNoteFor({
534 pushLanded,
535 verdict: verdict.verdict,
536 maintainerCanModify: pr.maintainerCanModify,
537 }),
538 label,
539 securityNote: securityNoteFor({
540 markSecure,
541 approvedRuns,
542 approveError,
543 }),
544 })
545 await upsertReviewComment(
546 opts.client,
547 opts.repo,
548 pr.number,
549 body,
550 opts.machineUserLogin,
551 )
552 return { skipped: false as const, verdict, label, pushLanded }
554​
555function securityNoteFor(input: {
556 markSecure: boolean
557 approvedRuns: number
558 approveError: string | null
559}) {
560 if (input.approveError !== null) {
561 return `clean. Did not add label \`secure\`. Could not approve workflows: ${input.approveError}`
562 }
563 if (!input.markSecure) {
564 return 'Did not mark secure. Verdict is not ai-ready.'
565 }
566 if (input.approvedRuns === 0) {
567 return 'clean. Added label `secure`. No waiting workflow runs.'
568 }
569 return `clean. Added label \`secure\`. Approved ${String(input.approvedRuns)} waiting workflow runs.`
571​
572function createProcessGitRunner(): GitRunner {
573 return (args, cwd, input) =>
574 new Promise((resolveResult, reject) => {
575 const env = { ...process.env }
576 delete env.AI_REVIEW_TOKEN
577 delete env.XAI_API_KEY
578 const child = spawn('git', args, { cwd, env })
579 let stdout = ''
580 let stderr = ''
581 let bytes = 0
582 let overflow = false
583 child.stdout.setEncoding('utf8')
584 child.stderr.setEncoding('utf8')
585 function withinLimit(chunk: string) {
586 bytes += Buffer.byteLength(chunk, 'utf8')
587 if (bytes > 10_000_000) {
588 overflow = true
589 child.kill()
590 return false
591 }
592 return true
593 }
594 child.stdout.on('data', (chunk: string) => {
595 if (withinLimit(chunk)) stdout += chunk
596 })
597 child.stderr.on('data', (chunk: string) => {
598 if (withinLimit(chunk)) stderr += chunk
599 })
600 child.on('error', reject)
601 child.stdin.end(input)
602 child.on('close', (code) => {
603 resolveResult({
604 stdout,
605 stderr: overflow ? 'Git output exceeds 10 MB' : stderr,
606 code: overflow ? 1 : (code ?? 1),
607 })
608 })
609 })
611​
612async function resolveReviewToken() {
613 const fromEnv = process.env.AI_REVIEW_TOKEN
614 if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv
615 try {
616 return await resolveToken()
617 } catch (error) {
618 throw new Error('missing AI_REVIEW_TOKEN', { cause: error })
619 }
621​
622function requireEnv(name: string) {
623 const value = process.env[name]
624 if (value === undefined || value.length === 0) {
625 throw new Error(`missing ${name}`)
626 }
627 return value
629​
630function isExecutedDirectly() {
631 const entry = process.argv[1]
632 if (entry === undefined) return false
633 return fileURLToPath(import.meta.url) === resolve(entry)
635​
636/**
637 * Production entry. Fills `runReviewJob` opts from env.
638 *
639 * Needs `AI_REVIEW_TOKEN` (or a resolvable GitHub token) and `XAI_API_KEY`.
640 */
641export async function main() {
642 const token = await resolveReviewToken()
643 requireEnv('XAI_API_KEY')
644 const eventName = process.env.GITHUB_EVENT_NAME
645 const eventPath = process.env.GITHUB_EVENT_PATH
646 const repo = process.env.GITHUB_REPOSITORY
647 if (
648 eventName === undefined ||
649 eventName.length === 0 ||
650 eventPath === undefined ||
651 eventPath.length === 0 ||
652 repo === undefined ||
653 repo.length === 0
654 ) {
655 throw new Error(
656 'missing GITHUB_EVENT_NAME, GITHUB_EVENT_PATH, or GITHUB_REPOSITORY',
657 )
658 }
659 const eventText = await readFile(eventPath, 'utf8')
660 const event: unknown = JSON.parse(eventText)
661 const config = await loadConfig()
662 const worktreeRoot =
663 process.env.AI_REVIEW_WORKTREE ??
664 process.env.GITHUB_WORKSPACE ??
665 process.cwd()
666 const repoRoot = process.env.GITHUB_WORKSPACE ?? process.cwd()
667 const machineUserLogin =
668 process.env.AI_REVIEW_MACHINE_USER ?? 'tanstack-ai-bot'
669 const client = createGitHubClient({ token })
670 const result = await runReviewJob({
671 client,
672 repo,
673 token,
674 config,
675 eventName,
676 event,
677 worktreeRoot,
678 repoRoot,
679 machineUserLogin,
680 gitRunner: createProcessGitRunner(),
681 review: createGrokReview(),
682 prepareWorktree: ({ number, headSha, worktreeRoot: pullWorktree }) =>
683 preparePullWorktree(
684 repoRoot,
685 pullWorktree,
686 number,
687 headSha,
688 createProcessGitRunner(),
689 ),
690 })
691 if (result.skipped) {
692 console.log(`ai-review skipped: ${result.reason}`)
693 if ('security' in result && result.security !== undefined) {
694 for (const reason of result.security.reasons) {
695 console.log(`ai-review security: ${reason}`)
696 }
697 }
698 return
699 }
700 console.log(
701 `ai-review done label=${result.label} push=${String(result.pushLanded)}`,
702 )
704​
705if (isExecutedDirectly()) {
706 main().catch((error) => {
707 console.error(error)
708 process.exitCode = 1
709 })