From ca683f253b808b480fb2c96967f9cf168140eec1 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Sun, 29 Nov 2026 16:29:06 +0800 Subject: [PATCH 1/6] Add event-driven PR workflow labels Track the next PR action with ordinary GitHub events instead of hosted AI triage and a shared personal token. Keep semantic review and merge acceptance with reviewers and maintainers. Use default-branch code for label writes, relay fork review notifications without privileged PR execution, and invalidate readiness when the head or required merge conditions change. --- .github/agents/pr-triage.agent.md | 26 ++ .github/scripts/pr-status-label.cjs | 280 +++++++++++++++++ .github/scripts/pr-status-label.test.cjs | 373 +++++++++++++++++++++++ .github/skills/pr-workflow/SKILL.md | 132 ++++++++ .github/workflows/pr-review-signal.yml | 18 ++ .github/workflows/pr-status-label.yml | 76 +++++ .github/workflows/pr-workflow-checks.yml | 26 ++ CONTRIBUTING.md | 41 +++ 8 files changed, 972 insertions(+) create mode 100644 .github/agents/pr-triage.agent.md create mode 100644 .github/scripts/pr-status-label.cjs create mode 100644 .github/scripts/pr-status-label.test.cjs create mode 100644 .github/skills/pr-workflow/SKILL.md create mode 100644 .github/workflows/pr-review-signal.yml create mode 100644 .github/workflows/pr-status-label.yml create mode 100644 .github/workflows/pr-workflow-checks.yml diff --git a/.github/agents/pr-triage.agent.md b/.github/agents/pr-triage.agent.md new file mode 100644 index 0000000000..aa5579f705 --- /dev/null +++ b/.github/agents/pr-triage.agent.md @@ -0,0 +1,26 @@ +--- +name: PR triage +description: Explain an apache/brpc PR's next action or hand off a completed review using the shared workflow skill. Read-only unless a label update is explicitly requested. +tools: ['read', 'search', 'execute'] +--- + +Load `.github/skills/pr-workflow/SKILL.md`. Use its state definitions and handoff +rules with the current PR head, reviews, unresolved threads, author replies and +required checks. Do not infer acceptance from a push, a COMMENT review or a +passing optional check. + +Report the current state, proposed state and deciding evidence. New work with no +accepted review stays ready for review; an author answer that needs evaluation +belongs to a maintainer. A maintainer's acceptance of the current head and its +merge requirements are needed before ready to merge. + +Apply labels only when the user explicitly asks. Re-read the head, lifecycle and +labels before writing and verify the result afterward. If facts changed, discard +the old decision. If label access is unavailable, report the required handoff; +do not switch credentials. + +This is an interactive helper, not a hosted agent or slash-command service. It +needs no shared personal AI token. The repository's ordinary Action handles +observable lifecycle and review events; this agent handles interpretation when +asked. Do not launch another AI to decide labels automatically, change code, +push, approve or merge as a side effect of triage. diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs new file mode 100644 index 0000000000..a207a6558d --- /dev/null +++ b/.github/scripts/pr-status-label.cjs @@ -0,0 +1,280 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +// Deterministic PR handoffs. All decisions use GitHub API facts, never prose +// interpretation, PR code, workflow artifacts, or a personal credential. +const STATUS = [ + 'status/ready-for-review', 'status/review-in-progress', + 'status/awaiting-author', 'status/awaiting-maintainer', + 'status/ready-to-merge', 'status/blocked', +]; +const READY = 'status/ready-to-merge'; +const TRACKER = /^$/; +const WARNING = ''; +const SIGNAL = /^PR review signal #(\d+) review #(\d+)$/; +const statusOf = pr => pr.labels.map(label => label.name) + .filter(name => STATUS.includes(name)).sort(); +const active = pr => pr.state === 'open' && !pr.draft; +const unchanged = (a, b) => a.head.sha === b.head.sha && a.state === b.state + && a.draft === b.draft && statusOf(a).join() === statusOf(b).join(); +const numberOf = value => /^\d+$/.test(String(value || '')) && Number(value) > 0 + && Number.isSafeInteger(Number(value)) ? Number(value) : null; + +async function collect({ github, context }) { + const event = context.payload; + if (context.eventName === 'issue_comment') { + return event.issue.pull_request ? [event.issue.number] : []; + } + if (event.pull_request) return [event.pull_request.number]; + const { owner, repo } = context.repo; + if (context.eventName === 'workflow_run') { + const run = event.workflow_run; + const signal = run.name === 'PR review signal' && SIGNAL.exec(run.display_title || ''); + if (signal) return [Number(signal[1])]; + const prs = run.pull_requests?.length ? run.pull_requests + : (await github.rest.repos.listPullRequestsAssociatedWithCommit({ + owner, repo, commit_sha: run.head_sha, + })).data; + return [...new Set(prs.filter(pr => !pr.base?.repo?.full_name + || pr.base.repo.full_name === `${owner}/${repo}`) + .map(pr => pr.number))]; + } + const requested = event.inputs?.pr_number; + if (requested) { + const number = numberOf(requested); + if (!number) throw new Error('pr_number must be a positive integer'); + return [number]; + } + const prs = await github.paginate(github.rest.pulls.list, + { owner, repo, state: 'open', per_page: 100 }); + const numbers = prs.map(pr => pr.number).sort((a, b) => a - b); + // Bound batch work, rotating through unchanged PRs rather than letting the + // same first page monopolize every scan. Events still synchronize their PR. + if (numbers.length <= 20) return numbers; + const start = (Math.floor(Date.now() / 1800000) * 20) % numbers.length; + return [...numbers.slice(start), ...numbers.slice(0, start)].slice(0, 20); +} + +async function sync({ github, context, core, number }) { + if (!numberOf(number)) throw new Error('Invalid PR number'); + const { owner, repo } = context.repo; + const args = { owner, repo, issue_number: number }; + const event = context.payload; + const readPr = async () => (await github.rest.pulls.get({ + owner, repo, pull_number: number, + })).data; + const comments = () => github.paginate(github.rest.issues.listComments, + { ...args, per_page: 100 }); + const trackers = async () => (await comments()).filter(comment => + comment.user?.login === 'github-actions[bot]' && TRACKER.test(comment.body.trim())); + const dropTracker = async () => { + for (const comment of await trackers()) { + await github.rest.issues.deleteComment({ owner, repo, comment_id: comment.id }); + } + }; + const recordTracker = async sha => { + if (!/^[0-9a-f]{40}$/.test(sha || '')) throw new Error('Invalid head SHA'); + const existing = await trackers(); + const body = ``; + if (existing[0]?.body.trim() === body) return; + if (existing.length) { + await github.rest.issues.updateComment({ owner, repo, + comment_id: existing[0].id, body }); + } else { + await github.rest.issues.createComment({ ...args, body }); + } + for (const extra of existing.slice(1)) { + await github.rest.issues.deleteComment({ owner, repo, comment_id: extra.id }); + } + }; + const remove = async name => { + try { + await github.rest.issues.removeLabel({ ...args, name }); + } catch (error) { + if (error.status !== 404) throw error; + } + }; + const pr = await readPr(); + if (!active(pr)) { + for (let attempt = 0; attempt < 3; attempt++) { + const latest = await readPr(); + if (active(latest)) return; + const labels = statusOf(latest); + if (!labels.length) { + await dropTracker(); + return; + } + for (const name of labels) await remove(name); + } + return; + } + const current = statusOf(pr); + if (current.length > 1) { + if (!unchanged(pr, await readPr())) return; + if (!(await comments()).some(comment => comment.user?.login === 'github-actions[bot]' + && comment.body.startsWith(WARNING))) { + await github.rest.issues.createComment({ ...args, body: `${WARNING}\n` + + 'Multiple workflow states are set. A maintainer should retain the one ' + + `pending action: ${current.join(', ')}.` }); + } + return; + } + const state = current[0]; + if (context.eventName === 'pull_request_target' && event.action === 'synchronize' + && event.pull_request.head.sha !== pr.head.sha) return; + const setStatus = async next => { + if (state === next || !unchanged(pr, await readPr())) return; + for (const name of current) await remove(name); + if (state === READY) await dropTracker(); + // Do not add a state if a human changed the PR after removal. Label APIs + // have no compare-and-swap; preserve unrelated labels and recheck afterward. + const latest = await readPr(); + if (!active(latest) || latest.head.sha !== pr.head.sha || statusOf(latest).length) return; + await github.rest.issues.addLabels({ ...args, labels: [next] }); + const landed = await readPr(); + if (!active(landed)) await remove(next); + core.info(`PR #${number}: ${state || 'none'} -> ${next}`); + }; + + const signal = context.eventName === 'workflow_run' + && event.workflow_run.name === 'PR review signal' + && SIGNAL.exec(event.workflow_run.display_title || ''); + const checkReadiness = async () => { + // Only the server's merge requirements can invalidate a manually granted + // readiness state. A passing optional review/check never grants readiness. + let cursor = null; + do { + const data = await github.graphql(`query($owner:String!, $repo:String!, $number:Int!, $cursor:String) { + repository(owner:$owner,name:$repo) { pullRequest(number:$number) { + headRefOid reviewDecision mergeStateStatus + commits(last:1) { nodes { commit { statusCheckRollup { + contexts(first:100,after:$cursor) { + pageInfo { hasNextPage endCursor } + nodes { + ... on CheckRun { isRequired(pullRequestNumber:$number) status conclusion } + ... on StatusContext { isRequired(pullRequestNumber:$number) state } + } + } + } } } } + } } + }`, { owner, repo, number, cursor }); + const merge = data.repository.pullRequest; + if (merge.headRefOid !== pr.head.sha) return; + const checks = merge.commits?.nodes[0]?.commit.statusCheckRollup?.contexts; + const notPassing = checks?.nodes.some(check => check.isRequired && + (check.status ? check.status !== 'COMPLETED' + || !['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(check.conclusion) + : check.state !== 'SUCCESS')); + if (notPassing || ['CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(merge.reviewDecision) + || ['BLOCKED', 'DIRTY'].includes(merge.mergeStateStatus)) { + await setStatus('status/awaiting-maintainer'); + return; + } + cursor = checks?.pageInfo.hasNextPage ? checks.pageInfo.endCursor : null; + } while (cursor); + }; + + // A delayed unlabeled event must not delete a newer readiness record. + if (context.eventName === 'pull_request_target' && event.action === 'unlabeled' + && event.label?.name === READY && state !== READY) await dropTracker(); + if (state === READY) { + if (context.eventName === 'pull_request_target' && event.action === 'labeled' + && event.label?.name === READY && event.pull_request.head.sha === pr.head.sha) { + if (!unchanged(pr, await readPr())) return; + await recordTracker(pr.head.sha); + } + const records = await trackers(); + if (!records.some(comment => TRACKER.exec(comment.body.trim())[1] === pr.head.sha)) { + await setStatus('status/ready-for-review'); + return; + } + if (!signal) { + await checkReadiness(); + return; + } + } + if (state === 'status/blocked') return; // Only its owner can interpret the unblock condition. + + if (context.eventName === 'issue_comment') { + const comment = event.comment; + if (state === 'status/awaiting-author' && comment.user.login === pr.user.login + && comment.body.trim() && !comment.body.trim().startsWith('/')) { + // A reply asks for verification; it does not resolve blocking feedback. + await setStatus('status/awaiting-maintainer'); + } + return; + } + // Routine scans preserve explicit handoffs. They repair unlabeled PRs; + // review completion is processed only from an actual review notification. + if (state && !signal) return; + const reviews = (await github.paginate(github.rest.pulls.listReviews, + { owner, repo, pull_number: number, per_page: 100 })).sort((a, b) => + (a.submitted_at || '').localeCompare(b.submitted_at || '') || a.id - b.id); + let notifiedReview; + if (signal) { + if (Number(signal[1]) !== number) return; + const review = reviews.find(item => item.id === Number(signal[2])); + if (!review || review.commit_id !== pr.head.sha || review.state === 'PENDING') return; + notifiedReview = review; + // Do not replay an old completion over a review taken up more recently. + const timeline = await github.paginate(github.rest.issues.listEventsForTimeline, + { ...args, per_page: 100 }); + const signaledAt = event.workflow_run.created_at || review.submitted_at; + if (timeline.some(item => item.event === 'labeled' && item.label?.name === state + && item.created_at > signaledAt)) return; + } + const currentReviews = reviews.filter(review => review.commit_id === pr.head.sha + && ['COMMENTED', 'APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)); + if (!currentReviews.length) { + if (!state) await setStatus('status/ready-for-review'); + return; + } + const opinions = new Map(); + for (const review of currentReviews) { + if (['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)) { + opinions.set(review.user.login, review); + } + } + const requests = []; + for (const review of opinions.values()) { + if (review.state !== 'CHANGES_REQUESTED') continue; + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner, repo, username: review.user.login, + }); + if (['write', 'maintain', 'admin'].includes(data.permission)) requests.push(review); + } + const authorComments = requests.length ? (await comments()).filter(comment => + comment.user?.login === pr.user.login && comment.body.trim() + && !comment.body.trim().startsWith('/')) : []; + const unanswered = requests.some(review => !authorComments.some(comment => + (comment.updated_at || comment.created_at) > review.submitted_at)); + const withdrewRequest = notifiedReview && (notifiedReview.state === 'DISMISSED' + || notifiedReview.state === 'APPROVED' && currentReviews.some(review => + review.state === 'CHANGES_REQUESTED' && review.user.login === notifiedReview.user.login + && review.id < notifiedReview.id)); + if (unanswered) { + await setStatus('status/awaiting-author'); + } else if (state === READY) { + await checkReadiness(); + } else if (state !== 'status/awaiting-author' || authorComments.length || withdrewRequest) { + // COMMENT reviews and outside reviewers' requests need maintainer judgment. + // No comment parsing, automatic approval, or automatic merge readiness. + await setStatus('status/awaiting-maintainer'); + } +} + +module.exports = { collect, sync }; diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs new file mode 100644 index 0000000000..4f2b710dbf --- /dev/null +++ b/.github/scripts/pr-status-label.test.cjs @@ -0,0 +1,373 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { collect, sync } = require('./pr-status-label.cjs'); + +const HEAD = 'b'.repeat(40); +const OLD = 'a'.repeat(40); +const READY = 'status/ready-to-merge'; +const REVIEWABLE = 'status/ready-for-review'; +const MAINTAINER = 'status/awaiting-maintainer'; +const AUTHOR = 'status/awaiting-author'; +const PROGRESS = 'status/review-in-progress'; +const BLOCKED = 'status/blocked'; +const marker = sha => ``; +const review = (state, overrides = {}) => ({ id: 10, state, commit_id: HEAD, + user: { login: 'reviewer' }, submitted_at: '2026-11-28T02:00:00Z', ...overrides }); + +function fixture(options = {}) { + const pr = { number: 1, state: options.state || 'open', draft: options.draft || false, + head: { sha: HEAD }, user: { login: 'author' }, + labels: (options.labels || []).map(name => ({ name })) }; + const comments = structuredClone(options.comments || []); + const writes = []; + let reads = 0; + let checkPages = 0; + const context = { repo: { owner: 'apache', repo: 'brpc' }, + eventName: options.eventName || 'pull_request_target', + payload: { action: options.action || 'opened', pull_request: { + number: 1, head: { sha: options.eventHead || HEAD } }, + label: { name: options.eventLabel }, + repository: { default_branch: 'master' }, ...options.payload } }; + const issues = { + listComments() {}, listEventsForTimeline() {}, + async removeLabel({ name }) { + writes.push(['remove', name]); + pr.labels = pr.labels.filter(label => label.name !== name); + }, + async addLabels({ labels }) { + writes.push(['add', ...labels]); + for (const name of labels) pr.labels.push({ name }); + }, + async createComment({ body }) { + writes.push(['comment', body]); + comments.push({ id: comments.length + 100, user: { login: 'github-actions[bot]' }, body }); + }, + async updateComment({ comment_id, body }) { + writes.push(['edit-comment', comment_id]); + comments.find(comment => comment.id === comment_id).body = body; + }, + async deleteComment({ comment_id }) { + writes.push(['delete-comment', comment_id]); + const index = comments.findIndex(comment => comment.id === comment_id); + if (index >= 0) comments.splice(index, 1); + }, + }; + const pulls = { list() {}, listReviews() {}, async get() { + options.onRead?.(pr, ++reads); + return { data: structuredClone(pr) }; + } }; + const repos = { listPullRequestsAssociatedWithCommit() {}, + async getCollaboratorPermissionLevel() { + return { data: { permission: options.permission || 'write' } }; + } }; + const github = { + rest: { pulls, issues, repos }, + async paginate(method) { + if (method === issues.listComments) return structuredClone(comments); + if (method === issues.listEventsForTimeline) return options.timeline || []; + if (method === pulls.listReviews) return structuredClone(options.reviews || []); + if (method === pulls.list) return options.openPrs || []; + throw new Error('Unexpected API pagination'); + }, + async graphql() { return { repository: { pullRequest: { headRefOid: HEAD, + reviewDecision: null, mergeStateStatus: 'CLEAN', ...options.merge, + commits: { nodes: [{ commit: { statusCheckRollup: { contexts: + options.checkPages?.[checkPages++] || { nodes: options.checks || [], + pageInfo: { hasNextPage: false } } } } }] }, + } } }; }, + }; + return { pr, github, context, comments, writes, + async run() { + await sync({ github, context, core: { info() {} }, number: 1 }); + return pr.labels.map(label => label.name).sort(); + } }; +} + +function signalOptions(reviews, extra = {}) { + return { labels: [PROGRESS], reviews, eventName: 'workflow_run', + payload: { workflow_run: { name: 'PR review signal', + display_title: `PR review signal #1 review #${reviews[reviews.length - 1].id}` } }, ...extra }; +} + +test('new PR gets its initial state without replacing unrelated labels', async () => { + assert.deepEqual(await fixture({ labels: ['area/http'] }).run(), ['area/http', REVIEWABLE]); +}); + +test('draft and closed PRs clear statuses and trusted readiness records', async () => { + for (const lifecycle of [{ draft: true }, { state: 'closed' }]) { + const f = fixture({ ...lifecycle, action: 'labeled', eventLabel: READY, + labels: [READY, 'area/http'], comments: [ + { id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }, + ] }); + assert.deepEqual(await f.run(), ['area/http']); + assert.equal(f.comments.length, 0); + } +}); + +test('draft cleanup stops if the PR becomes active', async () => { + const f = fixture({ draft: true, labels: [REVIEWABLE], onRead(pr, count) { + if (count === 2) { pr.draft = false; pr.labels = [{ name: PROGRESS }]; } + } }); + assert.deepEqual(await f.run(), [PROGRESS]); + assert.equal(f.writes.length, 0); +}); + +test('reopening an unlabeled PR restores ready-for-review', async () => { + assert.deepEqual(await fixture({ action: 'reopened' }).run(), [REVIEWABLE]); +}); + +test('queued initial event does not overwrite a review already in progress', async () => { + assert.deepEqual(await fixture({ labels: [PROGRESS] }).run(), [PROGRESS]); +}); + +test('current-head readiness is recorded only after a single valid label', async () => { + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY }); + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.comments[0].body, marker(HEAD)); +}); + +test('new head invalidates readiness without using commit timestamps', async () => { + const f = fixture({ labels: [READY], action: 'synchronize', comments: [ + { id: 1, user: { login: 'github-actions[bot]' }, body: marker(OLD) }, + ] }); + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.equal(f.comments.length, 0); +}); + +test('stale push event does not invalidate a newer handoff', async () => { + const f = fixture({ labels: [READY], action: 'synchronize', eventHead: OLD }); + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.writes.length, 0); +}); + +test('current-head tracker survives a delayed push and optional CI failure', async () => { + const f = fixture({ labels: [READY], action: 'synchronize', + merge: { mergeStateStatus: 'UNSTABLE' }, comments: [ + { id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }, + ] }); + assert.deepEqual(await f.run(), [READY]); +}); + +test('forged or quoted trackers cannot preserve readiness or be edited/deleted', async () => { + for (const comment of [ + { id: 1, user: { login: 'author' }, body: marker(HEAD) }, + { id: 2, user: { login: 'github-actions[bot]' }, body: `Quoted example: ${marker(HEAD)}` }, + ]) { + const f = fixture({ labels: [READY], action: 'synchronize', comments: [comment] }); + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.deepEqual(f.comments, [comment]); + } +}); + +test('stale unlabeled event does not remove the record of a reapplied label', async () => { + const f = fixture({ labels: [READY], action: 'unlabeled', eventLabel: READY, + comments: [{ id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }] }); + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.comments.length, 1); +}); + +test('required merge constraints return readiness to maintainer', async () => { + const f = fixture({ labels: [READY], merge: { reviewDecision: 'REVIEW_REQUIRED' }, + comments: [{ id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('applying ready-to-merge immediately checks the required merge conditions', async () => { + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + merge: { reviewDecision: 'REVIEW_REQUIRED' } }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('required check failure or pending status invalidates readiness, optional failure does not', async () => { + for (const [check, expected] of [ + [{ isRequired: true, status: 'COMPLETED', conclusion: 'FAILURE' }, MAINTAINER], + [{ isRequired: true, state: 'PENDING' }, MAINTAINER], + [{ isRequired: false, status: 'COMPLETED', conclusion: 'FAILURE' }, READY], + [{ isRequired: true, status: 'COMPLETED', conclusion: 'SKIPPED' }, READY], + ]) { + const f = fixture({ labels: [READY], checks: [check], comments: [ + { id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }, + ] }); + assert.deepEqual(await f.run(), [expected]); + } +}); + +test('required checks are read beyond the first page', async () => { + const f = fixture({ labels: [READY], checkPages: [ + { nodes: [], pageInfo: { hasNextPage: true, endCursor: 'page2' } }, + { nodes: [{ isRequired: true, state: 'FAILURE' }], pageInfo: { hasNextPage: false } }, + ], comments: [{ id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('concurrent head or handoff change aborts the old decision', async () => { + for (const change of [pr => { pr.head.sha = OLD; }, + pr => { pr.labels = [{ name: BLOCKED }]; }]) { + const f = fixture({ onRead(pr, count) { if (count === 2) change(pr); } }); + await f.run(); + assert.equal(f.writes.length, 0); + } +}); + +test('a handoff inserted between removal and addition is preserved', async () => { + const f = fixture(signalOptions([review('COMMENTED')], { onRead(pr, count) { + if (count === 3) pr.labels = [{ name: BLOCKED }]; + } })); + assert.deepEqual(await f.run(), [BLOCKED]); + assert.ok(!f.writes.some(write => write[0] === 'add')); +}); + +test('current-head COMMENT review completes handoff without implying approval', async () => { + assert.deepEqual(await fixture(signalOptions([review('COMMENTED')])).run(), [MAINTAINER]); +}); + +test('approval also needs maintainer decision before ready-to-merge', async () => { + assert.deepEqual(await fixture(signalOptions([review('APPROVED')])).run(), [MAINTAINER]); +}); + +test('trusted changes request routes to author; outside reviewer routes to maintainer', async () => { + assert.deepEqual(await fixture(signalOptions([review('CHANGES_REQUESTED')])).run(), [AUTHOR]); + assert.deepEqual(await fixture(signalOptions([review('CHANGES_REQUESTED')], + { permission: 'read' })).run(), [MAINTAINER]); +}); + +test('new blocking feedback invalidates readiness even without a required-review rule', async () => { + const f = fixture(signalOptions([review('CHANGES_REQUESTED')], { labels: [READY], + comments: [{ id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }] })); + assert.deepEqual(await f.run(), [AUTHOR]); +}); + +test('an optional positive review does not undo maintainer merge readiness', async () => { + const f = fixture(signalOptions([review('APPROVED')], { labels: [READY], + comments: [{ id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }] })); + assert.deepEqual(await f.run(), [READY]); +}); + +test('another reviewer approval does not clear a blocking request', async () => { + const reviews = [review('CHANGES_REQUESTED'), review('APPROVED', + { id: 11, user: { login: 'other-reviewer' } })]; + assert.deepEqual(await fixture(signalOptions(reviews)).run(), [AUTHOR]); +}); + +test('reviewer followup supersedes their own previous changes request', async () => { + const reviews = [review('CHANGES_REQUESTED'), review('APPROVED', { id: 11 })]; + assert.deepEqual(await fixture(signalOptions(reviews)).run(), [MAINTAINER]); +}); + +test('reviewer COMMENT does not withdraw their existing formal changes request', async () => { + const reviews = [review('CHANGES_REQUESTED'), review('COMMENTED', { id: 11 })]; + assert.deepEqual(await fixture(signalOptions(reviews)).run(), [AUTHOR]); +}); + +test('dismissal or withdrawal of a blocking review returns to maintainer', async () => { + for (const reviews of [[review('DISMISSED')], + [review('CHANGES_REQUESTED'), review('APPROVED', { id: 11 })]]) { + const f = fixture(signalOptions(reviews, { labels: [AUTHOR] })); + assert.deepEqual(await f.run(), [MAINTAINER]); + } +}); + +test('dismissal is ordered by the notification rather than original submission time', async () => { + const f = fixture(signalOptions([review('DISMISSED')], { labels: [AUTHOR], + timeline: [{ event: 'labeled', label: { name: AUTHOR }, created_at: '2026-11-28T03:00:00Z' }], + payload: { workflow_run: { name: 'PR review signal', + display_title: 'PR review signal #1 review #10', created_at: '2026-11-28T04:00:00Z' } }, + })); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('author reply asks maintainer to verify; other comments do not change handoff', async () => { + for (const [login, expected] of [['author', MAINTAINER], ['other', AUTHOR]]) { + const f = fixture({ labels: [AUTHOR], eventName: 'issue_comment', + payload: { comment: { user: { login }, body: 'Here is the clarification.' } } }); + assert.deepEqual(await f.run(), [expected]); + } +}); + +test('a push alone does not answer author feedback', async () => { + assert.deepEqual(await fixture({ action: 'synchronize', labels: [AUTHOR] }).run(), [AUTHOR]); +}); + +test('author response to a formal request remains a maintainer verification task', async () => { + const f = fixture(signalOptions([review('CHANGES_REQUESTED')], { comments: [ + { id: 1, user: { login: 'author' }, body: 'Please verify the clarification.', + created_at: '2026-11-28T03:00:00Z' }, + ] })); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('old-head and nonexistent review signals do not update labels', async () => { + for (const reviews of [[review('COMMENTED', { commit_id: OLD })], []]) { + const f = fixture(signalOptions([review('COMMENTED')], { reviews })); + assert.deepEqual(await f.run(), [PROGRESS]); + assert.equal(f.writes.length, 0); + } +}); + +test('an old review completion does not replay over a newer accepted task', async () => { + const f = fixture(signalOptions([review('COMMENTED')], { timeline: [ + { event: 'labeled', label: { name: PROGRESS }, created_at: '2026-11-28T03:00:00Z' }, + ] })); + assert.deepEqual(await f.run(), [PROGRESS]); +}); + +test('routine scans preserve an explicit handoff even when old reviews exist', async () => { + const f = fixture({ labels: [PROGRESS], reviews: [review('COMMENTED')], eventName: 'schedule' }); + assert.deepEqual(await f.run(), [PROGRESS]); + assert.equal(f.writes.length, 0); +}); + +test('batch repairs a missing state from current reviews and preserves blockers', async () => { + assert.deepEqual(await fixture({ eventName: 'schedule', reviews: [review('COMMENTED')] }).run(), + [MAINTAINER]); + assert.deepEqual(await fixture(signalOptions([review('APPROVED')], { labels: [BLOCKED] })).run(), + [BLOCKED]); +}); + +test('conflicting statuses are reported once, with no arbitrary selection', async () => { + const f = fixture({ labels: [AUTHOR, MAINTAINER] }); + assert.deepEqual(await f.run(), [AUTHOR, MAINTAINER].sort()); + await f.run(); + assert.equal(f.comments.length, 1); +}); + +test('collection ignores issues and accepts PR comments without slash commands', async () => { + for (const [pull_request, expected] of [[undefined, []], [{ url: 'pr' }, [1]]]) { + const f = fixture({ eventName: 'issue_comment', payload: { + issue: { number: 1, pull_request }, pull_request: undefined } }); + assert.deepEqual(await collect(f), expected); + } +}); + +test('fork review notification identifies the PR without a privileged PR checkout', async () => { + const f = fixture(signalOptions([review('COMMENTED')], { payload: { pull_request: undefined, + workflow_run: { name: 'PR review signal', display_title: 'PR review signal #1 review #10' } } })); + assert.deepEqual(await collect(f), [1]); +}); + +test('manual scan validates an explicit PR number and scans all small backlogs', async () => { + const f = fixture({ eventName: 'workflow_dispatch', openPrs: [{ number: 3 }, { number: 1 }], + payload: { pull_request: undefined } }); + assert.deepEqual(await collect(f), [1, 3]); + f.context.payload.inputs = { pr_number: '12' }; + assert.deepEqual(await collect(f), [12]); + f.context.payload.inputs.pr_number = '-1'; + await assert.rejects(collect(f), /positive integer/); +}); diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md new file mode 100644 index 0000000000..b0b39890d7 --- /dev/null +++ b/.github/skills/pr-workflow/SKILL.md @@ -0,0 +1,132 @@ +--- +name: pr-workflow +description: Decide or explain the next-action workflow label of an apache/brpc pull request, or hand off a completed review. Use with any reviewer or AI service; it does not launch an AI review or authorize repository writes. +license: Apache-2.0 +--- + +# PR workflow labels + +Reference proposal: . +The status meanings and handoffs apply to other Git hosting systems too. GitHub +Actions is an adapter for observable events, not the source of review decisions. + +## States + +- `status/ready-for-review`: new or revised work awaiting an arranged review. +- `status/review-in-progress`: a human has started or an AI service has accepted + the review, including an accepted task waiting to run. A request alone is not + acceptance. +- `status/awaiting-author`: review requires author changes or clarification. +- `status/awaiting-maintainer`: a maintainer decision, verification, or approval + is needed, including evaluation of an author's answer or disputed AI finding. +- `status/ready-to-merge`: a maintainer has accepted the current head, required + approvals and checks pass now, and no blocking feedback remains. +- `status/blocked`: an external dependency prevents progress. The PR states the + reason and the condition that unblocks it. + +At most one status label applies. Draft/WIP and closed or merged changes have +none. Labels identify the next action, not ownership; independent reviews of +any scope are welcome and need no extra participation report. + +## Review and handoff + +1. Read the current head, lifecycle, labels, checks, reviews, review threads and + relevant author replies. A review summary alone may omit outstanding feedback. +2. New work starts ready for review. Once a reviewer or service takes the task, + it can enter in progress. Starting a tool that was rejected is not acceptance. +3. Finish the review through the ordinary review mechanism. Required author + changes go to awaiting author; otherwise hand off to awaiting maintainer. + Distinguish blocking findings from suggestions. Another positive review does + not resolve existing blocking feedback. +4. An author reply requests verification, not automatic acceptance. A prepared + code revision can return to ready for review; clarification can return directly + to awaiting maintainer. A push alone does not answer the feedback. +5. Maintainers decide whether to request changes, arrange more review, or accept + the current head and mark ready to merge. Passing CI or a COMMENT review alone + does not supply that decision. Never merge merely because the label is set. + +AI findings are advisory: authors can respond with code or an explanation; +maintainers settle disagreements. No author needs an AI subscription. Use an +available review service or local agent, or review directly. This skill requires +no particular model, shared personal token, AW installation, or `/triage` command. + +## Decide the pending action + +Apply these distinctions: + +- Draft/closed/merged: no status label. +- Concrete external blocker: blocked. Normal CI execution is not a blocker. +- Unanswered blocking feedback: awaiting author. +- A reply that needs evaluation, a disputed finding, or failed/cancelled review: + awaiting maintainer. An in-progress label must not conceal an abandoned task. +- An accepted review still handling the current handoff: review in progress. +- Explicit maintainer acceptance of the current head with merge requirements + satisfied now: ready to merge. +- Completed review awaiting a decision: awaiting maintainer. +- No review taken up for the new or revised work: ready for review. + +Keep the state when the pending action has not changed. An optional parallel +review does not delay an otherwise completed handoff. If facts do not establish +whether feedback was answered or accepted, leave that judgment to a maintainer; +do not infer approval from words such as "LGTM" in an unrelated comment. + +## Using GitHub + +For example, read the basic facts with: + +```bash +gh pr view --repo apache/brpc --json \ + number,title,isDraft,state,labels,headRefOid,reviewDecision,reviews,statusCheckRollup +gh pr checks --repo apache/brpc +``` + +Read review threads and author replies as needed, rather than treating an old +review or unresolved disagreement as a fresh clean review. Report the current +state, proposed state, and the deciding facts. Apply a label only when authorized +by the user or by the explicitly invoked review workflow. Without label access, +report the handoff for a maintainer; do not obtain a different credential. + +Immediately before writing, re-read the head, lifecycle and status labels. If +another action changed them, discard the old decision. Required merge conditions +must also still hold when marking ready to merge. + +```bash +gh pr edit --repo apache/brpc \ + --remove-label status/ --add-label status/ +gh pr view --repo apache/brpc --json labels,headRefOid,state,isDraft +``` + +Omit removal or addition when that state is absent. The label APIs do not offer +compare-and-swap; do not overwrite a concurrent handoff or claim atomicity. +For blocked, include the dependency and unblock condition in a short comment. + +The ordinary Action records the head when a maintainer sets ready-to-merge using +the GitHub UI or their normal CLI credentials. A separate automation using +`GITHUB_TOKEN` does not trigger that event: it must record the verified full head +as `` before setting +the label. Only the workflow bot's exact record is trusted. A new head invalidates +readiness for the old head regardless of commit creation time. + +## Automatic synchronization boundary + +`.github/workflows/pr-status-label.yml` uses only `GITHUB_TOKEN` and rules: + +- PR lifecycle events maintain the initial state and remove stale readiness. +- Review notifications re-read the current review. A maintainer's formal changes + request can route to author; COMMENT reviews, outside reviewers' requests and + approvals route to maintainer for interpretation. An approval never grants + ready-to-merge automatically. +- Author conversation replies while awaiting author route to maintainer for + verification. Neither comment prose nor a push is interpreted as acceptance. +- CI completion checks whether an existing ready-to-merge state still satisfies + GitHub's merge requirements. Optional failures do not become blocking findings. +- Every half hour, and on manual dispatch, a rotating batch of at most 20 open + PRs is checked for lifecycle cleanup, missing/conflicting states and stale + readiness. Explicit handoffs are preserved; unchanged PRs receive no comment. + +Fork review events use a read-only notification workflow and a default-branch +receiver; no PR code or artifacts are executed with a write token. Services that +publish reviews using `GITHUB_TOKEN` do not generate downstream events and must +perform their authorized handoff themselves. Semantic review, AI scheduling, +review-service timeout detection, approval and merging stay with reviewers and +maintainers, not this Action. There is no per-PR AI triage command or LLM scan. diff --git a/.github/workflows/pr-review-signal.yml b/.github/workflows/pr-review-signal.yml new file mode 100644 index 0000000000..77e553b5c5 --- /dev/null +++ b/.github/workflows/pr-review-signal.yml @@ -0,0 +1,18 @@ +# Fork review events have a read-only token. Only event identity is forwarded; +# PR status label re-reads the actual review through the API before acting. +# No artifact, PR content, or PR code is trusted. +name: PR review signal +run-name: 'PR review signal #${{ github.event.pull_request.number }} review #${{ github.event.review.id }}' + +on: + pull_request_review: + types: [submitted, edited, dismissed] + +permissions: {} + +jobs: + notify: + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - run: echo 'Review activity received; status synchronization re-reads the review.' diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml new file mode 100644 index 0000000000..417a9e0ecd --- /dev/null +++ b/.github/workflows/pr-status-label.yml @@ -0,0 +1,76 @@ +# Trusted default-branch code only; never checks out PR code. Uses GITHUB_TOKEN. +name: PR status label + +on: + pull_request_target: + types: [opened, reopened, ready_for_review, converted_to_draft, synchronize, labeled, unlabeled, closed] + issue_comment: + types: [created, edited] + workflow_run: + workflows: + - PR review signal + - Build and Test on Linux + - Build on Macos + - FlatBuffers ON + - License Check + - PR workflow checks + types: [completed] + schedule: + - cron: '17,47 * * * *' + workflow_dispatch: + inputs: + pr_number: + description: 'PR number; leave empty for a rotating batch of up to 20 open PRs' + required: false + type: string + +permissions: + contents: read + pull-requests: read + +jobs: + collect: + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + numbers: ${{ steps.prs.outputs.numbers }} + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/github-script@v7 + id: prs + with: + script: | + const { collect } = require('./.github/scripts/pr-status-label.cjs'); + core.setOutput('numbers', JSON.stringify(await collect({ github, context }))); + + sync: + needs: collect + if: needs.collect.outputs.numbers != '[]' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: write + strategy: + fail-fast: false + max-parallel: 5 + matrix: + number: ${{ fromJSON(needs.collect.outputs.numbers) }} + concurrency: + group: pr-status-label-${{ matrix.number }} + cancel-in-progress: false + steps: + - uses: actions/checkout@v7.0.1 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/github-script@v7 + env: + PR_NUMBER: ${{ matrix.number }} + with: + script: | + const { sync } = require('./.github/scripts/pr-status-label.cjs'); + await sync({ github, context, core, number: Number(process.env.PR_NUMBER) }); diff --git a/.github/workflows/pr-workflow-checks.yml b/.github/workflows/pr-workflow-checks.yml new file mode 100644 index 0000000000..81ab0a8e94 --- /dev/null +++ b/.github/workflows/pr-workflow-checks.yml @@ -0,0 +1,26 @@ +name: PR workflow checks + +on: + pull_request: + paths: + - '.github/scripts/pr-status-label*.cjs' + - '.github/workflows/pr-*.yml' + - '.github/skills/pr-workflow/**' + push: + branches: [master] + paths: + - '.github/scripts/pr-status-label*.cjs' + - '.github/workflows/pr-*.yml' + - '.github/skills/pr-workflow/**' + +permissions: + contents: read + +jobs: + handoffs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - run: node --test .github/scripts/pr-status-label.test.cjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a458f38611..b90242011f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,6 +12,28 @@ After the PR: * Make sure the [GitHub Actions](https://github.com/apache/brpc/actions) passed. +## Review workflow labels + +A pull request is tracked with at most one `status/*` label that records where +it needs attention next: + +* `status/ready-for-review`: waiting for a review to be arranged. +* `status/review-in-progress`: a person or an AI service has taken up the review. +* `status/awaiting-author`: the author needs to answer review feedback. +* `status/awaiting-maintainer`: a maintainer needs to decide, verify, or approve. +* `status/ready-to-merge`: required approvals and checks are satisfied; ready to merge. +* `status/blocked`: an external dependency stops progress; the reason is in the PR. + +Draft, closed, and merged pull requests carry no workflow label. A label records +the pending action, not ownership, so anyone may still review. AI findings are +advisory; maintainers decide whether feedback blocks progress. Ordinary GitHub +Actions synchronize observable lifecycle and review events using the +repository's built-in token. No personal AI token or per-PR `/triage` command is +required. Author replies request verification, and approvals do not automatically +mark a PR ready to merge. +Reviewers may use any service or local agent; the full handoff rules are in +[.github/skills/pr-workflow/SKILL.md](.github/skills/pr-workflow/SKILL.md). + # Chinese version 如果你遇到问题或需要新功能,欢迎[创建issue](https://github.com/apache/brpc/issues/new/choose)。 @@ -27,3 +49,22 @@ After the PR: 提交PR后请确认: * [GitHub Actions](https://github.com/apache/brpc/actions)成功通过。 + +## 评审工作流标签 + +每个 PR 最多带一个 `status/*` 标签,用来表示下一步需要谁处理: + +* `status/ready-for-review`:等待安排评审。 +* `status/review-in-progress`:评审已被人工或 AI 服务接手。 +* `status/awaiting-author`:需要作者回应评审意见。 +* `status/awaiting-maintainer`:需要 maintainer 判断、验证或批准。 +* `status/ready-to-merge`:所需批准与检查均已满足,可以合入。 +* `status/blocked`:被外部依赖阻塞,原因写在 PR 中。 + +草稿、已关闭和已合入的 PR 不带工作流标签。标签表示待办动作,不代表所有权, +任何人都可以评审。AI 意见仅供参考,是否阻塞推进由 maintainer 判断。 +普通 GitHub Actions 使用仓库自带 token 同步可观察的生命周期和评审事件, +不要求个人 AI token,也无需逐个 PR 执行 `/triage`。作者回复后仍需验证, +批准也不会自动将 PR 标为可合入。评审可以使用任意服务或本地 agent。 +完整的交接规则见 +[.github/skills/pr-workflow/SKILL.md](.github/skills/pr-workflow/SKILL.md)。 From 1c308858e3b4301e05558ccf162f89addf5fa2fb Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Sun, 29 Nov 2026 23:45:35 +0800 Subject: [PATCH 2/6] Skip inactive unenrolled PRs in batch scans Default batch enrollment to PRs updated within 90 days, configurable via PR_WORKFLOW_IDLE_DAYS. Keep existing workflow states under observation and always process direct events and explicit PR requests. --- .github/scripts/pr-status-label.cjs | 15 ++++++++++--- .github/scripts/pr-status-label.test.cjs | 28 ++++++++++++++++++++++++ .github/skills/pr-workflow/SKILL.md | 4 ++++ .github/workflows/pr-status-label.yml | 6 ++++- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index a207a6558d..3e4e241700 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -34,7 +34,7 @@ const unchanged = (a, b) => a.head.sha === b.head.sha && a.state === b.state const numberOf = value => /^\d+$/.test(String(value || '')) && Number(value) > 0 && Number.isSafeInteger(Number(value)) ? Number(value) : null; -async function collect({ github, context }) { +async function collect({ github, context, idleDays = 90, now = Date.now() }) { const event = context.payload; if (context.eventName === 'issue_comment') { return event.issue.pull_request ? [event.issue.number] : []; @@ -59,13 +59,22 @@ async function collect({ github, context }) { if (!number) throw new Error('pr_number must be a positive integer'); return [number]; } + const days = Number(idleDays); + if (!Number.isSafeInteger(days) || days <= 0) { + throw new Error('PR_WORKFLOW_IDLE_DAYS must be a positive integer'); + } + const cutoff = now - days * 86400000; const prs = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100 }); - const numbers = prs.map(pr => pr.number).sort((a, b) => a - b); + // Keep enrolled PRs even when idle. Events and explicit requests above always + // bypass this batch-only filter; an old PR can resume through new activity. + const numbers = prs.filter(pr => (pr.labels || []).some(label => STATUS.includes(label.name)) + || !(Date.parse(pr.updated_at) < cutoff)) + .map(pr => pr.number).sort((a, b) => a - b); // Bound batch work, rotating through unchanged PRs rather than letting the // same first page monopolize every scan. Events still synchronize their PR. if (numbers.length <= 20) return numbers; - const start = (Math.floor(Date.now() / 1800000) * 20) % numbers.length; + const start = (Math.floor(now / 1800000) * 20) % numbers.length; return [...numbers.slice(start), ...numbers.slice(0, start)].slice(0, 20); } diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 4f2b710dbf..0a6ec06646 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -371,3 +371,31 @@ test('manual scan validates an explicit PR number and scans all small backlogs', f.context.payload.inputs.pr_number = '-1'; await assert.rejects(collect(f), /positive integer/); }); + +test('batch skips idle unenrolled PRs but retains active and enrolled work', async () => { + const now = Date.parse('2026-11-29T00:00:00Z'); + const ago = days => new Date(now - days * 86400000).toISOString(); + for (const eventName of ['schedule', 'workflow_dispatch']) { + const f = fixture({ eventName, payload: { pull_request: undefined }, openPrs: [ + { number: 1, updated_at: ago(91), labels: [] }, + { number: 2, updated_at: ago(90), labels: [] }, + { number: 3, updated_at: ago(1), labels: [], created_at: ago(365) }, + { number: 4, updated_at: ago(365), labels: [{ name: AUTHOR }] }, + { number: 5, updated_at: ago(365), labels: [{ name: 'area/http' }] }, + ] }); + assert.deepEqual(await collect({ ...f, now }), [2, 3, 4]); + assert.deepEqual(await collect({ ...f, now, idleDays: '30' }), [3, 4]); + f.context.payload.inputs = { pr_number: '1' }; + assert.deepEqual(await collect({ ...f, now }), [1]); + } +}); + +test('batch rejects invalid idle thresholds; PR events bypass the age filter', async () => { + const f = fixture({ eventName: 'schedule', payload: { pull_request: undefined } }); + for (const idleDays of [0, -1, 1.5, 'invalid', '']) { + await assert.rejects(collect({ ...f, idleDays }), /positive integer/); + } + const event = fixture({ payload: { pull_request: { number: 1, + updated_at: '2020-01-01T00:00:00Z' } } }); + assert.deepEqual(await collect(event), [1]); +}); diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index b0b39890d7..7f088cc26b 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -123,6 +123,10 @@ readiness for the old head regardless of commit creation time. - Every half hour, and on manual dispatch, a rotating batch of at most 20 open PRs is checked for lifecycle cleanup, missing/conflicting states and stale readiness. Explicit handoffs are preserved; unchanged PRs receive no comment. + Batch scans skip PRs without workflow labels last updated over 90 days ago. Set the + repository Actions variable `PR_WORKFLOW_IDLE_DAYS` to a positive integer to + change this threshold. Existing workflow labels, new events and an explicitly + requested PR bypass the age filter; age is based on update time, not creation. Fork review events use a read-only notification workflow and a default-branch receiver; no PR code or artifacts are executed with a write token. Services that diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index 417a9e0ecd..6df1cd87aa 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -41,10 +41,14 @@ jobs: persist-credentials: false - uses: actions/github-script@v7 id: prs + env: + PR_WORKFLOW_IDLE_DAYS: ${{ vars.PR_WORKFLOW_IDLE_DAYS || '90' }} with: script: | const { collect } = require('./.github/scripts/pr-status-label.cjs'); - core.setOutput('numbers', JSON.stringify(await collect({ github, context }))); + core.setOutput('numbers', JSON.stringify(await collect({ + github, context, idleDays: process.env.PR_WORKFLOW_IDLE_DAYS, + }))); sync: needs: collect From a99d8e89b0ec0ecf2457bad73651fe48ff8adb8c Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Sun, 29 Nov 2026 23:45:51 +0800 Subject: [PATCH 3/6] Use Node.js 24 for PR status scripts Upgrade github-script to v8 to avoid the Node.js 20 deprecation warning seen in the demo workflow. Keep the runtime update separate from PR eligibility changes. --- .github/workflows/pr-status-label.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index 6df1cd87aa..c498d822ca 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -39,7 +39,7 @@ jobs: with: ref: ${{ github.event.repository.default_branch }} persist-credentials: false - - uses: actions/github-script@v7 + - uses: actions/github-script@v8 id: prs env: PR_WORKFLOW_IDLE_DAYS: ${{ vars.PR_WORKFLOW_IDLE_DAYS || '90' }} @@ -71,7 +71,7 @@ jobs: with: ref: ${{ github.event.repository.default_branch }} persist-credentials: false - - uses: actions/github-script@v7 + - uses: actions/github-script@v8 env: PR_NUMBER: ${{ matrix.number }} with: From 3a1cfd6d1f23cefd2c3beb7fba3899b95e1fd092 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Sun, 29 Nov 2026 23:55:07 +0800 Subject: [PATCH 4/6] Add ASF license headers to PR workflow files --- .github/agents/pr-triage.agent.md | 19 +++++++++++++++++++ .github/skills/pr-workflow/SKILL.md | 19 +++++++++++++++++++ .github/workflows/pr-review-signal.yml | 17 +++++++++++++++++ .github/workflows/pr-status-label.yml | 17 +++++++++++++++++ .github/workflows/pr-workflow-checks.yml | 17 +++++++++++++++++ 5 files changed, 89 insertions(+) diff --git a/.github/agents/pr-triage.agent.md b/.github/agents/pr-triage.agent.md index aa5579f705..fa1e6df1b2 100644 --- a/.github/agents/pr-triage.agent.md +++ b/.github/agents/pr-triage.agent.md @@ -4,6 +4,25 @@ description: Explain an apache/brpc PR's next action or hand off a completed rev tools: ['read', 'search', 'execute'] --- + + Load `.github/skills/pr-workflow/SKILL.md`. Use its state definitions and handoff rules with the current PR head, reviews, unresolved threads, author replies and required checks. Do not infer acceptance from a push, a COMMENT review or a diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index 7f088cc26b..bd88f32822 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -4,6 +4,25 @@ description: Decide or explain the next-action workflow label of an apache/brpc license: Apache-2.0 --- + + # PR workflow labels Reference proposal: . diff --git a/.github/workflows/pr-review-signal.yml b/.github/workflows/pr-review-signal.yml index 77e553b5c5..a98735a324 100644 --- a/.github/workflows/pr-review-signal.yml +++ b/.github/workflows/pr-review-signal.yml @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + # Fork review events have a read-only token. Only event identity is forwarded; # PR status label re-reads the actual review through the API before acting. # No artifact, PR content, or PR code is trusted. diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index c498d822ca..eee15b6701 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + # Trusted default-branch code only; never checks out PR code. Uses GITHUB_TOKEN. name: PR status label diff --git a/.github/workflows/pr-workflow-checks.yml b/.github/workflows/pr-workflow-checks.yml index 81ab0a8e94..e61662db0d 100644 --- a/.github/workflows/pr-workflow-checks.yml +++ b/.github/workflows/pr-workflow-checks.yml @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + name: PR workflow checks on: From df536cf6037115e26c54f7b3f5b49e7f2a712cfb Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Mon, 30 Nov 2026 18:35:45 +0800 Subject: [PATCH 5/6] Validate permission before granting merge readiness Require write, maintain or admin permission before recording the head accepted as ready to merge. A triage-only labeler must hand the decision to a maintainer. Treat missing collaborators as untrusted and propagate other permission lookup failures. --- .github/scripts/pr-status-label.cjs | 21 +++++++++++++--- .github/scripts/pr-status-label.test.cjs | 32 ++++++++++++++++++++++++ .github/skills/pr-workflow/SKILL.md | 4 ++- 3 files changed, 52 insertions(+), 5 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 3e4e241700..5388f96abb 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -83,6 +83,18 @@ async function sync({ github, context, core, number }) { const { owner, repo } = context.repo; const args = { owner, repo, issue_number: number }; const event = context.payload; + const canDecide = async username => { + if (!username) return false; + try { + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner, repo, username, + }); + return ['write', 'maintain', 'admin'].includes(data.permission); + } catch (error) { + if (error.status === 404) return false; + throw error; + } + }; const readPr = async () => (await github.rest.pulls.get({ owner, repo, pull_number: number, })).data; @@ -204,6 +216,10 @@ async function sync({ github, context, core, number }) { if (context.eventName === 'pull_request_target' && event.action === 'labeled' && event.label?.name === READY && event.pull_request.head.sha === pr.head.sha) { if (!unchanged(pr, await readPr())) return; + if (!await canDecide(event.sender?.login)) { + await setStatus('status/awaiting-maintainer'); + return; + } await recordTracker(pr.head.sha); } const records = await trackers(); @@ -261,10 +277,7 @@ async function sync({ github, context, core, number }) { const requests = []; for (const review of opinions.values()) { if (review.state !== 'CHANGES_REQUESTED') continue; - const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ - owner, repo, username: review.user.login, - }); - if (['write', 'maintain', 'admin'].includes(data.permission)) requests.push(review); + if (await canDecide(review.user.login)) requests.push(review); } const authorComments = requests.length ? (await comments()).filter(comment => comment.user?.login === pr.user.login && comment.body.trim() diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 0a6ec06646..835cbeb443 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -44,6 +44,7 @@ function fixture(options = {}) { payload: { action: options.action || 'opened', pull_request: { number: 1, head: { sha: options.eventHead || HEAD } }, label: { name: options.eventLabel }, + sender: { login: 'labeler' }, repository: { default_branch: 'master' }, ...options.payload } }; const issues = { listComments() {}, listEventsForTimeline() {}, @@ -75,6 +76,8 @@ function fixture(options = {}) { } }; const repos = { listPullRequestsAssociatedWithCommit() {}, async getCollaboratorPermissionLevel() { + if (options.permissionError) throw Object.assign(new Error('Permission lookup failed'), + { status: options.permissionError }); return { data: { permission: options.permission || 'write' } }; } }; const github = { @@ -143,6 +146,19 @@ test('current-head readiness is recorded only after a single valid label', async assert.equal(f.comments[0].body, marker(HEAD)); }); +test('readiness requires a labeler with write, maintain or admin permission', async () => { + for (const permission of ['write', 'maintain', 'admin', 'triage', 'read', 'none']) { + const allowed = ['write', 'maintain', 'admin'].includes(permission); + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, permission }); + assert.deepEqual(await f.run(), [allowed ? READY : MAINTAINER]); + assert.equal(f.comments.length, allowed ? 1 : 0); + } + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + payload: { sender: undefined } }); + assert.deepEqual(await f.run(), [MAINTAINER]); + assert.equal(f.comments.length, 0); +}); + test('new head invalidates readiness without using commit timestamps', async () => { const f = fixture({ labels: [READY], action: 'synchronize', comments: [ { id: 1, user: { login: 'github-actions[bot]' }, body: marker(OLD) }, @@ -260,6 +276,22 @@ test('an optional positive review does not undo maintainer merge readiness', asy assert.deepEqual(await f.run(), [READY]); }); +test('missing collaborators are untrusted while other permission errors propagate', async () => { + for (const permissionError of [404, 403, 500]) { + for (const f of [ + fixture(signalOptions([review('CHANGES_REQUESTED')], { permissionError })), + fixture({ labels: [READY], action: 'labeled', eventLabel: READY, permissionError }), + ]) { + if (permissionError === 404) { + assert.deepEqual(await f.run(), [MAINTAINER]); + } else { + await assert.rejects(f.run(), error => error.status === permissionError); + assert.equal(f.writes.length, 0); + } + } + } +}); + test('another reviewer approval does not clear a blocking request', async () => { const reviews = [review('CHANGES_REQUESTED'), review('APPROVED', { id: 11, user: { login: 'other-reviewer' } })]; diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index bd88f32822..01dfc4de4a 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -120,7 +120,9 @@ compare-and-swap; do not overwrite a concurrent handoff or claim atomicity. For blocked, include the dependency and unblock condition in a short comment. The ordinary Action records the head when a maintainer sets ready-to-merge using -the GitHub UI or their normal CLI credentials. A separate automation using +the GitHub UI or their normal CLI credentials. The labeler must have repository +write, maintain or admin permission; triage permission alone cannot grant merge +readiness. A separate automation using `GITHUB_TOKEN` does not trigger that event: it must record the verified full head as `` before setting the label. Only the workflow bot's exact record is trusted. A new head invalidates From a94bad6fba429a99631d60b4ee93ac3ca0a07632 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Mon, 30 Nov 2026 18:36:08 +0800 Subject: [PATCH 6/6] Recheck readiness after ambiguous review feedback Return a ready PR to maintainer evaluation after a new COMMENT review or outside changes request. Preserve readiness after optional positive reviews; trusted unanswered changes requests still route to the author. --- .github/scripts/pr-status-label.cjs | 3 +++ .github/scripts/pr-status-label.test.cjs | 9 +++++++++ .github/skills/pr-workflow/SKILL.md | 4 +++- 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 5388f96abb..b9ef699413 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -290,6 +290,9 @@ async function sync({ github, context, core, number }) { && review.id < notifiedReview.id)); if (unanswered) { await setStatus('status/awaiting-author'); + } else if (state === READY + && ['COMMENTED', 'CHANGES_REQUESTED'].includes(notifiedReview?.state)) { + await setStatus('status/awaiting-maintainer'); } else if (state === READY) { await checkReadiness(); } else if (state !== 'status/awaiting-author' || authorComments.length || withdrewRequest) { diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 835cbeb443..b1b7c0687a 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -276,6 +276,15 @@ test('an optional positive review does not undo maintainer merge readiness', asy assert.deepEqual(await f.run(), [READY]); }); +test('new ambiguous or outside feedback revokes readiness for maintainer evaluation', async () => { + for (const state of ['COMMENTED', 'CHANGES_REQUESTED']) { + const f = fixture(signalOptions([review(state)], { labels: [READY], permission: 'none', + comments: [{ id: 1, user: { login: 'github-actions[bot]' }, body: marker(HEAD) }] })); + assert.deepEqual(await f.run(), [MAINTAINER]); + assert.equal(f.comments.length, 0); + } +}); + test('missing collaborators are untrusted while other permission errors propagate', async () => { for (const permissionError of [404, 403, 500]) { for (const f of [ diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index 01dfc4de4a..3a470986eb 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -136,7 +136,9 @@ readiness for the old head regardless of commit creation time. - Review notifications re-read the current review. A maintainer's formal changes request can route to author; COMMENT reviews, outside reviewers' requests and approvals route to maintainer for interpretation. An approval never grants - ready-to-merge automatically. + ready-to-merge automatically. New COMMENT reviews and outside changes requests + also revoke existing readiness for maintainer evaluation; a positive optional + review alone does not revoke it. - Author conversation replies while awaiting author route to maintainer for verification. Neither comment prose nor a push is interpreted as acceptance. - CI completion checks whether an existing ready-to-merge state still satisfies