close-prs.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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 teamAssociations = new Set(["OWNER", "MEMBER", "COLLABORATOR"])
  63. const headers = {
  64. Authorization: `Bearer ${token}`,
  65. "Content-Type": "application/json",
  66. Accept: "application/vnd.github+json",
  67. "X-GitHub-Api-Version": "2022-11-28",
  68. }
  69. type PullRequest = {
  70. number: number
  71. title: string
  72. url: string
  73. createdAt: string
  74. authorAssociation: string
  75. reactionGroups: Array<{
  76. content: string
  77. users: {
  78. totalCount: number
  79. }
  80. }>
  81. labels: {
  82. nodes: Array<{
  83. name: string
  84. }>
  85. }
  86. }
  87. type GraphqlResponse = {
  88. data?: {
  89. rateLimit: {
  90. cost: number
  91. remaining: number
  92. resetAt: string
  93. }
  94. repository: {
  95. pullRequests: {
  96. pageInfo: {
  97. hasNextPage: boolean
  98. endCursor: string | null
  99. }
  100. nodes: PullRequest[]
  101. }
  102. }
  103. }
  104. errors?: Array<{
  105. message: string
  106. }>
  107. }
  108. type CleanupCandidate = PullRequest & {
  109. positiveReactions: number
  110. }
  111. const message = `Automated PR Cleanup
  112. Thank you for contributing to opencode.
  113. 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.
  114. This PR was closed because it matched the following cleanup criteria:
  115. - The PR was created more than ${ageMonths === 1 ? "1 month" : `${ageMonths} months`} ago
  116. - The PR had fewer than ${threshold} positive reactions
  117. - Positive reactions are counted as thumbs-up, heart, celebration, or rocket reactions on the PR
  118. PRs created within the last ${ageMonths === 1 ? "month are" : `${ageMonths} months are`} not affected by this cleanup.
  119. 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.
  120. Thanks again for taking the time to contribute.`
  121. async function main() {
  122. console.log(`${values.execute ? "EXECUTE" : "DRY RUN"}: PR cleanup for ${repo.owner}/${repo.name}`)
  123. console.log(`Cutoff: ${cutoff.toISOString()}`)
  124. console.log(`Threshold: fewer than ${threshold} positive reactions`)
  125. const prs = await fetchOpenPullRequests()
  126. const scored = prs.map((pr) => ({ ...pr, positiveReactions: positiveReactionCount(pr) }))
  127. const recentCount = scored.filter((pr) => new Date(pr.createdAt) >= cutoff).length
  128. const teamCount = scored.filter((pr) => isTeamMember(pr)).length
  129. const matching = scored.filter(
  130. (pr) => !isTeamMember(pr) && new Date(pr.createdAt) < cutoff && pr.positiveReactions < threshold,
  131. )
  132. const candidates = matching.filter((pr) => !hasPriorCleanup(pr))
  133. const selected = maxClose === undefined ? candidates : candidates.slice(0, maxClose)
  134. console.log(`Fetched ${prs.length} open PRs`)
  135. console.log(`Matching cleanup criteria: ${matching.length}`)
  136. console.log(`Skipped previously cleaned PRs: ${matching.length - candidates.length}`)
  137. console.log(`Team member PRs untouched: ${teamCount}`)
  138. console.log(`Recent PRs untouched: ${recentCount}`)
  139. console.log(
  140. `Older PRs with at least ${threshold} positive reactions untouched: ${
  141. scored.filter((pr) => !isTeamMember(pr) && new Date(pr.createdAt) < cutoff && pr.positiveReactions >= threshold)
  142. .length
  143. }`,
  144. )
  145. if (selected.length === 0) return
  146. if (!values.execute) {
  147. console.log(`\nDry-run only. Re-run with --execute to comment and close matching PRs.`)
  148. console.log(`Showing ${Math.min(printLimit, selected.length)} of ${selected.length} matching PRs:\n`)
  149. for (const pr of selected.slice(0, printLimit)) {
  150. console.log(`#${pr.number} ${pr.createdAt} positive=${pr.positiveReactions} ${pr.url}`)
  151. }
  152. if (selected.length > printLimit) console.log(`... ${selected.length - printLimit} more not shown`)
  153. return
  154. }
  155. await ensureCleanupLabel()
  156. console.log(`\nCommenting and closing ${selected.length} PRs...`)
  157. for (const pr of selected) {
  158. await closePullRequest(pr)
  159. if (sleepMs > 0) await sleep(sleepMs)
  160. }
  161. console.log(`Closed ${selected.length} PRs`)
  162. }
  163. async function fetchOpenPullRequests() {
  164. const prs: PullRequest[] = []
  165. let endCursor: string | null = null
  166. while (true) {
  167. const page = await graphql({
  168. query: `query($owner: String!, $name: String!, $endCursor: String) {
  169. rateLimit {
  170. cost
  171. remaining
  172. resetAt
  173. }
  174. repository(owner: $owner, name: $name) {
  175. pullRequests(first: 100, states: OPEN, orderBy: { field: CREATED_AT, direction: ASC }, after: $endCursor) {
  176. pageInfo {
  177. hasNextPage
  178. endCursor
  179. }
  180. nodes {
  181. number
  182. title
  183. url
  184. createdAt
  185. authorAssociation
  186. reactionGroups {
  187. content
  188. users {
  189. totalCount
  190. }
  191. }
  192. labels(first: 100) {
  193. nodes {
  194. name
  195. }
  196. }
  197. }
  198. }
  199. }
  200. }`,
  201. variables: {
  202. owner: repo.owner,
  203. name: repo.name,
  204. endCursor,
  205. },
  206. })
  207. prs.push(...page.repository.pullRequests.nodes)
  208. console.log(
  209. `Fetched ${prs.length} PRs, GraphQL rate limit remaining ${page.rateLimit.remaining} (cost ${page.rateLimit.cost})`,
  210. )
  211. if (page.rateLimit.remaining < 100) {
  212. const delay = Math.max(0, new Date(page.rateLimit.resetAt).getTime() - Date.now()) + 1_000
  213. console.warn(`GraphQL rate limit low; sleeping ${Math.ceil(delay / 1000)}s until reset`)
  214. await sleep(delay)
  215. }
  216. if (!page.repository.pullRequests.pageInfo.hasNextPage) return prs
  217. endCursor = page.repository.pullRequests.pageInfo.endCursor
  218. }
  219. }
  220. async function graphql(input: { query: string; variables: Record<string, string | null> }) {
  221. const response = await githubRequest("/graphql", {
  222. method: "POST",
  223. body: JSON.stringify(input),
  224. })
  225. const body = (await response.json()) as GraphqlResponse
  226. if (body.errors?.length)
  227. throw new Error(`GitHub GraphQL error: ${body.errors.map((error) => error.message).join(", ")}`)
  228. if (!body.data) throw new Error("GitHub GraphQL response did not include data")
  229. return body.data
  230. }
  231. async function closePullRequest(pr: CleanupCandidate) {
  232. await githubRequest(`/repos/${repo.owner}/${repo.name}/issues/${pr.number}/comments`, {
  233. method: "POST",
  234. body: JSON.stringify({ body: message }),
  235. })
  236. await githubRequest(`/repos/${repo.owner}/${repo.name}/pulls/${pr.number}`, {
  237. method: "PATCH",
  238. body: JSON.stringify({ state: "closed" }),
  239. })
  240. await githubRequest(`/repos/${repo.owner}/${repo.name}/issues/${pr.number}/labels`, {
  241. method: "POST",
  242. body: JSON.stringify({ labels: [cleanupLabel] }),
  243. })
  244. console.log(`Closed #${pr.number} positive=${pr.positiveReactions} ${pr.url}`)
  245. }
  246. async function ensureCleanupLabel() {
  247. const response = await fetch(
  248. `https://api.github.com/repos/${repo.owner}/${repo.name}/labels/${encodeURIComponent(cleanupLabel)}`,
  249. {
  250. headers,
  251. },
  252. )
  253. if (response.ok) return
  254. if (response.status !== 404)
  255. throw new Error(`Failed to check cleanup label: ${response.status} ${response.statusText}`)
  256. await githubRequest(`/repos/${repo.owner}/${repo.name}/labels`, {
  257. method: "POST",
  258. body: JSON.stringify({
  259. name: cleanupLabel,
  260. color: "ededed",
  261. description: "PR was closed by automated cleanup",
  262. }),
  263. })
  264. }
  265. async function githubRequest(path: string, init: RequestInit, attempt = 0): Promise<Response> {
  266. const response = await fetch(path.startsWith("https://") ? path : `https://api.github.com${path}`, {
  267. ...init,
  268. headers: {
  269. ...headers,
  270. ...init.headers,
  271. },
  272. })
  273. if (response.ok) return response
  274. const body = await response.text()
  275. const retryAfter = response.headers.get("retry-after")
  276. const reset = response.headers.get("x-ratelimit-reset")
  277. const retryMs = retryAfter
  278. ? Number(retryAfter) * 1000
  279. : response.headers.get("x-ratelimit-remaining") === "0" && reset
  280. ? Math.max(0, Number(reset) * 1000 - Date.now()) + 1_000
  281. : body.toLowerCase().includes("secondary rate limit")
  282. ? 300_000
  283. : response.status >= 500
  284. ? Math.min(300_000, 10_000 * 2 ** attempt)
  285. : 0
  286. if ((response.status === 403 || response.status === 429 || response.status >= 500) && retryMs > 0 && attempt < 10) {
  287. console.warn(`GitHub request failed; sleeping ${Math.ceil(retryMs / 1000)}s before retry ${attempt + 1}`)
  288. await sleep(retryMs)
  289. return githubRequest(path, init, attempt + 1)
  290. }
  291. throw new Error(`GitHub request failed: ${response.status} ${response.statusText}\n${body}`)
  292. }
  293. function positiveReactionCount(pr: PullRequest) {
  294. return pr.reactionGroups
  295. .filter((group) => positiveReactions.has(group.content))
  296. .reduce((total, group) => total + group.users.totalCount, 0)
  297. }
  298. function hasPriorCleanup(pr: PullRequest) {
  299. return pr.labels.nodes.some((label) => label.name === cleanupLabel)
  300. }
  301. function isTeamMember(pr: PullRequest) {
  302. return teamAssociations.has(pr.authorAssociation)
  303. }
  304. function requireRepo(value: string | undefined) {
  305. if (!value) throw new Error("repo is required")
  306. const [owner, name] = value.split("/")
  307. if (!owner || !name) throw new Error(`Invalid repo ${value}; expected owner/name`)
  308. return { owner, name }
  309. }
  310. async function requireToken() {
  311. const envToken = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN
  312. if (envToken) return envToken
  313. const proc = Bun.spawn(["gh", "auth", "token"], {
  314. stdout: "pipe",
  315. stderr: "pipe",
  316. })
  317. const stdout = await new Response(proc.stdout).text()
  318. const stderr = await new Response(proc.stderr).text()
  319. const exitCode = await proc.exited
  320. if (exitCode === 0 && stdout.trim()) return stdout.trim()
  321. throw new Error(
  322. `GitHub authentication is required. Set GITHUB_TOKEN/GH_TOKEN or run gh auth login.\n${stderr.trim()}`,
  323. )
  324. }
  325. function requirePositiveInteger(name: string, value: string | undefined) {
  326. const parsed = Number(value)
  327. if (!Number.isInteger(parsed) || parsed <= 0) throw new Error(`${name} must be a positive integer`)
  328. return parsed
  329. }
  330. function requireNonNegativeInteger(name: string, value: string | undefined) {
  331. const parsed = Number(value)
  332. if (!Number.isInteger(parsed) || parsed < 0) throw new Error(`${name} must be a non-negative integer`)
  333. return parsed
  334. }
  335. function subtractMonths(date: Date, months: number) {
  336. const result = new Date(date)
  337. const day = result.getUTCDate()
  338. result.setUTCDate(1)
  339. result.setUTCMonth(result.getUTCMonth() - months)
  340. result.setUTCDate(
  341. Math.min(day, new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate()),
  342. )
  343. return result
  344. }
  345. function sleep(ms: number) {
  346. return new Promise((resolve) => setTimeout(resolve, ms))
  347. }
  348. void main().catch((error) => {
  349. console.error("Error:", error)
  350. process.exit(1)
  351. })