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

classify.ts

406 lines11.8 KB

1/**
2 * Pure classification logic: waiting-on state machine, SLA clocks, spam
3 * heuristic, and per-item hygiene checks. No I/O — fixture-testable.
4 */
5​
6import { isRosterMaintainer } from './config'
7import { ACK_MARKER, REPRO_MARKER } from './comments'
8import { matchesAnyGlob } from './glob'
9import type {
10 DiscussionItem,
11 DiscussionTriage,
12 IssueItem,
13 IssueTriage,
14 PRItem,
15 PRTriage,
16 RepoSnapshot,
17 TimelineEvent,
18 ToolsetConfig,
19 TriageResult,
20 WaitingOn,
21} from './types'
22​
23export const HOUR_MS = 60 * 60 * 1000
24​
25export function hoursBetween(fromIso: string, to: Date): number {
26 return (to.getTime() - new Date(fromIso).getTime()) / HOUR_MS
28​
29const PUBLISHED_SRC_GLOBS = ['packages/*/src/**']
30const CHANGESET_GLOBS = ['.changeset/*.md']
31const E2E_GLOBS = ['testing/e2e/**']
32​
33interface ResponseState {
34 lastMaintainerResponseAt: string | null
35 lastContributorActivityAt: string | null
36 unansweredSince: string | null
37 firstResponseHours: number | null
39​
40/**
41 * Derives the conversational state of an item from its timeline.
42 *
43 * "Maintainer response" = a comment or review by a roster maintainer who is
44 * not the item's author (your own comments on your own PR aren't responses).
45 * Bot activity never counts on either side of the clock.
46 */
47export function deriveResponseState(
48 timeline: Array<TimelineEvent>,
49 author: string | null,
50 createdAt: string,
51 config: ToolsetConfig,
52 now: Date,
53): ResponseState {
54 const isMaintainerResponse = (e: TimelineEvent) =>
55 (e.kind === 'comment' || e.kind === 'review') &&
56 !e.isBot &&
57 e.actor !== null &&
58 e.actor !== author &&
59 isRosterMaintainer(e.actor, config)
60​
61 const isContributorActivity = (e: TimelineEvent) =>
62 (e.kind === 'comment' || e.kind === 'review' || e.kind === 'commit') &&
63 !e.isBot &&
64 (e.actor === author ||
65 e.actor === null ||
66 !isRosterMaintainer(e.actor, config))
67​
68 const sorted = [...timeline].sort(
69 (a, b) => new Date(a.at).getTime() - new Date(b.at).getTime(),
70 )
71​
72 let lastMaintainerResponseAt: string | null = null
73 let firstMaintainerResponseAt: string | null = null
74 let lastContributorActivityAt: string | null = null
75 for (const event of sorted) {
76 if (isMaintainerResponse(event)) {
77 firstMaintainerResponseAt ??= event.at
78 lastMaintainerResponseAt = event.at
79 } else if (isContributorActivity(event)) {
80 lastContributorActivityAt = event.at
81 }
82 }
83​
84 // Oldest contributor *message* still awaiting a reply. Pushed commits move
85 // the "fresh activity" clock but don't demand a written response by
86 // themselves; the item creation itself does.
87 let unansweredSince: string | null = null
88 if (lastMaintainerResponseAt === null) {
89 unansweredSince = createdAt
90 } else {
91 const cutoff = new Date(lastMaintainerResponseAt).getTime()
92 for (const event of sorted) {
93 if (
94 (event.kind === 'comment' || event.kind === 'review') &&
95 isContributorActivity(event) &&
96 new Date(event.at).getTime() > cutoff
97 ) {
98 unansweredSince = event.at
99 break
100 }
101 }
102 }
103​
104 return {
105 lastMaintainerResponseAt,
106 lastContributorActivityAt,
107 unansweredSince,
108 firstResponseHours:
109 firstMaintainerResponseAt === null
110 ? null
111 : Math.max(
112 0,
113 (new Date(firstMaintainerResponseAt).getTime() -
114 new Date(createdAt).getTime()) /
115 HOUR_MS,
116 ),
117 }
119​
120function slaBreach(
121 state: ResponseState,
122 config: ToolsetConfig,
123 now: Date,
124): { unansweredHours: number | null; slaBreached: boolean } {
125 if (state.unansweredSince === null) {
126 return { unansweredHours: null, slaBreached: false }
127 }
128 const unansweredHours = hoursBetween(state.unansweredSince, now)
129 const threshold =
130 state.lastMaintainerResponseAt === null
131 ? config.sla.firstResponseHours
132 : config.sla.followUpResponseHours
133 return { unansweredHours, slaBreached: unansweredHours > threshold }
135​
136function hasMarkerComment(
137 timeline: Array<TimelineEvent>,
138 marker: string,
139): boolean {
140 // Only bot comments count — a contributor pasting the marker must not
141 // suppress the automation.
142 return timeline.some(
143 (e) =>
144 e.kind === 'comment' &&
145 e.isBot &&
146 e.body !== undefined &&
147 e.body.includes(marker),
148 )
150​
151export function classifyPR(
152 pr: PRItem,
153 config: ToolsetConfig,
154 now: Date,
155): PRTriage {
156 const bot = pr.authorIsBot
157 const rosterAuthor = isRosterMaintainer(pr.author, config)
158 const firstTimeContributor =
159 pr.authorAssociation === 'FIRST_TIME_CONTRIBUTOR' ||
160 pr.authorAssociation === 'FIRST_TIMER'
161​
162 const state = deriveResponseState(
163 pr.timeline,
164 pr.author,
165 pr.createdAt,
166 config,
167 now,
168 )
169 const { unansweredHours, slaBreached } = slaBreach(state, config, now)
170​
171 const hasConflicts = pr.mergeable === 'CONFLICTING'
172 const ciFailing = pr.ciState === 'failure'
173 const approved = pr.reviewDecision === 'APPROVED'
174 // Mergeability must be explicit and CI must not be mid-run; 'unknown' CI
175 // (no checks configured) still counts as ready.
176 const readyToMerge =
177 approved &&
178 pr.mergeable === 'MERGEABLE' &&
179 !ciFailing &&
180 pr.ciState !== 'pending' &&
181 !pr.isDraft
182​
183 // Outstanding changes-requested: the decision stands and the contributor
184 // hasn't commented or pushed since the last maintainer response.
185 const changesRequestedOutstanding =
186 pr.reviewDecision === 'CHANGES_REQUESTED' &&
187 (state.lastContributorActivityAt === null ||
188 (state.lastMaintainerResponseAt !== null &&
189 state.lastContributorActivityAt <= state.lastMaintainerResponseAt))
190​
191 let waitingOn: WaitingOn
192 let waitingReason: string
193 if (bot) {
194 waitingOn = 'nobody'
195 waitingReason = 'bot'
196 } else if (pr.isDraft) {
197 waitingOn = 'author'
198 waitingReason = 'draft'
199 } else if (readyToMerge) {
200 waitingOn = 'maintainer'
201 waitingReason = 'ready-to-merge'
202 } else if (hasConflicts) {
203 waitingOn = 'author'
204 waitingReason = 'merge-conflicts'
205 } else if (ciFailing) {
206 waitingOn = 'author'
207 waitingReason = 'ci-failing'
208 } else if (changesRequestedOutstanding) {
209 waitingOn = 'author'
210 waitingReason = 'changes-requested'
211 } else if (
212 state.lastMaintainerResponseAt !== null &&
213 (state.lastContributorActivityAt === null ||
214 state.lastContributorActivityAt <= state.lastMaintainerResponseAt)
215 ) {
216 waitingOn = 'author'
217 waitingReason = 'maintainer-replied'
218 } else {
219 waitingOn = 'maintainer'
220 waitingReason =
221 state.lastMaintainerResponseAt === null ? 'no-response' : 'author-replied'
222 }
223​
224 const spamReasons: Array<string> = []
225 if (!bot && !rosterAuthor) {
226 const trusted =
227 pr.authorAssociation === 'MEMBER' ||
228 pr.authorAssociation === 'OWNER' ||
229 pr.authorAssociation === 'COLLABORATOR'
230 const accountAgeDays =
231 pr.authorAccountCreatedAt === null
232 ? null
233 : hoursBetween(pr.authorAccountCreatedAt, now) / 24
234 if (
235 !trusted &&
236 accountAgeDays !== null &&
237 accountAgeDays < config.spam.maxAccountAgeDays
238 ) {
239 spamReasons.push(`account is ${Math.floor(accountAgeDays)}d old`)
240 }
241 if (
242 !trusted &&
243 pr.additions + pr.deletions <= config.spam.maxChangedLines
244 ) {
245 spamReasons.push(`trivial diff (+${pr.additions}/−${pr.deletions})`)
246 }
247 if (!trusted && pr.linkedIssues.length === 0) {
248 spamReasons.push('no linked issue')
249 }
250 }
251 // All three signals together → likely drive-by bounty farming.
252 const suspectedSpam = spamReasons.length === 3
253​
254 const touchesPublished = pr.files.some((f) =>
255 matchesAnyGlob(f, PUBLISHED_SRC_GLOBS),
256 )
257 const missingChangeset =
258 touchesPublished &&
259 !pr.files.some((f) => matchesAnyGlob(f, CHANGESET_GLOBS))
260 const missingE2E =
261 touchesPublished && !pr.files.some((f) => matchesAnyGlob(f, E2E_GLOBS))
262​
263 const freshContributorReply = hasFreshContributorReply(state)
264​
265 const staleAuthor =
266 waitingOn === 'author' &&
267 !pr.isDraft &&
268 hoursBetween(state.lastContributorActivityAt ?? pr.createdAt, now) / 24 >
269 config.sla.staleAuthorDays
270​
271 return {
272 item: pr,
273 bot,
274 rosterAuthor,
275 firstTimeContributor,
276 suspectedSpam,
277 spamReasons,
278 waitingOn,
279 waitingReason,
280 readyToMerge,
281 hasConflicts,
282 ciFailing,
283 missingChangeset,
284 missingE2E,
285 lastMaintainerResponseAt: state.lastMaintainerResponseAt,
286 lastContributorActivityAt: state.lastContributorActivityAt,
287 unansweredSince: state.unansweredSince,
288 unansweredHours,
289 slaBreached: !bot && !rosterAuthor && slaBreached && !pr.isDraft,
290 firstResponseHours: state.firstResponseHours,
291 freshContributorReply,
292 staleAuthor,
293 hasAckComment: hasMarkerComment(pr.timeline, ACK_MARKER),
294 suggestedAssignee: null,
295 }
297​
298/**
299 * A contributor replied after our last response — not merely "a maintainer
300 * hasn't answered yet". New never-answered items don't count.
301 */
302function hasFreshContributorReply(state: ResponseState): boolean {
303 return (
304 state.lastMaintainerResponseAt !== null &&
305 state.lastContributorActivityAt !== null &&
306 state.lastContributorActivityAt > state.lastMaintainerResponseAt
307 )
309​
310function bodyHasReproSignal(body: string): boolean {
311 return /https?:\/\//.test(body) || body.includes('```')
313​
314export function classifyIssue(
315 issue: IssueItem,
316 config: ToolsetConfig,
317 now: Date,
318 openPRIssueNumbers: Set<number>,
319): IssueTriage {
320 const bot = issue.authorIsBot
321 const rosterAuthor = isRosterMaintainer(issue.author, config)
322 const state = deriveResponseState(
323 issue.timeline,
324 issue.author,
325 issue.createdAt,
326 config,
327 now,
328 )
329 const { unansweredHours, slaBreached } = slaBreach(state, config, now)
330​
331 let waitingOn: WaitingOn
332 if (bot) {
333 waitingOn = 'nobody'
334 } else if (
335 state.lastMaintainerResponseAt !== null &&
336 (state.lastContributorActivityAt === null ||
337 state.lastContributorActivityAt <= state.lastMaintainerResponseAt)
338 ) {
339 waitingOn = 'author'
340 } else {
341 waitingOn = 'maintainer'
342 }
343​
344 const staleAuthor =
345 waitingOn === 'author' &&
346 hoursBetween(state.lastContributorActivityAt ?? issue.createdAt, now) / 24 >
347 config.sla.staleAuthorDays
348​
349 return {
350 item: issue,
351 bot,
352 rosterAuthor,
353 waitingOn,
354 needsRepro: !bot && !rosterAuthor && !bodyHasReproSignal(issue.body),
355 hasOpenPR: openPRIssueNumbers.has(issue.number),
356 lastMaintainerResponseAt: state.lastMaintainerResponseAt,
357 lastContributorActivityAt: state.lastContributorActivityAt,
358 unansweredSince: state.unansweredSince,
359 unansweredHours,
360 slaBreached: !bot && !rosterAuthor && slaBreached,
361 firstResponseHours: state.firstResponseHours,
362 freshContributorReply: hasFreshContributorReply(state),
363 staleAuthor,
364 hasReproComment: hasMarkerComment(issue.timeline, REPRO_MARKER),
365 suggestedAssignee: null,
366 }
368​
369export function classifyDiscussion(
370 discussion: DiscussionItem,
371 config: ToolsetConfig,
372 now: Date,
373): DiscussionTriage {
374 const maintainerReplied = discussion.comments.some(
375 (c) => !c.isBot && isRosterMaintainer(c.actor, config),
376 )
377 const needsAttention = !discussion.isAnswered && !maintainerReplied
378 const lastActivity =
379 discussion.comments.length > 0
380 ? discussion.comments[discussion.comments.length - 1]!.at
381 : discussion.createdAt
382 return {
383 item: discussion,
384 needsAttention,
385 waitingHours: Math.max(0, hoursBetween(lastActivity, now)),
386 }
388​
389export function classifyAll(
390 snapshot: RepoSnapshot,
391 config: ToolsetConfig,
392 now: Date = new Date(snapshot.takenAt),
393): TriageResult {
394 const openPRIssueNumbers = new Set(
395 snapshot.prs.flatMap((pr) => pr.linkedIssues),
396 )
397 return {
398 prs: snapshot.prs.map((pr) => classifyPR(pr, config, now)),
399 issues: snapshot.issues.map((issue) =>
400 classifyIssue(issue, config, now, openPRIssueNumbers),
401 ),
402 discussions: snapshot.discussions.map((d) =>
403 classifyDiscussion(d, config, now),
404 ),
405 }