// Daily stale sweep, run by .github/workflows/stale.yml. The rules are described in CONTRIBUTING.md. import { BOT_LOGIN, loadMaintainers, sameUser } from "./issue-claims.mjs"; const PR_REMIND_DAYS = 45; const PR_CLOSE_DAYS = 5; const RESPONSE_REMIND_DAYS = 7; const RESPONSE_CLOSE_DAYS = 7; export const PENDING_LABEL = "pending-response"; const EXEMPT_LABELS = ["security", "onhold"]; export const MARKER = ""; // Marks the reminder for a `pending-response` wait, so the 45-day path never counts it as its own. export const PENDING_MARKER = ""; const DAY_MS = 24 * 60 * 60 * 1000; // Comments, reviews, commits, force pushes and reopens reset the clock; label, assignment and mention events don't. const ACTIVITY = ["commented", "reviewed", "committed", "head_ref_force_pushed", "reopened"]; const isBot = (user) => Boolean(user && (user.type === "Bot" || user.login?.endsWith("[bot]"))); // Dependabot commits name the bot as author and GitHub as committer. const isBotCommit = (event) => [event.author?.name, event.committer?.name].some((name) => name?.endsWith("[bot]")); const hasLabel = (item, name) => item.labels.some((label) => sameUser(label.name, name)); const isExempt = (item) => EXEMPT_LABELS.some((name) => hasLabel(item, name)); /** Reminds once the item has been quiet long enough, and closes only after a reminder nobody answered. */ export function decideStale({ now, lastActivityAt, remindedAt, remindDays, closeDays }) { // Never before the full interval. Scheduled runs only start late, so at worst this acts a day later. const waited = (date, days) => now.getTime() - date.getTime() >= days * DAY_MS; if (remindedAt && remindedAt >= lastActivityAt) { return waited(remindedAt, closeDays) ? "close" : "keep"; } return waited(lastActivityAt, remindDays) ? "remind" : "keep"; } /** * The latest human activity on a PR. Replies in review threads aren't in the timeline, so they are * passed in separately. Comments, reviews and pushes are dated by GitHub, but a commit's date is set * by whoever made it, so a commit dated after the PR last changed (`updatedAt`) is ignored. That only * catches the obvious case: once something else updates the PR, a commit with a future date counts. * An empty push keeps a PR open anyway, so it isn't worth more than that. */ // shortcut: GitHub gives no push time for a plain push, so a commit counts from its committer date; // pushing an old commit after a reminder doesn't reset the clock. A rebase or force push does. // With `by`, only those people's activity counts. A timeline commit names no GitHub login, so who made it // comes from `committedBy` (sha to login, from the PR's commit list); a commit with no linked account // counts, since the branch belongs to the PR's author. export function lastHumanActivity({ timeline, reviewComments, createdAt, updatedAt, by, committedBy = new Map() }) { const isBy = (login) => by.some((name) => sameUser(login, name)); const commitBy = (sha) => !committedBy.get(sha) || isBy(committedBy.get(sha)); const times = [...timeline.filter((event) => ACTIVITY.includes(event.event)), ...reviewComments] .filter((item) => !isBot(item.actor ?? item.user) && !isBotCommit(item)) .filter((item) => !by || (item.committer ? commitBy(item.sha) : isBy((item.actor ?? item.user)?.login))) .filter((item) => !item.committer || new Date(item.committer.date) <= new Date(updatedAt)) .map((item) => new Date(item.created_at ?? item.submitted_at ?? item.committer.date).getTime()); return new Date(Math.max(new Date(createdAt).getTime(), ...times)); } const isComment = (event) => event.event === "commented"; /** * True when the PR is waiting on the maintainers, not its author, so it never goes stale: no maintainer * has reviewed it yet, the author pushed, committed or commented after the latest maintainer review * (`authorActedAt`), or a maintainer approved it and no maintainer's latest verdict asks for changes. * Only reviews count, not plain comments, and a dismissed review is skipped. A push never dismisses a * change request, which is why the author's later activity is checked; a push after an approval makes * it our turn the same way, whether or not the repository dismisses approvals on a new push. */ export function waitingOnMaintainers(timeline, maintainers, authorActedAt = null) { const reviews = timeline.filter((e) => e.event === "reviewed" && e.state !== "dismissed" && maintainers.some((m) => sameUser(m, e.user?.login))); const verdicts = new Map(); for (const e of reviews.filter((review) => ["approved", "changes_requested"].includes(review.state))) { verdicts.set(e.user.login.toLowerCase(), e.state); } const states = [...verdicts.values()]; const lastReviewAt = Math.max(...reviews.map((review) => new Date(review.submitted_at).getTime())); return ( reviews.length === 0 || (authorActedAt !== null && authorActedAt.getTime() > lastReviewAt) || (states.includes("approved") && !states.includes("changes_requested")) ); } function latestReminder(timeline, pending) { const reminder = timeline .filter((e) => isComment(e) && sameUser(e.user?.login, BOT_LOGIN) && e.body?.includes(MARKER)) .filter((e) => e.body.includes(PENDING_MARKER) === pending) .at(-1); return reminder ? new Date(reminder.created_at) : null; } const latest = (...dates) => new Date(Math.max(...dates.map((date) => date.getTime()))); /** `pending-response` issues and PRs: waiting on the author's reply, which removes the label. */ function decidePending({ now, timeline, activity, author, remindedAt, start }) { const labeled = timeline.filter((e) => e.event === "labeled" && sameUser(e.label?.name, PENDING_LABEL)).at(-1); const labeledAt = new Date(labeled?.created_at ?? activity.createdAt); // Any reply since the label counts, including one posted while the item was closed. On a PR a push counts too. // Reopening isn't a reply: it only restarts the wait below. const replies = { ...activity, timeline: activity.timeline.filter((e) => e.event !== "reopened") }; if (lastHumanActivity({ ...replies, by: [author] }) > labeledAt) { return "unlabel"; } // A reopen restarts the wait, so an item reopened after a close isn't closed again the next day. const reopened = timeline.filter((e) => e.event === "reopened").at(-1); const startedAt = latest(labeledAt, new Date(reopened?.created_at ?? 0), start); return decideStale({ now, lastActivityAt: startedAt, remindedAt, remindDays: RESPONSE_REMIND_DAYS, closeDays: RESPONSE_CLOSE_DAYS }); } /** * When this workflow reached the default branch: the merge of the PR that added it, since a commit's own * date can be older. Nothing counts as quiet from before then, so the first run doesn't close a backlog. * Before the workflow is on the branch, that's now, so nothing goes stale. * shortcut: the same lookup as prRulesStart in #1674 with another path; share it once both have merged. */ async function sweepStart(github, repoRef, branch, now) { const commits = await github.paginate(github.rest.repos.listCommits, { ...repoRef, sha: branch, path: ".github/workflows/stale.yml", per_page: 100 }); const first = commits.at(-1); if (!first) { return now; } const prs = (await github.rest.repos.listPullRequestsAssociatedWithCommit({ ...repoRef, commit_sha: first.sha })).data; const merged = prs.map((pr) => pr.merged_at).filter(Boolean).sort(); return new Date(merged[0] ?? first.commit.committer.date); } async function sweepItem({ github, repoRef, core, now, dryRun, maintainers, start, item, isPr, pending }) { const number = item.number; const author = item.user.login; const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { ...repoRef, issue_number: number, per_page: 100 }); const remindedAt = latestReminder(timeline, pending); let activity = { timeline, reviewComments: [], createdAt: item.created_at, updatedAt: item.updated_at }; if (isPr) { const reviewComments = await github.paginate(github.rest.pulls.listReviewComments, { ...repoRef, pull_number: number, per_page: 100 }); // A maintainer's commit, such as "Update branch" or a rebase, isn't the author's turn. A commit is dated by // its committer, so that's who made this version of it: a maintainer who rebases the author's commits is // their committer. GitHub's web edits name `web-flow` as committer, so those go by the commit's author. // shortcut: GitHub lists at most 250 commits, so later ones count as the author's; fine unless a PR grows past that. // shortcut: an "Update branch" done by rebase may commit as `web-flow` under the author's name, so it counts as theirs; unverified on GitHub. const commits = await github.paginate(github.rest.pulls.listCommits, { ...repoRef, pull_number: number, per_page: 100 }); const madeBy = (commit) => (commit.committer?.login && commit.committer.login !== "web-flow" ? commit.committer.login : commit.author?.login); const committedBy = new Map(commits.map((commit) => [commit.sha, madeBy(commit)])); // Read after the activity, so a push since the PR list was read isn't taken for a forged commit date. const { data: pr } = await github.rest.pulls.get({ ...repoRef, pull_number: number }); activity = { timeline, reviewComments, createdAt: pr.created_at, updatedAt: pr.updated_at, committedBy }; } let decision; if (pending) { decision = decidePending({ now, timeline, activity, author, remindedAt, start }); } else if (!item.draft && waitingOnMaintainers(timeline, maintainers, lastHumanActivity({ ...activity, by: [author] }))) { // A draft is still the author's to finish, so it's never waiting on us. decision = "keep"; } else { // Only the author and maintainers move the clock, so someone else's "+1" can't keep a PR open. const lastActivityAt = latest(lastHumanActivity({ ...activity, by: [author, ...maintainers] }), start); decision = decideStale({ now, lastActivityAt, remindedAt, remindDays: PR_REMIND_DAYS, closeDays: PR_CLOSE_DAYS }); } if (decision === "keep") { return; } core.info(`#${number}: ${decision}${dryRun ? " (dry run)" : ""}`); if (dryRun) { return; } // The list was read when the sweep started. Anything since (a reply, a push, a maintainer exempting, // closing, unlabelling or relabelling it) skips the item, and the next run looks at it again. The list // gave a pull for a quiet PR and an issue otherwise, so updated_at is compared with the same kind of object. const current = (await github.rest.issues.get({ ...repoRef, issue_number: number })).data; const fresh = isPr && !pending ? (await github.rest.pulls.get({ ...repoRef, pull_number: number })).data : current; if (fresh.updated_at !== item.updated_at || current.state !== "open" || isExempt(current) || (pending && !hasLabel(current, PENDING_LABEL))) { core.info(`#${number}: changed since the sweep started, skipping`); return; } if (decision === "unlabel") { await github.rest.issues.removeLabel({ ...repoRef, issue_number: number, name: PENDING_LABEL }); return; } const text = { quiet: { remind: `${MARKER}\n@${author} this pull request has had no activity for ${PR_REMIND_DAYS} days. A push or a comment from you keeps it open; otherwise it will be closed in ${PR_CLOSE_DAYS} days.`, close: `Thanks for the work here. I'm closing this after ${PR_REMIND_DAYS + PR_CLOSE_DAYS} days without activity. If you pick it back up, ask a maintainer to reopen it.`, }, pending: { remind: `${MARKER}${PENDING_MARKER}\n@${author} this ${isPr ? "pull request" : "issue"} is waiting on a reply from you. It will be closed in ${RESPONSE_CLOSE_DAYS} days if there's none.`, close: isPr ? `Thanks for the work here. I'm closing this because there was no reply for ${RESPONSE_REMIND_DAYS + RESPONSE_CLOSE_DAYS} days. If you pick it back up, ask a maintainer to reopen it.` : `Thanks for reporting this. I'm closing it because there was no reply for ${RESPONSE_REMIND_DAYS + RESPONSE_CLOSE_DAYS} days. Comment here if it's still a problem.`, }, }; // Close before commenting: the close comment has no marker, so commenting first and then failing to // close would post it again on the next run. If the comment fails instead, the run fails where a // maintainer sees it, and the reminder has already told the author why. if (decision === "close") { await (isPr ? github.rest.pulls.update({ ...repoRef, pull_number: number, state: "closed" }) : github.rest.issues.update({ ...repoRef, issue_number: number, state: "closed", state_reason: "not_planned" })); } await github.rest.issues.createComment({ ...repoRef, issue_number: number, body: text[pending ? "pending" : "quiet"][decision] }); } export async function sweepStale({ github, context, core, maintainers, now = new Date(), dryRun = false }) { const maintainerList = maintainers ?? (await loadMaintainers(core)); // Without the list, approved PRs can't be recognised and could be closed. if (maintainerList.length === 0) { core.setFailed("No maintainers found in MAINTAINERS.md, so approved pull requests can't be recognised. Nothing was changed."); return; } const repoRef = context.repo; const start = await sweepStart(github, repoRef, context.payload?.repository?.default_branch, now); const [prs, labelled] = await Promise.all([ github.paginate(github.rest.pulls.list, { ...repoRef, state: "open", per_page: 100 }), github.paginate(github.rest.issues.listForRepo, { ...repoRef, state: "open", labels: PENDING_LABEL, per_page: 100 }), ]); // An issue or PR opened by a maintainer or a bot is ours to finish or close, not its author's to keep alive. const ours = (item) => isBot(item.user) || maintainerList.some((login) => sameUser(login, item.user.login)); // A labelled PR waits on its author like an issue does, so it goes through the pending path only. const items = [ ...prs.filter((pr) => !isExempt(pr) && !ours(pr) && !hasLabel(pr, PENDING_LABEL)).map((item) => ({ item, isPr: true, pending: false })), ...labelled .filter((item) => !isExempt(item) && !ours(item)) .map((item) => ({ item, isPr: Boolean(item.pull_request), pending: true })), ]; const failed = []; for (const { item, isPr, pending } of items) { try { await sweepItem({ github, repoRef, core, now, dryRun, maintainers: maintainerList, start, item, isPr, pending }); } catch (error) { failed.push(`#${item.number}`); core.warning(`#${item.number}: ${error instanceof Error ? error.message : String(error)}`); } } if (failed.length > 0) { core.setFailed(`Stale sweep failed for ${failed.join(", ")}`); } }