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

actions.ts

185 lines5.3 KB

1/**
2 * Mutation planning + execution for the sweep. The sweep builds a plan of
3 * `Mutation` objects first (printable in dry-run mode), then executes them
4 * through the REST API.
5 */
6​
7import type { GitHubClient } from './github'
8​
9export const MANAGED_LABELS: Array<{
10 name: string
11 color: string
12 description: string
13}> = [
14 {
15 name: 'waiting-on: maintainer',
16 color: 'd93f0b',
17 description: 'The ball is in the maintainers’ court',
18 },
19 {
20 name: 'waiting-on: author',
21 color: 'fbca04',
22 description: 'Waiting for the author to respond or update',
23 },
24 {
25 name: 'ready-to-merge',
26 color: '0e8a16',
27 description: 'Approved, CI green, no conflicts',
28 },
29 {
30 name: 'merge-conflicts',
31 color: 'b60205',
32 description: 'Conflicts with the base branch — needs a rebase',
33 },
34 {
35 name: 'needs-repro',
36 color: 'e99695',
37 description: 'Needs a minimal reproduction before it can be worked on',
38 },
39 {
40 name: 'has-pr',
41 color: 'bfd4f2',
42 description: 'An open PR references this issue',
43 },
45​
46const MANAGED_LABEL_NAMES = new Set(MANAGED_LABELS.map((l) => l.name))
47​
48export type Mutation =
49 | { kind: 'request-review'; number: number; reviewer: string }
50 | { kind: 'assign'; number: number; assignee: string }
51 | { kind: 'comment'; number: number; body: string; note: string }
52 | { kind: 'add-labels'; number: number; labels: Array<string> }
53 | { kind: 'remove-label'; number: number; label: string }
54​
55export function describeMutation(m: Mutation): string {
56 switch (m.kind) {
57 case 'request-review':
58 return `request review #${m.number} → @${m.reviewer}`
59 case 'assign':
60 return `assign #${m.number} → @${m.assignee}`
61 case 'comment':
62 return `comment on #${m.number} (${m.note})`
63 case 'add-labels':
64 return `label #${m.number} + [${m.labels.join(', ')}]`
65 case 'remove-label':
66 return `label #${m.number} − [${m.label}]`
67 }
69​
70/**
71 * Diff an item's current labels against the desired managed labels; labels
72 * outside MANAGED_LABELS are never touched.
73 */
74export function planLabelChanges(
75 number: number,
76 currentLabels: Array<string>,
77 desiredManaged: Array<string>,
78): Array<Mutation> {
79 const current = new Set(
80 currentLabels.filter((l) => MANAGED_LABEL_NAMES.has(l)),
81 )
82 const desired = new Set(desiredManaged)
83 const mutations: Array<Mutation> = []
84 const toAdd = [...desired].filter((l) => !current.has(l))
85 if (toAdd.length > 0) {
86 mutations.push({ kind: 'add-labels', number, labels: toAdd })
87 }
88 for (const label of current) {
89 if (!desired.has(label)) {
90 mutations.push({ kind: 'remove-label', number, label })
91 }
92 }
93 return mutations
95​
96export async function ensureManagedLabels(
97 client: GitHubClient,
98 repo: string,
99): Promise<void> {
100 for (const label of MANAGED_LABELS) {
101 try {
102 await client.rest('POST', `/repos/${repo}/labels`, label)
103 } catch (error) {
104 // 422 = already exists; anything else should surface.
105 if (!(error instanceof Error) || !error.message.includes('422')) {
106 throw error
107 }
108 }
109 }
111​
112async function executeOne(
113 client: GitHubClient,
114 repo: string,
115 m: Mutation,
116): Promise<void> {
117 switch (m.kind) {
118 case 'request-review':
119 await client.rest(
120 'POST',
121 `/repos/${repo}/pulls/${m.number}/requested_reviewers`,
122 { reviewers: [m.reviewer] },
123 )
124 break
125 case 'assign':
126 await client.rest('POST', `/repos/${repo}/issues/${m.number}/assignees`, {
127 assignees: [m.assignee],
128 })
129 break
130 case 'comment':
131 await client.rest('POST', `/repos/${repo}/issues/${m.number}/comments`, {
132 body: m.body,
133 })
134 break
135 case 'add-labels':
136 await client.rest('POST', `/repos/${repo}/issues/${m.number}/labels`, {
137 labels: m.labels,
138 })
139 break
140 case 'remove-label':
141 await client.rest(
142 'DELETE',
143 `/repos/${repo}/issues/${m.number}/labels/${encodeURIComponent(m.label)}`,
144 )
145 break
146 }
148​
149function isRateLimitError(error: unknown): boolean {
150 return error instanceof Error && /HTTP (403|429)/.test(error.message)
152​
153const sleep = (ms: number) =>
154 new Promise<void>((resolve) => setTimeout(resolve, ms))
155​
156export interface ExecuteOptions {
157 /** Pause between mutations — GitHub's secondary rate limit wants ≥1s between content-creating requests. */
158 pacingMs?: number
159 sleepImpl?: (ms: number) => Promise<void>
161​
162export async function executeMutations(
163 client: GitHubClient,
164 repo: string,
165 mutations: Array<Mutation>,
166 options: ExecuteOptions = {},
167): Promise<void> {
168 const pacingMs = options.pacingMs ?? 1000
169 const sleepImpl = options.sleepImpl ?? sleep
170 for (const [i, m] of mutations.entries()) {
171 if (i > 0) await sleepImpl(pacingMs)
172 try {
173 await executeOne(client, repo, m)
174 } catch (error) {
175 if (!isRateLimitError(error)) throw error
176 // Likely the secondary rate limit; back off once and retry before
177 // giving up (an aborted run converges on the next sweep anyway).
178 console.log(` ⏳ rate limited, backing off 60s (${describeMutation(m)})`)
179 await sleepImpl(60_000)
180 await executeOne(client, repo, m)
181 }
182 // Per-mutation progress keeps watchdogs (and humans) from presuming death.
183 console.log(` ✔ [${i + 1}/${mutations.length}] ${describeMutation(m)}`)
184 }