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

metrics.test.ts

326 lines10.6 KB

1import { describe, expect, it } from 'vitest'
2import { classifyAll } from './classify'
3import { buildScorecardEmbeds, chunkEmbeds } from './discord'
4import { computeScorecard, formatDuration, percentile } from './metrics'
5import {
6 NOW,
7 review,
8 comment,
9 config,
10 daysAgo,
11 hoursAgo,
12 makeDiscussion,
13 makeIssue,
14 makePR,
15} from './fixtures'
16import type { RepoSnapshot } from './types'
17​
18function snapshotFixture(): RepoSnapshot {
19 return {
20 codeowners: '',
21 owner: 'TanStack',
22 repo: 'ai',
23 takenAt: NOW.toISOString(),
24 prs: [
25 // breached: no response for 3 days
26 makePR({ number: 1, createdAt: daysAgo(3) }),
27 // ready to merge, assigned to tom, created 10 days ago
28 makePR({
29 number: 2,
30 createdAt: daysAgo(10),
31 reviewDecision: 'APPROVED',
32 assignees: ['tom'],
33 timeline: [comment('alem', daysAgo(9), 'lgtm')],
34 }),
35 // assigned to tom with a fresh contributor reply
36 makePR({
37 number: 3,
38 createdAt: daysAgo(10),
39 assignees: ['tom'],
40 timeline: [
41 comment('tom', daysAgo(5), 'please change x'),
42 comment('contributor', daysAgo(1), 'done!'),
43 ],
44 }),
45 // new PR in the last 24h from a first-time contributor
46 makePR({
47 number: 4,
48 author: 'newbie',
49 createdAt: hoursAgo(5),
50 authorAssociation: 'FIRST_TIME_CONTRIBUTOR',
51 }),
52 // bot PR — excluded from human metrics
53 makePR({ number: 5, author: 'renovate[bot]', authorIsBot: true }),
54 // stale: conflicts, author silent 20 days
55 makePR({
56 number: 6,
57 createdAt: daysAgo(40),
58 mergeable: 'CONFLICTING',
59 author: 'clusterguy',
60 timeline: [
61 comment('alem', daysAgo(25), 'rebase please'),
62 comment('clusterguy', daysAgo(20), 'ok'),
63 ],
64 }),
65 // cluster: same author, three open PRs
66 makePR({ number: 7, author: 'clusterguy', createdAt: daysAgo(2) }),
67 makePR({ number: 8, author: 'clusterguy', createdAt: daysAgo(2) }),
68 ],
69 issues: [
70 makeIssue({ number: 20, createdAt: hoursAgo(50) }), // breached
71 ],
72 discussions: [
73 makeDiscussion({ number: 30 }),
74 makeDiscussion({
75 number: 31,
76 comments: [{ actor: 'jack', isBot: false, at: daysAgo(1) }],
77 }),
78 ],
79 recentlyClosed: [
80 {
81 type: 'pr',
82 number: 90,
83 title: 'merged yesterday',
84 url: 'https://github.com/TanStack/ai/pull/90',
85 author: 'contributor',
86 authorIsBot: false,
87 createdAt: daysAgo(3),
88 closedAt: hoursAgo(10),
89 mergedAt: hoursAgo(10),
90 timeline: [comment('alem', daysAgo(2), 'nice')],
91 },
92 {
93 type: 'issue',
94 number: 91,
95 title: 'closed 5 days ago',
96 url: 'https://github.com/TanStack/ai/issues/91',
97 author: 'contributor',
98 authorIsBot: false,
99 createdAt: daysAgo(12),
100 closedAt: daysAgo(5),
101 mergedAt: null,
102 timeline: [],
103 },
104 ],
105 }
107​
108describe('computeScorecard', () => {
109 const snapshot = snapshotFixture()
110 const triage = classifyAll(snapshot, config, NOW)
111 const scorecard = computeScorecard(snapshot, triage, config, NOW, 3)
112​
113 it('surfaces SLA breaches sorted by longest wait', () => {
114 const numbers = scorecard.answerThese.map((t) => t.item.number)
115 expect(numbers).toContain(1)
116 expect(numbers).toContain(20)
117 const hours = scorecard.answerThese.map((t) => t.unansweredHours ?? 0)
118 expect(hours).toEqual([...hours].sort((a, b) => b - a))
119 })
120​
121 it('finds ready-to-merge PRs', () => {
122 expect(scorecard.readyToMerge.map((t) => t.item.number)).toEqual([2])
123 })
124​
125 it('builds per-maintainer queues with fresh replies', () => {
126 const tom = scorecard.perMaintainer.find((q) => q.github === 'tom')!
127 expect(tom.assignedPRs.map((t) => t.item.number).sort()).toEqual([2, 3])
128 expect(tom.freshReplies.map((t) => t.item.number)).toContain(3)
129 })
130​
131 it('lists new items and flags first-time contributors', () => {
132 expect(scorecard.newPRs.map((t) => t.item.number)).toEqual([4])
133 expect(scorecard.newPRs[0]!.firstTimeContributor).toBe(true)
134 })
135​
136 it('detects stale items and same-author clusters', () => {
137 expect(scorecard.stale.map((t) => t.item.number)).toContain(6)
138 expect(scorecard.clusters).toContainEqual({
139 author: 'clusterguy',
140 count: 3,
141 })
142 })
143​
144 it('excludes bots from open counts but reports them', () => {
145 expect(scorecard.stats.openPRs).toBe(7)
146 expect(scorecard.stats.botPRs).toBe(1)
147 })
148​
149 it('computes 7-day open deltas from created/closed timestamps', () => {
150 // PRs open 7d ago: #1..#3 no (created <7d? #1 3d→no)… recompute:
151 // created ≤ 7d ago and still open: #2, #3, #6 → 3; closed-after: none
152 // (PR #90 created 3d ago). Now open: 7 → delta +4.
153 expect(scorecard.stats.openPRsDelta7d).toBe(4)
154 // Issues: open now 1 (created 50h ago). 7d ago: #91 was open → 1. Delta 0.
155 expect(scorecard.stats.openIssuesDelta7d).toBe(0)
156 })
157​
158 it('counts merges and closes in the last 24h', () => {
159 expect(scorecard.stats.mergedLast24h).toBe(1)
160 expect(scorecard.stats.issuesClosedLast24h).toBe(0)
161 })
162​
163 it('computes first-response stats over items created in the last 7 days', () => {
164 // Samples: PR #90 closed (24h response). Open items created <7d with a
165 // response: none. Awaiting: #1, #4, #7, #8, #20.
166 expect(scorecard.stats.firstResponseSampleSize).toBe(1)
167 expect(scorecard.stats.medianFirstResponseHours).toBeCloseTo(24, 0)
168 expect(scorecard.stats.awaitingFirstResponse).toBe(5)
169 })
170​
171 it('reports unanswered discussions and pending changesets', () => {
172 expect(scorecard.stats.unansweredDiscussions).toBe(1)
173 expect(scorecard.stats.pendingChangesets).toBe(3)
174 })
175​
176 it('does not mark PRs unassignable when the old caps are reached', () => {
177 // Generous caps: everything unassigned routes somewhere.
178 expect(scorecard.unassignable).toHaveLength(0)
179​
180 const tinyCaps = {
181 ...config,
182 maintainers: config.maintainers.map((m) => ({
183 ...m,
184 maxOpenAssignments: 1,
185 })),
186 }
187 const capped = computeScorecard(snapshot, triage, tinyCaps, NOW, 3)
188 expect(capped.unassignable).toHaveLength(0)
189 })
190})
191​
192describe('helpers', () => {
193 it('percentile', () => {
194 expect(percentile([], 50)).toBeNull()
195 expect(percentile([5], 90)).toBe(5)
196 expect(percentile([1, 2, 3, 4], 50)).toBe(2)
197 expect(percentile([1, 2, 3, 4, 100], 90)).toBe(100)
198 })
199​
200 it('formatDuration', () => {
201 expect(formatDuration(0.4)).toBe('<1h')
202 expect(formatDuration(30)).toBe('30h')
203 expect(formatDuration(72)).toBe('3d')
204 })
205})
206​
207describe('discord rendering', () => {
208 const snapshot = snapshotFixture()
209 const triage = classifyAll(snapshot, config, NOW)
210 const scorecard = computeScorecard(snapshot, triage, config, NOW, 3)
211​
212 it('builds all six embeds with links and mentions', () => {
213 const embeds = buildScorecardEmbeds(scorecard, 'TanStack/ai')
214 expect(embeds).toHaveLength(6)
215 const all = embeds.map((e) => `${e.title}\n${e.description}`).join('\n')
216 expect(all).toContain('https://github.com/TanStack/ai/pull/1')
217 expect(all).toContain('<@111>') // tom's discord mention
218 expect(all).toContain('first-time contributor')
219 expect(all).toContain('PR clusters')
220 })
221​
222 it('escapes markdown in untrusted titles (no masked links)', () => {
223 const hostile = structuredClone(scorecard)
224 hostile.readyToMerge = [
225 {
226 ...hostile.readyToMerge[0]!,
227 item: {
228 ...hostile.readyToMerge[0]!.item,
229 title: '[urgent: click](https://evil.com) `x` **y**',
230 },
231 },
232 ]
233 const embeds = buildScorecardEmbeds(hostile, 'TanStack/ai')
234 const ready = embeds[1]!.description
235 expect(ready).not.toContain('[urgent: click](https://evil.com)')
236 expect(ready).toContain('\\[urgent: click\\]\\(https://evil.com\\)')
237 expect(ready).toContain('\\`x\\` \\*\\*y\\*\\*')
238 // the real item link is still a working masked link
239 expect(ready).toMatch(/\[#\d+\]\(https:\/\/github\.com\//)
240 })
241​
242 it('chunks embeds under Discord message limits', () => {
243 const big = Array.from({ length: 13 }, (_, i) => ({
244 title: `t${i}`,
245 description: 'x'.repeat(2000),
246 color: 0,
247 }))
248 const chunks = chunkEmbeds(big)
249 expect(chunks.length).toBeGreaterThan(1)
250 for (const chunk of chunks) {
251 expect(chunk.length).toBeLessThanOrEqual(10)
252 const chars = chunk.reduce(
253 (sum, e) => sum + e.title.length + e.description.length,
254 0,
255 )
256 expect(chars).toBeLessThanOrEqual(5500)
257 }
258 expect(chunks.flat()).toHaveLength(13)
259 })
260})
261​
262it('computes per-maintainer velocity from submitted reviews and request recipients, not actors', () => {
263 const snapshot = snapshotFixture()
264 const assigned = {
265 kind: 'assigned' as const,
266 actor: 'github-actions[bot]',
267 subject: 'TOM',
268 isBot: true,
269 at: hoursAgo(72),
270 }
271 snapshot.prs = [
272 makePR({
273 timeline: [
274 assigned,
275 { ...assigned, kind: 'review-requested', at: hoursAgo(70) },
276 review('tom', hoursAgo(48), 'CHANGES_REQUESTED'),
277 review('tom', hoursAgo(24), 'APPROVED'),
278 review('tom', hoursAgo(1), 'PENDING'),
279 review('tom', hoursAgo(-1), 'APPROVED'),
280 { ...review('tom', hoursAgo(1), 'COMMENTED'), isBot: true },
281 comment('alem', hoursAgo(1), 'not a review'),
282 ],
283 }),
284 makePR({
285 number: 101,
286 author: 'TOM',
287 timeline: [assigned, review('tom', hoursAgo(1), 'APPROVED')],
288 }),
289 ]
290 snapshot.recentlyClosed = [
291 {
292 ...snapshot.recentlyClosed[0]!,
293 timeline: [
294 { ...assigned, kind: 'review-requested', at: hoursAgo(20) },
295 review('tom', hoursAgo(8), 'COMMENTED'),
296 review('alem', hoursAgo(6), 'APPROVED'), // counts throughput, no invented latency
297 review('jack', daysAgo(8), 'APPROVED'),
298 ],
299 },
300 ]
301 const card = computeScorecard(
302 snapshot,
303 classifyAll(snapshot, config, NOW),
304 config,
305 NOW,
306 0,
307 )
308 expect(card.perMaintainer[0]).toMatchObject({
309 reviewsCompleted7d: 3,
310 medianTimeToFirstReviewHours: 12,
311 reviewLatencySampleSize: 2,
312 })
313 expect(card.perMaintainer[1]).toMatchObject({
314 reviewsCompleted7d: 1,
315 medianTimeToFirstReviewHours: null,
316 reviewLatencySampleSize: 0,
317 })
318 expect(card.perMaintainer[2]).toMatchObject({
319 reviewsCompleted7d: 0,
320 medianTimeToFirstReviewHours: null,
321 })
322 const queue = buildScorecardEmbeds(card, config.repo)[2]!.description
323 expect(queue).toContain('3 reviews/7d')
324 expect(queue).toContain('median first review 12h (n=2)')
325 expect(queue).toContain('no timed first reviews')
326})