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

run.test.ts

990 lines29.9 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 = 'a'.repeat(40)
11const POLISH_SHA = 'c'.repeat(40)
12const BASE_SHA = 'b'.repeat(40)
13const MACHINE = 'tanstack-ai-bot'
14const TOKEN = 'ghs_test'
15const WORKTREE = '/tmp/review'
16const HEAD_REF = 'fix-chat'
17const HEAD_REPO = 'alice/ai'
18const AUTOMATED =
19 'This comment is automated by a Grok agent. It is not a maintainer review.'
20const GENERATED_DIFF =
21 'diff --git a/src/chat.ts b/src/chat.ts\n--- a/src/chat.ts\n+++ b/src/chat.ts\n@@ -1 +1 @@\n-old\n+new\n'
22​
23type StoredComment = { id: number; issueNumber: number; body: string }
24type GitResult = { stdout: string; stderr: string; code: number }
25​
26function samplePull(
27 overrides: {
28 draft?: boolean
29 maintainer_can_modify?: boolean
30 login?: string
31 labels?: Array<string>
32 baseRef?: string
33 } = {},
34) {
35 return {
36 number: NUMBER,
37 state: 'open',
38 title: 'Fix chat crash',
39 body: 'Handle empty messages.',
40 html_url: 'https://github.com/TanStack/ai/pull/42',
41 draft: overrides.draft ?? false,
42 user: { login: overrides.login ?? 'alice' },
43 base: {
44 sha: BASE_SHA,
45 ref: overrides.baseRef ?? 'main',
46 repo: { full_name: REPO },
47 },
48 head: {
49 sha: SHA,
50 ref: HEAD_REF,
51 repo: {
52 full_name: HEAD_REPO,
53 owner: { login: 'alice' },
54 },
55 user: { login: 'alice' },
56 },
57 maintainer_can_modify: overrides.maintainer_can_modify ?? false,
58 labels: (overrides.labels ?? ['bug']).map((name) => ({ name })),
59 }
61​
62function sampleFiles() {
63 return [
64 {
65 filename: 'src/chat.ts',
66 status: 'modified',
67 patch: '@@ -1,2 +1,3 @@\n line',
68 },
69 ]
71​
72function readCommentBody(body: unknown) {
73 if (
74 typeof body === 'object' &&
75 body !== null &&
76 'body' in body &&
77 typeof body.body === 'string'
78 ) {
79 return body.body
80 }
81 throw new Error('expected { body: string }')
83​
84function readLabelName(body: unknown) {
85 if (
86 typeof body === 'object' &&
87 body !== null &&
88 'name' in body &&
89 typeof body.name === 'string'
90 ) {
91 return body.name
92 }
93 throw new Error('label body is missing name')
95​
96function readIssueLabelNames(body: unknown) {
97 if (
98 typeof body === 'object' &&
99 body !== null &&
100 'labels' in body &&
101 Array.isArray(body.labels)
102 ) {
103 const names: Array<string> = []
104 for (const label of body.labels) {
105 if (typeof label !== 'string') {
106 throw new Error('labels must be strings')
107 }
108 names.push(label)
109 }
110 return names
111 }
112 throw new Error('issue label body is missing labels')
114​
115function createFakeGitHub(
116 options: {
117 pull?: ReturnType<typeof samplePull>
118 files?: ReturnType<typeof sampleFiles>
119 waitingRunIds?: Array<number>
120 approveError?: string
121 initialIssueLabels?: Array<string>
122 labelDeleteError?: string
123 } = {},
124) {
125 const pull = options.pull ?? samplePull()
126 const files = options.files ?? sampleFiles()
127 const comments: Array<StoredComment> = []
128 let nextId = 1
129 const issueLabels = new Set(options.initialIssueLabels ?? [])
130 const repoLabels = new Set<string>()
131 const approvedRuns: Array<number> = []
132 const waitingRunIds = options.waitingRunIds ?? []
133 const pullPath = `/repos/${REPO}/pulls/${NUMBER}`
134 const filesPath = `/repos/${REPO}/pulls/${NUMBER}/files`
135 const repoLabelsPath = `/repos/${REPO}/labels`
136 const issueLabelsPath = `/repos/${REPO}/issues/${NUMBER}/labels`
137​
138 const client = {
139 graphql() {
140 throw new Error('not used')
141 },
142 async rest(method, path, body) {
143 if (method === 'GET' && path === pullPath) return pull
144 if (method === 'GET' && path === `/repos/${REPO}/actions/runs/123`)
145 return {
146 id: 123,
147 workflow_id: 7,
148 event: 'pull_request',
149 status: 'completed',
150 conclusion: 'success',
151 repository: { full_name: REPO },
152 head_repository: {
153 full_name: HEAD_REPO,
154 owner: { login: HEAD_REPO.split('/')[0] },
155 },
156 head_branch: HEAD_REF,
157 head_sha: SHA,
158 }
159 if (
160 method === 'GET' &&
161 path === `/repos/${REPO}/actions/workflows/ai-review-signal.yml`
162 )
163 return { id: 7, path: '.github/workflows/ai-review-signal.yml' }
164 if (
165 method === 'GET' &&
166 path.startsWith(`/repos/${REPO}/pulls?state=open&base=main&head=`)
167 )
168 return [pull]
169​
170 if (method === 'GET' && path.startsWith(`/repos/${REPO}/actions/runs?`)) {
171 const params = new URL(`https://api.github.com${path}`).searchParams
172 const ids =
173 params.get('status') === 'waiting' &&
174 params.get('head_sha') === pull.head.sha
175 ? waitingRunIds
176 : []
177 return {
178 workflow_runs: ids.map((id) => ({
179 id,
180 head_sha: pull.head.sha,
181 status: params.get('status'),
182 })),
183 }
184 }
185 const approveMatch =
186 /^\/repos\/TanStack\/ai\/actions\/runs\/(\d+)\/approve$/.exec(path)
187 if (method === 'POST' && approveMatch?.[1] !== undefined) {
188 if (options.approveError !== undefined) {
189 throw new Error(
190 `GitHub REST POST ${path} → HTTP 403: ${options.approveError}`,
191 )
192 }
193 approvedRuns.push(Number(approveMatch[1]))
194 return null
195 }
196 if (method === 'GET' && path.startsWith(`${filesPath}?`)) {
197 const params = new URL(`https://api.github.com${path}`).searchParams
198 const page = Number(params.get('page') ?? '1')
199 const perPage = Number(params.get('per_page') ?? '100')
200 const start = (page - 1) * perPage
201 return files.slice(start, start + perPage)
202 }
203 if (method === 'GET' && path.includes('/git/trees/')) {
204 return {
205 truncated: false,
206 tree: files.map((file) => ({
207 path: file.filename,
208 mode: '100644',
209 type: 'blob',
210 })),
211 }
212 }
213​
214 const listMatch =
215 /^\/repos\/[^/]+\/[^/]+\/issues\/(\d+)\/comments(?:\?per_page=100)?$/.exec(
216 path,
217 )
218 const patchMatch =
219 /^\/repos\/[^/]+\/[^/]+\/issues\/comments\/(\d+)$/.exec(path)
220​
221 if (method === 'GET' && listMatch?.[1] !== undefined) {
222 const issueNumber = Number(listMatch[1])
223 return comments.filter((comment) => comment.issueNumber === issueNumber)
224 }
225​
226 if (method === 'POST' && listMatch?.[1] !== undefined) {
227 const issueNumber = Number(listMatch[1])
228 const comment = {
229 id: nextId,
230 issueNumber,
231 body: readCommentBody(body),
232 }
233 nextId += 1
234 comments.push(comment)
235 return comment
236 }
237​
238 if (method === 'PATCH' && patchMatch?.[1] !== undefined) {
239 const id = Number(patchMatch[1])
240 const existing = comments.find((comment) => comment.id === id)
241 if (!existing) {
242 throw new Error(`comment ${id} not found`)
243 }
244 existing.body = readCommentBody(body)
245 return existing
246 }
247​
248 if (method === 'POST' && path === repoLabelsPath) {
249 const name = readLabelName(body)
250 if (repoLabels.has(name)) {
251 throw new Error(`GitHub REST POST ${path} → HTTP 422: already exists`)
252 }
253 repoLabels.add(name)
254 return null
255 }
256​
257 if (method === 'POST' && path === issueLabelsPath) {
258 const names = readIssueLabelNames(body)
259 for (const name of names) issueLabels.add(name)
260 return null
261 }
262​
263 if (method === 'DELETE' && path.startsWith(`${issueLabelsPath}/`)) {
264 if (options.labelDeleteError !== undefined)
265 throw new Error(
266 `GitHub REST DELETE ${path} → ${options.labelDeleteError}`,
267 )
268 const name = decodeURIComponent(
269 path.slice(`${issueLabelsPath}/`.length),
270 )
271 if (!issueLabels.has(name)) {
272 throw new Error(`GitHub REST DELETE ${path} → HTTP 404: Not Found`)
273 }
274 issueLabels.delete(name)
275 return null
276 }
277​
278 throw new Error(`unexpected ${method} ${path}`)
279 },
280 } satisfies GitHubClient
281​
282 return { client, comments, issueLabels, approvedRuns }
284​
285function createFakeRunner(
286 impl?: (args: Array<string>, cwd: string) => GitResult,
287) {
288 const calls: Array<{ args: Array<string>; cwd: string; input?: string }> = []
289 const runner: GitRunner = async (args, cwd, input) => {
290 calls.push({
291 args: [...args],
292 cwd,
293 ...(input === undefined ? {} : { input }),
294 })
295 if (impl) {
296 return impl(args, cwd)
297 }
298 return {
299 stdout: args[0] === 'rev-parse' ? POLISH_SHA : '',
300 stderr: '',
301 code: 0,
302 }
303 }
304 return { runner, calls }
306​
307const BUG = {
308 severity: 'bug' as const,
309 file: 'src/chat.ts',
310 line: 40,
311 description: 'null crash on empty messages',
312 suggestion: 'return early when messages is empty',
314​
315const NIT = {
316 severity: 'nit' as const,
317 file: 'src/chat.ts',
318 line: 12,
319 description: 'extra blank line',
320 suggestion: 'delete the blank line',
322​
323function unusedReview() {
324 return Promise.reject(new Error('review should not run'))
326​
327async function readyReview() {
328 return { verdict: 'ready' as const, issues: [] }
330​
331async function polishReview() {
332 return {
333 verdict: 'polish' as const,
334 issues: [BUG, NIT],
335 generatedDiff: GENERATED_DIFF,
336 }
338​
339async function rejectReview() {
340 return { verdict: 'reject' as const, issues: [] }
342​
343async function unsafePolishReview() {
344 return {
345 verdict: 'polish' as const,
346 issues: [BUG],
347 generatedDiff:
348 'diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml\n--- a/.github/workflows/ci.yml\n+++ b/.github/workflows/ci.yml\n@@ -1 +1 @@\n-old\n+new\n',
349 }
351​
352function workflowRunEvent() {
353 return {
354 action: 'completed',
355 workflow_run: {
356 id: 123,
357 conclusion: 'success',
358 pull_requests: [{ number: NUMBER }],
359 },
360 }
362​
363async function runJob(options: {
364 eventName?: string
365 event?: unknown
366 pull?: ReturnType<typeof samplePull>
367 review?: Parameters<typeof runReviewJob>[0]['review']
368 alreadyReviewedSha?: string | null
369 headCommitAuthorLogin?: string | null
370 gitImpl?: (args: Array<string>, cwd: string) => GitResult
371 files?: ReturnType<typeof sampleFiles>
372 waitingRunIds?: Array<number>
373 approveError?: string
374 initialIssueLabels?: Array<string>
375 labelDeleteError?: string
376 sandboxSecrets?: Array<string>
377 fetchFails?: boolean
378 staleReadAfterPush?: boolean
379}) {
380 const pull = options.pull ?? samplePull()
381 const github = createFakeGitHub({
382 pull,
383 files: options.files,
384 waitingRunIds: options.waitingRunIds,
385 approveError: options.approveError,
386 initialIssueLabels: options.initialIssueLabels,
387 labelDeleteError: options.labelDeleteError,
388 })
389 const git = createFakeRunner(options.gitImpl)
390 const result = await runReviewJob({
391 client: github.client,
392 repo: REPO,
393 token: TOKEN,
394 config,
395 eventName: options.eventName ?? 'workflow_run',
396 event: options.event ?? workflowRunEvent(),
397 worktreeRoot: WORKTREE,
398 repoRoot: WORKTREE,
399 machineUserLogin: MACHINE,
400 gitRunner: async (args, cwd, input) => {
401 const files = options.files ?? sampleFiles()
402 if (args[0] === 'fetch')
403 return options.fetchFails
404 ? { stdout: '', stderr: 'could not resolve host', code: 128 }
405 : { stdout: '', stderr: '', code: 0 }
406 if (args[0] === 'merge-base')
407 return { stdout: BASE_SHA, stderr: '', code: 0 }
408 if (args[0] === 'diff')
409 return {
410 stdout: args.includes('--raw')
411 ? files
412 .map(
413 (file) =>
414 `:100644 100644 ${BASE_SHA} ${SHA} M\0${file.filename}\0`,
415 )
416 .join('')
417 : files
418 .map(
419 (file) =>
420 `diff --git a/${file.filename} b/${file.filename}\n${file.patch}\n`,
421 )
422 .join(''),
423 stderr: '',
424 code: 0,
425 }
426 const gitResult = await git.runner(args, cwd, input)
427 if (
428 args[0] === 'push' &&
429 gitResult.code === 0 &&
430 !options.staleReadAfterPush
431 )
432 pull.head.sha = POLISH_SHA
433 return gitResult
434 },
435 review: options.review ?? unusedReview,
436 prepareWorktree: async () => {},
437 alreadyReviewedSha: options.alreadyReviewedSha ?? null,
438 headCommitAuthorLogin: options.headCommitAuthorLogin ?? 'alice',
439 sandboxSecrets: options.sandboxSecrets,
440 })
441 return {
442 result,
443 comments: github.comments,
444 issueLabels: github.issueLabels,
445 gitCalls: git.calls,
446 approvedRuns: github.approvedRuns,
447 }
449​
450describe('runReviewJob', () => {
451 it.each(['base', 'closed', 'edits'])(
452 'does not apply or push polish when %s changes during review',
453 async (field) => {
454 const pull = samplePull({ maintainer_can_modify: true })
455 const result = await runJob({
456 pull,
457 review: async () => {
458 if (field === 'base') pull.base.sha = 'd'.repeat(40)
459 if (field === 'closed') pull.state = 'closed'
460 if (field === 'edits') pull.maintainer_can_modify = false
461 return polishReview()
462 },
463 })
464 expect(result.result).toEqual({ skipped: true, reason: 'head-changed' })
465 expect(result.gitCalls).toEqual([])
466 expect(result.comments).toEqual([])
467 },
468 )
469 it('does not repeat a paid review for an automatic replay', async () => {
470 const pull = samplePull()
471 let reviews = 0
472 const review = async () => {
473 reviews += 1
474 return readyReview()
475 }
476 const first = await runJob({ pull, review })
477 expect(first.result.skipped).toBe(false)
478 const replay = await runJob({
479 pull,
480 review,
481 event: { workflow_run: { id: 123, pull_requests: [] } },
482 alreadyReviewedSha: SHA,
483 })
484 expect(replay.result.skipped).toBe(true)
485 expect(reviews).toBe(1)
486 })
487​
488 it('throws when a stale label delete fails with a non-404 status', async () => {
489 await expect(
490 runJob({
491 labelDeleteError: 'HTTP 500: upstream said HTTP 404',
492 initialIssueLabels: ['secure'],
493 }),
494 ).rejects.toThrow('HTTP 500')
495 })
496​
497 it.each(['base', 'headRepo', 'headRef'])(
498 'publishes nothing when %s identity changes during review',
499 async (field) => {
500 const pull = samplePull()
501 const result = await runJob({
502 pull,
503 review: async () => {
504 if (field === 'base') pull.base.sha = 'd'.repeat(40)
505 if (field === 'headRepo') pull.head.repo.full_name = 'other/ai'
506 if (field === 'headRef') pull.head.ref = 'other-branch'
507 return readyReview()
508 },
509 })
510 expect(result.result).toEqual({ skipped: true, reason: 'head-changed' })
511 expect(result.comments).toEqual([])
512 expect(result.approvedRuns).toEqual([])
513 },
514 )
515​
516 it.each(['input', 'generated', 'verdict'])(
517 'removes stale security labels when the %s audit fails',
518 async (stage) => {
519 const { result, issueLabels, approvedRuns, gitCalls, comments } =
520 await runJob({
521 initialIssueLabels: ['secure', 'ai-ready', 'bug', 'ready-to-merge'],
522 waitingRunIds: [101],
523 files:
524 stage === 'input'
525 ? [
526 {
527 filename: '.github/workflows/ci.yml',
528 status: 'modified',
529 patch: '@@ -1 +1 @@\n-old\n+new\n',
530 },
531 ]
532 : sampleFiles(),
533 review:
534 stage === 'input'
535 ? unusedReview
536 : stage === 'generated'
537 ? unsafePolishReview
538 : async () => ({
539 ...(await readyReview()),
540 generatedDiff: GENERATED_DIFF,
541 }),
542 })
543​
544 expect(result).toMatchObject({
545 skipped: true,
546 reason: 'security-blocked',
547 })
548 expect([...issueLabels].sort()).toEqual(['bug', 'ready-to-merge'])
549 expect(approvedRuns).toEqual([])
550 expect(gitCalls).toEqual([])
551 // The block shows on the PR, and its head SHA stops a paid repeat.
552 expect(comments).toHaveLength(1)
553 expect(comments[0]?.body).toContain('The security check blocked')
554 expect(comments[0]?.body).toContain(`**Head SHA:** ${SHA}`)
555 },
556 )
557​
558 it.each(['diff', 'verdict'])(
559 'blocks a sandbox secret in the generated %s',
560 async (where) => {
561 const secret = 'xai-test-secret'
562 const { result, comments, gitCalls } = await runJob({
563 pull: samplePull({ maintainer_can_modify: true }),
564 sandboxSecrets: [secret],
565 review: async () =>
566 where === 'diff'
567 ? {
568 ...(await polishReview()),
569 generatedDiff: GENERATED_DIFF.replace('+', `+${secret}`),
570 }
571 : {
572 verdict: 'ready' as const,
573 issues: [{ ...NIT, description: `key is ${secret}` }],
574 },
575 })
576 expect(result).toMatchObject({
577 skipped: true,
578 reason: 'security-blocked',
579 })
580 expect(gitCalls).toEqual([])
581 expect(JSON.stringify(comments)).not.toContain(secret)
582 },
583 )
584​
585 it('fails the job when the snapshot fetch fails', async () => {
586 await expect(runJob({ fetchFails: true })).rejects.toThrow(/git fetch/)
587 })
588​
589 it('still comments when GitHub reports the old head after the polish push', async () => {
590 const { result, comments } = await runJob({
591 pull: samplePull({ maintainer_can_modify: true }),
592 review: polishReview,
593 staleReadAfterPush: true,
594 })
595 expect(result).toMatchObject({ skipped: false, pushLanded: true })
596 expect(comments[0]?.body).toContain(`**Head SHA:** ${POLISH_SHA}`)
597 })
598​
599 it('does not publish readiness for a head changed during review', async () => {
600 const pull = samplePull()
601 const { result, issueLabels, approvedRuns, comments } = await runJob({
602 pull,
603 initialIssueLabels: ['secure', 'ai-ready', 'bug'],
604 waitingRunIds: [101],
605 review: async () => {
606 pull.head.sha = 'd'.repeat(40)
607 return readyReview()
608 },
609 })
610​
611 expect(result).toMatchObject({ skipped: true, reason: 'head-changed' })
612 expect([...issueLabels]).toEqual(['bug'])
613 expect(approvedRuns).toEqual([])
614 expect(comments).toEqual([])
615 })
616​
617 it('preserves the verdict when the same SHA is skipped', async () => {
618 const { result, issueLabels } = await runJob({
619 alreadyReviewedSha: SHA,
620 initialIssueLabels: ['secure', 'ai-ready', 'bug'],
621 })
622​
623 expect(result).toEqual({ skipped: true, reason: 'same-sha' })
624 expect([...issueLabels]).toEqual(['secure', 'ai-ready', 'bug'])
625 })
626​
627 it.each([SHA, 'd'.repeat(40)])(
628 'clears draft readiness with reviewed SHA %s',
629 async (alreadyReviewedSha) => {
630 const { result, issueLabels } = await runJob({
631 pull: samplePull({ draft: true }),
632 alreadyReviewedSha,
633 initialIssueLabels: ['secure', 'ai-ready', 'bug'],
634 })
635​
636 expect(result).toEqual({ skipped: true, reason: 'draft' })
637 expect([...issueLabels]).toEqual(['bug'])
638 },
639 )
640​
641 it('skips a pull request that does not target main', async () => {
642 const { result, comments, gitCalls } = await runJob({
643 eventName: 'workflow_dispatch',
644 event: { inputs: { pr_number: NUMBER } },
645 pull: samplePull({ baseRef: 'next' }),
646 })
647​
648 expect(result).toEqual({ skipped: true, reason: 'not-main' })
649 expect(comments).toEqual([])
650 expect(gitCalls).toEqual([])
651 })
652​
653 it('skips a draft auto run and does not post a comment', async () => {
654 const { result, comments, gitCalls } = await runJob({
655 pull: samplePull({ draft: true }),
656 })
657​
658 expect(result).toEqual({ skipped: true, reason: 'draft' })
659 expect(comments).toEqual([])
660 expect(gitCalls).toEqual([])
661 })
662​
663 it('skips an auto run from a roster maintainer and does not post a comment', async () => {
664 const { result, comments, gitCalls } = await runJob({
665 pull: samplePull({ login: 'alem' }),
666 })
667​
668 expect(result).toEqual({ skipped: true, reason: 'maintainer-author' })
669 expect(comments).toEqual([])
670 expect(gitCalls).toEqual([])
671 })
672​
673 it('runs a workflow_run signal in auto mode', async () => {
674 const { result, comments } = await runJob({
675 eventName: 'workflow_run',
676 event: workflowRunEvent(),
677 review: readyReview,
678 })
679​
680 expect(result).toEqual({
681 skipped: false,
682 verdict: { verdict: 'ready', issues: [] },
683 label: 'ai-ready',
684 pushLanded: false,
685 })
686 expect(comments).toHaveLength(1)
687 })
688​
689 it('keeps workflow_run automatic when ai-review remains on the PR', async () => {
690 const { result, comments } = await runJob({
691 eventName: 'workflow_run',
692 pull: samplePull({ login: 'alem', labels: ['ai-review'] }),
693 event: workflowRunEvent(),
694 })
695 expect(result).toEqual({ skipped: true, reason: 'maintainer-author' })
696 expect(comments).toEqual([])
697 })
698​
699 it('skips a workflow_run for a maintainer PR without the ai-review label', async () => {
700 const { result, comments, gitCalls } = await runJob({
701 eventName: 'workflow_run',
702 pull: samplePull({ login: 'alem' }),
703 event: workflowRunEvent(),
704 })
705​
706 expect(result).toEqual({ skipped: true, reason: 'maintainer-author' })
707 expect(comments).toEqual([])
708 expect(gitCalls).toEqual([])
709 })
710​
711 it('skips an issue_comment that is not the /ai-review command', async () => {
712 const { result, comments, gitCalls } = await runJob({
713 eventName: 'issue_comment',
714 event: {
715 issue: {
716 number: NUMBER,
717 state: 'open',
718 pull_request: {
719 url: 'https://api.github.com/repos/TanStack/ai/pulls/42',
720 },
721 },
722 comment: {
723 body: 'please review this',
724 user: { login: 'alem' },
725 },
726 },
727 })
728​
729 expect(result).toEqual({ skipped: true, reason: 'not-command' })
730 expect(comments).toEqual([])
731 expect(gitCalls).toEqual([])
732 })
733​
734 it('runs a maintainer /ai-review comment in manual mode', async () => {
735 const { result, comments } = await runJob({
736 eventName: 'issue_comment',
737 event: {
738 issue: {
739 number: NUMBER,
740 state: 'open',
741 pull_request: {
742 url: 'https://api.github.com/repos/TanStack/ai/pulls/42',
743 },
744 },
745 comment: {
746 body: '/ai-review',
747 user: { login: 'alem' },
748 },
749 },
750 review: readyReview,
751 })
752​
753 expect(result).toEqual({
754 skipped: false,
755 verdict: { verdict: 'ready', issues: [] },
756 label: 'ai-ready',
757 pushLanded: false,
758 })
759 expect(comments).toHaveLength(1)
760 })
761​
762 it('skips an issue_comment from a non-maintainer', async () => {
763 const { result, comments, gitCalls } = await runJob({
764 eventName: 'issue_comment',
765 event: {
766 issue: {
767 number: NUMBER,
768 state: 'open',
769 pull_request: {
770 url: 'https://api.github.com/repos/TanStack/ai/pulls/42',
771 },
772 },
773 comment: {
774 body: '/ai-review',
775 user: { login: 'stranger' },
776 },
777 },
778 })
779​
780 expect(result).toEqual({ skipped: true, reason: 'not-maintainer' })
781 expect(comments).toEqual([])
782 expect(gitCalls).toEqual([])
783 })
784​
785 it('upserts a ready comment, sets ai-ready, and does not push', async () => {
786 const { result, comments, issueLabels, gitCalls } = await runJob({
787 review: readyReview,
788 })
789​
790 expect(result).toEqual({
791 skipped: false,
792 verdict: { verdict: 'ready', issues: [] },
793 label: 'ai-ready',
794 pushLanded: false,
795 })
796 expect(comments).toHaveLength(1)
797 expect(comments[0]?.body.startsWith(AUTOMATED)).toBe(true)
798 expect(comments[0]?.body).toContain(COMMENT_MARKER)
799 expect(comments[0]?.body).toContain('**Verdict:** ready')
800 expect(comments[0]?.body).toContain(`**Head SHA:** ${SHA}`)
801 expect(comments[0]?.body).toContain('**Label:** `ai-ready`')
802 expect(comments[0]?.body).toContain('Did not push.')
803 expect([...issueLabels]).toEqual(['ai-ready', 'secure'])
804 expect(gitCalls).toEqual([])
805 })
806​
807 it('pushes polish with --force-with-lease when maintainer edits are on', async () => {
808 const { result, comments, issueLabels, gitCalls, approvedRuns } =
809 await runJob({
810 pull: samplePull({ maintainer_can_modify: true }),
811 review: polishReview,
812 waitingRunIds: [101],
813 })
814​
815 expect(result).toEqual({
816 skipped: false,
817 verdict: { verdict: 'polish', issues: [BUG, NIT] },
818 label: 'ai-ready',
819 pushLanded: true,
820 })
821 expect(comments[0]?.body).toContain('**Verdict:** polish')
822 expect(comments[0]?.body).toContain(`**Head SHA:** ${POLISH_SHA}`)
823 expect(approvedRuns).toEqual([101])
824 expect(comments[0]?.body).toContain(
825 '- [bug] src/chat.ts:40 null crash on empty messages',
826 )
827 expect(comments[0]?.body).toContain(
828 '- [nit] src/chat.ts:12 extra blank line',
829 )
830 expect(comments[0]?.body).toContain(
831 'Pushed polish commit to the PR branch.',
832 )
833 expect(comments[0]?.body).toContain('**Label:** `ai-ready`')
834 expect([...issueLabels]).toEqual(['ai-ready', 'secure'])
835 expect(gitCalls).toEqual([
836 {
837 args: ['apply', '--check', '--whitespace=error-all', '-'],
838 cwd: WORKTREE,
839 input: GENERATED_DIFF,
840 },
841 {
842 args: ['apply', '--whitespace=error-all', '-'],
843 cwd: WORKTREE,
844 input: GENERATED_DIFF,
845 },
846 { args: ['add', '-A'], cwd: WORKTREE },
847 {
848 args: [
849 '-c',
850 `user.name=${MACHINE}`,
851 '-c',
852 `user.email=${MACHINE}@users.noreply.github.com`,
853 'commit',
854 '-m',
855 'ai-review: apply review polish for #42',
856 ],
857 cwd: WORKTREE,
858 },
859 {
860 args: ['rev-parse', 'HEAD'],
861 cwd: WORKTREE,
862 },
863 {
864 args: [
865 'push',
866 `--force-with-lease=refs/heads/${HEAD_REF}:${SHA}`,
867 `https://x-access-token:${TOKEN}@github.com/${HEAD_REPO}.git`,
868 `HEAD:${HEAD_REF}`,
869 ],
870 cwd: WORKTREE,
871 },
872 ])
873 expect(gitCalls[5]?.args).toContain(
874 `--force-with-lease=refs/heads/${HEAD_REF}:${SHA}`,
875 )
876 expect(gitCalls[5]?.args).not.toContain('--force')
877 })
878​
879 it('does not apply an unsafe generated diff', async () => {
880 const { result, comments, issueLabels, gitCalls } = await runJob({
881 pull: samplePull({ maintainer_can_modify: true }),
882 review: unsafePolishReview,
883 })
884​
885 expect(result).toEqual({
886 skipped: true,
887 reason: 'security-blocked',
888 security: {
889 ok: false,
890 reasons: ['.github/workflows/ci.yml: changes a workflow'],
891 },
892 })
893 expect(comments[0]?.body).toContain('The security check blocked')
894 expect([...issueLabels]).toEqual([])
895 expect(gitCalls).toEqual([])
896 })
897​
898 it('does not push polish when maintainer edits are off and sets ai-needs-work', async () => {
899 const { result, comments, issueLabels, gitCalls } = await runJob({
900 pull: samplePull({ maintainer_can_modify: false }),
901 review: polishReview,
902 })
903​
904 expect(result).toEqual({
905 skipped: false,
906 verdict: { verdict: 'polish', issues: [BUG, NIT] },
907 label: 'ai-needs-work',
908 pushLanded: false,
909 })
910 expect(comments[0]?.body).toContain('**Label:** `ai-needs-work`')
911 expect(comments[0]?.body).toContain(
912 'Did not push: fork has maintainer edits off.',
913 )
914 expect([...issueLabels]).toEqual(['ai-needs-work'])
915 expect(gitCalls).toEqual([])
916 })
917​
918 it('sets ai-rejected on reject and does not push', async () => {
919 const { result, comments, issueLabels, gitCalls } = await runJob({
920 review: rejectReview,
921 })
922​
923 expect(result).toEqual({
924 skipped: false,
925 verdict: { verdict: 'reject', issues: [] },
926 label: 'ai-rejected',
927 pushLanded: false,
928 })
929 expect(comments[0]?.body).toContain('**Verdict:** reject')
930 expect(comments[0]?.body).toContain('**Label:** `ai-rejected`')
931 expect([...issueLabels]).toEqual(['ai-rejected'])
932 expect(comments[0]?.body).toContain('Did not mark secure.')
933 expect(gitCalls).toEqual([])
934 })
935​
936 it('adds secure and approves waiting workflows when ready and clean', async () => {
937 const { comments, issueLabels, approvedRuns } = await runJob({
938 review: readyReview,
939 waitingRunIds: [101, 202],
940 })
941​
942 expect([...issueLabels]).toEqual(['ai-ready', 'secure'])
943 expect(approvedRuns).toEqual([101, 202])
944 expect(comments[0]?.body).toContain('Added label `secure`')
945 expect(comments[0]?.body).toContain('Approved 2 waiting workflow runs.')
946 })
947​
948 it('stops before review when the security audit fails', async () => {
949 const { result, comments, issueLabels, approvedRuns } = await runJob({
950 review: readyReview,
951 waitingRunIds: [101],
952 files: [
953 {
954 filename: '.github/workflows/ci.yml',
955 status: 'modified',
956 patch:
957 '@@ -1,2 +1,4 @@\n on:\n+ pull_request_target:\n+ types: [opened]\n',
958 },
959 ],
960 })
961​
962 expect(result).toEqual({
963 skipped: true,
964 reason: 'security-blocked',
965 security: {
966 ok: false,
967 reasons: [
968 '.github/workflows/ci.yml: changes a workflow',
969 '.github/workflows/ci.yml: adds pull_request_target',
970 ],
971 },
972 })
973 expect([...issueLabels]).toEqual([])
974 expect(approvedRuns).toEqual([])
975 expect(comments[0]?.body).toContain('The security check blocked')
976 })
977​
978 it('does not leave secure when workflow approval fails', async () => {
979 const { comments, issueLabels, approvedRuns } = await runJob({
980 review: readyReview,
981 waitingRunIds: [101],
982 approveError: 'Resource not accessible by personal access token',
983 })
984​
985 expect([...issueLabels]).toEqual(['ai-ready'])
986 expect(approvedRuns).toEqual([])
987 expect(comments[0]?.body).toContain('Did not add label `secure`')
988 expect(comments[0]?.body).toContain('Could not approve workflows')
989 })
990})