The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | const fs = require("node:fs"); |
| 2 | |
| 3 | const HOUR_MS = 60 * 60 * 1000; |
| 4 | const OPEN_LIMIT = 3; |
| 5 | const CONFLICT_IDLE_MS = 7 * 24 * HOUR_MS; |
| 6 | const NOTICE_MS = 72 * HOUR_MS; |
| 7 | // A first run meets the whole backlog. These keep one run from flooding watchers or GitHub's |
| 8 | // limit on how fast a token may comment. |
| 9 | const MAX_REQUESTS_PER_RUN = 100; |
| 10 | const MAX_CLOSES_PER_RUN = 50; |
| 11 | // A last look that ends in "not today" closes nothing, so the looks need a cap of their own. |
| 12 | const MAX_RECHECKS_PER_RUN = 150; |
| 13 | const WRITE_PAUSE_MS = 1_000; |
| 14 | // Measured here: about two and a half minutes until every open PR has an answer. |
| 15 | const MERGEABLE_WAIT_MS = 150_000; |
| 16 | const READ_ATTEMPTS = 4; |
| 17 | const READ_RETRY_MS = 5_000; |
| 18 | // GitHub stamps a label event and the PR's updatedAt a second or two apart. |
| 19 | const SAME_MOMENT_MS = 15_000; |
| 20 | |
| 21 | const REBASE_LABEL = "needs-rebase"; |
| 22 | const CLOSING_LABEL = "triage:closing"; |
| 23 | const KEEP_OPEN_LABEL = "triage:keep-open"; |
| 24 | const UNVOUCHED_LABEL = "vouch:unvouched"; |
| 25 | const WRITE_PERMISSIONS = new Set(["admin", "maintain", "write"]); |
| 26 | const EXEMPTIONS_PATH = ".github/TRIAGE_EXEMPTIONS.td"; |
| 27 | const VOUCHED_PATH = ".github/VOUCHED.td"; |
| 28 | const LOGIN_PATTERN = /^github:([A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38})$/; |
| 29 | |
| 30 | // `labels` matches a PR that carries any one of them. |
| 31 | const SWEEP_QUERY = ` |
| 32 | query ($owner: String!, $repo: String!, $labels: [String!], $cursor: String) { |
| 33 | repository(owner: $owner, name: $repo) { |
| 34 | pullRequests(states: OPEN, labels: $labels, first: 50, after: $cursor) { |
| 35 | pageInfo { hasNextPage endCursor } |
| 36 | nodes { |
| 37 | number |
| 38 | mergeable |
| 39 | baseRefName |
| 40 | updatedAt |
| 41 | author { login } |
| 42 | labels(first: 100) { nodes { name } } |
| 43 | timelineItems(itemTypes: [LABELED_EVENT], last: 20) { |
| 44 | nodes { ... on LabeledEvent { createdAt label { name } } } |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | }`; |
| 50 | |
| 51 | const RECHECK_QUERY = ` |
| 52 | query ($owner: String!, $repo: String!, $number: Int!) { |
| 53 | repository(owner: $owner, name: $repo) { |
| 54 | pullRequest(number: $number) { |
| 55 | state |
| 56 | mergeable |
| 57 | updatedAt |
| 58 | labels(first: 100) { nodes { name } } |
| 59 | } |
| 60 | } |
| 61 | }`; |
| 62 | |
| 63 | const AUTHOR_OPEN_PRS_QUERY = ` |
| 64 | query ($q: String!) { |
| 65 | search(query: $q, type: ISSUE, first: 50) { |
| 66 | nodes { ... on PullRequest { number } } |
| 67 | } |
| 68 | }`; |
| 69 | |
| 70 | const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 71 | |
| 72 | // GitHub answers a heavy list request with a 502 now and then, and one of those must not end the |
| 73 | // run. Only reads go through here: repeating a read is safe, repeating a comment is not. |
| 74 | async function read(github, query, variables) { |
| 75 | for (let attempt = 1; ; attempt += 1) { |
| 76 | try { |
| 77 | return await github.graphql(query, variables); |
| 78 | } catch (error) { |
| 79 | const transient = typeof error.status === "number" && error.status >= 500; |
| 80 | if (attempt === READ_ATTEMPTS || !transient) throw error; |
| 81 | await pause(attempt * READ_RETRY_MS); |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // Fails closed: a missing, empty, or malformed list must never read as "nobody is exempt". |
| 87 | function parseExemptions(text) { |
| 88 | const logins = new Set(); |
| 89 | for (const raw of text.split("\n")) { |
| 90 | const line = raw.trim(); |
| 91 | if (line === "" || line.startsWith("#")) continue; |
| 92 | const match = LOGIN_PATTERN.exec(line); |
| 93 | if (!match) throw new Error(`${EXEMPTIONS_PATH}: malformed entry "${line}"`); |
| 94 | const login = match[1].toLowerCase(); |
| 95 | if (logins.has(login)) throw new Error(`${EXEMPTIONS_PATH}: duplicate entry "${line}"`); |
| 96 | logins.add(login); |
| 97 | } |
| 98 | if (logins.size === 0) throw new Error(`${EXEMPTIONS_PATH}: no entries`); |
| 99 | return logins; |
| 100 | } |
| 101 | |
| 102 | // VOUCHED.td: one `github:login` per line, `#` comments, and `-github:login reason` to denounce. |
| 103 | // A login listed both ways is an error: pr-vouch.yml's action reads its first line and |
| 104 | // issue-vouch.yml its last, so no answer here would agree with both labels. |
| 105 | function parseVouchList(text) { |
| 106 | const vouched = new Set(); |
| 107 | const denounced = new Set(); |
| 108 | for (const raw of text.split("\n")) { |
| 109 | const match = /^(-?)github:(\S+)/.exec(raw.trim()); |
| 110 | if (!match) continue; |
| 111 | const login = match[2].toLowerCase(); |
| 112 | const [listed, other] = match[1] ? [denounced, vouched] : [vouched, denounced]; |
| 113 | if (other.has(login)) |
| 114 | throw new Error(`${VOUCHED_PATH}: ${login} is both vouched and denounced`); |
| 115 | listed.add(login); |
| 116 | } |
| 117 | if (vouched.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`); |
| 118 | return { vouched, denounced }; |
| 119 | } |
| 120 | |
| 121 | function labeledAt(pr, name) { |
| 122 | const last = pr.timelineItems.nodes.filter((event) => event.label?.name === name).at(-1); |
| 123 | return last ? Date.parse(last.createdAt) : undefined; |
| 124 | } |
| 125 | |
| 126 | // The whole policy for the two windows. Activity is anything that moves the PR's updatedAt: a |
| 127 | // push, a comment, a review, a label. Nobody can set that time, so nothing here trusts the author. |
| 128 | function decide(pr, exemptions, now) { |
| 129 | const labels = new Set(pr.labels.nodes.map((label) => label.name)); |
| 130 | if (labels.has(KEEP_OPEN_LABEL)) return "skip"; |
| 131 | const updatedAt = Date.parse(pr.updatedAt); |
| 132 | |
| 133 | if (labels.has(CLOSING_LABEL)) { |
| 134 | const since = labeledAt(pr, CLOSING_LABEL); |
| 135 | if (since === undefined) return "unknown-notice"; |
| 136 | // Any activity after the notice sends the PR back to triage. |
| 137 | if (updatedAt - since > SAME_MOMENT_MS) return "clear-notice"; |
| 138 | return now - since >= NOTICE_MS ? "close-notice" : "skip"; |
| 139 | } |
| 140 | |
| 141 | const exempt = exemptions.has((pr.author?.login ?? "").toLowerCase()); |
| 142 | const subject = labels.has(UNVOUCHED_LABEL) && !exempt; |
| 143 | if (labels.has(REBASE_LABEL)) { |
| 144 | if (!subject || pr.mergeable === "MERGEABLE") return "clear-rebase"; |
| 145 | // Activity restarts the seven days and keeps the label, so a PR is asked to rebase once. |
| 146 | const idle = now - updatedAt >= CONFLICT_IDLE_MS; |
| 147 | return idle && pr.mergeable === "CONFLICTING" ? "close-conflict" : "skip"; |
| 148 | } |
| 149 | return subject && pr.mergeable === "CONFLICTING" ? "request-rebase" : "skip"; |
| 150 | } |
| 151 | |
| 152 | function guideLink(context, anchor) { |
| 153 | return `https://github.com/${context.repo.owner}/${context.repo.repo}/blob/main/CONTRIBUTING.md#${anchor}`; |
| 154 | } |
| 155 | |
| 156 | async function removeLabel(github, context, number, name) { |
| 157 | try { |
| 158 | await github.rest.issues.removeLabel({ ...context.repo, issue_number: number, name }); |
| 159 | } catch (error) { |
| 160 | if (error.status !== 404) throw error; |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | async function closeWithComment(github, context, number, body) { |
| 165 | await github.rest.issues.createComment({ ...context.repo, issue_number: number, body }); |
| 166 | await github.rest.pulls.update({ ...context.repo, pull_number: number, state: "closed" }); |
| 167 | } |
| 168 | |
| 169 | async function sweep({ github, context, core, dryRun }) { |
| 170 | const exemptions = parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")); |
| 171 | const repo = { owner: context.repo.owner, repo: context.repo.repo }; |
| 172 | |
| 173 | const list = async () => { |
| 174 | const prs = []; |
| 175 | for (let cursor = null; ;) { |
| 176 | const page = ( |
| 177 | await read(github, SWEEP_QUERY, { |
| 178 | ...repo, |
| 179 | cursor, |
| 180 | labels: [UNVOUCHED_LABEL, REBASE_LABEL, CLOSING_LABEL], |
| 181 | }) |
| 182 | ).repository.pullRequests; |
| 183 | prs.push(...page.nodes); |
| 184 | if (!page.pageInfo.hasNextPage) return prs; |
| 185 | cursor = page.pageInfo.endCursor; |
| 186 | } |
| 187 | }; |
| 188 | // GitHub computes mergeability lazily and forgets it whenever the base moves. Asking starts the |
| 189 | // computation, so ask once more. A PR that is still unknown waits for tomorrow's run. |
| 190 | let prs = await list(); |
| 191 | if (prs.some((pr) => pr.mergeable === "UNKNOWN")) { |
| 192 | await pause(MERGEABLE_WAIT_MS); |
| 193 | prs = await list(); |
| 194 | } |
| 195 | |
| 196 | const now = Date.now(); |
| 197 | // Start further down the list each day. The step is no larger than a run's cap, so a cap that |
| 198 | // is reached cannot leave the same PRs waiting behind the same others every day. |
| 199 | const start = (Math.floor(now / (24 * HOUR_MS)) * MAX_RECHECKS_PER_RUN) % (prs.length || 1); |
| 200 | prs = [...prs.slice(start), ...prs.slice(0, start)]; |
| 201 | const count = {}; |
| 202 | let rechecks = 0; |
| 203 | for (const pr of prs) { |
| 204 | const { number } = pr; |
| 205 | let action = decide(pr, exemptions, now); |
| 206 | if (action === "skip") continue; |
| 207 | if (action === "unknown-notice") { |
| 208 | core.warning(`#${number}: cannot tell when ${CLOSING_LABEL} was applied, leaving it open.`); |
| 209 | continue; |
| 210 | } |
| 211 | if (action === "request-rebase" && (count[action] ?? 0) >= MAX_REQUESTS_PER_RUN) continue; |
| 212 | if (action.startsWith("close")) { |
| 213 | if ((count["close-conflict"] ?? 0) + (count["close-notice"] ?? 0) >= MAX_CLOSES_PER_RUN) { |
| 214 | continue; |
| 215 | } |
| 216 | if (rechecks >= MAX_RECHECKS_PER_RUN) continue; |
| 217 | rechecks += 1; |
| 218 | // The list is minutes old by now. Closing is the one step worth a second look. |
| 219 | const fresh = (await read(github, RECHECK_QUERY, { ...repo, number })).repository.pullRequest; |
| 220 | if (fresh.state !== "OPEN") continue; |
| 221 | // A merge to the base can resolve a conflict without touching the PR, so this is re-read |
| 222 | // too. An answer that is not ready yet reads as "not conflicting" and waits for tomorrow. |
| 223 | action = decide({ ...pr, ...fresh }, exemptions, now); |
| 224 | if (!action.startsWith("close")) continue; |
| 225 | } |
| 226 | |
| 227 | count[action] = (count[action] ?? 0) + 1; |
| 228 | core.info(`#${number} ${action}${dryRun ? " (dry run)" : ""}`); |
| 229 | if (dryRun) continue; |
| 230 | |
| 231 | if (action === "request-rebase") { |
| 232 | // The request goes first: a label without it would start a clock nobody was told about. |
| 233 | await github.rest.issues.createComment({ |
| 234 | ...context.repo, |
| 235 | issue_number: number, |
| 236 | body: [ |
| 237 | `This PR conflicts with \`${pr.baseRefName}\`. Rebase it or merge \`${pr.baseRefName}\` into it. If it still conflicts after 7 days with no activity, it will be closed automatically.`, |
| 238 | "", |
| 239 | `See the [conflict window](${guideLink(context, "conflict-window")}).`, |
| 240 | ].join("\n"), |
| 241 | }); |
| 242 | await github.rest.issues.addLabels({ |
| 243 | ...context.repo, |
| 244 | issue_number: number, |
| 245 | labels: [REBASE_LABEL], |
| 246 | }); |
| 247 | } else if (action === "clear-rebase") { |
| 248 | await removeLabel(github, context, number, REBASE_LABEL); |
| 249 | } else if (action === "clear-notice") { |
| 250 | await removeLabel(github, context, number, CLOSING_LABEL); |
| 251 | } else { |
| 252 | const conflict = action === "close-conflict"; |
| 253 | await closeWithComment( |
| 254 | github, |
| 255 | context, |
| 256 | number, |
| 257 | conflict |
| 258 | ? [ |
| 259 | `Closing: this PR still conflicts with \`${pr.baseRefName}\` and has had no activity for 7 days since the rebase request.`, |
| 260 | "", |
| 261 | `To continue, rebase the branch and open a new PR that links this one. See the [conflict window](${guideLink(context, "conflict-window")}).`, |
| 262 | ].join("\n") |
| 263 | : [ |
| 264 | "Closing: 72 hours have passed since the triage notice above with no activity on this PR.", |
| 265 | "", |
| 266 | `To ask for reconsideration, address the notice and comment here, or open a focused replacement PR that links this one. See [closure and reconsideration](${guideLink(context, "closure-and-reconsideration")}).`, |
| 267 | ].join("\n"), |
| 268 | ); |
| 269 | // Without this a maintainer's reopen would be closed again by the next run. |
| 270 | await removeLabel(github, context, number, conflict ? REBASE_LABEL : CLOSING_LABEL); |
| 271 | } |
| 272 | await pause(WRITE_PAUSE_MS); |
| 273 | } |
| 274 | |
| 275 | const summary = Object.entries(count).map(([action, n]) => `${n} ${action}`); |
| 276 | core.info( |
| 277 | `${dryRun ? "Dry run. " : ""}${prs.length} PRs read: ${summary.join(", ") || "nothing to do"}.`, |
| 278 | ); |
| 279 | return count; |
| 280 | } |
| 281 | |
| 282 | async function enforceOpenLimit({ github, context, core, dryRun }) { |
| 283 | const pr = context.payload.pull_request; |
| 284 | const author = pr.user.login; |
| 285 | // Who is trusted is decided here rather than by the vouch action, which reports its own failed |
| 286 | // lookups as "not vouched". Every read below throws on failure, and a throw closes nothing. |
| 287 | if (pr.user.type === "Bot") return; |
| 288 | if (parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")).has(author.toLowerCase())) return; |
| 289 | const { vouched, denounced } = parseVouchList(fs.readFileSync(VOUCHED_PATH, "utf8")); |
| 290 | if (vouched.has(author.toLowerCase())) return; |
| 291 | const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({ |
| 292 | ...context.repo, |
| 293 | username: author, |
| 294 | }); |
| 295 | if (WRITE_PERMISSIONS.has(access.permission)) return; |
| 296 | if (pr.labels.some((label) => label.name === KEEP_OPEN_LABEL)) return; |
| 297 | // Someone else reopening a PR is a maintainer overriding the limit. |
| 298 | const reopened = context.payload.action === "reopened"; |
| 299 | if (reopened && context.payload.sender.login.toLowerCase() !== author.toLowerCase()) return; |
| 300 | |
| 301 | if (denounced.has(author.toLowerCase())) { |
| 302 | if (dryRun) { |
| 303 | core.notice(`Dry run. PR #${pr.number} would close: ${author} is denounced.`); |
| 304 | return; |
| 305 | } |
| 306 | await closeWithComment( |
| 307 | github, |
| 308 | context, |
| 309 | pr.number, |
| 310 | `Closing: ${author} is banned from contributing here, so this PR will not be reviewed. See [bans](${guideLink(context, "bans")}).`, |
| 311 | ); |
| 312 | core.info(`PR #${pr.number}: closed, ${author} is denounced.`); |
| 313 | return; |
| 314 | } |
| 315 | |
| 316 | const q = `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open author:${author} sort:created-asc`; |
| 317 | const { search } = await read(github, AUTHOR_OPEN_PRS_QUERY, { q }); |
| 318 | // A new PR counts only the older ones, so two opened together cannot close each other. |
| 319 | const others = search.nodes.filter( |
| 320 | (node) => node.number && (reopened ? node.number !== pr.number : node.number < pr.number), |
| 321 | ).length; |
| 322 | if (others < OPEN_LIMIT) { |
| 323 | core.info(`PR #${pr.number}: ${author} has ${others} other open PRs.`); |
| 324 | return; |
| 325 | } |
| 326 | if (dryRun) { |
| 327 | core.notice(`Dry run. PR #${pr.number} would close: ${author} has ${others} other open PRs.`); |
| 328 | return; |
| 329 | } |
| 330 | |
| 331 | await closeWithComment( |
| 332 | github, |
| 333 | context, |
| 334 | pr.number, |
| 335 | [ |
| 336 | `Closing: ${author} already has ${OPEN_LIMIT} or more open PRs here, which is the limit for contributors who are not vouched.`, |
| 337 | "", |
| 338 | `Once one of them is merged or closed, open this again. See the [open PR limit](${guideLink(context, "open-pr-limit")}).`, |
| 339 | ].join("\n"), |
| 340 | ); |
| 341 | core.info(`PR #${pr.number}: closed, ${author} has ${others} other open PRs.`); |
| 342 | } |
| 343 | |
| 344 | module.exports = { decide, enforceOpenLimit, parseExemptions, sweep }; |