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

run.test.ts

622 lines18.2 KB

1import { describe, expect, it } from 'vitest'
2import type { GitHubClient } from '../../scripts/maintainer/github.ts'
3import { config } from '../../scripts/maintainer/fixtures.ts'
4import { COMMENT_MARKER } from './comments.ts'
5import type { GitRunner } from './git.ts'
6import { runReviewJob } from './run.ts'
7​
8const REPO = 'TanStack/ai'
9const NUMBER = 42
10const SHA = 'abc123def456'
11const MACHINE = 'tanstack-ai-bot'
12const TOKEN = 'ghs_test'
13const WORKTREE = '/tmp/review'
14const HEAD_REF = 'fix-chat'
15const HEAD_REPO = 'alice/ai'
16const AUTOMATED =
17 'This comment is automated by a Grok agent. It is not a maintainer review.'
18​
19type StoredComment = { id: number; issueNumber: number; body: string }
20type GitResult = { stdout: string; stderr: string; code: number }
21​
22function samplePull(
23 overrides: {
24 draft?: boolean
25 maintainer_can_modify?: boolean
26 login?: string
27 } = {},
28) {
29 return {
30 number: NUMBER,
31 title: 'Fix chat crash',
32 body: 'Handle empty messages.',
33 html_url: 'https://github.com/TanStack/ai/pull/42',
34 draft: overrides.draft ?? false,
35 user: { login: overrides.login ?? 'alice' },
36 head: {
37 sha: SHA,
38 ref: HEAD_REF,
39 repo: {
40 full_name: HEAD_REPO,
41 owner: { login: 'alice' },
42 },
43 user: { login: 'alice' },
44 },
45 maintainer_can_modify: overrides.maintainer_can_modify ?? false,
46 labels: [{ name: 'bug' }],
47 }
49​
50function sampleFiles() {
51 return [
52 {
53 filename: 'src/chat.ts',
54 patch: '@@ -1,2 +1,3 @@\n line',
55 },
56 ]
58​
59function readCommentBody(body: unknown) {
60 if (
61 typeof body === 'object' &&
62 body !== null &&
63 'body' in body &&
64 typeof body.body === 'string'
65 ) {
66 return body.body
67 }
68 throw new Error('expected { body: string }')
70​
71function readLabelName(body: unknown) {
72 if (
73 typeof body === 'object' &&
74 body !== null &&
75 'name' in body &&
76 typeof body.name === 'string'
77 ) {
78 return body.name
79 }
80 throw new Error('label body is missing name')
82​
83function readIssueLabelNames(body: unknown) {
84 if (
85 typeof body === 'object' &&
86 body !== null &&
87 'labels' in body &&
88 Array.isArray(body.labels)
89 ) {
90 const names: Array<string> = []
91 for (const label of body.labels) {
92 if (typeof label !== 'string') {
93 throw new Error('labels must be strings')
94 }
95 names.push(label)
96 }
97 return names
98 }
99 throw new Error('issue label body is missing labels')
101​
102function createFakeGitHub(
103 options: {
104 pull?: ReturnType<typeof samplePull>
105 files?: ReturnType<typeof sampleFiles>
106 waitingRunIds?: Array<number>
107 approveError?: string
108 } = {},
109) {
110 const pull = options.pull ?? samplePull()
111 const files = options.files ?? sampleFiles()
112 const comments: Array<StoredComment> = []
113 let nextId = 1
114 const issueLabels = new Set<string>()
115 const repoLabels = new Set<string>()
116 const approvedRuns: Array<number> = []
117 const waitingRunIds = options.waitingRunIds ?? []
118 const pullPath = `/repos/${REPO}/pulls/${NUMBER}`
119 const filesPath = `/repos/${REPO}/pulls/${NUMBER}/files`
120 const repoLabelsPath = `/repos/${REPO}/labels`
121 const issueLabelsPath = `/repos/${REPO}/issues/${NUMBER}/labels`
122​
123 const client = {
124 graphql() {
125 throw new Error('not used')
126 },
127 async rest(method, path, body) {
128 if (method === 'GET' && path === pullPath) return pull
129 if (method === 'GET' && path.startsWith(`/repos/${REPO}/actions/runs?`)) {
130 const params = new URL(`https://api.github.com${path}`).searchParams
131 const ids =
132 params.get('status') === 'waiting' && params.get('head_sha') === SHA
133 ? waitingRunIds
134 : []
135 return {
136 workflow_runs: ids.map((id) => ({
137 id,
138 head_sha: SHA,
139 status: params.get('status'),
140 })),
141 }
142 }
143 const approveMatch =
144 /^\/repos\/TanStack\/ai\/actions\/runs\/(\d+)\/approve$/.exec(path)
145 if (method === 'POST' && approveMatch?.[1] !== undefined) {
146 if (options.approveError !== undefined) {
147 throw new Error(
148 `GitHub REST POST ${path} → HTTP 403: ${options.approveError}`,
149 )
150 }
151 approvedRuns.push(Number(approveMatch[1]))
152 return null
153 }
154 if (method === 'GET' && path.startsWith(`${filesPath}?`)) {
155 const params = new URL(`https://api.github.com${path}`).searchParams
156 const page = Number(params.get('page') ?? '1')
157 const perPage = Number(params.get('per_page') ?? '100')
158 const start = (page - 1) * perPage
159 return files.slice(start, start + perPage)
160 }
161​
162 const listMatch = /^\/repos\/[^/]+\/[^/]+\/issues\/(\d+)\/comments$/.exec(
163 path,
164 )
165 const patchMatch =
166 /^\/repos\/[^/]+\/[^/]+\/issues\/comments\/(\d+)$/.exec(path)
167​
168 if (method === 'GET' && listMatch?.[1] !== undefined) {
169 const issueNumber = Number(listMatch[1])
170 return comments.filter((comment) => comment.issueNumber === issueNumber)
171 }
172​
173 if (method === 'POST' && listMatch?.[1] !== undefined) {
174 const issueNumber = Number(listMatch[1])
175 const comment = {
176 id: nextId,
177 issueNumber,
178 body: readCommentBody(body),
179 }
180 nextId += 1
181 comments.push(comment)
182 return comment
183 }
184​
185 if (method === 'PATCH' && patchMatch?.[1] !== undefined) {
186 const id = Number(patchMatch[1])
187 const existing = comments.find((comment) => comment.id === id)
188 if (!existing) {
189 throw new Error(`comment ${id} not found`)
190 }
191 existing.body = readCommentBody(body)
192 return existing
193 }
194​
195 if (method === 'POST' && path === repoLabelsPath) {
196 const name = readLabelName(body)
197 if (repoLabels.has(name)) {
198 throw new Error(`GitHub REST POST ${path} → HTTP 422: already exists`)
199 }
200 repoLabels.add(name)
201 return null
202 }
203​
204 if (method === 'POST' && path === issueLabelsPath) {
205 const names = readIssueLabelNames(body)
206 for (const name of names) issueLabels.add(name)
207 return null
208 }
209​
210 if (method === 'DELETE' && path.startsWith(`${issueLabelsPath}/`)) {
211 const name = decodeURIComponent(
212 path.slice(`${issueLabelsPath}/`.length),
213 )
214 if (!issueLabels.has(name)) {
215 throw new Error(`GitHub REST DELETE ${path} → HTTP 404: Not Found`)
216 }
217 issueLabels.delete(name)
218 return null
219 }
220​
221 throw new Error(`unexpected ${method} ${path}`)
222 },
223 } satisfies GitHubClient
224​
225 return { client, comments, issueLabels, approvedRuns }
227​
228function createFakeRunner(
229 impl?: (args: Array<string>, cwd: string) => GitResult,
230) {
231 const calls: Array<{ args: Array<string>; cwd: string }> = []
232 const runner: GitRunner = async (args, cwd) => {
233 calls.push({ args: [...args], cwd })
234 if (impl) {
235 return impl(args, cwd)
236 }
237 return { stdout: '', stderr: '', code: 0 }
238 }
239 return { runner, calls }
241​
242const BUG = {
243 severity: 'bug' as const,
244 file: 'src/chat.ts',
245 line: 40,
246 description: 'null crash on empty messages',
247 suggestion: 'return early when messages is empty',
249​
250const NIT = {
251 severity: 'nit' as const,
252 file: 'src/chat.ts',
253 line: 12,
254 description: 'extra blank line',
255 suggestion: 'delete the blank line',
257​
258async function unusedReview() {
259 throw new Error('review should not run')
261​
262async function readyReview() {
263 return { verdict: 'ready' as const, issues: [] }
265​
266async function polishReview() {
267 return { verdict: 'polish' as const, issues: [BUG, NIT] }
269​
270async function rejectReview() {
271 return { verdict: 'reject' as const, issues: [] }
273​
274function pullRequestEvent() {
275 return { pull_request: { number: NUMBER } }
277​
278async function runJob(options: {
279 eventName?: string
280 event?: unknown
281 pull?: ReturnType<typeof samplePull>
282 review?:
283 | typeof unusedReview
284 | typeof readyReview
285 | typeof polishReview
286 | typeof rejectReview
287 alreadyReviewedSha?: string | null
288 headCommitAuthorLogin?: string | null
289 gitImpl?: (args: Array<string>, cwd: string) => GitResult
290 files?: ReturnType<typeof sampleFiles>
291 waitingRunIds?: Array<number>
292 approveError?: string
293}) {
294 const github = createFakeGitHub({
295 pull: options.pull,
296 files: options.files,
297 waitingRunIds: options.waitingRunIds,
298 approveError: options.approveError,
299 })
300 const git = createFakeRunner(options.gitImpl)
301 const result = await runReviewJob({
302 client: github.client,
303 repo: REPO,
304 token: TOKEN,
305 config,
306 eventName: options.eventName ?? 'pull_request',
307 event: options.event ?? pullRequestEvent(),
308 worktreeRoot: WORKTREE,
309 machineUserLogin: MACHINE,
310 gitRunner: git.runner,
311 review: options.review ?? unusedReview,
312 alreadyReviewedSha: options.alreadyReviewedSha ?? null,
313 headCommitAuthorLogin: options.headCommitAuthorLogin ?? 'alice',
314 })
315 return {
316 result,
317 comments: github.comments,
318 issueLabels: github.issueLabels,
319 gitCalls: git.calls,
320 approvedRuns: github.approvedRuns,
321 }
323​
324describe('runReviewJob', () => {
325 it('skips a draft auto run and does not post a comment', async () => {
326 const { result, comments, gitCalls } = await runJob({
327 pull: samplePull({ draft: true }),
328 })
329​
330 expect(result).toEqual({ skipped: true, reason: 'draft' })
331 expect(comments).toEqual([])
332 expect(gitCalls).toEqual([])
333 })
334​
335 it('skips an auto run from a roster maintainer and does not post a comment', async () => {
336 const { result, comments, gitCalls } = await runJob({
337 pull: samplePull({ login: 'alem' }),
338 })
339​
340 expect(result).toEqual({ skipped: true, reason: 'maintainer-author' })
341 expect(comments).toEqual([])
342 expect(gitCalls).toEqual([])
343 })
344​
345 it('runs when the ai-review label is added to a maintainer PR', async () => {
346 const { result, comments } = await runJob({
347 pull: samplePull({ login: 'alem' }),
348 event: {
349 action: 'labeled',
350 label: { name: 'ai-review' },
351 sender: { login: 'alem' },
352 pull_request: { number: NUMBER },
353 },
354 review: readyReview,
355 })
356​
357 expect(result).toEqual({
358 skipped: false,
359 verdict: { verdict: 'ready', issues: [] },
360 label: 'ai-ready',
361 pushLanded: false,
362 })
363 expect(comments).toHaveLength(1)
364 })
365​
366 it('skips a labeled pull_request that is not the ai-review label', async () => {
367 const { result, comments, gitCalls } = await runJob({
368 event: {
369 action: 'labeled',
370 label: { name: 'bug' },
371 pull_request: { number: NUMBER },
372 },
373 })
374​
375 expect(result).toEqual({ skipped: true, reason: 'not-label' })
376 expect(comments).toEqual([])
377 expect(gitCalls).toEqual([])
378 })
379​
380 it('skips an issue_comment that is not the /ai-review command', async () => {
381 const { result, comments, gitCalls } = await runJob({
382 eventName: 'issue_comment',
383 event: {
384 issue: {
385 number: NUMBER,
386 pull_request: {
387 url: 'https://api.github.com/repos/TanStack/ai/pulls/42',
388 },
389 },
390 comment: {
391 body: 'please review this',
392 user: { login: 'alem' },
393 },
394 },
395 })
396​
397 expect(result).toEqual({ skipped: true, reason: 'not-command' })
398 expect(comments).toEqual([])
399 expect(gitCalls).toEqual([])
400 })
401​
402 it('runs a maintainer /ai-review comment in manual mode', async () => {
403 const { result, comments } = await runJob({
404 eventName: 'issue_comment',
405 event: {
406 issue: {
407 number: NUMBER,
408 pull_request: {
409 url: 'https://api.github.com/repos/TanStack/ai/pulls/42',
410 },
411 },
412 comment: {
413 body: '/ai-review',
414 user: { login: 'alem' },
415 },
416 },
417 review: readyReview,
418 })
419​
420 expect(result).toEqual({
421 skipped: false,
422 verdict: { verdict: 'ready', issues: [] },
423 label: 'ai-ready',
424 pushLanded: false,
425 })
426 expect(comments).toHaveLength(1)
427 })
428​
429 it('skips an issue_comment from a non-maintainer', async () => {
430 const { result, comments, gitCalls } = await runJob({
431 eventName: 'issue_comment',
432 event: {
433 issue: {
434 number: NUMBER,
435 pull_request: {
436 url: 'https://api.github.com/repos/TanStack/ai/pulls/42',
437 },
438 },
439 comment: {
440 body: '/ai-review',
441 user: { login: 'stranger' },
442 },
443 },
444 })
445​
446 expect(result).toEqual({ skipped: true, reason: 'not-maintainer' })
447 expect(comments).toEqual([])
448 expect(gitCalls).toEqual([])
449 })
450​
451 it('upserts a ready comment, sets ai-ready, and does not push', async () => {
452 const { result, comments, issueLabels, gitCalls } = await runJob({
453 review: readyReview,
454 })
455​
456 expect(result).toEqual({
457 skipped: false,
458 verdict: { verdict: 'ready', issues: [] },
459 label: 'ai-ready',
460 pushLanded: false,
461 })
462 expect(comments).toHaveLength(1)
463 expect(comments[0]?.body.startsWith(AUTOMATED)).toBe(true)
464 expect(comments[0]?.body).toContain(COMMENT_MARKER)
465 expect(comments[0]?.body).toContain('**Verdict:** ready')
466 expect(comments[0]?.body).toContain(`**Head SHA:** ${SHA}`)
467 expect(comments[0]?.body).toContain('**Label:** `ai-ready`')
468 expect(comments[0]?.body).toContain('Did not push.')
469 expect([...issueLabels]).toEqual(['ai-ready', 'secure'])
470 expect(gitCalls).toEqual([])
471 })
472​
473 it('pushes polish with --force-with-lease when maintainer edits are on', async () => {
474 const { result, comments, issueLabels, gitCalls } = await runJob({
475 pull: samplePull({ maintainer_can_modify: true }),
476 review: polishReview,
477 })
478​
479 expect(result).toEqual({
480 skipped: false,
481 verdict: { verdict: 'polish', issues: [BUG, NIT] },
482 label: 'ai-ready',
483 pushLanded: true,
484 })
485 expect(comments[0]?.body).toContain('**Verdict:** polish')
486 expect(comments[0]?.body).toContain(
487 '- [bug] src/chat.ts:40 null crash on empty messages',
488 )
489 expect(comments[0]?.body).toContain(
490 '- [nit] src/chat.ts:12 extra blank line',
491 )
492 expect(comments[0]?.body).toContain(
493 'Pushed polish commit to the PR branch.',
494 )
495 expect(comments[0]?.body).toContain('**Label:** `ai-ready`')
496 expect([...issueLabels]).toEqual(['ai-ready', 'secure'])
497 expect(gitCalls).toEqual([
498 { args: ['add', '-A'], cwd: WORKTREE },
499 {
500 args: [
501 '-c',
502 `user.name=${MACHINE}`,
503 '-c',
504 `user.email=${MACHINE}@users.noreply.github.com`,
505 'commit',
506 '-m',
507 'ai-review: apply review polish for #42',
508 ],
509 cwd: WORKTREE,
510 },
511 {
512 args: [
513 'push',
514 '--force-with-lease',
515 `https://x-access-token:${TOKEN}@github.com/${HEAD_REPO}.git`,
516 `HEAD:${HEAD_REF}`,
517 ],
518 cwd: WORKTREE,
519 },
520 ])
521 expect(gitCalls[2]?.args).toContain('--force-with-lease')
522 expect(gitCalls[2]?.args).not.toContain('--force')
523 })
524​
525 it('does not push polish when maintainer edits are off and sets ai-needs-work', async () => {
526 const { result, comments, issueLabels, gitCalls } = await runJob({
527 pull: samplePull({ maintainer_can_modify: false }),
528 review: polishReview,
529 })
530​
531 expect(result).toEqual({
532 skipped: false,
533 verdict: { verdict: 'polish', issues: [BUG, NIT] },
534 label: 'ai-needs-work',
535 pushLanded: false,
536 })
537 expect(comments[0]?.body).toContain('**Label:** `ai-needs-work`')
538 expect(comments[0]?.body).toContain(
539 'Did not push: fork has maintainer edits off.',
540 )
541 expect([...issueLabels]).toEqual(['ai-needs-work'])
542 expect(gitCalls).toEqual([])
543 })
544​
545 it('sets ai-rejected on reject and does not push', async () => {
546 const { result, comments, issueLabels, gitCalls } = await runJob({
547 review: rejectReview,
548 })
549​
550 expect(result).toEqual({
551 skipped: false,
552 verdict: { verdict: 'reject', issues: [] },
553 label: 'ai-rejected',
554 pushLanded: false,
555 })
556 expect(comments[0]?.body).toContain('**Verdict:** reject')
557 expect(comments[0]?.body).toContain('**Label:** `ai-rejected`')
558 expect([...issueLabels]).toEqual(['ai-rejected'])
559 expect(comments[0]?.body).toContain('Did not mark secure.')
560 expect(gitCalls).toEqual([])
561 })
562​
563 it('adds secure and approves waiting workflows when ready and clean', async () => {
564 const { comments, issueLabels, approvedRuns } = await runJob({
565 review: readyReview,
566 waitingRunIds: [101, 202],
567 })
568​
569 expect([...issueLabels]).toEqual(['ai-ready', 'secure'])
570 expect(approvedRuns).toEqual([101, 202])
571 expect(comments[0]?.body).toContain('Added label `secure`')
572 expect(comments[0]?.body).toContain('Approved 2 waiting workflow runs.')
573 })
574​
575 it('does not mark secure or approve workflows when the diff looks like malware', async () => {
576 const { comments, issueLabels, approvedRuns } = await runJob({
577 review: readyReview,
578 waitingRunIds: [101],
579 files: [
580 {
581 filename: '.github/workflows/ci.yml',
582 patch:
583 '@@ -1,2 +1,4 @@\n on:\n+ pull_request_target:\n+ types: [opened]\n',
584 },
585 ],
586 })
587​
588 expect([...issueLabels]).toEqual(['ai-ready'])
589 expect(approvedRuns).toEqual([])
590 expect(comments[0]?.body).toContain('blocked. Did not approve workflows.')
591 expect(comments[0]?.body).toContain('adds pull_request_target')
592 })
593​
594 it('skips a labeled ai-review event from a non-maintainer', async () => {
595 const { result, comments, approvedRuns } = await runJob({
596 event: {
597 action: 'labeled',
598 label: { name: 'ai-review' },
599 sender: { login: 'stranger' },
600 pull_request: { number: NUMBER },
601 },
602 waitingRunIds: [101],
603 })
604​
605 expect(result).toEqual({ skipped: true, reason: 'not-maintainer' })
606 expect(comments).toEqual([])
607 expect(approvedRuns).toEqual([])
608 })
609​
610 it('does not leave secure when workflow approval fails', async () => {
611 const { comments, issueLabels, approvedRuns } = await runJob({
612 review: readyReview,
613 waitingRunIds: [101],
614 approveError: 'Resource not accessible by personal access token',
615 })
616​
617 expect([...issueLabels]).toEqual(['ai-ready'])
618 expect(approvedRuns).toEqual([])
619 expect(comments[0]?.body).toContain('Did not add label `secure`')
620 expect(comments[0]?.body).toContain('Could not approve workflows')
621 })
622})