From 8c80aff92ba359a67fe6d2a961a76cad067b0686 Mon Sep 17 00:00:00 2001 From: Adam Hearn <22334119+hearnadam@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:37:32 -0800 Subject: [PATCH] chore(ci): tighten stale issue closing and add linked-ref/slop workflows (#65954) --- .github/workflows/triage-close-issues.yml | 20 +- .github/workflows/triage-close-linked.yml | 397 ++++++++++++++++++++++ .github/workflows/triage-slop.yml | 90 +++++ script/github/close-issues.ts | 266 ++++++++++----- 4 files changed, 681 insertions(+), 92 deletions(-) create mode 100644 .github/workflows/triage-close-linked.yml create mode 100644 .github/workflows/triage-slop.yml diff --git a/.github/workflows/triage-close-issues.yml b/.github/workflows/triage-close-issues.yml index c2898ba8e06..1dd377284a8 100644 --- a/.github/workflows/triage-close-issues.yml +++ b/.github/workflows/triage-close-issues.yml @@ -2,8 +2,17 @@ name: triage-close-issues on: schedule: - - cron: "0 2 * * *" # Daily at 2:00 AM + - cron: "0 2 * * *" # Daily at 2:00 AM UTC workflow_dispatch: + inputs: + dry-run: + description: "Log matching issues without closing them" + type: boolean + default: true + +concurrency: + group: triage-close-issues + cancel-in-progress: false jobs: close: @@ -18,7 +27,12 @@ jobs: with: bun-version: latest - - name: Close stale issues + - name: Close stale waiting-for-info issues env: GITHUB_TOKEN: ${{ github.token }} - run: bun script/github/close-issues.ts + run: | + args=() + if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ "${{ inputs['dry-run'] }}" != "false" ]; then + args+=("--dry-run") + fi + bun script/github/close-issues.ts "${args[@]}" diff --git a/.github/workflows/triage-close-linked.yml b/.github/workflows/triage-close-linked.yml new file mode 100644 index 00000000000..813f8d2ddbf --- /dev/null +++ b/.github/workflows/triage-close-linked.yml @@ -0,0 +1,397 @@ +name: triage-close-linked + +# Closes what GitHub native auto-close misses on merge into the default branch: +# - additional issues in lists ("Fixes #1, #2 and #3" -> closes #2 and #3; GitHub closes #1) +# - superseded pull requests ("Supersedes #4", "Replaces #5") +# +# Runs entirely against the GitHub API with no checkout, so pull_request_target is safe. + +permissions: + contents: read + +on: + pull_request_target: + types: [closed] + workflow_dispatch: + inputs: + pr_number: + description: "Merged PR whose description to read" + required: true + type: string + dry_run: + description: "Log targets without closing them" + required: false + type: boolean + default: true + +jobs: + close-linked: + if: > + github.repository == 'anomalyco/opencode' && + (github.event_name == 'workflow_dispatch' || github.event.pull_request.merged == true) + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + issues: write + pull-requests: write + steps: + - name: Close linked issues and superseded PRs + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const ISSUE_KEYWORDS = new Set([ + "close", "closes", "closed", + "fix", "fixes", "fixed", + "resolve", "resolves", "resolved", + ]); + const PR_KEYWORDS = new Set([ + "supersede", "supersedes", "superseded", + "replace", "replaces", "replaced", + ]); + const KEYWORDS = new Set([...ISSUE_KEYWORDS, ...PR_KEYWORDS]); + const HEDGES = new Set([ + "may", "might", "could", "would", "possibly", "probably", "potentially", + "maybe", "perhaps", "hopefully", "likely", "unlikely", "partially", "partly", "partial", + ]); + const SUBORDINATORS = new Set(["if", "whether", "when", "whenever", "once", "until", "unless", "before", "after"]); + const DISQUALIFIERS = new Set([ + "not", "never", "neither", "nor", "without", "cannot", "can't", "doesn't", "don't", + "won't", "didn't", "isn't", "wasn't", "hasn't", "haven't", "hadn't", "wouldn't", + "couldn't", "shouldn't", "mightn't", "mustn't", + ...HEDGES, + ...SUBORDINATORS, + "the", "a", "an", "of", "on", "in", "by", "from", "with", "for", "than", + ]); + const BASE_FORMS = new Set(["close", "fix", "resolve", "supersede", "replace"]); + const VERB_MARKERS = new Set(["does", "do", "did", "and"]); + const DETERMINERS = new Set(["this", "that", "the", "a", "an"]); + const INTERVENING = new Set([ + "also", "fully", "completely", "entirely", "actually", "really", "yet", "directly", "properly", + "have", "has", "had", + ]); + const MAX_TARGETS = 10; + + function stripNonProse(body) { + const lines = body.replaceAll("\r\n", "\n").split("\n"); + const kept = []; + let fence = null; + let inComment = false; + let paragraph = false; + for (const line of lines) { + if (inComment) { + const end = line.indexOf("-->"); + if (end === -1) { kept.push(""); continue; } + inComment = false; + kept.push(line.slice(end + 3)); + continue; + } + const trimmed = line.trim(); + if (fence !== null) { + if (trimmed.startsWith(fence) && [...trimmed].every(c => c === fence[0])) fence = null; + paragraph = false; + kept.push(""); + continue; + } + if (trimmed === "") { paragraph = false; kept.push(""); continue; } + // Skip 4-space or tab indented code blocks outside a paragraph. + if (!paragraph && (/^ {4}/.test(line) || line.startsWith("\t"))) { + kept.push(""); + continue; + } + const fenceMatch = /^(`{3,}|~{3,})/.exec(trimmed); + if (fenceMatch && (fenceMatch[1][0] === "~" || !trimmed.slice(fenceMatch[1].length).includes("`"))) { + fence = fenceMatch[1]; + paragraph = false; + kept.push(""); + continue; + } + if (trimmed.startsWith(">")) { paragraph = false; kept.push(""); continue; } + // Skip markdown task list items like "- [ ] Fix #99". + if (/^[-*+]\s+\[[ xX]\]/.test(trimmed)) { paragraph = false; kept.push(""); continue; } + // Strip inline code spans BEFORE HTML comments so `", start + 4); + if (end === -1) { + cleaned = cleaned.slice(0, start); + inComment = true; + break; + } + cleaned = cleaned.slice(0, start) + " " + cleaned.slice(end + 3); + } + paragraph = !/^#{1,6}\s/.test(trimmed); + kept.push(cleaned); + } + let text = kept.join("\n"); + text = text.replace(/~~[^~\n]+~~/g, " "); + text = text.replace(/<(?:s|del|strike)\b[^>]*>[\s\S]*?<\/(?:s|del|strike)>/gi, " "); + return text; + } + + function tokenize(text) { + const tokens = []; + let i = 0; + while (i < text.length) { + const c = text[i]; + if (c === "\n") { + if (tokens.at(-1)?.kind === "newline") tokens[tokens.length - 1] = { kind: "break" }; + else if (tokens.at(-1)?.kind !== "break") tokens.push({ kind: "newline" }); + i++; + continue; + } + if (c.trim() === "") { i++; continue; } + const urlMatch = /^https?:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/(?:issues|pull)\/(\d+)(?![\w])/i.exec(text.slice(i)); + if (urlMatch) { + tokens.push({ kind: "ref", repository: urlMatch[1].toLowerCase(), number: Number(urlMatch[2]) }); + i += urlMatch[0].length; + continue; + } + const repoRefMatch = /^([\w.-]+\/[\w.-]+)#(\d+)(?![\w'\u2019])/.exec(text.slice(i)); + if (repoRefMatch) { + tokens.push({ kind: "ref", repository: repoRefMatch[1].toLowerCase(), number: Number(repoRefMatch[2]) }); + i += repoRefMatch[0].length; + continue; + } + const bareRefMatch = /^#(\d+)(?![\w'\u2019])/.exec(text.slice(i)); + if (bareRefMatch) { + tokens.push({ kind: "ref", repository: null, number: Number(bareRefMatch[1]) }); + i += bareRefMatch[0].length; + continue; + } + const wordMatch = /^[A-Za-z][A-Za-z0-9'\u2019-]*/.exec(text.slice(i)); + if (wordMatch) { + tokens.push({ kind: "word", text: wordMatch[0].toLowerCase().replaceAll("\u2019", "'") }); + i += wordMatch[0].length; + continue; + } + tokens.push({ kind: "punct", text: c }); + i++; + } + return tokens; + } + + const isPunct = (t, s) => t?.kind === "punct" && t.text === s; + const isWord = (t, s) => t?.kind === "word" && t.text === s; + const skipEmph = (tokens, i) => { while (isPunct(tokens[i], "*") || isPunct(tokens[i], "_")) i++; return i; }; + const skipEmphBack = (tokens, i) => { while (i >= 0 && (isPunct(tokens[i], "*") || isPunct(tokens[i], "_"))) i--; return i; }; + const skipInterveningBack = (tokens, i) => { + for (;;) { + i = skipEmphBack(tokens, i); + if (i < 0 || tokens[i].kind !== "word" || !INTERVENING.has(tokens[i].text)) return i; + i--; + } + }; + const endsWithRef = (tokens, k) => { + const p = skipEmphBack(tokens, k); + const t = tokens[p]; + if (!t) return false; + if (t.kind === "ref") return true; + if (isPunct(t, ">")) return tokens[p - 1]?.kind === "ref" && isPunct(tokens[p - 2], "<"); + if (isPunct(t, ")")) { + if (tokens[p - 1]?.kind === "ref" && isPunct(tokens[p - 2], "(")) return true; + if (isPunct(tokens[p - 2], "(") && isPunct(tokens[p - 3], "]")) return tokens[p - 4]?.kind === "ref" && isPunct(tokens[p - 5], "["); + } + return false; + }; + + // A continuation reference must terminate cleanly (end of text/line/clause or list separator), + // so "Fixes #12, #13 is tracked separately" does NOT close #13. + const endsCleanly = (tokens, j) => { + const next = tokens[skipEmph(tokens, j)]; + if (!next || next.kind === "newline" || next.kind === "break") return true; + if (next.kind === "punct" && ".,;:)&".includes(next.text)) return true; + if (isWord(next, "and")) return true; + return false; + }; + + function isClosingStatement(tokens, index, keyword) { + let k = skipInterveningBack(tokens, index - 1); + // Skip parenthetical / dash / colon lead-ins from a reference ("Reverts #100 (fixes #99)", "TODO: fix #99"). + if (isPunct(tokens[k], ":") && tokens[k - 1]?.kind === "word" && ["todo", "note", "fyi"].includes(tokens[k - 1].text)) return false; + if (tokens[k]?.kind === "punct" && "(—–-".includes(tokens[k].text)) { + let q = skipInterveningBack(tokens, k - 1); + while (tokens[q]?.kind === "punct" && "-—–".includes(tokens[q].text)) q = skipInterveningBack(tokens, q - 1); + if (endsWithRef(tokens, q)) return false; + } + if (endsWithRef(tokens, k)) return false; + const lineStart = tokens[k]?.kind === "newline" || tokens[k]?.kind === "break" || k < 0; + if (tokens[k]?.kind === "newline") { + const e = skipEmphBack(tokens, k - 1); + const w = skipInterveningBack(tokens, e); + if (w < e && endsWithRef(tokens, w)) return false; + k = w; + } + const before = tokens[k]; + if (!before || before.kind !== "word") return true; + if (before.text === "which" || before.text === "that") { + let p = skipInterveningBack(tokens, k - 1); + while (tokens[p]?.kind === "newline" || (tokens[p]?.kind === "punct" && ",(;:-\u2013\u2014".includes(tokens[p].text))) { + p = skipInterveningBack(tokens, p - 1); + } + if (endsWithRef(tokens, p)) return false; + } + if (DISQUALIFIERS.has(before.text)) return false; + let p = skipInterveningBack(tokens, k - 1); + if (tokens[p]?.kind === "newline") p = skipInterveningBack(tokens, p - 1); + if (tokens[p]?.kind === "word" && DETERMINERS.has(tokens[p].text)) { + p = skipInterveningBack(tokens, p - 1); + if (tokens[p]?.kind === "newline") p = skipInterveningBack(tokens, p - 1); + } + if (isPunct(tokens[p], ",")) p = skipInterveningBack(tokens, p - 1); + if (tokens[p]?.kind === "word" && (SUBORDINATORS.has(tokens[p].text) || HEDGES.has(tokens[p].text))) return false; + if (!BASE_FORMS.has(keyword)) return true; + return lineStart ? before.text !== "to" : VERB_MARKERS.has(before.text); + } + + function readRef(tokens, index) { + index = skipEmph(tokens, index); + const t = tokens[index]; + if (!t) return null; + if (t.kind === "ref") return { token: t, end: index + 1 }; + if (isPunct(t, "<") && tokens[index + 1]?.kind === "ref" && isPunct(tokens[index + 2], ">")) { + return { token: tokens[index + 1], end: index + 3 }; + } + if (isPunct(t, "[")) { + let close = index + 1; + while (close < tokens.length && close < index + 10 && !isPunct(tokens[close], "]")) { + if (tokens[close].kind === "newline" || tokens[close].kind === "break") return null; + close++; + } + if (isPunct(tokens[close], "]") && isPunct(tokens[close + 1], "(") && isPunct(tokens[close + 3], ")")) { + if (tokens[close + 2]?.kind === "ref") return { token: tokens[close + 2], end: close + 4 }; + if (close === index + 2 && tokens[index + 1]?.kind === "ref") return { token: tokens[index + 1], end: close + 4 }; + } + } + return null; + } + + function findLinkedReferences(body, repository) { + const self = repository.toLowerCase(); + const tokens = tokenize(stripNonProse(body)); + const found = []; + let i = 0; + while (i < tokens.length) { + const token = tokens[i]; + if (token.kind !== "word" || !KEYWORDS.has(token.text) || !isClosingStatement(tokens, i, token.text)) { + i++; + continue; + } + const targetKind = PR_KEYWORDS.has(token.text) ? "pull" : "issue"; + let j = i + 1; + if (isPunct(tokens[j], ":")) j++; + let ref = readRef(tokens, j); + if (!ref) { i++; continue; } + let pos = 0; + for (;;) { + // For issue keywords, GitHub natively closes pos === 0 when bare #N/URL/owner/repo#N. + // Still emit pos === 0 only for markdown-link/PR keywords, or list continuations (pos > 0), + // avoiding racing GitHub native auto-close. + const nativeClose = targetKind === "issue" && pos === 0 && tokens[skipEmph(tokens, j)]?.kind === "ref"; + if (!nativeClose && (pos === 0 || endsCleanly(tokens, ref.end))) { + found.push({ repository: ref.token.repository ?? self, number: ref.token.number, keyword: token.text, targetKind }); + } + j = ref.end; + pos++; + let k = skipEmph(tokens, j); + let sep = false; + if (isPunct(tokens[k], ",")) { k++; sep = true; } + if (isWord(tokens[k], "and") || isPunct(tokens[k], "&")) { k++; sep = true; } + if (!sep) break; + ref = readRef(tokens, k); + if (!ref) break; + if (!endsCleanly(tokens, ref.end)) break; + } + i = j; + } + return found; + } + + const { owner, repo } = context.repo; + const repository = `${owner}/${repo}`; + const expectedRepoUrl = `https://api.github.com/repos/${repository.toLowerCase()}`; + const inputs = context.payload.inputs ?? {}; + const event = context.payload.pull_request; + const prNumber = event?.number ?? Number(inputs.pr_number); + const dryRun = String(inputs.dry_run ?? "false") === "true"; + + if (!Number.isInteger(prNumber) || prNumber <= 0) { + core.setFailed(`Invalid pull request number: ${inputs.pr_number}`); + return; + } + + const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber }); + if (!pr.merged) { + core.info(`#${prNumber}: not merged, skipping`); + return; + } + const defaultBranch = pr.base.repo.default_branch; + if (pr.base.ref !== defaultBranch) { + core.info(`#${prNumber}: merged into ${pr.base.ref}, not ${defaultBranch}, skipping`); + return; + } + + const prAuthor = pr.user?.login?.toLowerCase(); + const trustedAuthor = ["OWNER", "MEMBER"].includes(pr.author_association); + const body = (event ? event.body : pr.body) ?? ""; + const seen = new Set(); + const targets = []; + for (const ref of findLinkedReferences(body, repository)) { + if (ref.repository !== repository.toLowerCase()) continue; + if (ref.number === prNumber || seen.has(ref.number)) continue; + seen.add(ref.number); + targets.push(ref); + } + if (targets.length === 0) { + core.info(`#${prNumber}: no additional linked references to close`); + return; + } + if (targets.length > MAX_TARGETS) { + core.warning(`#${prNumber}: found ${targets.length} references (cap ${MAX_TARGETS}); refusing bulk close`); + return; + } + + let failed = 0; + for (const ref of targets) { + let item; + try { + ({ data: item } = await github.rest.issues.get({ owner, repo, issue_number: ref.number })); + } catch (error) { + if (error.status === 404 || error.status === 410) continue; + failed++; + core.error(`#${ref.number}: ${error.message}`); + continue; + } + if (item.repository_url && item.repository_url.toLowerCase() !== expectedRepoUrl) continue; + if (item.state !== "open") continue; + const isPull = item.pull_request !== undefined; + // Only close issues for close/fix/resolve, and only close PRs for supersede/replace. + if (ref.targetKind === "issue" && isPull) continue; + if (ref.targetKind === "pull" && !isPull) continue; + // Only allow an outside contributor PR to supersede their own PR. + if (isPull && !trustedAuthor && item.user?.login?.toLowerCase() !== prAuthor) { + core.info(`#${ref.number}: skipping supersede of another contributor PR by non-member`); + continue; + } + if (dryRun) { + core.info(`[dry-run] Would close ${isPull ? "PR" : "issue"} #${ref.number} (${ref.keyword} in #${prNumber})`); + continue; + } + try { + if (isPull) { + await github.rest.pulls.update({ owner, repo, pull_number: ref.number, state: "closed" }); + } else { + await github.rest.issues.update({ owner, repo, issue_number: ref.number, state: "closed", state_reason: "completed" }); + } + await github.rest.issues.createComment({ + owner, + repo, + issue_number: ref.number, + body: isPull ? `Superseded by #${prNumber}.` : `Closed as completed by #${prNumber}.`, + }); + } catch (error) { + failed++; + core.error(`#${ref.number}: ${error.message}`); + } + } + if (failed > 0) core.setFailed(`${failed} of ${targets.length} references could not be closed`); diff --git a/.github/workflows/triage-slop.yml b/.github/workflows/triage-slop.yml new file mode 100644 index 00000000000..2b5b6a98608 --- /dev/null +++ b/.github/workflows/triage-slop.yml @@ -0,0 +1,90 @@ +name: triage-slop + +permissions: + contents: read + +on: + pull_request_target: + types: [labeled] + +jobs: + close-slop: + runs-on: ubuntu-latest + if: > + github.event.label.name == 'slop' && + github.repository == 'anomalyco/opencode' && + github.event.pull_request.state == 'open' + timeout-minutes: 5 + permissions: + contents: read + issues: write + pull-requests: write + steps: + - name: Close, scrub, and comment on AI slop PR + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const pr = context.payload.pull_request; + const pullNumber = pr.number; + const login = pr.user?.login?.toLowerCase(); + + // Never touch merged/closed PRs, bots, or team members. + if (pr.state !== "open" || pr.merged) return; + if (pr.user?.type === "Bot" || ["OWNER", "MEMBER"].includes(pr.author_association)) { + core.info(`Skipping #${pullNumber}: author ${pr.user?.login} is exempt`); + return; + } + try { + const { data: file } = await github.rest.repos.getContent({ + owner: context.repo.owner, + repo: context.repo.repo, + path: ".github/TEAM_MEMBERS", + ref: "dev", + }); + const members = new Set( + Buffer.from(file.content, "base64").toString("utf8").split("\n").map((l) => l.trim().toLowerCase()).filter(Boolean), + ); + if (login && members.has(login)) { + core.info(`Skipping #${pullNumber}: author ${pr.user?.login} is in TEAM_MEMBERS`); + return; + } + } catch (error) { + core.warning(`Could not read TEAM_MEMBERS: ${error.message}`); + return; + } + + // Close and scrub first so a failed update never leaves a misleading closed comment. + await github.rest.pulls.update({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + title: 'ai slop', + body: 'This pull request was closed as AI slop and its title/description were cleared to avoid misleading reviewers. If you believe this was closed in error, leave a comment explaining why.', + state: 'closed', + }); + + const marker = ""; + const { data: comments } = await github.rest.issues.listComments({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pullNumber, + per_page: 100, + }); + if (comments.some((c) => (c.body || "").includes(marker))) return; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pullNumber, + body: [ + marker, + 'This pull request has been closed because it was flagged as low-quality AI slop.', + '', + 'Common reasons include:', + '- Failing to verify the underlying problem exists', + '- Failing to test that the change actually fixes it', + '- Making unverified assumptions about the codebase or adding speculative/misleading changes', + '', + 'If you believe this was closed in error, leave a comment explaining how you reproduced and verified the change.', + ].join('\n'), + }); diff --git a/script/github/close-issues.ts b/script/github/close-issues.ts index 12d7aa191f8..baf50b1c934 100755 --- a/script/github/close-issues.ts +++ b/script/github/close-issues.ts @@ -1,115 +1,203 @@ #!/usr/bin/env bun +import { parseArgs } from "util" + const repo = "anomalyco/opencode" const days = 60 -const msg = `To stay organized issues are automatically closed after ${days} days of no activity. If the issue is still relevant please open a new one.` +const eligibleLabels = new Set(["triaging", "needs info"]) +const msg = `Closing this issue because it has been waiting for more information with no activity for ${days} days. If this still happens and you can share the requested details, please open a new issue.` -const token = process.env.GITHUB_TOKEN -if (!token) { - console.error("GITHUB_TOKEN environment variable is required") - process.exit(1) -} - -const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000) -const agentLogin = "opencode-agent[bot]" -const teamMembers = new Set( - (await Bun.file(new URL("../../.github/TEAM_MEMBERS", import.meta.url)).text()) - .split("\n") - .map((line) => line.trim().toLowerCase()) - .filter(Boolean), -) const teamAssociations = new Set(["OWNER", "MEMBER"]) -type Issue = { +export type Issue = { number: number + state?: string updated_at: string author_association: string - user: { login: string } | null + user: { login: string; type?: string } | null + labels?: Array<{ name?: string } | string> + pull_request?: unknown } -const headers = { - Authorization: `Bearer ${token}`, - "Content-Type": "application/json", - Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": "2022-11-28", +export type Comment = { + user: { login: string; type?: string } | null + author_association?: string } -function shouldSkip(i: Issue) { - const login = i.user?.login.toLowerCase() - return login === agentLogin || (login ? teamMembers.has(login) : false) || teamAssociations.has(i.author_association) +export type TimelineEvent = { + event?: string + source?: { + issue?: { + state?: string + pull_request?: unknown + } + } } -async function close(num: number) { - const base = `https://api.github.com/repos/${repo}/issues/${num}` +export function labelNames(issue: Issue) { + return (issue.labels ?? []) + .map((label) => (typeof label === "string" ? label : (label.name ?? "")).toLowerCase()) + .filter(Boolean) +} - const comment = await fetch(`${base}/comments`, { - method: "POST", - headers, - body: JSON.stringify({ body: msg }), - }) - if (!comment.ok) throw new Error(`Failed to comment #${num}: ${comment.status} ${comment.statusText}`) +export function isTeamActor( + user: { login: string } | null | undefined, + association: string | undefined, + teamMembers: ReadonlySet, +) { + const login = user?.login.toLowerCase() + return (login ? teamMembers.has(login) : false) || (association ? teamAssociations.has(association) : false) +} - const patch = await fetch(base, { - method: "PATCH", - headers, - body: JSON.stringify({ state: "closed", state_reason: "not_planned" }), - }) - if (!patch.ok) throw new Error(`Failed to close #${num}: ${patch.status} ${patch.statusText}`) - - console.log(`Closed https://github.com/${repo}/issues/${num}`) +export function shouldCloseIssue( + issue: Issue, + cutoff: Date, + teamMembers: ReadonlySet, + details?: { comments: ReadonlyArray; timeline: ReadonlyArray }, +) { + if (issue.pull_request !== undefined) return false + if (issue.state !== undefined && issue.state !== "open") return false + if (new Date(issue.updated_at) >= cutoff) return false + if (issue.user?.type === "Bot") return false + if (isTeamActor(issue.user, issue.author_association, teamMembers)) return false + if (!labelNames(issue).some((label) => eligibleLabels.has(label))) return false + if (!details) return true + // Never undo a reopen (by a maintainer or by the bot on an author reply). + if (details.timeline.some((entry) => entry.event === "reopened")) return false + // Never close when an open PR cross-references the issue. + if ( + details.timeline.some( + (entry) => + entry.event === "cross-referenced" && + entry.source?.issue?.pull_request !== undefined && + entry.source.issue.state === "open", + ) + ) + return false + // Never close if a team member engaged in the thread. + if (details.comments.some((comment) => isTeamActor(comment.user, comment.author_association, teamMembers))) + return false + // Never close if the author was the last human to reply (the bot stalled, not the author). + const authorLogin = issue.user?.login.toLowerCase() + const lastHuman = [...details.comments].reverse().find((comment) => comment.user?.type !== "Bot") + if (authorLogin && lastHuman?.user?.login.toLowerCase() === authorLogin) return false + return true } async function main() { - let page = 1 - let closed = 0 + const { values } = parseArgs({ + args: Bun.argv.slice(2), + options: { + "dry-run": { type: "boolean", default: false }, + }, + }) - while (true) { - const res = await fetch( - `https://api.github.com/repos/${repo}/issues?state=open&sort=updated&direction=asc&per_page=100&page=${page}`, - { headers }, - ) - if (!res.ok) throw new Error(res.statusText) - - const all = (await res.json()) as Issue[] - if (all.length === 0) break - console.log(`Fetched page ${page} ${all.length} issues`) - - const stale: number[] = [] - for (const i of all) { - const updated = new Date(i.updated_at) - if (updated < cutoff) { - if (shouldSkip(i)) { - console.log(`Skipping stale issue #${i.number}; author ${i.user?.login ?? "unknown"} is exempt`) - continue - } - stale.push(i.number) - } else { - console.log(`\nFound fresh issue #${i.number}, stopping`) - if (stale.length > 0) { - for (const num of stale) { - await close(num) - closed++ - } - } - console.log(`Closed ${closed} issues total`) - return - } - } - - if (stale.length > 0) { - for (const num of stale) { - await close(num) - closed++ - } - } - - page++ + const token = process.env.GITHUB_TOKEN + if (!token) { + console.error("GITHUB_TOKEN environment variable is required") + process.exit(1) } - console.log(`Closed ${closed} issues total`) + const dryRun = values["dry-run"] + const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000) + const teamMembers = new Set( + (await Bun.file(new URL("../../.github/TEAM_MEMBERS", import.meta.url)).text()) + .split("\n") + .map((line) => line.trim().toLowerCase()) + .filter(Boolean), + ) + + const headers = { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + } + + async function getJson(url: string) { + const res = await fetch(url, { headers }) + if (!res.ok) throw new Error(`GET ${url} failed: ${res.status} ${res.statusText}`) + return (await res.json()) as T + } + + async function close(num: number) { + if (dryRun) { + console.log(`[dry-run] Would close https://github.com/${repo}/issues/${num}`) + return + } + const base = `https://api.github.com/repos/${repo}/issues/${num}` + // Close first so a partial failure never leaves a "Closing this issue" comment on an open issue. + const patch = await fetch(base, { + method: "PATCH", + headers, + body: JSON.stringify({ state: "closed", state_reason: "not_planned" }), + }) + if (!patch.ok) throw new Error(`Failed to close #${num}: ${patch.status} ${patch.statusText}`) + + const comment = await fetch(`${base}/comments`, { + method: "POST", + headers, + body: JSON.stringify({ body: msg }), + }) + if (!comment.ok) { + console.warn(`Closed #${num}, but failed to post comment: ${comment.status} ${comment.statusText}`) + return + } + console.log(`Closed https://github.com/${repo}/issues/${num}`) + } + + // Collect all candidate numbers first so closing items never shifts pagination. + const candidateNumbers = new Set() + for (const label of eligibleLabels) { + let page = 1 + while (true) { + const query = new URLSearchParams({ + state: "open", + labels: label, + sort: "updated", + direction: "asc", + per_page: "100", + page: String(page), + }) + const all = await getJson(`https://api.github.com/repos/${repo}/issues?${query}`) + if (all.length === 0) break + console.log(`Fetched label "${label}" page ${page}: ${all.length} items`) + + let hitFresh = false + for (const issue of all) { + if (new Date(issue.updated_at) >= cutoff) { + hitFresh = true + break + } + if (shouldCloseIssue(issue, cutoff, teamMembers)) candidateNumbers.add(issue.number) + } + if (hitFresh) break + page++ + } + } + + let closed = 0 + for (const num of candidateNumbers) { + const base = `https://api.github.com/repos/${repo}/issues/${num}` + const [live, comments, timeline] = await Promise.all([ + getJson(base), + getJson(`${base}/comments?per_page=100`), + getJson(`${base}/timeline?per_page=100`), + ]) + if (!shouldCloseIssue(live, cutoff, teamMembers, { comments, timeline })) { + console.log(`Skipping #${num} after live thread check`) + continue + } + await close(num) + closed++ + } + + console.log(`${dryRun ? "[dry-run] Would close" : "Closed"} ${closed} issues total`) } -main().catch((err) => { - console.error("Error:", err) - process.exit(1) -}) +if (import.meta.main) { + main().catch((err) => { + console.error("Error:", err) + process.exit(1) + }) +}