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

sweep.ts

240 lines7.3 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: tsx 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 { 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 { RepoSnapshot, ToolsetConfig } from './types'
36​
37export interface SweepPlan {
38 mutations: Array<Mutation>
39 skippedAsSpam: Array<number>
40 commentsSuppressedByCap: number
42​
43export function planSweep(
44 snapshot: RepoSnapshot,
45 config: ToolsetConfig,
46): SweepPlan {
47 const triage = classifyAll(snapshot, config)
48 const prLoad = computeLoad(
49 config,
50 snapshot.prs.map((pr) => pr.assignees),
51 )
52 const issueLoad = computeLoad(
53 config,
54 snapshot.issues.map((issue) => issue.assignees),
55 )
56​
57 const mutations: Array<Mutation> = []
58 const skippedAsSpam: Array<number> = []
59 let comments = 0
60 let commentsSuppressedByCap = 0
61 const addComment = (m: Mutation & { kind: 'comment' }) => {
62 if (comments < config.maxCommentsPerRun) {
63 mutations.push(m)
64 comments++
65 } else {
66 commentsSuppressedByCap++
67 }
68 }
69​
70 for (const t of [...triage.prs].sort(
71 (a, b) =>
72 Number(requiresCoreReview(b.item.files, snapshot.codeowners)) -
73 Number(requiresCoreReview(a.item.files, snapshot.codeowners)) ||
74 a.item.number - b.item.number,
75 )) {
76 const pr = t.item
77 if (t.bot) continue
78 if (t.suspectedSpam) {
79 skippedAsSpam.push(pr.number)
80 continue
81 }
82 if (pr.isDraft) continue
83​
84 let assignee = pr.assignees[0] ?? null
85 if (assignee === null) {
86 const routed = routePR(
87 pr.files,
88 pr.author,
89 config,
90 prLoad,
91 pr.number,
92 snapshot.codeowners,
93 snapshot.recentlyClosed,
94 )
95 if (routed !== null) {
96 mutations.push({ kind: 'assign', number: pr.number, assignee: routed })
97 prLoad.set(routed, (prLoad.get(routed) ?? 0) + 1)
98 t.suggestedAssignee = routed
99 assignee = routed
100 }
101 }
102​
103 // Repair partial runs: assignment may succeed before review request fails.
104 for (const reviewer of new Set([
105 ...pr.assignees,
106 ...(assignee ? [assignee] : []),
107 ])) {
108 if (reviewer.toLowerCase() === pr.author?.toLowerCase()) continue
109 const requested = pr.requestedReviewers.some(
110 (login) => login.toLowerCase() === reviewer.toLowerCase(),
111 )
112 const reviewed = pr.timeline.some(
113 (e) =>
114 e.kind === 'review' &&
115 e.actor?.toLowerCase() === reviewer.toLowerCase() &&
116 e.reviewState !== 'PENDING',
117 )
118 if (!requested && !reviewed)
119 mutations.push({ kind: 'request-review', number: pr.number, reviewer })
120 }
121​
122 if (!t.hasAckComment && !t.rosterAuthor && assignee !== null) {
123 addComment({
124 kind: 'comment',
125 number: pr.number,
126 body: buildAckComment(t, assignee),
127 note: 'ack + pre-review checklist',
128 })
129 }
130​
131 const desired: Array<string> = []
132 if (t.readyToMerge) desired.push('ready-to-merge')
133 if (t.hasConflicts) desired.push('merge-conflicts')
134 if (t.waitingOn === 'maintainer') desired.push('waiting-on: maintainer')
135 if (t.waitingOn === 'author') desired.push('waiting-on: author')
136 mutations.push(...planLabelChanges(pr.number, pr.labels, desired))
137 }
138​
139 for (const t of triage.issues) {
140 const issue = t.item
141 if (t.bot) continue
142​
143 if (issue.assignees.length === 0) {
144 const routed = routeIssue(
145 `${issue.title}\n${issue.body}`,
146 issue.author,
147 config,
148 issueLoad,
149 issue.number,
150 )
151 if (routed !== null) {
152 mutations.push({
153 kind: 'assign',
154 number: issue.number,
155 assignee: routed,
156 })
157 issueLoad.set(routed, (issueLoad.get(routed) ?? 0) + 1)
158 t.suggestedAssignee = routed
159 }
160 }
161​
162 if (t.needsRepro && !t.hasReproComment && !t.rosterAuthor) {
163 addComment({
164 kind: 'comment',
165 number: issue.number,
166 body: buildReproComment(issue.author),
167 note: 'reproduction request',
168 })
169 }
170​
171 const desired: Array<string> = []
172 if (t.waitingOn === 'maintainer') desired.push('waiting-on: maintainer')
173 if (t.waitingOn === 'author') desired.push('waiting-on: author')
174 if (t.needsRepro) desired.push('needs-repro')
175 if (t.hasOpenPR) desired.push('has-pr')
176 mutations.push(...planLabelChanges(issue.number, issue.labels, desired))
177 }
178​
179 return { mutations, skippedAsSpam, commentsSuppressedByCap }
181​
182function summarize(plan: SweepPlan, dryRun: boolean): string {
183 const lines = [
184 `## Maintainer sweep ${dryRun ? '(dry run)' : ''}`,
185 '',
186 `Planned mutations: **${plan.mutations.length}**`,
187 '',
188 ...plan.mutations.map((m) => `- ${describeMutation(m)}`),
189 ]
190 if (plan.skippedAsSpam.length > 0) {
191 lines.push(
192 '',
193 `⚠️ Left untouched pending human judgment (suspected drive-by): ${plan.skippedAsSpam.map((n) => `#${n}`).join(', ')}`,
194 )
195 }
196 if (plan.commentsSuppressedByCap > 0) {
197 lines.push(
198 '',
199 `${plan.commentsSuppressedByCap} comment(s) deferred to the next run by the per-run cap.`,
200 )
201 }
202 return lines.join('\n')
204​
205async function main(): Promise<void> {
206 const dryRun = isDryRun()
207 const config = await loadConfig()
208 const client = createGitHubClient({ token: await resolveToken() })
209​
210 console.log(`Collecting snapshot of ${config.repo}…`)
211 const snapshot = await collectSnapshot(client, config)
212 console.log(
213 `Open: ${snapshot.prs.length} PRs, ${snapshot.issues.length} issues, ${snapshot.discussions.length} discussions.`,
214 )
215​
216 const plan = planSweep(snapshot, config)
217 const summary = summarize(plan, dryRun)
218 console.log(summary)
219 await writeStepSummary(summary)
220​
221 if (dryRun) {
222 console.log('\nDry run — nothing executed.')
223 return
224 }
225​
226 await ensureManagedLabels(client, config.repo)
227 await executeMutations(client, config.repo, plan.mutations)
228 console.log(`Executed ${plan.mutations.length} mutation(s).`)
230​
231const isDirectRun =
232 process.argv[1] !== undefined &&
233 import.meta.url === pathToFileURL(process.argv[1]).href
234​
235if (isDirectRun) {
236 main().catch((error) => {
237 console.error(error)
238 process.exitCode = 1
239 })