close-prs.ts 12 KB

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