From d245f8e2858c7f411d6bbbb66f1bbfebde41e656 Mon Sep 17 00:00:00 2001 From: Turtle Date: Mon, 16 Nov 2026 15:55:46 +0800 Subject: [PATCH] feat(ci): close pull requests after 21 days without activity Refs #8432 --- .github/stale-pull-requests/remind.mjs | 66 ++++++++++++-------- .github/stale-pull-requests/remind.test.mjs | 67 +++++++++++++-------- .github/workflows/stale-pull-requests.yml | 10 +-- 3 files changed, 87 insertions(+), 56 deletions(-) diff --git a/.github/stale-pull-requests/remind.mjs b/.github/stale-pull-requests/remind.mjs index adff87f633..0b863dc865 100644 --- a/.github/stale-pull-requests/remind.mjs +++ b/.github/stale-pull-requests/remind.mjs @@ -1,24 +1,30 @@ /** - * Daily stale pull-request reminders for the `Stale pull requests` workflow. + * Daily stale pull-request reminders and closing for the `Stale pull requests` workflow. * * A pull request's last activity is the latest of its creation, a commit, a force push, a reopen or ready-for-review * event, and a comment or review from a non-bot account. Other timeline events, such as mentions, labels and cross - * references, do not count, so reminder comments never extend it. After 7 and 14 days without activity the workflow - * comments once per stage and mentions the author. Activity starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` - * and pull requests opened by bots receive no reminders. The workflow never closes pull requests. + * references, do not count, so reminder and closing comments never extend it. After 7 and 14 days without activity the + * workflow comments once per stage and mentions the author. After 21 days without activity, and at least 7 days after + * the 14-day reminder, it comments and closes the pull request; the reminder therefore always gives the author 7 days' + * notice, including for pull requests that were already inactive when the workflow started. Activity, including + * reopening, starts a new cycle. Pull requests labelled `DO_NOT_CLOSE` and pull requests opened by bots are neither + * reminded nor closed. * * Each run reads the timeline of every open pull request that is neither exempt nor bot-authored, because `updated_at` - * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` reminders, least recently + * also changes on events that are not activity. Each run posts at most `MAX_COMMENTS_PER_RUN` comments, least recently * updated pull requests first, so a backlog spreads over several days within GitHub's content-creation limits. A failed * pull request is reported and skipped. */ -/** Label that exempts a pull request from reminders. */ +/** Label that exempts a pull request from reminders and closing. */ export const EXEMPT_LABEL = 'DO_NOT_CLOSE' /** Days without activity after which each reminder is posted, in ascending order. */ export const REMINDER_DAYS = [7, 14] +/** Days without activity after which a pull request is closed. */ +export const CLOSE_DAYS = 21 + const DAY_MS = 24 * 60 * 60 * 1000 // GitHub asks integrations to wait at least one second between content-creating requests. const COMMENT_INTERVAL_MS = 1000 @@ -55,39 +61,44 @@ function activityTimes(event) { } /** - * Selects the reminder a pull request is due for. + * Selects the reminder or closing a pull request is due for. * @param {object} options * @param {string} options.createdAt Pull-request creation time. * @param {object[]} options.timeline Complete issue timeline of the pull request. * @param {Date} options.now Evaluation time. - * @returns {number | undefined} Due reminder stage in days, or `undefined` when none is due. + * @returns {number | undefined} Due stage in days, `CLOSE_DAYS` for closing, or `undefined` when nothing is due. */ -export function dueReminder({ createdAt, timeline, now }) { +export function dueStage({ createdAt, timeline, now }) { const times = [createdAt, ...timeline.flatMap(activityTimes)].map(time => Date.parse(time)).filter(Number.isFinite) const lastActivity = Math.max(...times) - const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) - if (due === undefined) return undefined const sent = timeline .filter(event => event.event === 'commented' && isBot(event.actor) && Date.parse(event.created_at) > lastActivity) - .map(event => Number(MARKER.exec(event.body ?? '')?.[1])) - return sent.some(days => days >= due) ? undefined : due + .map(event => ({ days: Number(MARKER.exec(event.body ?? '')?.[1]), at: Date.parse(event.created_at) })) + const finalReminder = REMINDER_DAYS.at(-1) + const noticeMs = (CLOSE_DAYS - finalReminder) * DAY_MS + if (now.getTime() - lastActivity >= CLOSE_DAYS * DAY_MS && sent.some(({ days, at }) => days === finalReminder && now.getTime() - at >= noticeMs)) { + return CLOSE_DAYS + } + const due = REMINDER_DAYS.filter(days => now.getTime() - lastActivity >= days * DAY_MS).at(-1) + if (due === undefined) return undefined + return sent.some(({ days }) => days >= due) ? undefined : due } /** - * Builds the reminder comment. + * Builds the reminder or closing comment. * @param {string} author Pull-request author login. - * @param {number} days Reminder stage in days. + * @param {number} days Stage in days; `CLOSE_DAYS` builds the closing comment. * @returns {string} Comment body. */ -export function reminderBody(author, days) { - return [ - ``, - `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop these reminders.`, - ].join('\n') +export function stageBody(author, days) { + const text = days === CLOSE_DAYS + ? `@${author} This pull request has had no activity for ${days} days and is now closed. Reopen it, or ask a maintainer to reopen it, if you continue the work.` + : `@${author} This pull request has had no activity for ${days} days. Please update it, reply to keep it open, or close it if it is no longer needed. Pull requests are closed after ${CLOSE_DAYS} days without activity and at least ${CLOSE_DAYS - REMINDER_DAYS.at(-1)} days after the ${REMINDER_DAYS.at(-1)}-day reminder. Add the \`${EXEMPT_LABEL}\` label, or ask a maintainer to add it, to stop reminders and closing.` + return `\n${text}` } /** - * Posts every due reminder on open pull requests of the workflow repository. + * Posts every due reminder and closes every due pull request among the open pull requests of the workflow repository. * @param {object} options * @param {object} options.github Authenticated Octokit client from `actions/github-script`. * @param {object} options.context Workflow context from `actions/github-script`. @@ -96,7 +107,7 @@ export function reminderBody(author, days) { * @param {(ms: number) => Promise} [options.sleep] Delay between comments. * @returns {Promise} */ -export async function remindStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { +export async function processStalePullRequests({ github, context, core, now = new Date(), sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) }) { const { owner, repo } = context.repo const pulls = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', sort: 'updated', direction: 'asc', per_page: 100 }) let posted = 0 @@ -107,12 +118,17 @@ export async function remindStalePullRequests({ github, context, core, now = new if (pull.labels.some(label => label.name === EXEMPT_LABEL)) continue try { const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, { owner, repo, issue_number: pull.number, per_page: 100 }) - const days = dueReminder({ createdAt: pull.created_at, timeline, now }) + const days = dueStage({ createdAt: pull.created_at, timeline, now }) if (days === undefined) continue if (posted > 0) await sleep(COMMENT_INTERVAL_MS) - await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: reminderBody(pull.user.login, days) }) + await github.rest.issues.createComment({ owner, repo, issue_number: pull.number, body: stageBody(pull.user.login, days) }) posted++ - core.info(`#${pull.number}: posted the ${days}-day reminder`) + if (days === CLOSE_DAYS) { + await github.rest.pulls.update({ owner, repo, pull_number: pull.number, state: 'closed' }) + core.info(`#${pull.number}: closed after ${days} days without activity`) + } else { + core.info(`#${pull.number}: posted the ${days}-day reminder`) + } } catch (error) { failed++ core.warning(`#${pull.number}: ${error.message}`) diff --git a/.github/stale-pull-requests/remind.test.mjs b/.github/stale-pull-requests/remind.test.mjs index cb2d56b437..be430e6576 100644 --- a/.github/stale-pull-requests/remind.test.mjs +++ b/.github/stale-pull-requests/remind.test.mjs @@ -1,47 +1,58 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { dueReminder, reminderBody, remindStalePullRequests } from './remind.mjs' +import { dueStage, stageBody, processStalePullRequests } from './remind.mjs' const now = new Date('2026-11-30T00:00:00Z') const daysAgo = days => new Date(now.getTime() - days * 24 * 60 * 60 * 1000).toISOString() const human = { login: 'author', type: 'User' } const bot = { login: 'github-actions[bot]', type: 'Bot' } const comment = (actor, days, body = 'ok') => ({ event: 'commented', actor, created_at: daysAgo(days), body }) -const reminder = (days, stage) => comment(bot, days, reminderBody('author', stage)) +const reminder = (days, stage) => comment(bot, days, stageBody('author', stage)) test('no reminder is due within 7 days of the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(6), timeline: [], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(6), timeline: [], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(30), timeline: [comment(human, 6)], now }), undefined) }) test('the latest due stage is posted once after the last activity', () => { - assert.equal(dueReminder({ createdAt: daysAgo(7), timeline: [], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(7), timeline: [], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(10), timeline: [reminder(3, 7)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(17), timeline: [reminder(3, 14)], now }), undefined) +}) + +test('a pull request closes after 21 days without activity and 7 days after the 14-day reminder', () => { + assert.equal(dueStage({ createdAt: daysAgo(21), timeline: [reminder(14, 7), reminder(7, 14)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(20, 14)], now }), 21) + // A pull request that was already inactive gets the 14-day reminder first and 7 days' notice. + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(6, 14)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [reminder(30, 7)], now }), 14) + // A 14-day reminder from before the last activity gives no notice. + assert.equal(dueStage({ createdAt: daysAgo(60), timeline: [reminder(40, 14), comment(human, 25)], now }), 14) }) test('human activity restarts the cycle and bot activity does not', () => { const sentBefore = [reminder(30, 7), reminder(23, 14)] - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), undefined) - assert.equal(dueReminder({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment(human, 8)], now }), 7) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'committed', committer: { date: daysAgo(3) } }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reviewed', user: human, submitted_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'line-commented', comments: [{ user: human, created_at: daysAgo(3) }] }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'head_ref_force_pushed', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, { event: 'reopened', actor: human, created_at: daysAgo(3) }], now }), undefined) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ci[bot]', type: 'Bot' }, 1)], now }), 21) + assert.equal(dueStage({ createdAt: daysAgo(40), timeline: [...sentBefore, comment({ login: 'ds-review-bot', type: 'User' }, 1)], now }), 21) }) test('mentions, labels and cross references are not activity', () => { const at = (event, days) => ({ event, actor: human, created_at: daysAgo(days) }) // GitHub records a `mentioned` event for the author right after each reminder. - assert.equal(dueReminder({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) - assert.equal(dueReminder({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(14), timeline: [reminder(7, 7), at('mentioned', 7 - 1e-5), at('subscribed', 7 - 1e-5)], now }), 14) + assert.equal(dueStage({ createdAt: daysAgo(20), timeline: [at('labeled', 1), at('cross-referenced', 1), at('review_requested', 1)], now }), 14) }) -test('reminders mention the author and skip exempt and bot-authored pull requests', async () => { +test('reminders and closing mention the author and skip exempt and bot-authored pull requests', async () => { const pull = (number, overrides = {}) => ({ number, user: human, labels: [], created_at: daysAgo(20), updated_at: daysAgo(20), ...overrides }) const pulls = [ pull(1), @@ -51,12 +62,14 @@ test('reminders mention the author and skip exempt and bot-authored pull request pull(4, { updated_at: daysAgo(1) }), pull(6), pull(5), + pull(7, { created_at: daysAgo(30) }), ] const comments = [] + const closed = [] const timelines = [] const github = { rest: { - pulls: { list: 'pulls' }, + pulls: { list: 'pulls', update: async params => closed.push(params) }, issues: { listEventsForTimeline: 'timeline', createComment: async params => { @@ -68,20 +81,22 @@ test('reminders mention the author and skip exempt and bot-authored pull request paginate: async (method, params) => { if (method === 'pulls') return pulls timelines.push(params.issue_number) - return [] + return params.issue_number === 7 ? [reminder(9, 14)] : [] }, } const sleeps = [] const warnings = [] const failures = [] const core = { info() {}, warning: message => warnings.push(message), setFailed: message => failures.push(message) } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) - assert.deepEqual(timelines, [1, 4, 6, 5]) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core, now, sleep: async ms => sleeps.push(ms) }) + assert.deepEqual(timelines, [1, 4, 6, 5, 7]) assert.deepEqual(warnings, ['#6: locked']) assert.equal(failures.length, 1) - assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5]) + assert.deepEqual(comments.map(({ issue_number }) => issue_number), [1, 4, 5, 7]) assert.match(comments[0].body, /^\n@author This pull request has had no activity for 14 days\./) - assert.deepEqual(sleeps, [1000, 1000, 1000]) + assert.match(comments[3].body, /^\n@author This pull request has had no activity for 21 days and is now closed\./) + assert.deepEqual(closed, [{ owner: 'o', repo: 'r', pull_number: 7, state: 'closed' }]) + assert.deepEqual(sleeps, [1000, 1000, 1000, 1000]) }) test('a run posts at most 100 reminders', async () => { @@ -91,6 +106,6 @@ test('a run posts at most 100 reminders', async () => { rest: { pulls: { list: 'pulls' }, issues: { listEventsForTimeline: 'timeline', createComment: async () => comments++ } }, paginate: async method => method === 'pulls' ? pulls : [], } - await remindStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) + await processStalePullRequests({ github, context: { repo: { owner: 'o', repo: 'r' } }, core: { info() {} }, now, sleep: async () => {} }) assert.equal(comments, 100) }) diff --git a/.github/workflows/stale-pull-requests.yml b/.github/workflows/stale-pull-requests.yml index a0ccb7f2b5..db1c3f8115 100644 --- a/.github/workflows/stale-pull-requests.yml +++ b/.github/workflows/stale-pull-requests.yml @@ -1,4 +1,4 @@ -# Reminds authors of open pull requests after 7 and 14 days without activity; never closes them. +# Reminds authors of open pull requests after 7 and 14 days without activity and closes them after 21 days. # Rules: .github/stale-pull-requests/remind.mjs. name: Stale pull requests @@ -16,7 +16,7 @@ concurrency: jobs: remind: - name: Remind stale pull requests + name: Remind and close stale pull requests runs-on: ubuntu-latest permissions: contents: read @@ -27,9 +27,9 @@ jobs: with: sparse-checkout: .github/stale-pull-requests persist-credentials: false - - name: Post due reminders + - name: Post due reminders and close stale pull requests uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 with: script: | - const { remindStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) - await remindStalePullRequests({ github, context, core }) + const { processStalePullRequests } = await import(`${process.env.GITHUB_WORKSPACE}/.github/stale-pull-requests/remind.mjs`) + await processStalePullRequests({ github, context, core })