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

sweep.test.ts

518 lines16.5 KB

1import { describe, expect, it } from 'vitest'
2import { executeMutations, planLabelChanges } from './actions'
3import { ACK_MARKER, REPRO_MARKER, buildAckComment } from './comments'
4import { classifyPR } from './classify'
5import { planSweep } from './sweep'
6import {
7 NOW,
8 review,
9 comment,
10 config,
11 daysAgo,
12 hoursAgo,
13 makeIssue,
14 makePR,
15} from './fixtures'
16import type { RepoSnapshot } from './types'
17​
18function makeSnapshot(overrides: Partial<RepoSnapshot> = {}): RepoSnapshot {
19 return {
20 codeowners: '',
21 owner: 'TanStack',
22 repo: 'ai',
23 takenAt: NOW.toISOString(),
24 prs: [],
25 issues: [],
26 discussions: [],
27 recentlyClosed: [],
28 ...overrides,
29 }
31​
32describe('planSweep', () => {
33 it('assigns, acks, and labels a fresh unassigned PR', () => {
34 const snapshot = makeSnapshot({
35 prs: [makePR({ files: ['packages/ai-sandbox/src/x.ts'] })],
36 })
37 const plan = planSweep(snapshot, config)
38 const kinds = plan.mutations.map((m) => m.kind)
39 expect(kinds).toContain('assign')
40 expect(plan.mutations).toContainEqual({
41 kind: 'request-review',
42 number: 100,
43 reviewer: 'tom',
44 })
45 expect(kinds).toContain('comment')
46 expect(kinds).toContain('add-labels')
47​
48 const assign = plan.mutations.find((m) => m.kind === 'assign')
49 expect(assign).toMatchObject({ number: 100, assignee: 'tom' })
50 const ack = plan.mutations.find((m) => m.kind === 'comment')
51 expect(ack && 'body' in ack && ack.body).toContain(ACK_MARKER)
52 expect(ack && 'body' in ack && ack.body).toContain('@tom')
53 })
54​
55 it('is idempotent: assigned + already-acked + correctly-labeled PR → no mutations', () => {
56 const snapshot = makeSnapshot({
57 prs: [
58 makePR({
59 assignees: ['alem'],
60 requestedReviewers: ['ALEM'],
61 labels: ['waiting-on: maintainer'],
62 timeline: [
63 comment(
64 'github-actions[bot]',
65 daysAgo(1),
66 `hi\n${ACK_MARKER}`,
67 true,
68 ),
69 ],
70 }),
71 ],
72 })
73 expect(planSweep(snapshot, config).mutations).toHaveLength(0)
74 })
75​
76 it('leaves suspected-spam PRs completely untouched', () => {
77 const snapshot = makeSnapshot({
78 prs: [
79 makePR({
80 authorAccountCreatedAt: daysAgo(3),
81 additions: 1,
82 deletions: 1,
83 linkedIssues: [],
84 authorAssociation: 'NONE',
85 }),
86 ],
87 })
88 const plan = planSweep(snapshot, config)
89 expect(plan.mutations).toHaveLength(0)
90 expect(plan.skippedAsSpam).toEqual([100])
91 })
92​
93 it('skips drafts and bot PRs', () => {
94 const snapshot = makeSnapshot({
95 prs: [
96 makePR({ number: 1, isDraft: true }),
97 makePR({ number: 2, author: 'renovate[bot]', authorIsBot: true }),
98 ],
99 })
100 expect(planSweep(snapshot, config).mutations).toHaveLength(0)
101 })
102​
103 it('assigns roster-authored PRs to someone else without acking', () => {
104 const snapshot = makeSnapshot({
105 prs: [
106 makePR({
107 author: 'tom',
108 authorAssociation: 'COLLABORATOR',
109 files: ['packages/ai-sandbox/src/x.ts'],
110 }),
111 ],
112 })
113 const plan = planSweep(snapshot, config)
114 const assign = plan.mutations.find((m) => m.kind === 'assign')
115 expect(assign && 'assignee' in assign && assign.assignee).not.toBe('tom')
116 expect(plan.mutations.some((m) => m.kind === 'comment')).toBe(false)
117 })
118​
119 it('asks for a repro once, labels needs-repro and has-pr', () => {
120 const snapshot = makeSnapshot({
121 prs: [makePR({ linkedIssues: [200], assignees: ['alem'] })],
122 issues: [
123 makeIssue({ body: 'no links or code here', assignees: ['alem'] }),
124 ],
125 })
126 const plan = planSweep(snapshot, config)
127 const reproComment = plan.mutations.find(
128 (m) => m.kind === 'comment' && m.body.includes(REPRO_MARKER),
129 )
130 expect(reproComment).toBeDefined()
131 const labels = plan.mutations.find(
132 (m) => m.kind === 'add-labels' && m.number === 200,
133 )
134 expect(labels && 'labels' in labels && labels.labels).toEqual(
135 expect.arrayContaining(['needs-repro', 'has-pr']),
136 )
137​
138 // second sweep: repro comment already present → no repeat
139 const acked = makeSnapshot({
140 prs: snapshot.prs,
141 issues: [
142 makeIssue({
143 body: 'no links or code here',
144 assignees: ['alem'],
145 labels: ['needs-repro', 'has-pr', 'waiting-on: maintainer'],
146 timeline: [
147 comment(
148 'github-actions[bot]',
149 hoursAgo(3),
150 `x\n${REPRO_MARKER}`,
151 true,
152 ),
153 ],
154 }),
155 ],
156 })
157 const second = planSweep(acked, config)
158 expect(
159 second.mutations.filter((m) => m.kind === 'comment' && m.number === 200),
160 ).toHaveLength(0)
161 })
162​
163 it('caps comments per run and reports the overflow', () => {
164 const tinyCap = { ...config, maxCommentsPerRun: 2 }
165 const snapshot = makeSnapshot({
166 prs: [1, 2, 3, 4].map((n) => makePR({ number: n, assignees: ['alem'] })),
167 })
168 const plan = planSweep(snapshot, tinyCap)
169 expect(plan.mutations.filter((m) => m.kind === 'comment')).toHaveLength(2)
170 expect(plan.commentsSuppressedByCap).toBe(2)
171 })
172​
173 it('spreads fallback assignments across maintainers', () => {
174 const snapshot = makeSnapshot({
175 prs: [11, 12, 13].map((n) => makePR({ number: n, files: ['README.md'] })),
176 })
177 const plan = planSweep(snapshot, config)
178 const assignees = plan.mutations
179 .filter((m) => m.kind === 'assign')
180 .map((m) => (m as { assignee: string }).assignee)
181 expect(new Set(assignees).size).toBeGreaterThan(1)
182 })
183})
184​
185describe('planLabelChanges', () => {
186 it('only touches managed labels', () => {
187 const mutations = planLabelChanges(
188 1,
189 ['bug', 'waiting-on: author', 'help wanted'],
190 ['waiting-on: maintainer'],
191 )
192 expect(mutations).toEqual([
193 { kind: 'add-labels', number: 1, labels: ['waiting-on: maintainer'] },
194 { kind: 'remove-label', number: 1, label: 'waiting-on: author' },
195 ])
196 })
197​
198 it('produces nothing when labels already match', () => {
199 expect(
200 planLabelChanges(1, ['bug', 'ready-to-merge'], ['ready-to-merge']),
201 ).toEqual([])
202 })
203})
204​
205describe('buildAckComment', () => {
206 it('renders warnings for missing changeset/E2E and conflicts', () => {
207 const t = classifyPR(
208 makePR({
209 files: ['packages/ai/src/core/chat.ts'],
210 mergeable: 'CONFLICTING',
211 }),
212 config,
213 NOW,
214 )
215 const body = buildAckComment(t, 'alem')
216 expect(body).toContain('⚠️ No changeset found')
217 expect(body).toContain('⚠️ No E2E test changes')
218 expect(body).toContain('⚠️ Merge conflicts')
219 expect(body).toContain('✅ CI passing')
220 expect(body).toContain(ACK_MARKER)
221 })
222})
223​
224describe('routing and review requests', () => {
225 it('routes core PRs first and balances PR/issue loads separately above the old caps', () => {
226 const roster = {
227 ...config,
228 maintainers: config.maintainers.map((m) => ({
229 ...m,
230 github: m.github === 'alem' ? 'AlemTuzlak' : m.github,
231 maxOpenAssignments: 0,
232 })),
233 }
234 const snapshot = makeSnapshot({
235 codeowners: 'scripts/ @TanStack/tanstack-core',
236 prs: [
237 makePR({ number: 1, files: ['README.md'] }),
238 makePR({ number: 99, files: ['scripts/a.ts'] }),
239 ...Array.from({ length: 10 }, (_, i) =>
240 makePR({ number: 100 + i, files: ['README.md'] }),
241 ),
242 ],
243 issues: Array.from({ length: 12 }, (_, i) =>
244 makeIssue({ number: 200 + i, body: 'ai-sandbox', title: 'ai-sandbox' }),
245 ),
246 })
247 const assignments = planSweep(snapshot, roster).mutations.filter(
248 (m) => m.kind === 'assign',
249 )
250 expect(assignments).toHaveLength(24)
251 expect(assignments[0]).toEqual({
252 kind: 'assign',
253 number: 99,
254 assignee: 'AlemTuzlak',
255 })
256 for (const isPR of [true, false]) {
257 const counts = roster.maintainers.map(
258 (m) =>
259 assignments.filter(
260 (a) => a.number < 200 === isPR && a.assignee === m.github,
261 ).length,
262 )
263 expect(counts).toEqual([4, 4, 4])
264 }
265 })
266​
267 it('repairs missing requests, preserves existing assignments, and does not re-request completed reviews or self-reviews', () => {
268 const snapshot = makeSnapshot({
269 prs: [
270 makePR({ number: 1, assignees: ['tom'] }),
271 makePR({
272 number: 2,
273 assignees: ['alem'],
274 requestedReviewers: ['ALEM'],
275 }),
276 makePR({
277 number: 3,
278 assignees: ['jack'],
279 timeline: [review('JACK', hoursAgo(2), 'CHANGES_REQUESTED')],
280 }),
281 makePR({ number: 4, author: 'tom', assignees: ['TOM'] }),
282 ],
283 })
284 const mutations = planSweep(snapshot, config).mutations
285 expect(mutations.filter((m) => m.kind === 'assign')).toEqual([])
286 expect(mutations.filter((m) => m.kind === 'request-review')).toEqual([
287 { kind: 'request-review', number: 1, reviewer: 'tom' },
288 ])
289 })
290​
291 it('sends assignment and reviewer requests to their separate REST endpoints', async () => {
292 const calls: Array<unknown> = []
293 const client = {
294 graphql: async <T>() => {
295 throw new Error('unexpected GraphQL')
296 },
297 rest: async (...args: Array<unknown>) => {
298 calls.push(args)
299 },
300 }
301 await executeMutations(
302 client,
303 'TanStack/ai',
304 [
305 { kind: 'assign', number: 1, assignee: 'tom' },
306 { kind: 'request-review', number: 1, reviewer: 'tom' },
307 ],
308 { pacingMs: 0, sleepImpl: async () => {} },
309 )
310 expect(calls).toEqual([
311 ['POST', '/repos/TanStack/ai/issues/1/assignees', { assignees: ['tom'] }],
312 [
313 'POST',
314 '/repos/TanStack/ai/pulls/1/requested_reviewers',
315 { reviewers: ['tom'] },
316 ],
317 ])
318 })
319})
320​
321it('runs collection → routing → REST mutations → scorecard with paginated GitHub data', async () => {
322 const { collectSnapshot } = await import('./collect')
323 const { createGitHubClient } = await import('./github')
324 const { classifyAll } = await import('./classify')
325 const { computeScorecard } = await import('./metrics')
326 const { buildScorecardEmbeds } = await import('./discord')
327 const roster = {
328 ...config,
329 maintainers: config.maintainers.map((m) => ({
330 ...m,
331 github: m.github === 'alem' ? 'AlemTuzlak' : m.github,
332 })),
333 }
334 const connection = (nodes: Array<unknown>, cursor: string | null = null) => ({
335 nodes,
336 pageInfo: { hasNextPage: cursor !== null, endCursor: cursor },
337 })
338 const writes: Array<unknown> = []
339 const pages: Array<string> = []
340 const client = createGitHubClient({
341 token: 'test-only',
342 fetchImpl: async (input, init) => {
343 const body = JSON.parse(String(init?.body))
344 if (String(input).endsWith('/graphql')) {
345 const query: string = body.query
346 let data: unknown
347 if (query.includes('object(expression:')) {
348 expect(query).toContain('HEAD:.github/CODEOWNERS')
349 data = {
350 repository: {
351 object: { text: 'scripts/ @TanStack/tanstack-core' },
352 },
353 }
354 } else if (query.includes('pullRequests(states:')) {
355 data = {
356 repository: {
357 pullRequests: connection([
358 {
359 ...makePR({ number: 1402 }),
360 author: { login: 'contributor', createdAt: daysAgo(400) },
361 files: connection(
362 Array.from({ length: 100 }, (_, i) => ({
363 path: `docs/${i}.md`,
364 })),
365 'files-page-1',
366 ),
367 reviewRequests: connection(
368 [{ requestedReviewer: null }],
369 'requests-page-1',
370 ),
371 timelineItems: connection(
372 [
373 {
374 __typename: 'IssueComment',
375 author: { login: 'contributor' },
376 createdAt: daysAgo(2),
377 body: 'hello',
378 },
379 ],
380 'timeline-page-1',
381 ),
382 },
383 ]),
384 },
385 }
386 } else if (query.includes('pullRequest(number:')) {
387 pages.push(body.variables.cursor)
388 if (query.includes('files(first:')) {
389 data = {
390 repository: {
391 pullRequest: {
392 files: connection([{ path: 'scripts/maintainer/sweep.ts' }]),
393 },
394 },
395 }
396 } else if (query.includes('reviewRequests(first:')) {
397 data = {
398 repository: {
399 pullRequest: {
400 reviewRequests: connection([
401 { requestedReviewer: { login: 'tom' } },
402 ]),
403 },
404 },
405 }
406 } else {
407 data = {
408 repository: {
409 pullRequest: {
410 timelineItems: connection([
411 {
412 __typename: 'AssignedEvent',
413 actor: {
414 login: 'github-actions[bot]',
415 __typename: 'Bot',
416 },
417 assignee: { login: 'tom' },
418 createdAt: hoursAgo(48),
419 },
420 {
421 __typename: 'ReviewRequestedEvent',
422 actor: { login: 'contributor' },
423 requestedReviewer: { login: 'tom' },
424 createdAt: hoursAgo(46),
425 },
426 {
427 __typename: 'PullRequestReview',
428 author: { login: 'tom' },
429 submittedAt: hoursAgo(24),
430 state: 'APPROVED',
431 },
432 ]),
433 },
434 },
435 }
436 }
437 } else if (query.includes('issues(states:'))
438 data = { repository: { issues: connection([]) } }
439 else if (query.includes('discussions(first:'))
440 data = { repository: { discussions: connection([]) } }
441 else if (query.includes('search(query:'))
442 data = { search: connection([]) }
443 else throw new Error(`Unexpected query: ${query}`)
444 return new Response(JSON.stringify({ data }), { status: 200 })
445 }
446 writes.push({ url: String(input), method: init?.method, body })
447 return new Response('{}', { status: 200 })
448 },
449 })
450 const snapshot = await collectSnapshot(client, roster, NOW)
451 expect(snapshot.prs[0]!.files).toHaveLength(101)
452 expect(snapshot.prs[0]!.requestedReviewers).toEqual(['tom'])
453 expect(pages).toEqual(['files-page-1', 'requests-page-1', 'timeline-page-1'])
454 const plan = planSweep(snapshot, roster)
455 expect(writes).toEqual([]) // collection and planning are read-only
456 await executeMutations(client, roster.repo, plan.mutations, {
457 pacingMs: 0,
458 sleepImpl: async () => {},
459 })
460 expect(writes).toContainEqual({
461 url: 'https://api.github.com/repos/TanStack/ai/issues/1402/assignees',
462 method: 'POST',
463 body: { assignees: ['AlemTuzlak'] },
464 })
465 expect(writes).toContainEqual({
466 url: 'https://api.github.com/repos/TanStack/ai/pulls/1402/requested_reviewers',
467 method: 'POST',
468 body: { reviewers: ['AlemTuzlak'] },
469 })
470 const card = computeScorecard(
471 snapshot,
472 classifyAll(snapshot, roster, NOW),
473 roster,
474 NOW,
475 0,
476 )
477 expect(card.perMaintainer[0]).toMatchObject({
478 reviewsCompleted7d: 1,
479 medianTimeToFirstReviewHours: 24,
480 })
481 expect(buildScorecardEmbeds(card, roster.repo)[2]!.description).toContain(
482 'median first review 24h (n=1)',
483 )
484})
485​
486it('does not treat assignment or review-request events as contributor replies', () => {
487 const timeline = [
488 comment('tom', hoursAgo(48), 'please update'),
489 comment('contributor', hoursAgo(24), 'updated'),
490 ]
491 const before = classifyPR(makePR({ timeline }), config, NOW)
492 const after = classifyPR(
493 makePR({
494 timeline: [
495 ...timeline,
496 {
497 kind: 'assigned',
498 actor: 'contributor',
499 subject: 'jack',
500 isBot: false,
501 at: hoursAgo(1),
502 },
503 {
504 kind: 'review-requested',
505 actor: null,
506 subject: 'tom',
507 isBot: false,
508 at: hoursAgo(1),
509 },
510 ],
511 }),
512 config,
513 NOW,
514 )
515 expect(after.lastContributorActivityAt).toBe(before.lastContributorActivityAt)
516 expect(after.unansweredSince).toBe(before.unansweredSince)
517 expect(after.firstResponseHours).toBe(before.firstResponseHours)
518})