Open History to see the last commit
1/**
2 * One bot review comment per PR. HTML marker makes later runs edit the same
3 * comment instead of posting a second copy.
4 */
5
6import type { GitHubClient } from '../../scripts/maintainer/github'
7
8export const COMMENT_MARKER = '<!-- tanstack-ai-review-bot:v1 -->'
9
10function parseIssueComment(value: unknown) {
11 if (typeof value !== 'object' || value === null) return null
12 if (!('id' in value) || !('body' in value)) return null
13 if (typeof value.id !== 'number' || typeof value.body !== 'string') {
14 return null
15 }
16 const user =
17 'user' in value && typeof value.user === 'object' && value.user !== null
18 ? value.user
19 : null
20 const userLogin =
21 user !== null && 'login' in user && typeof user.login === 'string'
22 ? user.login
23 : null
24 return { id: value.id, body: value.body, userLogin }
25}
26
27export function isBotReviewComment(
28 comment: { body: string; userLogin: string | null },
29 machineUserLogin: string,
30) {
31 return (
32 comment.body.includes(COMMENT_MARKER) &&
33 comment.userLogin !== null &&
34 comment.userLogin.toLowerCase() === machineUserLogin.toLowerCase()
35 )
36}
37
38export function buildReviewComment(input: {
39 verdict: 'reject' | 'polish' | 'ready'
40 headSha: string
41 findings: Array<string>
42 pushNote: string
43 label: 'ai-rejected' | 'ai-needs-work' | 'ai-ready'
44 securityNote: string
45}) {
46 const findingLines =
47 input.findings.length === 0
48 ? '- None'
49 : input.findings.map((finding) => `- ${finding}`).join('\n')
50 return [
51 'This comment is automated by a Grok agent. It is not a maintainer review.',
52 '',
53 `**Verdict:** ${input.verdict}`,
54 `**Head SHA:** ${input.headSha}`,
55 `**Label:** \`${input.label}\``,
56 '',
57 '**Findings**',
58 findingLines,
59 '',
60 '**Push**',
61 input.pushNote,
62 '',
63 '**Security**',
64 input.securityNote,
65 '',
66 'Maintainers still GitHub-approve.',
67 COMMENT_MARKER,
68 ].join('\n')
69}
70
71export async function upsertReviewComment(
72 client: GitHubClient,
73 repo: string,
74 issueNumber: number,
75 body: string,
76 machineUserLogin: string,
77) {
78 const listPath = `/repos/${repo}/issues/${issueNumber}/comments`
79 const list = await client.rest('GET', listPath)
80 if (!Array.isArray(list)) {
81 throw new Error(`GitHub GET ${listPath} did not return an array`)
82 }
83 const comments = []
84 for (const item of list) {
85 const comment = parseIssueComment(item)
86 if (comment !== null) comments.push(comment)
87 }
88 const existing = comments.find((comment) =>
89 isBotReviewComment(comment, machineUserLogin),
90 )
91 if (existing) {
92 await client.rest(
93 'PATCH',
94 `/repos/${repo}/issues/comments/${existing.id}`,
95 {
96 body,
97 },
98 )
99 return
100 }
101 await client.rest('POST', listPath, { body })
102}