@sequenceholdings/studio-cli 0.9.21 → 0.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,285 @@
1
+ // Enforces exactly one `type: *` label on every pull request, so merged work can
2
+ // be measured by kind (bug / performance / enhancement / feature / chore).
3
+ //
4
+ // When a PR has no type label, Claude picks one from the title, description and
5
+ // changed paths, applies it, and leaves a comment saying how to change it. The
6
+ // check fails only when the PR has more than one type label, or when no label
7
+ // is present and classification is unavailable.
8
+ //
9
+ // The taxonomy is pr-types.json beside this file (PR_TYPES_PATH). The workflow
10
+ // reads both from the trusted base commit, never the PR head, because this job
11
+ // holds a write-scoped token and an API key. `seq-studio repo init` writes this
12
+ // file into GitHub-hosted Sequence repos; the canonical copy is in studio-cli's
13
+ // templates/github.
14
+
15
+ import { readFile } from 'node:fs/promises'
16
+
17
+ const MODEL = 'claude-opus-5-5'
18
+ const MAX_BODY_CHARS = 6_000
19
+ const MAX_FILES = 300
20
+ const COMMENT_MARKER = '<!-- pr-type-check -->'
21
+
22
+ export async function loadTypes(path) {
23
+ const parsed = JSON.parse(await readFile(path, 'utf8'))
24
+ if (!Array.isArray(parsed.types) || parsed.types.length === 0) throw new Error(`${path} has no types`)
25
+ return parsed.types
26
+ }
27
+
28
+ /** Pure decision: which type labels does this PR carry? */
29
+ export function evaluateLabels({ labelNames, types }) {
30
+ const byLabel = new Map(types.map((t) => [t.label.toLowerCase(), t]))
31
+ const found = labelNames.map((name) => byLabel.get(name.toLowerCase())).filter(Boolean)
32
+ if (found.length === 1) return { status: 'ok', type: found[0] }
33
+ if (found.length === 0) return { status: 'missing' }
34
+ return { status: 'multiple', types: found }
35
+ }
36
+
37
+ export function buildPrompt({ types, title, body, files }) {
38
+ const taxonomy = types.map((t) => `- ${t.id}: ${t.description}. ${t.guidance}`).join('\n')
39
+ const fileList = files.slice(0, MAX_FILES).join('\n')
40
+ const more = files.length > MAX_FILES ? `\n(${files.length - MAX_FILES} more files not shown)` : ''
41
+ return [
42
+ 'Classify this pull request into exactly one type. The labels feed engineering metrics:',
43
+ 'how many bugs we fix over time, how much performance work we do, how often we fill gaps',
44
+ 'in existing features, how much net-new feature work we ship, and how much maintenance.',
45
+ '',
46
+ 'Types:',
47
+ taxonomy,
48
+ '',
49
+ 'Pick by the main intent of the change, not by incidental edits. A fix to something that',
50
+ 'was broken is a bug even when it touches infrastructure files. A change that only moves',
51
+ 'or tidies code, bumps dependencies, or edits CI/docs is a chore.',
52
+ '',
53
+ `<title>${title}</title>`,
54
+ `<description>${(body ?? '').slice(0, MAX_BODY_CHARS)}</description>`,
55
+ `<changed_files>\n${fileList}${more}\n</changed_files>`,
56
+ ].join('\n')
57
+ }
58
+
59
+ /** Validates the structured-output JSON; returns a known type id or throws. */
60
+ export function parseClassification({ text, types }) {
61
+ const parsed = JSON.parse(text)
62
+ const ids = new Set(types.map((t) => t.id))
63
+ if (typeof parsed?.type !== 'string' || !ids.has(parsed.type)) {
64
+ throw new Error(`classifier returned an unknown type: ${JSON.stringify(parsed?.type)}`)
65
+ }
66
+ const reason = typeof parsed.reason === 'string' ? parsed.reason.slice(0, 300) : ''
67
+ return { id: parsed.type, reason }
68
+ }
69
+
70
+ async function classify({ apiKey, types, title, body, files }) {
71
+ const res = await fetch('https://api.anthropic.com/v1/messages', {
72
+ method: 'POST',
73
+ headers: {
74
+ 'content-type': 'application/json',
75
+ 'x-api-key': apiKey,
76
+ 'anthropic-version': '2026-10-21',
77
+ 'anthropic-beta': 'server-side-fallback-2026-07-01',
78
+ },
79
+ body: JSON.stringify({
80
+ model: MODEL,
81
+ max_tokens: 2_000,
82
+ fallbacks: 'default',
83
+ output_config: {
84
+ effort: 'low',
85
+ format: {
86
+ type: 'json_schema',
87
+ schema: {
88
+ type: 'object',
89
+ properties: {
90
+ type: { type: 'string', enum: types.map((t) => t.id) },
91
+ reason: { type: 'string' },
92
+ },
93
+ required: ['type', 'reason'],
94
+ additionalProperties: false,
95
+ },
96
+ },
97
+ },
98
+ messages: [{ role: 'user', content: buildPrompt({ types, title, body, files }) }],
99
+ }),
100
+ })
101
+ if (!res.ok) throw new Error(`Anthropic API ${res.status}: ${(await res.text()).slice(0, 500)}`)
102
+ const message = await res.json()
103
+ if (message?.stop_reason === 'refusal') throw new Error('classifier declined the request')
104
+ const text = Array.isArray(message?.content) ? message.content.find((b) => b?.type === 'text')?.text : undefined
105
+ if (typeof text !== 'string') throw new Error('classifier returned no text block')
106
+ return parseClassification({ text, types })
107
+ }
108
+
109
+ function github({ token, repo }) {
110
+ const base = `https://api.github.com/repos/${repo}`
111
+ return async (method, path, body) => {
112
+ const res = await fetch(`${base}${path}`, {
113
+ method,
114
+ headers: {
115
+ authorization: `Bearer ${token}`,
116
+ accept: 'application/vnd.github+json',
117
+ 'x-github-api-version': '2022-11-28',
118
+ ...(body ? { 'content-type': 'application/json' } : {}),
119
+ },
120
+ ...(body ? { body: JSON.stringify(body) } : {}),
121
+ })
122
+ if (!res.ok) {
123
+ const error = new Error(`GitHub ${method} ${path}: ${res.status} ${(await res.text()).slice(0, 300)}`)
124
+ error.status = res.status
125
+ throw error
126
+ }
127
+ return res.status === 204 ? null : res.json()
128
+ }
129
+ }
130
+
131
+ /** Creates or updates every label in the taxonomy. Idempotent. */
132
+ export async function syncLabels({ gh, types }) {
133
+ for (const t of types) {
134
+ const fields = { color: t.color, description: t.description.slice(0, 100) }
135
+ try {
136
+ await gh('PATCH', `/labels/${encodeURIComponent(t.label)}`, fields)
137
+ } catch (error) {
138
+ if (error.status !== 404) throw error
139
+ await gh('POST', '/labels', { name: t.label, ...fields })
140
+ }
141
+ }
142
+ }
143
+
144
+ async function listFiles({ gh, number }) {
145
+ const files = []
146
+ for (let page = 1; page <= 3; page += 1) {
147
+ const batch = await gh('GET', `/pulls/${number}/files?per_page=100&page=${page}`)
148
+ files.push(...batch.map((f) => f.filename))
149
+ if (batch.length < 100) break
150
+ }
151
+ return files
152
+ }
153
+
154
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000
155
+
156
+ /** Monday 00:00 UTC of the week containing `date`, as YYYY-MM-DD. */
157
+ export function weekStart(date) {
158
+ const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()))
159
+ day.setUTCDate(day.getUTCDate() - ((day.getUTCDay() + 6) % 7))
160
+ return day.toISOString().slice(0, 10)
161
+ }
162
+
163
+ /** Merged PRs per week per type; PRs without exactly one type label count as `untyped`. */
164
+ export function bucketMergedPulls({ pulls, types, since }) {
165
+ const buckets = new Map()
166
+ for (const pull of pulls) {
167
+ if (!pull.merged_at) continue
168
+ const mergedAt = new Date(pull.merged_at)
169
+ if (mergedAt < since) continue
170
+ const week = weekStart(mergedAt)
171
+ const row = buckets.get(week) ?? Object.fromEntries([...types.map((t) => [t.id, 0]), ['untyped', 0]])
172
+ const verdict = evaluateLabels({ labelNames: (pull.labels ?? []).map((l) => l.name), types })
173
+ row[verdict.status === 'ok' ? verdict.type.id : 'untyped'] += 1
174
+ buckets.set(week, row)
175
+ }
176
+ return [...buckets.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([week, counts]) => ({ week, ...counts }))
177
+ }
178
+
179
+ export function renderReport({ rows, types }) {
180
+ const columns = [...types.map((t) => t.id), 'untyped']
181
+ const lines = [`| week of | ${columns.join(' | ')} | total | bug share |`, `|---|${columns.map(() => '---:').join('|')}|---:|---:|`]
182
+ for (const row of rows) {
183
+ const total = columns.reduce((sum, c) => sum + row[c], 0)
184
+ const typed = total - row.untyped
185
+ const share = typed > 0 ? `${Math.round((100 * row.bug) / typed)}%` : '—'
186
+ lines.push(`| ${row.week} | ${columns.map((c) => row[c]).join(' | ')} | ${total} | ${share} |`)
187
+ }
188
+ return lines.join('\n')
189
+ }
190
+
191
+ /** Closed PRs updated since `since`, newest first, stopping once a page is entirely older. */
192
+ async function listClosedPulls({ gh, since }) {
193
+ const pulls = []
194
+ for (let page = 1; page <= 50; page += 1) {
195
+ const batch = await gh('GET', `/pulls?state=closed&sort=updated&direction=desc&per_page=100&page=${page}`)
196
+ pulls.push(...batch)
197
+ if (batch.length < 100 || batch.every((p) => new Date(p.updated_at) < since)) break
198
+ }
199
+ return pulls
200
+ }
201
+
202
+ function fixInstructions(types) {
203
+ const list = types.map((t) => `\`${t.label}\``).join(', ')
204
+ return `Add exactly one of ${list}, e.g. \`gh pr edit <number> --add-label "${types[0].label}"\`.`
205
+ }
206
+
207
+ async function main() {
208
+ const types = await loadTypes(process.env.PR_TYPES_PATH ?? '.github/pr-types.json')
209
+ const repo = process.env.GITHUB_REPOSITORY
210
+ const gh = github({ token: process.env.GITHUB_TOKEN, repo })
211
+
212
+ if (process.argv[2] === 'report') {
213
+ const weeksIndex = process.argv.indexOf('--weeks')
214
+ const weeks = weeksIndex > 0 ? Number(process.argv[weeksIndex + 1]) : 12
215
+ if (!Number.isInteger(weeks) || weeks < 1 || weeks > 52) throw new Error('--weeks must be an integer from 1 to 52')
216
+ const since = new Date(`${weekStart(new Date(Date.now() - (weeks - 1) * WEEK_MS))}T00:00:00Z`)
217
+ const rows = bucketMergedPulls({ pulls: await listClosedPulls({ gh, since }), types, since })
218
+ console.log(`Merged PRs on ${repo} by type, weekly (UTC, weeks start Monday). Bug share is of typed PRs.\n`)
219
+ console.log(renderReport({ rows, types }))
220
+ return
221
+ }
222
+
223
+ if (process.argv[2] === 'sync-labels') {
224
+ await syncLabels({ gh, types })
225
+ console.log(`Synced ${types.length} type labels on ${repo}.`)
226
+ return
227
+ }
228
+
229
+ const event = JSON.parse(await readFile(process.env.GITHUB_EVENT_PATH, 'utf8'))
230
+ const number = event.pull_request?.number
231
+ if (!number) throw new Error('This check runs on pull_request events only.')
232
+
233
+ // Re-read labels: the event payload is a snapshot from when the event fired.
234
+ const pull = await gh('GET', `/pulls/${number}`)
235
+ const verdict = evaluateLabels({ labelNames: pull.labels.map((l) => l.name), types })
236
+
237
+ if (verdict.status === 'ok') {
238
+ console.log(`PR #${number} is typed as ${verdict.type.label}.`)
239
+ return
240
+ }
241
+ if (verdict.status === 'multiple') {
242
+ console.error(`PR #${number} has ${verdict.types.length} type labels (${verdict.types.map((t) => t.label).join(', ')}). Keep exactly one.`)
243
+ process.exitCode = 1
244
+ return
245
+ }
246
+
247
+ // Label events only re-check: classifying on `unlabeled` would race an author
248
+ // who removed one type label to add another.
249
+ if (process.env.PR_TYPE_CLASSIFY !== 'true') {
250
+ console.error(`PR #${number} has no type label. ${fixInstructions(types)}`)
251
+ process.exitCode = 1
252
+ return
253
+ }
254
+ const apiKey = process.env.ANTHROPIC_API_KEY
255
+ if (!apiKey) {
256
+ console.error(`PR #${number} has no type label and no classifier key is available. ${fixInstructions(types)}`)
257
+ process.exitCode = 1
258
+ return
259
+ }
260
+
261
+ let picked
262
+ try {
263
+ picked = await classify({ apiKey, types, title: pull.title, body: pull.body, files: await listFiles({ gh, number }) })
264
+ } catch (error) {
265
+ console.error(`Could not classify PR #${number}: ${error.message}\n${fixInstructions(types)}`)
266
+ process.exitCode = 1
267
+ return
268
+ }
269
+
270
+ const type = types.find((t) => t.id === picked.id)
271
+ await syncLabels({ gh, types: [type] })
272
+ await gh('POST', `/issues/${number}/labels`, { labels: [type.label] })
273
+ const others = types.filter((t) => t.id !== type.id).map((t) => `\`${t.label}\``).join(', ')
274
+ await gh('POST', `/issues/${number}/comments`, {
275
+ body: `${COMMENT_MARKER}\nLabelled this PR **\`${type.label}\`**: ${picked.reason}\n\nIf that's wrong, swap it for one of ${others}. Every PR needs exactly one type label; they feed our bug / performance / feature trend metrics.\n\n---\n_Generated by [Claude Code](https://claude.ai/code)_`,
276
+ })
277
+ console.log(`PR #${number} had no type label; applied ${type.label} (${picked.reason}).`)
278
+ }
279
+
280
+ if (import.meta.url === `file://${process.argv[1]}`) {
281
+ main().catch((error) => {
282
+ console.error(error)
283
+ process.exitCode = 1
284
+ })
285
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "$comment": "Every pull request carries exactly one type label. Canonical copy: studio shared/services/studio-cli/templates/github/pr-types.json; Git Service Pulls mirror it in atlas git-service/pull-types.ts (a test enforces it). Add a type, never rename one: renaming splits the trend lines.",
3
+ "types": [
4
+ {
5
+ "id": "bug",
6
+ "label": "type: bug",
7
+ "color": "d73a4a",
8
+ "description": "Fixes behavior that is broken or wrong",
9
+ "guidance": "Something that used to work, or was meant to work, does the wrong thing: an error, a crash, wrong data, a regression."
10
+ },
11
+ {
12
+ "id": "performance",
13
+ "label": "type: performance",
14
+ "color": "fbca04",
15
+ "description": "Makes something faster, cheaper, or more reliable under load",
16
+ "guidance": "Latency, memory, cost, timeouts, rate limits, query plans, bundle size. Behavior is correct before and after; it is just slow or expensive."
17
+ },
18
+ {
19
+ "id": "enhancement",
20
+ "label": "type: enhancement",
21
+ "color": "a2eeef",
22
+ "description": "Fills a gap in an existing feature",
23
+ "guidance": "A capability that already exists but is missing something users would reasonably expect it to have: a missing filter, an edge case, a missing field, better UX on an existing flow."
24
+ },
25
+ {
26
+ "id": "feature",
27
+ "label": "type: feature",
28
+ "color": "0e8a16",
29
+ "description": "Adds a new capability",
30
+ "guidance": "Something users or developers could not do at all before: a new product surface, app, integration, command, or workflow."
31
+ },
32
+ {
33
+ "id": "chore",
34
+ "label": "type: chore",
35
+ "color": "c5def5",
36
+ "description": "Maintenance with no user-facing behavior change",
37
+ "guidance": "Infrastructure, CI, dependencies, refactors, docs, tests, tooling, config, and agent guides."
38
+ }
39
+ ]
40
+ }