1
0

close-prs.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #!/usr/bin/env bun
  2. import { parseArgs } from "util"
  3. const defaultRepo = "anomalyco/opencode"
  4. const defaultAgeMonths = 1
  5. const defaultThreshold = 2
  6. const defaultSleepMs = 20_000
  7. const defaultPrintLimit = 50
  8. const positiveReactions = new Set(["THUMBS_UP", "HEART", "HOORAY", "ROCKET"])
  9. const cleanupLabel = "automated-pr-cleanup"
  10. const { values } = parseArgs({
  11. args: Bun.argv.slice(2),
  12. options: {
  13. execute: { type: "boolean", default: false },
  14. "dry-run": { type: "boolean", default: false },
  15. repo: { type: "string", default: defaultRepo },
  16. threshold: { type: "string", default: String(defaultThreshold) },
  17. "age-months": { type: "string", default: String(defaultAgeMonths) },
  18. "max-close": { type: "string" },
  19. "sleep-ms": { type: "string", default: String(defaultSleepMs) },
  20. "print-limit": { type: "string", default: String(defaultPrintLimit) },
  21. help: { type: "boolean", short: "h", default: false },
  22. },
  23. })
  24. if (values.help) {
  25. console.log(`
  26. Usage: bun script/github/close-prs.ts [options]
  27. Dry-run is the default. The script only comments and closes PRs when --execute is passed.
  28. Criteria:
  29. - PRs created within the last month are untouched
  30. - PRs older than one month are closed when they have fewer than 2 positive reactions
  31. - Positive reactions are THUMBS_UP, HEART, HOORAY, and ROCKET reactions on the PR
  32. Options:
  33. --execute Comment and close matching PRs
  34. --dry-run Explicitly run without changing anything
  35. --repo <owner/repo> Repository to clean up (default: ${defaultRepo})
  36. --threshold <n> Positive reaction threshold (default: ${defaultThreshold})
  37. --age-months <n> Age cutoff in months (default: ${defaultAgeMonths})
  38. --max-close <n> Maximum matching PRs to process
  39. --sleep-ms <n> Delay between closing PRs (default: ${defaultSleepMs})
  40. --print-limit <n> Number of matching PRs to print in dry-run (default: ${defaultPrintLimit})
  41. -h, --help Show this help message
  42. Examples:
  43. bun script/github/close-prs.ts
  44. bun script/github/close-prs.ts --threshold 2 --print-limit 100
  45. bun script/github/close-prs.ts --execute --threshold 2 --max-close 25
  46. `)
  47. process.exit(0)
  48. }
  49. if (values.execute && values["dry-run"]) {
  50. console.error("Use either --execute or --dry-run, not both")
  51. process.exit(1)
  52. }
  53. const token = await requireToken()
  54. const repo = requireRepo(values.repo)
  55. const threshold = requirePositiveInteger("threshold", values.threshold)
  56. const ageMonths = requirePositiveInteger("age-months", values["age-months"])
  57. const maxClose =
  58. values["max-close"] === undefined ? undefined : requirePositiveInteger("max-close", values["max-close"])
  59. const sleepMs = requireNonNegativeInteger("sleep-ms", values["sleep-ms"])
  60. const printLimit = requireNonNegativeInteger("print-limit", values["print-limit"])
  61. const cutoff = subtractMonths(new Date(), ageMonths)
  62. const headers = {
  63. Authorization: `Bearer ${token}`,
  64. "Content-Type": "application/json",
  65. Accept: "application/vnd.github+json",
  66. "X-GitHub-Api-Version": "2022-11-28",
  67. }
  68. type PullRequest = {
  69. number: number
  70. title: string
  71. url: string
  72. createdAt: string
  73. reactionGroups: Array<{
  74. content: string
  75. users: {
  76. totalCount: number
  77. }
  78. }>
  79. labels: {
  80. nodes: Array<{
  81. name: string
  82. }>
  83. }
  84. }
  85. type GraphqlResponse = {
  86. data?: {
  87. rateLimit: {
  88. cost: number
  89. remaining: number
  90. resetAt: string
  91. }
  92. repository: {
  93. pullRequests: {
  94. pageInfo: {
  95. hasNextPage: boolean
  96. endCursor: string | null
  97. }
  98. nodes: PullRequest[]
  99. }
  100. }
  101. }
  102. errors?: Array<{
  103. message: string
  104. }>
  105. }
  106. type CleanupCandidate = PullRequest & {
  107. positiveReactions: number
  108. }
  109. const message = `Automated PR Cleanup
  110. Thank you for contributing to opencode.
  111. Due to the high volume of PRs from users and AI agents, we periodically close older PRs using automated criteria so maintainers can focus review time on the most active and community-supported contributions.
  112. This PR was closed because it matched the following cleanup criteria:
  113. - The PR was created more than ${ageMonths === 1 ? "1 month" : `${ageMonths} months`} ago
  114. - The PR had fewer than ${threshold} positive reactions
  115. - Positive reactions are counted as thumbs-up, heart, celebration, or rocket reactions on the PR
  116. PRs created within the last ${ageMonths === 1 ? "month are" : `${ageMonths} months are`} not affected by this cleanup.
  117. If you believe this PR was closed incorrectly, or if you are still actively working on it, please leave a comment explaining why it should be reopened. A maintainer can review and reopen it if appropriate.
  118. Thanks again for taking the time to contribute.`
  119. async function main() {
  120. console.log(`${values.execute ? "EXECUTE" : "DRY RUN"}: PR cleanup for ${repo.owner}/${repo.name}`)
  121. console.log(`Cutoff: ${cutoff.toISOString()}`)
  122. console.log(`Threshold: fewer than ${threshold} positive reactions`)
  123. const prs = await fetchOpenPullRequests()
  124. const recentCount = prs.filter((pr) => new Date(pr.createdAt) >= cutoff).length
  125. const matching = prs
  126. .map((pr) => ({ ...pr, positiveReactions: positiveReactionCount(pr) }))
  127. .filter((pr) => new Date(pr.createdAt) < cutoff && pr.positiveReactions < threshold)
  128. const candidates = matching.filter((pr) => !hasPriorCleanup(pr))
  129. const selected = maxClose === undefined ? candidates : candidates.slice(0, maxClose)
  130. console.log(`Fetched ${prs.length} open PRs`)
  131. console.log(`Matching cleanup criteria: ${matching.length}`)
  132. console.log(`Skipped previously cleaned PRs: ${matching.length - candidates.length}`)
  133. console.log(`Recent PRs untouched: ${recentCount}`)
  134. console.log(
  135. `Older PRs with at least ${threshold} positive reactions untouched: ${prs.length - matching.length - recentCount}`,
  136. )
  137. if (selected.length === 0) return
  138. if (!values.execute) {
  139. console.log(`\nDry-run only. Re-run with --execute to comment and close matching PRs.`)
  140. console.log(`Showing ${Math.min(printLimit, selected.length)} of ${selected.length} matching PRs:\n`)
  141. for (const pr of selected.slice(0, printLimit)) {
  142. console.log(`#${pr.number} ${pr.createdAt} positive=${pr.positiveReactions} ${pr.url}`)
  143. }
  144. if (selected.length > printLimit) console.log(`... ${selected.length - printLimit} more not shown`)
  145. return
  146. }
  147. await ensureCleanupLabel()
  148. console.log(`\nCommenting and closing ${selected.length} PRs...`)
  149. for (const pr of selected) {
  150. await closePullRequest(pr)
  151. if (sleepMs > 0) await sleep(sleepMs)
  152. }
  153. console.log(`Closed ${selected.length} PRs`)
  154. }
  155. async function fetchOpenPullRequests() {
  156. const prs: PullRequest[] = []
  157. let endCursor: string | null = null
  158. while (true) {
  159. const page = await graphql({
  160. query: `query($owner: String!, $name: String!, $endCursor: String) {
  161. rateLimit {
  162. cost
  163. remaining
  164. resetAt
  165. }
  166. repository(owner: $owner, name: $name) {
  167. pullRequests(first: 100, states: OPEN, orderBy: { field: CREATED_AT, direction: ASC }, after: $endCursor) {
  168. pageInfo {
  169. hasNextPage
  170. endCursor
  171. }
  172. nodes {
  173. number
  174. title
  175. url
  176. createdAt
  177. reactionGroups {
  178. content
  179. users {
  180. totalCount
  181. }
  182. }
  183. labels(first: 100) {
  184. nodes {
  185. name
  186. }
  187. }
  188. }
  189. }
  190. }
  191. }`,
  192. variables: {
  193. owner: repo.owner,
  194. name: repo.name,
  195. endCursor,
  196. },
  197. })
  198. prs.push(...page.repository.pullRequests.nodes)
  199. console.log(
  200. `Fetched ${prs.length} PRs, GraphQL rate limit remaining ${page.rateLimit.remaining} (cost ${page.rateLimit.cost})`,
  201. )
  202. if (page.rateLimit.remaining < 100) {
  203. const delay = Math.max(0, new Date(page.rateLimit.resetAt).getTime() - Date.now()) + 1_000
  204. console.warn(`GraphQL rate limit low; sleeping ${Math.ceil(delay / 1000)}s until reset`)
  205. await sleep(delay)
  206. }
  207. if (!page.repository.pullRequests.pageInfo.hasNextPage) return prs
  208. endCursor = page.repository.pullRequests.pageInfo.endCursor
  209. }
  210. }
  211. async function graphql(input: { query: string; variables: Record<string, string | null> }) {
  212. const response = await githubRequest("/graphql", {
  213. method: "POST",
  214. body: JSON.stringify(input),
  215. })
  216. const body = (await response.json()) as GraphqlResponse
  217. if (body.errors?.length)
  218. throw new Error(`GitHub GraphQL error: ${body.errors.map((error) => error.message).join(", ")}`)
  219. if (!body.data) throw new Error("GitHub GraphQL response did not include data")
  220. return body.data
  221. }
  222. async function closePullRequest(pr: CleanupCandidate) {
  223. await githubRequest(`/repos/${repo.owner}/${repo.name}/issues/${pr.number}/comments`, {
  224. method: "POST",
  225. body: JSON.stringify({ body: message }),
  226. })
  227. await githubRequest(`/repos/${repo.owner}/${repo.name}/pulls/${pr.number}`, {
  228. method: "PATCH",
  229. body: JSON.stringify({ state: "closed" }),
  230. })
  231. await githubRequest(`/repos/${repo.owner}/${repo.name}/issues/${pr.number}/labels`, {
  232. method: "POST",
  233. body: JSON.stringify({ labels: [cleanupLabel] }),
  234. })
  235. console.log(`Closed #${pr.number} positive=${pr.positiveReactions} ${pr.url}`)
  236. }
  237. async function ensureCleanupLabel() {
  238. const response = await fetch(
  239. `https://api.github.com/repos/${repo.owner}/${repo.name}/labels/${encodeURIComponent(cleanupLabel)}`,
  240. {
  241. headers,
  242. },
  243. )
  244. if (response.ok) return
  245. if (response.status !== 404)
  246. throw new Error(`Failed to check cleanup label: ${response.status} ${response.statusText}`)
  247. await githubRequest(`/repos/${repo.owner}/${repo.name}/labels`, {
  248. method: "POST",
  249. body: JSON.stringify({
  250. name: cleanupLabel,
  251. color: "ededed",
  252. description: "PR was closed by automated cleanup",
  253. }),
  254. })
  255. }
  256. async function githubRequest(path: string, init: RequestInit, attempt = 0): Promise<Response> {
  257. const response = await fetch(path.startsWith("https://") ? path : `https://api.github.com${path}`, {
  258. ...init,
  259. headers: {
  260. ...headers,
  261. ...init.headers,
  262. },
  263. })
  264. if (response.ok) return response
  265. const body = await response.text()
  266. const retryAfter = response.headers.get("retry-after")
  267. const reset = response.headers.get("x-ratelimit-reset")
  268. const retryMs = retryAfter
  269. ? Number(retryAfter) * 1000
  270. : response.headers.get("x-ratelimit-remaining") === "0" && reset
  271. ? Math.max(0, Number(reset) * 1000 - Date.now()) + 1_000
  272. : body.toLowerCase().includes("secondary rate limit")
  273. ? 300_000
  274. : response.status >= 500
  275. ? Math.min(300_000, 10_000 * 2 ** attempt)
  276. : 0
  277. if ((response.status === 403 || response.status === 429 || response.status >= 500) && retryMs > 0 && attempt < 10) {
  278. console.warn(`GitHub request failed; sleeping ${Math.ceil(retryMs / 1000)}s before retry ${attempt + 1}`)
  279. await sleep(retryMs)
  280. return githubRequest(path, init, attempt + 1)
  281. }
  282. throw new Error(`GitHub request failed: ${response.status} ${response.statusText}\n${body}`)
  283. }
  284. function positiveReactionCount(pr: PullRequest) {
  285. return pr.reactionGroups
  286. .filter((group) => positiveReactions.has(group.content))
  287. .reduce((total, group) => total + group.users.totalCount, 0)
  288. }
  289. function hasPriorCleanup(pr: PullRequest) {
  290. return pr.labels.nodes.some((label) => label.name === cleanupLabel)
  291. }
  292. function requireRepo(value: string | undefined) {
  293. if (!value) throw new Error("repo is required")
  294. const [owner, name] = value.split("/")
  295. if (!owner || !name) throw new Error(`Invalid repo ${value}; expected owner/name`)
  296. return { owner, name }
  297. }
  298. async function requireToken() {
  299. const envToken = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN
  300. if (envToken) return envToken
  301. const proc = Bun.spawn(["gh", "auth", "token"], {
  302. stdout: "pipe",
  303. stderr: "pipe",
  304. })
  305. const stdout = await new Response(proc.stdout).text()
  306. const stderr = await new Response(proc.stderr).text()
  307. const exitCode = await proc.exited
  308. if (exitCode === 0 && stdout.trim()) return stdout.trim()
  309. throw new Error(
  310. `GitHub authentication is required. Set GITHUB_TOKEN/GH_TOKEN or run gh auth login.\n${stderr.trim()}`,
  311. )
  312. }
  313. function requirePositiveInteger(name: string, value: string | undefined) {
  314. const parsed = Number(value)
  315. if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`${name} must be a positive integer`)
  316. return parsed
  317. }
  318. function requireNonNegativeInteger(name: string, value: string | undefined) {
  319. const parsed = Number(value)
  320. if (!Number.isInteger(parsed) || parsed < 0) throw new Error(`${name} must be a non-negative integer`)
  321. return parsed
  322. }
  323. function subtractMonths(date: Date, months: number) {
  324. const result = new Date(date)
  325. const day = result.getUTCDate()
  326. result.setUTCDate(1)
  327. result.setUTCMonth(result.getUTCMonth() - months)
  328. result.setUTCDate(
  329. Math.min(day, new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate()),
  330. )
  331. return result
  332. }
  333. function sleep(ms: number) {
  334. return new Promise((resolve) => setTimeout(resolve, ms))
  335. }
  336. void main().catch((error) => {
  337. console.error("Error:", error)
  338. process.exit(1)
  339. })