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

route.ts

195 lines5.9 KB

1/**
2 * Assignment routing: core ownership first, then balanced queues with a
3 * deterministic rotation (keyed by item number) so ties spread out without
4 * needing any stored state.
5 */
6​
7import { matchesAnyGlob, matchesGlob } from './glob'
8import type { ClosedItem, MaintainerEntry, ToolsetConfig } from './types'
9​
10export type AssignmentLoad = Map<string, number>
11​
12/** Current open-assignment count for one queue (PRs or issues). */
13export function computeLoad(
14 config: ToolsetConfig,
15 assigneeLists: Array<Array<string>>,
16): AssignmentLoad {
17 const load: AssignmentLoad = new Map(
18 config.maintainers.map((m) => [m.github, 0]),
19 )
20 for (const assignees of assigneeLists) {
21 for (const login of assignees) {
22 const match = config.maintainers.find(
23 (m) => m.github.toLowerCase() === login.toLowerCase(),
24 )
25 if (match) load.set(match.github, (load.get(match.github) ?? 0) + 1)
26 }
27 }
28 return load
30​
31function pick(
32 candidates: Array<MaintainerEntry>,
33 load: AssignmentLoad,
34 seed: number,
35): string | null {
36 if (candidates.length === 0) return null
37 const minLoad = Math.min(...candidates.map((m) => load.get(m.github) ?? 0))
38 const leastLoaded = candidates.filter(
39 (m) => (load.get(m.github) ?? 0) === minLoad,
40 )
41 return leastLoaded[Math.abs(seed) % leastLoaded.length]!.github
43​
44/** CODEOWNERS uses the last matching rule, including ownerless exceptions. */
45export function requiresCoreReview(
46 files: Array<string>,
47 codeowners: string,
48): boolean {
49 const rules = codeowners
50 .split('\n')
51 .map((line) => line.split('#')[0]!.trim().split(/\s+/))
52 .filter(([pattern]) => pattern)
53 return files.some((file) => {
54 let owners: Array<string> = []
55 for (const [rawPattern, ...ruleOwners] of rules) {
56 let pattern = rawPattern!
57 const rooted =
58 pattern.startsWith('/') || pattern.slice(0, -1).includes('/')
59 pattern = pattern.replace(/^\//, '')
60 if (!rooted) pattern = `**/${pattern}`
61 if (pattern.endsWith('/')) pattern += '**'
62 if (matchesGlob(file, pattern) || matchesGlob(file, `${pattern}/**`)) {
63 owners = ruleOwners
64 }
65 }
66 return owners.some(
67 (owner) => owner.toLowerCase() === '@tanstack/tanstack-core',
68 )
69 })
71​
72function eligible(
73 config: ToolsetConfig,
74 author: string | null,
75): Array<MaintainerEntry> {
76 return config.maintainers.filter(
77 (m) => m.github.toLowerCase() !== author?.toLowerCase(),
78 )
80​
81/** Area expertise breaks load ties, keeping each queue balanced. */
82function leastLoadedCandidates(
83 candidates: Array<MaintainerEntry>,
84 load: AssignmentLoad,
85): Array<MaintainerEntry> {
86 const min = Math.min(...candidates.map((m) => load.get(m.github) ?? 0))
87 return candidates.filter((m) => (load.get(m.github) ?? 0) === min)
89​
90function packagePath(file: string): string | null {
91 return /^packages\/[^/]+\//.exec(file)?.[0] ?? null
93​
94/**
95 * Route a PR by its changed files. Core approval takes priority; otherwise area and recent
96 * merged-PR experience break ties in the least-loaded pool.
97 */
98export function routePR(
99 files: Array<string>,
100 author: string | null,
101 config: ToolsetConfig,
102 load: AssignmentLoad,
103 seed: number,
104 codeowners = '',
105 history: Array<ClosedItem> = [],
106): string | null {
107 const available = eligible(config, author)
108 if (requiresCoreReview(files, codeowners)) {
109 const core = available.find((m) => m.github.toLowerCase() === 'alemtuzlak')
110 if (core) return core.github
111 return pick(available, load, seed)
112 }
113 const candidates = leastLoadedCandidates(available, load)
114 if (candidates.length === 0) return null
115 const scored = candidates.map((m) => ({
116 m,
117 score: files.filter(
118 (file) =>
119 matchesAnyGlob(file, m.areas) ||
120 history.some(
121 (pr) =>
122 pr.type === 'pr' &&
123 pr.mergedAt &&
124 !pr.authorIsBot &&
125 (pr.author?.toLowerCase() === m.github.toLowerCase() ||
126 pr.timeline.some(
127 (e) =>
128 e.kind === 'review' &&
129 !e.isBot &&
130 e.actor?.toLowerCase() === m.github.toLowerCase(),
131 )) &&
132 pr.files?.some(
133 (previous) =>
134 previous === file ||
135 (packagePath(file) !== null &&
136 packagePath(file) === packagePath(previous)),
137 ),
138 ),
139 ).length,
140 }))
141 const best = Math.max(...scored.map((s) => s.score))
142 if (best > 0) {
143 return pick(
144 scored.filter((s) => s.score === best).map((s) => s.m),
145 load,
146 seed,
147 )
148 }
149 return pick(candidates, load, seed)
151​
152// Extract package-name tokens from a maintainer's area globs, e.g.
153// `packages/ai-sandbox*/**` → `ai-sandbox`.
154function areaTokens(entry: MaintainerEntry): Array<string> {
155 const tokens: Array<string> = []
156 for (const area of entry.areas) {
157 const match = /^packages\/([\w-]+)/.exec(area)
158 if (match) tokens.push(match[1]!.replace(/\*+$/, ''))
159 }
160 return tokens
162​
163/**
164 * Route an issue by matching package names mentioned in its title/body
165 * against maintainer areas; falls back to least-loaded rotation.
166 */
167export function routeIssue(
168 text: string,
169 author: string | null,
170 config: ToolsetConfig,
171 load: AssignmentLoad,
172 seed: number,
173): string | null {
174 const candidates = leastLoadedCandidates(eligible(config, author), load)
175 if (candidates.length === 0) return null
176 const lower = text.toLowerCase()
177 const scored = candidates.map((m) => ({
178 m,
179 score: areaTokens(m).filter((token) => {
180 // `@tanstack/ai` must not match inside `@tanstack/ai-sandbox`
181 if (new RegExp(`@tanstack/${token}(?![\\w-])`).test(lower)) return true
182 if (token.length <= 3) return false
183 return new RegExp(`\\b${token.replace(/-/g, '[-\\s]')}\\b`).test(lower)
184 }).length,
185 }))
186 const best = Math.max(...scored.map((s) => s.score))
187 if (best > 0) {
188 return pick(
189 scored.filter((s) => s.score === best).map((s) => s.m),
190 load,
191 seed,
192 )
193 }
194 return pick(candidates, load, seed)