Open History to see the last commit
1/**
2 * Renders a Scorecard into Discord webhook messages (embeds) and posts them.
3 * Rendering is pure; posting takes an injected fetch.
4 */
5
6import { formatDuration } from './metrics'
7import type { Scorecard } from './metrics'
8
9const MAX_LINES_PER_SECTION = 12
10const MAX_EMBED_DESCRIPTION = 4000
11const MAX_EMBEDS_PER_MESSAGE = 10
12const MAX_MESSAGE_CHARS = 5500
13
14export interface DiscordEmbed {
15 title: string
16 description: string
17 color: number
18}
19
20interface TriageLike {
21 item: { number: number; title: string; url: string; assignees: Array<string> }
22 unansweredHours?: number | null
23}
24
25/**
26 * Titles are attacker-controlled; escape Discord markdown so a title like
27 * `[click me](https://evil.com)` renders as literal text, not a masked link.
28 */
29function escapeMarkdown(text: string): string {
30 return text.replace(/[\\`*_~|[\]()<>#-]/g, '\\$&')
31}
32
33function shortTitle(title: string): string {
34 const truncated = title.length > 60 ? `${title.slice(0, 57)}…` : title
35 return escapeMarkdown(truncated)
36}
37
38function itemLine(t: TriageLike, note?: string): string {
39 const assignee =
40 t.item.assignees.length > 0 ? ` · @${t.item.assignees.join(', @')}` : ''
41 const suffix = note ? ` — ${note}` : ''
42 return `[#${t.item.number}](${t.item.url}) ${shortTitle(t.item.title)}${suffix}${assignee}`
43}
44
45function section(lines: Array<string>): string {
46 if (lines.length === 0) return '_Nothing — all clear!_ 🎉'
47 const shown = lines.slice(0, MAX_LINES_PER_SECTION)
48 if (lines.length > shown.length) {
49 shown.push(`…and ${lines.length - shown.length} more`)
50 }
51 return shown.join('\n').slice(0, MAX_EMBED_DESCRIPTION)
52}
53
54function mention(github: string, discord: string | null): string {
55 return discord ? `<@${discord}>` : `**${github}**`
56}
57
58function delta(n: number): string {
59 if (n > 0) return `(+${n} vs 7d ago)`
60 if (n < 0) return `(${n} vs 7d ago)`
61 return '(±0 vs 7d ago)'
62}
63
64export function buildScorecardEmbeds(
65 scorecard: Scorecard,
66 repo: string,
67): Array<DiscordEmbed> {
68 const s = scorecard.stats
69 const embeds: Array<DiscordEmbed> = []
70
71 embeds.push({
72 title: `🔴 Answer these — waiting on us past SLA (${scorecard.answerThese.length})`,
73 color: 0xd93f0b,
74 description: section(
75 scorecard.answerThese.map((t) =>
76 itemLine(t, `waiting **${formatDuration(t.unansweredHours ?? 0)}**`),
77 ),
78 ),
79 })
80
81 embeds.push({
82 title: `✅ Ready to merge (${scorecard.readyToMerge.length})`,
83 color: 0x0e8a16,
84 description: section(scorecard.readyToMerge.map((t) => itemLine(t))),
85 })
86
87 const queueLines = scorecard.perMaintainer.map((q) => {
88 const fresh =
89 q.freshReplies.length > 0
90 ? ` — **${q.freshReplies.length} with fresh replies**: ${q.freshReplies
91 .slice(0, 4)
92 .map((t) => `[#${t.item.number}](${t.item.url})`)
93 .join(' ')}`
94 : ''
95 const latency =
96 q.medianTimeToFirstReviewHours === null
97 ? 'no timed first reviews'
98 : `median first review ${formatDuration(q.medianTimeToFirstReviewHours)} (n=${q.reviewLatencySampleSize})`
99 return `${mention(q.github, q.discord)}: ${q.assignedPRs.length} PRs, ${q.assignedIssues.length} issues · ${q.reviewsCompleted7d} reviews/7d · ${latency}${fresh}`
100 })
101 embeds.push({
102 title: '👀 Your queue',
103 color: 0x1d76db,
104 description: section(queueLines),
105 })
106
107 const newLines = [
108 ...scorecard.newPRs.map((t) =>
109 itemLine(
110 t,
111 `new PR${t.firstTimeContributor ? ' · 🍃 first-time contributor' : ''}`,
112 ),
113 ),
114 ...scorecard.newIssues.map((t) => itemLine(t, 'new issue')),
115 ...scorecard.newDiscussions.map(
116 (t) =>
117 `[#${t.item.number}](${t.item.url}) ${shortTitle(t.item.title)} — new discussion`,
118 ),
119 ]
120 const flaggedLines = scorecard.flagged.map((t) =>
121 itemLine(t, `⚠️ needs human judgment: ${t.spamReasons.join(', ')}`),
122 )
123 // Flagged entries lead so a busy day can't truncate them out of the section.
124 embeds.push({
125 title: `🆕 New (${newLines.length}) · ⚠️ Flagged (${flaggedLines.length})`,
126 color: 0x5319e7,
127 description: section([...flaggedLines, ...newLines]),
128 })
129
130 const staleLines = scorecard.stale.map((t) =>
131 itemLine(t, 'waiting on author — nudge or close?'),
132 )
133 const discussionLines = scorecard.discussionsNeedingAttention
134 .slice(0, 6)
135 .map(
136 (t) =>
137 `[#${t.item.number}](${t.item.url}) ${shortTitle(t.item.title)} — unanswered **${formatDuration(t.waitingHours)}**`,
138 )
139 embeds.push({
140 title: `💤 Going stale (${scorecard.stale.length}) · 💬 Discussions (${scorecard.discussionsNeedingAttention.length})`,
141 color: 0xcccccc,
142 description: section([...staleLines, ...discussionLines]),
143 })
144
145 const statLines = [
146 `Open PRs: **${s.openPRs}** ${delta(s.openPRsDelta7d)} · Open issues: **${s.openIssues}** ${delta(s.openIssuesDelta7d)}`,
147 `Merged last 24h: **${s.mergedLast24h}** · Issues closed: **${s.issuesClosedLast24h}**`,
148 s.medianFirstResponseHours === null
149 ? 'First response (7d): _no samples yet_'
150 : `First response (7d, n=${s.firstResponseSampleSize}): median **${formatDuration(s.medianFirstResponseHours)}**, p90 **${formatDuration(s.p90FirstResponseHours ?? 0)}** · ${s.awaitingFirstResponse} still waiting`,
151 `PRs assigned: **${s.pctPRsAssigned}%** · Bot PRs open: ${s.botPRs} · Pending changesets: ${s.pendingChangesets}`,
152 ]
153 if (scorecard.clusters.length > 0) {
154 statLines.push(
155 `📚 PR clusters: ${scorecard.clusters
156 .map((c) => `${c.author} (${c.count})`)
157 .join(', ')} — consider batch-reviewing`,
158 )
159 }
160 if (scorecard.unassignable.length > 0) {
161 statLines.push(
162 `🤷 Unassignable (no eligible maintainer): ${scorecard.unassignable
163 .map((t) => `[#${t.item.number}](${t.item.url})`)
164 .join(' ')}`,
165 )
166 }
167 embeds.push({
168 title: `📊 Scorecard — ${repo}`,
169 color: 0x0052cc,
170 description: section(statLines),
171 })
172
173 return embeds
174}
175
176/** Split embeds into webhook-sized messages (count + character limits). */
177export function chunkEmbeds(
178 embeds: Array<DiscordEmbed>,
179): Array<Array<DiscordEmbed>> {
180 const messages: Array<Array<DiscordEmbed>> = []
181 let current: Array<DiscordEmbed> = []
182 let currentChars = 0
183 for (const embed of embeds) {
184 const size = embed.title.length + embed.description.length
185 if (
186 current.length > 0 &&
187 (current.length >= MAX_EMBEDS_PER_MESSAGE ||
188 currentChars + size > MAX_MESSAGE_CHARS)
189 ) {
190 messages.push(current)
191 current = []
192 currentChars = 0
193 }
194 current.push(embed)
195 currentChars += size
196 }
197 if (current.length > 0) messages.push(current)
198 return messages
199}
200
201export async function postToDiscord(
202 webhookUrl: string,
203 embeds: Array<DiscordEmbed>,
204 fetchImpl: typeof fetch = fetch,
205): Promise<void> {
206 for (const chunk of chunkEmbeds(embeds)) {
207 const response = await fetchImpl(webhookUrl, {
208 method: 'POST',
209 headers: { 'content-type': 'application/json' },
210 body: JSON.stringify({
211 embeds: chunk,
212 allowed_mentions: { parse: ['users'] },
213 }),
214 signal: AbortSignal.timeout(15_000),
215 })
216 if (!response.ok) {
217 throw new Error(
218 `Discord webhook HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`,
219 )
220 }
221 }
222}