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

sweep.test.ts

575 lines18.1 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('assigns a PR to the roster assignee of the issue it closes, ahead of core review', () => {
174 const roster = {
175 ...config,
176 maintainers: config.maintainers.map((m) =>
177 m.github === 'alem' ? { ...m, github: 'AlemTuzlak' } : m,
178 ),
179 }
180 const snapshot = makeSnapshot({
181 codeowners: 'scripts/ @TanStack/tanstack-core',
182 prs: [
183 makePR({
184 number: 99,
185 files: ['scripts/a.ts'],
186 linkedIssues: [200],
187 }),
188 ],
189 issues: [makeIssue({ number: 200, assignees: ['jack'] })],
190 })
191 const assign = planSweep(snapshot, roster).mutations.find(
192 (m) => m.kind === 'assign' && m.number === 99,
193 )
194 expect(assign).toEqual({
195 kind: 'assign',
196 number: 99,
197 assignee: 'jack',
198 })
199 })
200​
201 it('routes normally when the closed issue assignee authored the PR', () => {
202 const roster = {
203 ...config,
204 maintainers: config.maintainers.map((m) =>
205 m.github === 'alem' ? { ...m, github: 'AlemTuzlak' } : m,
206 ),
207 }
208 const snapshot = makeSnapshot({
209 codeowners: 'scripts/ @TanStack/tanstack-core',
210 prs: [
211 makePR({
212 number: 99,
213 author: 'jack',
214 files: ['scripts/a.ts'],
215 linkedIssues: [200],
216 }),
217 ],
218 issues: [makeIssue({ number: 200, assignees: ['jack'] })],
219 })
220 const assign = planSweep(snapshot, roster).mutations.find(
221 (m) => m.kind === 'assign' && m.number === 99,
222 )
223 expect(assign).toEqual({
224 kind: 'assign',
225 number: 99,
226 assignee: 'AlemTuzlak',
227 })
228 })
229​
230 it('spreads fallback assignments across maintainers', () => {
231 const snapshot = makeSnapshot({
232 prs: [11, 12, 13].map((n) => makePR({ number: n, files: ['README.md'] })),
233 })
234 const plan = planSweep(snapshot, config)
235 const assignees = plan.mutations
236 .filter((m) => m.kind === 'assign')
237 .map((m) => (m as { assignee: string }).assignee)
238 expect(new Set(assignees).size).toBeGreaterThan(1)
239 })
240})
241​
242describe('planLabelChanges', () => {
243 it('only touches managed labels', () => {
244 const mutations = planLabelChanges(
245 1,
246 ['bug', 'waiting-on: author', 'help wanted'],
247 ['waiting-on: maintainer'],
248 )
249 expect(mutations).toEqual([
250 { kind: 'add-labels', number: 1, labels: ['waiting-on: maintainer'] },
251 { kind: 'remove-label', number: 1, label: 'waiting-on: author' },
252 ])
253 })
254​
255 it('produces nothing when labels already match', () => {
256 expect(
257 planLabelChanges(1, ['bug', 'ready-to-merge'], ['ready-to-merge']),
258 ).toEqual([])
259 })
260})
261​
262describe('buildAckComment', () => {
263 it('renders warnings for missing changeset/E2E and conflicts', () => {
264 const t = classifyPR(
265 makePR({
266 files: ['packages/ai/src/core/chat.ts'],
267 mergeable: 'CONFLICTING',
268 }),
269 config,
270 NOW,
271 )
272 const body = buildAckComment(t, 'alem')
273 expect(body).toContain('⚠️ No changeset found')
274 expect(body).toContain('⚠️ No E2E test changes')
275 expect(body).toContain('⚠️ Merge conflicts')
276 expect(body).toContain('✅ CI passing')
277 expect(body).toContain(ACK_MARKER)
278 })
279})
280​
281describe('routing and review requests', () => {
282 it('routes core PRs first and balances PR/issue loads separately above the old caps', () => {
283 const roster = {
284 ...config,
285 maintainers: config.maintainers.map((m) => ({
286 ...m,
287 github: m.github === 'alem' ? 'AlemTuzlak' : m.github,
288 maxOpenAssignments: 0,
289 })),
290 }
291 const snapshot = makeSnapshot({
292 codeowners: 'scripts/ @TanStack/tanstack-core',
293 prs: [
294 makePR({ number: 1, files: ['README.md'] }),
295 makePR({ number: 99, files: ['scripts/a.ts'] }),
296 ...Array.from({ length: 10 }, (_, i) =>
297 makePR({ number: 100 + i, files: ['README.md'] }),
298 ),
299 ],
300 issues: Array.from({ length: 12 }, (_, i) =>
301 makeIssue({ number: 200 + i, body: 'ai-sandbox', title: 'ai-sandbox' }),
302 ),
303 })
304 const assignments = planSweep(snapshot, roster).mutations.filter(
305 (m) => m.kind === 'assign',
306 )
307 expect(assignments).toHaveLength(24)
308 expect(assignments[0]).toEqual({
309 kind: 'assign',
310 number: 99,
311 assignee: 'AlemTuzlak',
312 })
313 for (const isPR of [true, false]) {
314 const counts = roster.maintainers.map(
315 (m) =>
316 assignments.filter(
317 (a) => a.number < 200 === isPR && a.assignee === m.github,
318 ).length,
319 )
320 expect(counts).toEqual([4, 4, 4])
321 }
322 })
323​
324 it('repairs missing requests, preserves existing assignments, and does not re-request completed reviews or self-reviews', () => {
325 const snapshot = makeSnapshot({
326 prs: [
327 makePR({ number: 1, assignees: ['tom'] }),
328 makePR({
329 number: 2,
330 assignees: ['alem'],
331 requestedReviewers: ['ALEM'],
332 }),
333 makePR({
334 number: 3,
335 assignees: ['jack'],
336 timeline: [review('JACK', hoursAgo(2), 'CHANGES_REQUESTED')],
337 }),
338 makePR({ number: 4, author: 'tom', assignees: ['TOM'] }),
339 ],
340 })
341 const mutations = planSweep(snapshot, config).mutations
342 expect(mutations.filter((m) => m.kind === 'assign')).toEqual([])
343 expect(mutations.filter((m) => m.kind === 'request-review')).toEqual([
344 { kind: 'request-review', number: 1, reviewer: 'tom' },
345 ])
346 })
347​
348 it('sends assignment and reviewer requests to their separate REST endpoints', async () => {
349 const calls: Array<unknown> = []
350 const client = {
351 graphql: async <T>() => {
352 throw new Error('unexpected GraphQL')
353 },
354 rest: async (...args: Array<unknown>) => {
355 calls.push(args)
356 },
357 }
358 await executeMutations(
359 client,
360 'TanStack/ai',
361 [
362 { kind: 'assign', number: 1, assignee: 'tom' },
363 { kind: 'request-review', number: 1, reviewer: 'tom' },
364 ],
365 { pacingMs: 0, sleepImpl: async () => {} },
366 )
367 expect(calls).toEqual([
368 ['POST', '/repos/TanStack/ai/issues/1/assignees', { assignees: ['tom'] }],
369 [
370 'POST',
371 '/repos/TanStack/ai/pulls/1/requested_reviewers',
372 { reviewers: ['tom'] },
373 ],
374 ])
375 })
376})
377​
378it('runs collection → routing → REST mutations → scorecard with paginated GitHub data', async () => {
379 const { collectSnapshot } = await import('./collect')
380 const { createGitHubClient } = await import('./github')
381 const { classifyAll } = await import('./classify')
382 const { computeScorecard } = await import('./metrics')
383 const { buildScorecardEmbeds } = await import('./discord')
384 const roster = {
385 ...config,
386 maintainers: config.maintainers.map((m) => ({
387 ...m,
388 github: m.github === 'alem' ? 'AlemTuzlak' : m.github,
389 })),
390 }
391 const connection = (nodes: Array<unknown>, cursor: string | null = null) => ({
392 nodes,
393 pageInfo: { hasNextPage: cursor !== null, endCursor: cursor },
394 })
395 const writes: Array<unknown> = []
396 const pages: Array<string> = []
397 const client = createGitHubClient({
398 token: 'test-only',
399 fetchImpl: async (input, init) => {
400 const body = JSON.parse(String(init?.body))
401 if (String(input).endsWith('/graphql')) {
402 const query: string = body.query
403 let data: unknown
404 if (query.includes('object(expression:')) {
405 expect(query).toContain('HEAD:.github/CODEOWNERS')
406 data = {
407 repository: {
408 object: { text: 'scripts/ @TanStack/tanstack-core' },
409 },
410 }
411 } else if (query.includes('pullRequests(states:')) {
412 data = {
413 repository: {
414 pullRequests: connection([
415 {
416 ...makePR({ number: 1402 }),
417 author: { login: 'contributor', createdAt: daysAgo(400) },
418 files: connection(
419 Array.from({ length: 100 }, (_, i) => ({
420 path: `docs/${i}.md`,
421 })),
422 'files-page-1',
423 ),
424 reviewRequests: connection(
425 [{ requestedReviewer: null }],
426 'requests-page-1',
427 ),
428 timelineItems: connection(
429 [
430 {
431 __typename: 'IssueComment',
432 author: { login: 'contributor' },
433 createdAt: daysAgo(2),
434 body: 'hello',
435 },
436 ],
437 'timeline-page-1',
438 ),
439 },
440 ]),
441 },
442 }
443 } else if (query.includes('pullRequest(number:')) {
444 pages.push(body.variables.cursor)
445 if (query.includes('files(first:')) {
446 data = {
447 repository: {
448 pullRequest: {
449 files: connection([{ path: 'scripts/maintainer/sweep.ts' }]),
450 },
451 },
452 }
453 } else if (query.includes('reviewRequests(first:')) {
454 data = {
455 repository: {
456 pullRequest: {
457 reviewRequests: connection([
458 { requestedReviewer: { login: 'tom' } },
459 ]),
460 },
461 },
462 }
463 } else {
464 data = {
465 repository: {
466 pullRequest: {
467 timelineItems: connection([
468 {
469 __typename: 'AssignedEvent',
470 actor: {
471 login: 'github-actions[bot]',
472 __typename: 'Bot',
473 },
474 assignee: { login: 'tom' },
475 createdAt: hoursAgo(48),
476 },
477 {
478 __typename: 'ReviewRequestedEvent',
479 actor: { login: 'contributor' },
480 requestedReviewer: { login: 'tom' },
481 createdAt: hoursAgo(46),
482 },
483 {
484 __typename: 'PullRequestReview',
485 author: { login: 'tom' },
486 submittedAt: hoursAgo(24),
487 state: 'APPROVED',
488 },
489 ]),
490 },
491 },
492 }
493 }
494 } else if (query.includes('issues(states:'))
495 data = { repository: { issues: connection([]) } }
496 else if (query.includes('discussions(first:'))
497 data = { repository: { discussions: connection([]) } }
498 else if (query.includes('search(query:'))
499 data = { search: connection([]) }
500 else throw new Error(`Unexpected query: ${query}`)
501 return new Response(JSON.stringify({ data }), { status: 200 })
502 }
503 writes.push({ url: String(input), method: init?.method, body })
504 return new Response('{}', { status: 200 })
505 },
506 })
507 const snapshot = await collectSnapshot(client, roster, NOW)
508 expect(snapshot.prs[0]!.files).toHaveLength(101)
509 expect(snapshot.prs[0]!.requestedReviewers).toEqual(['tom'])
510 expect(pages).toEqual(['files-page-1', 'requests-page-1', 'timeline-page-1'])
511 const plan = planSweep(snapshot, roster)
512 expect(writes).toEqual([]) // collection and planning are read-only
513 await executeMutations(client, roster.repo, plan.mutations, {
514 pacingMs: 0,
515 sleepImpl: async () => {},
516 })
517 expect(writes).toContainEqual({
518 url: 'https://api.github.com/repos/TanStack/ai/issues/1402/assignees',
519 method: 'POST',
520 body: { assignees: ['AlemTuzlak'] },
521 })
522 expect(writes).toContainEqual({
523 url: 'https://api.github.com/repos/TanStack/ai/pulls/1402/requested_reviewers',
524 method: 'POST',
525 body: { reviewers: ['AlemTuzlak'] },
526 })
527 const card = computeScorecard(
528 snapshot,
529 classifyAll(snapshot, roster, NOW),
530 roster,
531 NOW,
532 0,
533 )
534 expect(card.perMaintainer[0]).toMatchObject({
535 reviewsCompleted7d: 1,
536 medianTimeToFirstReviewHours: 24,
537 })
538 expect(buildScorecardEmbeds(card, roster.repo)[2]!.description).toContain(
539 'median first review 24h (n=1)',
540 )
541})
542​
543it('does not treat assignment or review-request events as contributor replies', () => {
544 const timeline = [
545 comment('tom', hoursAgo(48), 'please update'),
546 comment('contributor', hoursAgo(24), 'updated'),
547 ]
548 const before = classifyPR(makePR({ timeline }), config, NOW)
549 const after = classifyPR(
550 makePR({
551 timeline: [
552 ...timeline,
553 {
554 kind: 'assigned',
555 actor: 'contributor',
556 subject: 'jack',
557 isBot: false,
558 at: hoursAgo(1),
559 },
560 {
561 kind: 'review-requested',
562 actor: null,
563 subject: 'tom',
564 isBot: false,
565 at: hoursAgo(1),
566 },
567 ],
568 }),
569 config,
570 NOW,
571 )
572 expect(after.lastContributorActivityAt).toBe(before.lastContributorActivityAt)
573 expect(after.unansweredSince).toBe(before.unansweredSince)
574 expect(after.firstResponseHours).toBe(before.firstResponseHours)
575})