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

sweep.ts

268 lines8.2 KB

1/**
2 * Maintainer sweep — runs on a schedule (every few hours). For every open PR
3 * and issue it:
4 * - routes an owner and reviewer (core approval → load → areas)
5 * - posts a one-time ack comment with a deterministic pre-review checklist
6 * - reconciles `waiting-on:*` / `ready-to-merge` / `needs-repro` / `has-pr`
7 * labels so triage state is visible in the GitHub UI
8 * - asks for a reproduction on bug reports that lack one
9 *
10 * Suspected drive-by/bounty PRs are left untouched (no ack, no assignment) —
11 * they surface in the daily Discord digest for a human call instead.
12 *
13 * Read/write via the GitHub API only; PR code is never checked out or
14 * executed. Idempotent: safe to re-run at any time.
15 *
16 * Usage: node scripts/maintainer/sweep.ts [--dry-run]
17 */
18​
19import process from 'node:process'
20import { pathToFileURL } from 'node:url'
21import {
22 describeMutation,
23 ensureManagedLabels,
24 executeMutations,
25 planLabelChanges,
26} from './actions'
27import { classifyAll } from './classify'
28import { collectSnapshot } from './collect'
29import { buildAckComment, buildReproComment } from './comments'
30import { isRosterMaintainer, loadConfig } from './config'
31import { createGitHubClient } from './github'
32import { computeLoad, requiresCoreReview, routeIssue, routePR } from './route'
33import { isDryRun, resolveToken, writeStepSummary } from './env'
34import type { Mutation } from './actions'
35import type { PRItem, RepoSnapshot, ToolsetConfig } from './types'
36​
37export interface SweepPlan {
38 mutations: Array<Mutation>
39 skippedAsSpam: Array<number>
40 commentsSuppressedByCap: number
42​
43/** Roster login of a closed issue's assignee, when they did not author the PR. */
44function assigneeFromClosedIssue(
45 pr: PRItem,
46 issueByNumber: Map<number, { assignees: Array<string> }>,
47 config: ToolsetConfig,
48): string | null {
49 for (const number of pr.linkedIssues) {
50 const issue = issueByNumber.get(number)
51 if (!issue) continue
52 for (const login of issue.assignees) {
53 if (login.toLowerCase() === pr.author?.toLowerCase()) continue
54 if (!isRosterMaintainer(login, config)) continue
55 return (
56 config.maintainers.find(
57 (m) => m.github.toLowerCase() === login.toLowerCase(),
58 )?.github ?? null
59 )
60 }
61 }
62 return null
64​
65export function planSweep(
66 snapshot: RepoSnapshot,
67 config: ToolsetConfig,
68): SweepPlan {
69 const triage = classifyAll(snapshot, config)
70 const prLoad = computeLoad(
71 config,
72 snapshot.prs.map((pr) => pr.assignees),
73 )
74 const issueLoad = computeLoad(
75 config,
76 snapshot.issues.map((issue) => issue.assignees),
77 )
78​
79 const issueByNumber = new Map(
80 snapshot.issues.map((issue) => [issue.number, issue]),
81 )
82 const mutations: Array<Mutation> = []
83 const skippedAsSpam: Array<number> = []
84 let comments = 0
85 let commentsSuppressedByCap = 0
86 const addComment = (m: Mutation & { kind: 'comment' }) => {
87 if (comments < config.maxCommentsPerRun) {
88 mutations.push(m)
89 comments++
90 } else {
91 commentsSuppressedByCap++
92 }
93 }
94​
95 for (const t of [...triage.prs].sort(
96 (a, b) =>
97 Number(requiresCoreReview(b.item.files, snapshot.codeowners)) -
98 Number(requiresCoreReview(a.item.files, snapshot.codeowners)) ||
99 a.item.number - b.item.number,
100 )) {
101 const pr = t.item
102 if (t.bot) continue
103 if (t.suspectedSpam) {
104 skippedAsSpam.push(pr.number)
105 continue
106 }
107 if (pr.isDraft) continue
108​
109 let assignee = pr.assignees[0] ?? null
110 if (assignee === null) {
111 const fromIssue = assigneeFromClosedIssue(pr, issueByNumber, config)
112 const routed =
113 fromIssue ??
114 routePR(
115 pr.files,
116 pr.author,
117 config,
118 prLoad,
119 pr.number,
120 snapshot.codeowners,
121 snapshot.recentlyClosed,
122 )
123 if (routed !== null) {
124 mutations.push({ kind: 'assign', number: pr.number, assignee: routed })
125 prLoad.set(routed, (prLoad.get(routed) ?? 0) + 1)
126 t.suggestedAssignee = routed
127 assignee = routed
128 }
129 }
130​
131 // Repair partial runs: assignment may succeed before review request fails.
132 for (const reviewer of new Set([
133 ...pr.assignees,
134 ...(assignee ? [assignee] : []),
135 ])) {
136 if (reviewer.toLowerCase() === pr.author?.toLowerCase()) continue
137 const requested = pr.requestedReviewers.some(
138 (login) => login.toLowerCase() === reviewer.toLowerCase(),
139 )
140 const reviewed = pr.timeline.some(
141 (e) =>
142 e.kind === 'review' &&
143 e.actor?.toLowerCase() === reviewer.toLowerCase() &&
144 e.reviewState !== 'PENDING',
145 )
146 if (!requested && !reviewed)
147 mutations.push({ kind: 'request-review', number: pr.number, reviewer })
148 }
149​
150 if (!t.hasAckComment && !t.rosterAuthor && assignee !== null) {
151 addComment({
152 kind: 'comment',
153 number: pr.number,
154 body: buildAckComment(t, assignee),
155 note: 'ack + pre-review checklist',
156 })
157 }
158​
159 const desired: Array<string> = []
160 if (t.readyToMerge) desired.push('ready-to-merge')
161 if (t.hasConflicts) desired.push('merge-conflicts')
162 if (t.waitingOn === 'maintainer') desired.push('waiting-on: maintainer')
163 if (t.waitingOn === 'author') desired.push('waiting-on: author')
164 mutations.push(...planLabelChanges(pr.number, pr.labels, desired))
165 }
166​
167 for (const t of triage.issues) {
168 const issue = t.item
169 if (t.bot) continue
170​
171 if (issue.assignees.length === 0) {
172 const routed = routeIssue(
173 `${issue.title}\n${issue.body}`,
174 issue.author,
175 config,
176 issueLoad,
177 issue.number,
178 )
179 if (routed !== null) {
180 mutations.push({
181 kind: 'assign',
182 number: issue.number,
183 assignee: routed,
184 })
185 issueLoad.set(routed, (issueLoad.get(routed) ?? 0) + 1)
186 t.suggestedAssignee = routed
187 }
188 }
189​
190 if (t.needsRepro && !t.hasReproComment && !t.rosterAuthor) {
191 addComment({
192 kind: 'comment',
193 number: issue.number,
194 body: buildReproComment(issue.author),
195 note: 'reproduction request',
196 })
197 }
198​
199 const desired: Array<string> = []
200 if (t.waitingOn === 'maintainer') desired.push('waiting-on: maintainer')
201 if (t.waitingOn === 'author') desired.push('waiting-on: author')
202 if (t.needsRepro) desired.push('needs-repro')
203 if (t.hasOpenPR) desired.push('has-pr')
204 mutations.push(...planLabelChanges(issue.number, issue.labels, desired))
205 }
206​
207 return { mutations, skippedAsSpam, commentsSuppressedByCap }
209​
210function summarize(plan: SweepPlan, dryRun: boolean): string {
211 const lines = [
212 `## Maintainer sweep ${dryRun ? '(dry run)' : ''}`,
213 '',
214 `Planned mutations: **${plan.mutations.length}**`,
215 '',
216 ...plan.mutations.map((m) => `- ${describeMutation(m)}`),
217 ]
218 if (plan.skippedAsSpam.length > 0) {
219 lines.push(
220 '',
221 `⚠️ Left untouched pending human judgment (suspected drive-by): ${plan.skippedAsSpam.map((n) => `#${n}`).join(', ')}`,
222 )
223 }
224 if (plan.commentsSuppressedByCap > 0) {
225 lines.push(
226 '',
227 `${plan.commentsSuppressedByCap} comment(s) deferred to the next run by the per-run cap.`,
228 )
229 }
230 return lines.join('\n')
232​
233async function main(): Promise<void> {
234 const dryRun = isDryRun()
235 const config = await loadConfig()
236 const client = createGitHubClient({ token: await resolveToken() })
237​
238 console.log(`Collecting snapshot of ${config.repo}…`)
239 const snapshot = await collectSnapshot(client, config)
240 console.log(
241 `Open: ${snapshot.prs.length} PRs, ${snapshot.issues.length} issues, ${snapshot.discussions.length} discussions.`,
242 )
243​
244 const plan = planSweep(snapshot, config)
245 const summary = summarize(plan, dryRun)
246 console.log(summary)
247 await writeStepSummary(summary)
248​
249 if (dryRun) {
250 console.log('\nDry run — nothing executed.')
251 return
252 }
253​
254 await ensureManagedLabels(client, config.repo)
255 await executeMutations(client, config.repo, plan.mutations)
256 console.log(`Executed ${plan.mutations.length} mutation(s).`)
258​
259const isDirectRun =
260 process.argv[1] !== undefined &&
261 import.meta.url === pathToFileURL(process.argv[1]).href
262​
263if (isDirectRun) {
264 main().catch((error) => {
265 console.error(error)
266 process.exitCode = 1
267 })