From ca683f253b808b480fb2c96967f9cf168140eec1 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Sun, 29 Nov 2026 16:29:06 +0800 Subject: [PATCH 01/20] 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 02/20] 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 03/20] 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 04/20] 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 05/20] 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 06/20] 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 From 2b740e3a489e90ba29cb3777797124cd36664483 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Mon, 30 Nov 2026 21:30:13 +0800 Subject: [PATCH 07/20] Queue PR synchronization with check read permissions Allow pending per-PR jobs to queue rather than replacing one another. Grant the sync token the check and status read permissions required by its merge-readiness query. --- .github/workflows/pr-status-label.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index eee15b6701..c31a46f07b 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -75,6 +75,8 @@ jobs: permissions: contents: read pull-requests: write + checks: read + statuses: read strategy: fail-fast: false max-parallel: 5 @@ -83,6 +85,7 @@ jobs: concurrency: group: pr-status-label-${{ matrix.number }} cancel-in-progress: false + queue: max steps: - uses: actions/checkout@v7.0.1 with: From 5ccc57020cfff74c3528f1c784cc77780cf1f143 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Mon, 30 Nov 2026 21:30:13 +0800 Subject: [PATCH 08/20] Reconcile PR handoffs from durable GitHub activity Use GitHub-owned PR associations only to select work. Relay titles and run times must not authenticate review activity or replay old feedback. Reconcile reviews, dismissals and author replies against label history so scheduled scans can recover missed notifications. Record accepted review heads, preserve newer tasks and account for label swap ordering without inventing a head accepted for merge. Keep author self-reviews separate from independent reviews and enforce strict branch update requirements only when branch protection or rulesets enable them. --- .github/scripts/pr-status-label.cjs | 249 ++++++++++++++++------- .github/scripts/pr-status-label.test.cjs | 249 ++++++++++++++++++++--- .github/skills/pr-workflow/SKILL.md | 54 ++++- .github/workflows/pr-review-signal.yml | 9 +- 4 files changed, 445 insertions(+), 116 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index b9ef699413..11c22c161b 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -25,7 +25,8 @@ const STATUS = [ const READY = 'status/ready-to-merge'; const TRACKER = /^$/; const WARNING = ''; -const SIGNAL = /^PR review signal #(\d+) review #(\d+)$/; +const PROGRESS = 'status/review-in-progress'; +const PROGRESS_RECORD = /^$/; const statusOf = pr => pr.labels.map(label => label.name) .filter(name => STATUS.includes(name)).sort(); const active = pr => pr.state === 'open' && !pr.draft; @@ -43,14 +44,17 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { 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])]; + // Relay code and titles can be changed by a fork. Only GitHub-owned run + // associations select PRs; the receiver reconciles API history, not a title. + if (run.name === 'PR review signal' + && !['pull_request_review', 'pull_request_review_comment'].includes(run.event)) return []; 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}`) + : await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { + owner, repo, commit_sha: run.head_sha, per_page: 100, + }); + return [...new Set(prs.filter(pr => pr.base?.repo?.full_name + ? pr.base.repo.full_name === `${owner}/${repo}` + : pr.base?.repo?.id && pr.base.repo.id === event.repository?.id) .map(pr => pr.number))]; } const requested = event.inputs?.pr_number; @@ -78,20 +82,27 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { return [...numbers.slice(start), ...numbers.slice(0, start)].slice(0, 20); } -async function sync({ github, context, core, number }) { +async function sync({ github, context, core, number, now = Date.now() }) { 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 permissions = new Map(); const canDecide = async username => { if (!username) return false; + if (permissions.has(username)) return permissions.get(username); try { const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username, }); - return ['write', 'maintain', 'admin'].includes(data.permission); + const allowed = ['write', 'maintain', 'admin'].includes(data.permission); + permissions.set(username, allowed); + return allowed; } catch (error) { - if (error.status === 404) return false; + if (error.status === 404) { + permissions.set(username, false); + return false; + } throw error; } }; @@ -100,6 +111,19 @@ async function sync({ github, context, core, number }) { })).data; const comments = () => github.paginate(github.rest.issues.listComments, { ...args, per_page: 100 }); + let history; + const timeline = () => history ||= github.paginate(github.rest.issues.listEventsForTimeline, + { ...args, per_page: 100 }); + const latestLabel = async name => (await timeline()).filter(item => + item.event === 'labeled' && item.label?.name === name).sort((a, b) => + (b.created_at || '').localeCompare(a.created_at || '') || b.id - a.id)[0]; + const progressRecords = async () => (await comments()).filter(comment => + comment.user?.login === 'github-actions[bot]' && PROGRESS_RECORD.test(comment.body.trim())); + const dropProgress = async () => { + for (const comment of await progressRecords()) { + await github.rest.issues.deleteComment({ owner, repo, comment_id: comment.id }); + } + }; const trackers = async () => (await comments()).filter(comment => comment.user?.login === 'github-actions[bot]' && TRACKER.test(comment.body.trim())); const dropTracker = async () => { @@ -137,12 +161,32 @@ async function sync({ github, context, core, number }) { const labels = statusOf(latest); if (!labels.length) { await dropTracker(); + await dropProgress(); return; } for (const name of labels) await remove(name); } return; } + // Record exact event heads even during two-step label swaps. Ignore queued + // label applications superseded by another application on the same head. + const latestApplication = async name => { + if (context.eventName !== 'pull_request_target' || event.action !== 'labeled' + || event.label?.name !== name || event.pull_request.head.sha !== pr.head.sha + || !statusOf(pr).includes(name)) return null; + const label = await latestLabel(name); + return label && label.actor?.login === event.sender?.login + && label.created_at <= event.pull_request.updated_at ? label : null; + }; + const readyApplication = await latestApplication(READY); + const authorizedReady = readyApplication && await canDecide(event.sender?.login); + if (authorizedReady && unchanged(pr, await readPr())) await recordTracker(pr.head.sha); + const accepted = await latestApplication(PROGRESS); + if (accepted && unchanged(pr, await readPr())) { + await dropProgress(); + await github.rest.issues.createComment({ ...args, + body: `` }); + } const current = statusOf(pr); if (current.length > 1) { if (!unchanged(pr, await readPr())) return; @@ -161,6 +205,7 @@ async function sync({ github, context, core, number }) { if (state === next || !unchanged(pr, await readPr())) return; for (const name of current) await remove(name); if (state === READY) await dropTracker(); + if (state === PROGRESS) await dropProgress(); // 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(); @@ -171,9 +216,6 @@ async function sync({ github, context, core, number }) { 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. @@ -182,6 +224,7 @@ async function sync({ github, context, core, number }) { 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 + baseRef { name branchProtectionRule { requiresStrictStatusChecks } } commits(last:1) { nodes { commit { statusCheckRollup { contexts(first:100,after:$cursor) { pageInfo { hasNextPage endCursor } @@ -200,7 +243,18 @@ async function sync({ github, context, core, number }) { (check.status ? check.status !== 'COMPLETED' || !['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(check.conclusion) : check.state !== 'SUCCESS')); - if (notPassing || ['CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(merge.reviewDecision) + let behindRequired = false; + if (merge.mergeStateStatus === 'BEHIND') { + behindRequired = merge.baseRef?.branchProtectionRule?.requiresStrictStatusChecks === true; + if (!behindRequired && merge.baseRef) { + const rules = await github.paginate(github.rest.repos.getBranchRules, + { owner, repo, branch: merge.baseRef.name, per_page: 100 }); + behindRequired = rules.some(rule => rule.type === 'required_status_checks' + && rule.parameters?.strict_required_status_checks_policy === true); + } + } + if (behindRequired || notPassing + || ['CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(merge.reviewDecision) || ['BLOCKED', 'DIRTY'].includes(merge.mergeStateStatus)) { await setStatus('status/awaiting-maintainer'); return; @@ -212,64 +266,60 @@ async function sync({ github, context, core, number }) { // 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 === 'status/blocked') return; // Only its owner can interpret the unblock condition. + const handoff = await latestLabel(state); + const boundary = handoff?.created_at || ''; 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; - if (!await canDecide(event.sender?.login)) { - await setStatus('status/awaiting-maintainer'); - return; - } - await recordTracker(pr.head.sha); + if (readyApplication && !authorizedReady) { + await setStatus('status/awaiting-maintainer'); + return; } const records = await trackers(); if (!records.some(comment => TRACKER.exec(comment.body.trim())[1] === pr.head.sha)) { - await setStatus('status/ready-for-review'); + // Allow the authorized labeled job to record its exact event head when a + // label swap's other job wins the queue. Never invent that accepted head + // from the current head or from commit creation timestamps. + const pending = !records.length && handoff && await canDecide(handoff.actor?.login) + && now - Date.parse(boundary) < 10 * 60 * 1000; + if (pending && !(context.eventName === 'pull_request_target' + && event.action === 'synchronize')) { + await checkReadiness(); + return; + } + await setStatus(records.length ? 'status/ready-for-review' : 'status/awaiting-maintainer'); return; } - if (!signal) { - await checkReadiness(); + await checkReadiness(); + if (!unchanged(pr, await readPr())) return; + } + if (state === PROGRESS) { + const records = await progressRecords(); + if (records.some(comment => { + const [, sha, id] = PROGRESS_RECORD.exec(comment.body.trim()); + return Number(id) === handoff?.id && sha !== pr.head.sha; + })) { + await setStatus('status/ready-for-review'); 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; - } + // Every notification is only a wake-up. Durable API timestamps, bounded by + // the current handoff, prevent replay and let scheduled scans recover work. + // Edits never change a review's submitted_at or a reply's created_at. + const allReviews = await github.paginate(github.rest.pulls.listReviews, + { owner, repo, pull_number: number, per_page: 100 }); + const reviews = allReviews.filter(review => + review.user?.login !== pr.user.login && review.submitted_at + && ['COMMENTED', 'APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)) + .sort((a, b) => a.submitted_at.localeCompare(b.submitted_at) || a.id - b.id); + const currentReviews = reviews.filter(review => review.commit_id === pr.head.sha); + // Without a recorded handoff, do not reinterpret historical reviews over an + // explicit state. Unlabeled PRs can still be classified from current facts. + if (state && !handoff) return; + const fresh = currentReviews.filter(review => review.state !== 'DISMISSED' + && review.submitted_at > boundary); const opinions = new Map(); - for (const review of currentReviews) { + for (const review of reviews) { if (['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)) { opinions.set(review.user.login, review); } @@ -277,28 +327,71 @@ async function sync({ github, context, core, number }) { const requests = []; for (const review of opinions.values()) { if (review.state !== 'CHANGES_REQUESTED') continue; + if (state !== 'status/awaiting-author' && review.commit_id !== pr.head.sha) continue; + if (state === READY && review.submitted_at <= boundary) continue; 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() - && !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)); + let allAuthorReplies = []; + if (state === 'status/awaiting-author' || requests.length) { + const threadReplies = await github.paginate(github.rest.pulls.listReviewComments, + { owner, repo, pull_number: number, per_page: 100 }); + // Review bodies authored by the PR author are responses, not independent + // review completions. Empty self-annotations cannot advance the workflow. + allAuthorReplies = [...await comments(), ...threadReplies, + ...allReviews.filter(review => review.state === 'COMMENTED').map(review => + ({ ...review, created_at: review.submitted_at }))].filter(reply => + reply.user?.login === pr.user.login && reply.body?.trim() + && !reply.body.trim().startsWith('/') && reply.created_at); + } + const authorReplies = allAuthorReplies.filter(reply => reply.created_at > boundary); + const unanswered = requests.some(review => !allAuthorReplies.some(reply => + reply.created_at > review.submitted_at + && (state !== 'status/awaiting-author' || reply.created_at > boundary))); + const priorOpinion = username => reviews.filter(review => review.user.login === username + && ['APPROVED', 'CHANGES_REQUESTED'].includes(review.state) + && review.submitted_at <= boundary).at(-1); + const automatedAuthorHandoff = state === 'status/awaiting-author' + && handoff?.actor?.login === 'github-actions[bot]'; + let approvalWithdrawal = false; + if (automatedAuthorHandoff) { + for (const review of fresh) { + if (review.state === 'APPROVED' + && priorOpinion(review.user.login)?.state === 'CHANGES_REQUESTED' + && await canDecide(review.user.login)) approvalWithdrawal = true; + } + } + let dismissalWithdrawal = false; + for (const item of automatedAuthorHandoff ? await timeline() : []) { + if (item.event !== 'review_dismissed' || item.created_at <= boundary + || item.dismissed_review?.state?.toUpperCase() !== 'CHANGES_REQUESTED') continue; + const dismissed = reviews.find(review => review.id === item.dismissed_review.review_id); + // REST preserves the dismissed review's original submission time. An + // unrelated approval dismissal cannot withdraw the active blocking request. + if (!dismissed || dismissed.submitted_at > boundary) continue; + const previous = reviews.filter(review => review.user.login === dismissed.user.login + && ['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state) + && review.submitted_at <= boundary).at(-1); + if (previous?.id === dismissed.id && await canDecide(dismissed.user.login)) { + dismissalWithdrawal = true; + } + } + const replyNeedsVerification = authorReplies.length > 0; + if (state && !fresh.length && !approvalWithdrawal && !dismissalWithdrawal + && !(state === 'status/awaiting-author' && replyNeedsVerification)) return; 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) { - // COMMENT reviews and outside reviewers' requests need maintainer judgment. - // No comment parsing, automatic approval, or automatic merge readiness. + if (fresh.some(review => ['COMMENTED', 'CHANGES_REQUESTED'].includes(review.state))) { + await setStatus('status/awaiting-maintainer'); + } + } else if (state === 'status/awaiting-author') { + if (replyNeedsVerification || approvalWithdrawal || dismissalWithdrawal) { + await setStatus('status/awaiting-maintainer'); + } + } else if (currentReviews.length) { await setStatus('status/awaiting-maintainer'); + } else if (!state) { + await setStatus('status/ready-for-review'); } } diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index b1b7c0687a..6ca45b13b8 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -42,7 +42,9 @@ function fixture(options = {}) { 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 } }, + number: 1, head: { sha: options.eventHead || HEAD }, + updated_at: options.eventAt || options.timeline?.filter(item => item.event === 'labeled' + && item.label?.name === options.eventLabel).at(-1)?.created_at || '2026-11-28T01:00:00Z' }, label: { name: options.eventLabel }, sender: { login: 'labeler' }, repository: { default_branch: 'master' }, ...options.payload } }; @@ -70,11 +72,11 @@ function fixture(options = {}) { if (index >= 0) comments.splice(index, 1); }, }; - const pulls = { list() {}, listReviews() {}, async get() { + const pulls = { list() {}, listReviews() {}, listReviewComments() {}, async get() { options.onRead?.(pr, ++reads); return { data: structuredClone(pr) }; } }; - const repos = { listPullRequestsAssociatedWithCommit() {}, + const repos = { listPullRequestsAssociatedWithCommit() {}, getBranchRules() {}, async getCollaboratorPermissionLevel() { if (options.permissionError) throw Object.assign(new Error('Permission lookup failed'), { status: options.permissionError }); @@ -84,7 +86,14 @@ function fixture(options = {}) { rest: { pulls, issues, repos }, async paginate(method) { if (method === issues.listComments) return structuredClone(comments); - if (method === issues.listEventsForTimeline) return options.timeline || []; + if (method === issues.listEventsForTimeline) return options.timeline || (options.labels || []) + .filter(name => name.startsWith('status/')).map((name, i) => ({ + id: i + 1, event: 'labeled', label: { name }, actor: { login: name === AUTHOR ? 'github-actions[bot]' : 'labeler' }, + created_at: name === AUTHOR ? '2026-11-28T02:30:00Z' : '2026-11-28T01:00:00Z', + })); + if (method === pulls.listReviewComments) return options.threadReplies || []; + if (method === repos.getBranchRules) return options.rules || []; + if (method === repos.listPullRequestsAssociatedWithCommit) return options.associatedPrs || []; if (method === pulls.listReviews) return structuredClone(options.reviews || []); if (method === pulls.list) return options.openPrs || []; throw new Error('Unexpected API pagination'); @@ -98,7 +107,7 @@ function fixture(options = {}) { }; return { pr, github, context, comments, writes, async run() { - await sync({ github, context, core: { info() {} }, number: 1 }); + await sync({ github, context, core: { info() {} }, number: 1, now: options.now }); return pr.labels.map(label => label.name).sort(); } }; } @@ -106,6 +115,8 @@ function fixture(options = {}) { function signalOptions(reviews, extra = {}) { return { labels: [PROGRESS], reviews, eventName: 'workflow_run', payload: { workflow_run: { name: 'PR review signal', + event: 'pull_request_review', head_sha: HEAD, + pull_requests: [{ number: 1, head: { sha: HEAD }, base: { repo: { full_name: 'apache/brpc' } } }], display_title: `PR review signal #1 review #${reviews[reviews.length - 1].id}` } }, ...extra }; } @@ -187,7 +198,7 @@ test('forged or quoted trackers cannot preserve readiness or be edited/deleted', { 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(await f.run(), [MAINTAINER]); assert.deepEqual(f.comments, [comment]); } }); @@ -317,27 +328,30 @@ test('reviewer COMMENT does not withdraw their existing formal changes request', 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('withdrawal of the active blocking review returns to maintainer', async () => { + const reviews = [review('CHANGES_REQUESTED'), review('APPROVED', + { id: 11, submitted_at: '2026-11-28T03:00:00Z' })]; + 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' } }, - })); +test('dismissal uses GitHub history rather than relay creation time', async () => { + const f = fixture(signalOptions([review('DISMISSED')], { labels: [AUTHOR], timeline: [ + { id: 1, event: 'labeled', label: { name: AUTHOR }, actor: { login: 'github-actions[bot]' }, + created_at: '2026-11-28T03:00:00Z' }, + { event: 'review_dismissed', created_at: '2026-11-28T04:00:00Z', + dismissed_review: { review_id: 10, state: 'changes_requested' } }, + ] })); 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.' } } }); + payload: { comment: { user: { login }, body: 'Here is the clarification.', + created_at: '2026-11-28T04:00:00Z' } + }, comments: [{ user: { login }, body: 'Here is the clarification.', + created_at: '2026-11-28T04:00:00Z' }] }); assert.deepEqual(await f.run(), [expected]); } }); @@ -370,7 +384,9 @@ test('an old review completion does not replay over a newer accepted task', asyn }); test('routine scans preserve an explicit handoff even when old reviews exist', async () => { - const f = fixture({ labels: [PROGRESS], reviews: [review('COMMENTED')], eventName: 'schedule' }); + const f = fixture({ labels: [PROGRESS], reviews: [review('COMMENTED')], eventName: 'schedule', + timeline: [{ id: 1, event: 'labeled', label: { name: PROGRESS }, + created_at: '2026-11-28T03:00:00Z' }] }); assert.deepEqual(await f.run(), [PROGRESS]); assert.equal(f.writes.length, 0); }); @@ -397,10 +413,30 @@ test('collection ignores issues and accepts PR comments without slash commands', } }); -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' } } })); +test('relay collection ignores titles and uses only GitHub PR associations', async () => { + const f = fixture({ eventName: 'workflow_run', payload: { pull_request: undefined, + workflow_run: { name: 'PR review signal', event: 'pull_request_review', head_sha: HEAD, + display_title: 'PR review signal #999 review #10', + pull_requests: [{ number: 1, base: { repo: { full_name: 'apache/brpc' } } }] } } }); assert.deepEqual(await collect(f), [1]); + f.context.payload.workflow_run.event = 'push'; + assert.deepEqual(await collect(f), []); + f.context.payload.workflow_run.event = 'pull_request_review_comment'; + f.context.payload.workflow_run.pull_requests = []; + assert.deepEqual(await collect(f), []); // A forged title cannot fill a missing association. + const fallback = fixture({ eventName: 'workflow_run', associatedPrs: [ + { number: 2, base: { repo: { full_name: 'apache/brpc' } } }, + { number: 3, base: { repo: { full_name: 'other/brpc' } } }, + ], payload: { pull_request: undefined, workflow_run: { + name: 'PR review signal', event: 'pull_request_review', head_sha: HEAD } } }); + assert.deepEqual(await collect(fallback), [2]); + f.context.payload.repository.id = 123; + f.context.payload.workflow_run.pull_requests = [ + { number: 4, base: { repo: { id: 123 } } }, + { number: 5, base: { repo: { id: 456 } } }, + { number: 6 }, + ]; + assert.deepEqual(await collect(f), [4]); }); test('manual scan validates an explicit PR number and scans all small backlogs', async () => { @@ -440,3 +476,170 @@ test('batch rejects invalid idle thresholds; PR events bypass the age filter', a updated_at: '2020-01-01T00:00:00Z' } } }); assert.deepEqual(await collect(event), [1]); }); + +const labelEvent = (name, at, extra = {}) => ({ id: 1, event: 'labeled', label: { name }, + actor: { login: 'labeler' }, created_at: `2026-11-28T${at}:00Z`, ...extra }); +const botRecord = body => ({ id: 99, user: { login: 'github-actions[bot]' }, body }); +const progressMarker = (sha, id = 1) => + ``; + +test('a new relay cannot replay an edited review over a later handoff', async () => { + for (const state of [PROGRESS, READY]) { + const f = fixture(signalOptions([review('COMMENTED')], { labels: [state], + timeline: [labelEvent(state, '03:00')], + comments: state === READY ? [botRecord(marker(HEAD))] : [], + payload: { workflow_run: { name: 'PR review signal', + display_title: 'PR review signal #1 review #10', created_at: '2026-11-28T05:00:00Z' } }, + })); + assert.deepEqual(await f.run(), [state]); + assert.equal(f.writes.length, 0); + } +}); + +test('author self-review cannot complete an independent review but can answer feedback', async () => { + const selfReview = review('COMMENTED', { user: { login: 'author' }, body: 'Please verify.', + submitted_at: '2026-11-28T04:00:00Z' }); + for (const state of [REVIEWABLE, PROGRESS, AUTHOR]) { + const f = fixture(signalOptions([selfReview], { labels: [state] })); + assert.deepEqual(await f.run(), [state === AUTHOR ? MAINTAINER : state]); + } +}); + +test('queued or edited old author replies do not answer a newer handoff', async () => { + const reply = { user: { login: 'author' }, body: 'Old clarification.', + created_at: '2026-11-28T01:00:00Z', updated_at: '2026-11-28T04:00:00Z' }; + for (const eventName of ['issue_comment', 'schedule']) { + const f = fixture({ eventName, labels: [AUTHOR], comments: [reply], + payload: { comment: reply }, reviews: [review('CHANGES_REQUESTED'), + review('APPROVED', { id: 11, user: { login: 'other' }, + submitted_at: '2026-11-28T05:00:00Z' })] }); + assert.deepEqual(await f.run(), [AUTHOR]); + } +}); + +test('a fresh review-thread reply asks for verification and an old one does not', async () => { + for (const [at, expected] of [['01:00', AUTHOR], ['04:00', MAINTAINER]]) { + const f = fixture({ eventName: 'schedule', labels: [AUTHOR], + reviews: [review('CHANGES_REQUESTED')], threadReplies: [ + { user: { login: 'author' }, body: 'Addressed here.', in_reply_to_id: 123, + created_at: `2026-11-28T${at}:00Z` }, + ] }); + assert.deepEqual(await f.run(), [expected]); + } +}); + +test('scheduled reconciliation recovers a missed completion without resetting a newer review', async () => { + const f = fixture({ eventName: 'schedule', labels: [PROGRESS], reviews: [review('COMMENTED')] }); + assert.deepEqual(await f.run(), [MAINTAINER]); + const newer = fixture({ eventName: 'schedule', labels: [PROGRESS], + reviews: [review('COMMENTED')], timeline: [labelEvent(PROGRESS, '03:00')] }); + assert.deepEqual(await newer.run(), [PROGRESS]); +}); + +test('readiness records survive either order of a maintainer label swap', async () => { + const f = fixture({ labels: [READY], action: 'unlabeled', eventLabel: MAINTAINER, + now: Date.parse('2026-11-28T04:01:00Z'), timeline: [labelEvent(READY, '04:00')] }); + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.writes.length, 0); // The exact-head recording job is still pending. + f.context.payload.action = 'labeled'; + f.context.payload.label.name = READY; + f.context.payload.pull_request.updated_at = '2026-11-28T04:00:00Z'; + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.comments[0].body, marker(HEAD)); + + const swapped = fixture({ labels: [MAINTAINER, READY], action: 'labeled', eventLabel: READY }); + await swapped.run(); + assert.ok(swapped.comments.some(comment => comment.body === marker(HEAD))); + swapped.pr.labels = [{ name: READY }]; + swapped.context.payload.action = 'unlabeled'; + swapped.context.payload.label.name = MAINTAINER; + assert.deepEqual(await swapped.run(), [READY]); +}); + +test('missing readiness confirmation expires and a push cannot borrow the grace period', async () => { + for (const [action, now] of [ + ['opened', '2026-11-28T04:11:00Z'], ['synchronize', '2026-11-28T04:01:00Z'], + ]) { + const f = fixture({ labels: [READY], action, now: Date.parse(now), + timeline: [labelEvent(READY, '04:00')] }); + assert.deepEqual(await f.run(), [MAINTAINER]); + assert.equal(f.comments.length, 0); + } +}); + +test('accepted review head is recorded and only its superseded handoff is requeued', async () => { + const accepted = fixture({ labels: [PROGRESS], action: 'labeled', eventLabel: PROGRESS }); + assert.deepEqual(await accepted.run(), [PROGRESS]); + assert.equal(accepted.comments[0].body, progressMarker(HEAD)); + for (const eventName of ['pull_request_target', 'schedule', 'workflow_run']) { + const f = fixture({ labels: [PROGRESS], eventName, action: 'synchronize', + comments: [botRecord(progressMarker(OLD))] }); + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.equal(f.comments.length, 0); + } + const newer = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))], + timeline: [labelEvent(PROGRESS, '04:00', { id: 2 })] }); + assert.deepEqual(await newer.run(), [PROGRESS]); +}); + +test('an approval on a revised head can withdraw the active automated changes request', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', reviews: [ + review('CHANGES_REQUESTED', { commit_id: OLD }), + review('APPROVED', { id: 11, submitted_at: '2026-11-28T04:00:00Z' }), + ] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('unrelated dismissals and manual author questions cannot be cleared by withdrawal', async () => { + const dismissed = fixture({ labels: [AUTHOR], reviews: [review('DISMISSED')], timeline: [ + labelEvent(AUTHOR, '03:00', { actor: { login: 'github-actions[bot]' } }), + { event: 'review_dismissed', created_at: '2026-11-28T04:00:00Z', + dismissed_review: { review_id: 10, state: 'approved' } }, + ] }); + assert.deepEqual(await dismissed.run(), [AUTHOR]); + const manual = fixture({ labels: [AUTHOR], timeline: [labelEvent(AUTHOR, '03:00')], reviews: [ + review('CHANGES_REQUESTED'), review('APPROVED', + { id: 11, submitted_at: '2026-11-28T04:00:00Z' }), + ] }); + assert.deepEqual(await manual.run(), [AUTHOR]); +}); + +test('BEHIND blocks readiness only when legacy protection or rulesets require an up-to-date branch', async () => { + for (const [protection, rules, expected] of [ + [true, [], MAINTAINER], + [false, [{ type: 'required_status_checks', parameters: { + strict_required_status_checks_policy: true } }], MAINTAINER], + [false, [], READY], + ]) { + const f = fixture({ labels: [READY], comments: [botRecord(marker(HEAD))], + merge: { mergeStateStatus: 'BEHIND', baseRef: { name: 'master', + branchProtectionRule: { requiresStrictStatusChecks: protection } } }, rules }); + assert.deepEqual(await f.run(), [expected]); + } +}); + +test('new parallel feedback does not erase an earlier author answer awaiting verification', async () => { + const f = fixture({ labels: [MAINTAINER], timeline: [labelEvent(MAINTAINER, '04:00')], + comments: [{ user: { login: 'author' }, body: 'Please verify.', + created_at: '2026-11-28T03:00:00Z' }], reviews: [review('CHANGES_REQUESTED'), + review('COMMENTED', { id: 11, user: { login: 'other' }, + submitted_at: '2026-11-28T05:00:00Z' })] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('withdrawing one blocking opinion leaves another unanswered request with author', async () => { + const f = fixture({ labels: [AUTHOR], reviews: [review('CHANGES_REQUESTED'), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'other' } }), + review('APPROVED', { id: 12, submitted_at: '2026-11-28T04:00:00Z' })] }); + assert.deepEqual(await f.run(), [AUTHOR]); +}); + + +test('a delayed unauthorized label application cannot undo a newer authorized readiness', async () => { + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + eventAt: '2026-11-28T01:00:00Z', comments: [botRecord(marker(HEAD))], + timeline: [labelEvent(READY, '03:00', { actor: { login: 'maintainer' } })], + permission: 'triage' }); + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.writes.length, 0); +}); diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index 3a470986eb..bf58a2614e 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -128,32 +128,64 @@ as `` before setti 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. +During a label swap, the recording job may run after the job that removes the +previous label. An authorized readiness application gets up to ten minutes for +its exact-head record to arrive; an unconfirmed application then returns to +awaiting maintainer. A push does not receive this grace period. Never merge +solely on an unconfirmed label. + +When review-in-progress is applied, the Action records the accepted head and the +GitHub label-event ID as +``. +A head change requeues that recorded review, while a newer label application +protects a newly accepted task. Automation that sets this label using +`GITHUB_TOKEN` must supply its own bot-owned record for the actual accepted head +and label-event ID. An existing in-progress label without such a record needs +human judgment about which head is being reviewed; the Action does not guess. + ## 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 +- PR lifecycle events maintain the initial state, remove stale readiness and + requeue a review whose recorded head has been superseded. +- Notifications only wake reconciliation. PR selection uses GitHub-owned run + associations, never a relay title or a claimed review ID. Review submissions + and dismissal history are compared with the current label handoff; the relay + run's time and edits to old reviews cannot replay an old completion. +- 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. 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. +- New author conversation replies, review-thread replies and nonempty self-review + bodies while awaiting author route to maintainer for verification. Replies + predating the active handoff do not answer it. Author self-reviews never count + as an independent review completion. Neither prose nor a push is acceptance. +- A withdrawal can return an automated author handoff to maintainer when it + removes the corresponding trusted blocking opinion. Dismissing an unrelated + approval does not clear feedback; manual author questions still need a reply. - CI completion checks whether an existing ready-to-merge state still satisfies - GitHub's merge requirements. Optional failures do not become blocking findings. + GitHub's merge requirements. BEHIND revokes readiness only when branch + protection or a ruleset requires an up-to-date branch. 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. - Batch scans skip PRs without workflow labels last updated over 90 days ago. Set the + readiness and activity newer than the current handoff. This recovers missed + notifications without replaying older work over an explicit handoff. + 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 -publish reviews using `GITHUB_TOKEN` do not generate downstream events and must -perform their authorized handoff themselves. Semantic review, AI scheduling, +Fork review and thread-reply events use a read-only notification workflow and a +default-branch receiver; no PR code or artifacts run with a write token. Per-PR +writes are serialized with `queue: max` (up to 100 pending jobs); API-history +reconciliation also recovers missed activity during batch scans. Services that +publish reviews using `GITHUB_TOKEN` do not generate downstream events; they +should perform their authorized handoff for prompt updates rather than waiting +for a batch scan. 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 index a98735a324..162a0f5533 100644 --- a/.github/workflows/pr-review-signal.yml +++ b/.github/workflows/pr-review-signal.yml @@ -15,15 +15,16 @@ # 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. +# Fork review events have a read-only token. This only wakes reconciliation; +# PR associations and review activity are re-read from GitHub API history. # 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] + types: [submitted, dismissed] + pull_request_review_comment: + types: [created] permissions: {} From 5e4258077b7e1424babad4dc74f85efef8d666d6 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 09:37:41 +0800 Subject: [PATCH 09/20] Replace pull_request_target with read-only PR signal workflows ASF disables pull_request_target, so manual label and close events were not received by pr-status-label.yml. Split PR lifecycle notifications into zero-permission pull_request signal workflows (PR label signal and PR activity signal) that wake the default-branch workflow_run receiver, and skip non-status label runs to avoid unnecessary runner usage. --- .github/workflows/pr-label-signal.yml | 35 ++++++++++++++++++++++++++ .github/workflows/pr-review-signal.yml | 5 +++- .github/workflows/pr-status-label.yml | 13 +++++----- 3 files changed, 46 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/pr-label-signal.yml diff --git a/.github/workflows/pr-label-signal.yml b/.github/workflows/pr-label-signal.yml new file mode 100644 index 0000000000..426ab8c40d --- /dev/null +++ b/.github/workflows/pr-label-signal.yml @@ -0,0 +1,35 @@ +# 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. + +# No secrets, checkout or PR code execution. The default-branch receiver +# re-reads GitHub history and validates original run metadata before writing. +name: PR label signal +run-name: 'PR label #${{ github.event.pull_request.number }} ${{ github.event.label.name }} sha=${{ github.event.pull_request.head.sha }} at=${{ github.event.pull_request.updated_at }}' + +on: + pull_request: + types: [labeled] + +permissions: {} + +jobs: + notify: + if: startsWith(github.event.label.name, 'status/') + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - run: echo 'PR lifecycle activity received; default-branch synchronization follows.' diff --git a/.github/workflows/pr-review-signal.yml b/.github/workflows/pr-review-signal.yml index 162a0f5533..fa86945f0e 100644 --- a/.github/workflows/pr-review-signal.yml +++ b/.github/workflows/pr-review-signal.yml @@ -18,9 +18,11 @@ # Fork review events have a read-only token. This only wakes reconciliation; # PR associations and review activity are re-read from GitHub API history. # No artifact, PR content, or PR code is trusted. -name: PR review signal +name: PR activity signal on: + pull_request: + types: [opened, reopened, ready_for_review, converted_to_draft, synchronize, unlabeled, closed] pull_request_review: types: [submitted, dismissed] pull_request_review_comment: @@ -30,6 +32,7 @@ permissions: {} jobs: notify: + if: github.event_name != 'pull_request' || github.event.action != 'unlabeled' || startsWith(github.event.label.name, 'status/') runs-on: ubuntu-latest timeout-minutes: 2 steps: diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index c31a46f07b..689df95900 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -19,13 +19,12 @@ 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 + - PR label signal + - PR activity signal - Build and Test on Linux - Build on Macos - FlatBuffers ON @@ -41,12 +40,14 @@ on: required: false type: string -permissions: - contents: read - pull-requests: read +permissions: {} jobs: collect: + if: ${{ !(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'skipped' && (github.event.workflow_run.name == 'PR label signal' || github.event.workflow_run.name == 'PR activity signal')) }} + permissions: + contents: read + pull-requests: read runs-on: ubuntu-latest timeout-minutes: 5 outputs: From 31bb5833b5bb0d249f72aeecd225bd97d07c68d4 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 09:38:00 +0800 Subject: [PATCH 10/20] Harden PR status reconciliation and label confirmation Address PR #3786 review feedback and modularize pr-status-label.cjs: - Resolve fork PRs on workflow_run via head branch/SHA across open and closed PRs, and verify PR label signal definitions via 3-way merge-base blob comparison so un-rebased PRs still confirm labels safely. - Bind ready-to-merge confirmations to specific label event IDs, keep delayed review-in-progress heads for requeueing (including triage reviewers), and tolerate minor PR updated_at timestamp drift. - Combine merge-readiness checks and review classification into a single state decision, prefer populated test-merge check rollups, classify existing current-head reviews before requeuing superseded heads, and exclude dismissed-only reviews. - Match thread replies to their owning review via in_reply_to_id, guard null review/PR user identities, preserve concurrent manual handoffs on post-write readback, and refactor sync() into focused helpers with regression tests. --- .github/scripts/pr-status-label.cjs | 506 ++++++++++++++--------- .github/scripts/pr-status-label.test.cjs | 357 ++++++++++++++-- 2 files changed, 632 insertions(+), 231 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 11c22c161b..3adf738906 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -17,16 +17,27 @@ // 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 { readFileSync } = require('node:fs'); +const { join } = require('node:path'); +const { createHash } = require('node:crypto'); + +const BOT = 'github-actions[bot]'; +const LABEL_WORKFLOW = '.github/workflows/pr-label-signal.yml'; +const LABEL_SIGNAL = /^PR label #(\d+) (status\/(?:ready-to-merge|review-in-progress)) sha=([0-9a-f]{40}) at=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)$/; +const REVIEWABLE = 'status/ready-for-review'; const PROGRESS = 'status/review-in-progress'; +const AUTHOR = 'status/awaiting-author'; +const MAINTAINER = 'status/awaiting-maintainer'; +const READY = 'status/ready-to-merge'; +const BLOCKED = 'status/blocked'; +const STATUS = [REVIEWABLE, PROGRESS, AUTHOR, MAINTAINER, READY, BLOCKED]; +const TRACKER = /^$/; const PROGRESS_RECORD = /^$/; +const WARNING = ''; +const SIGNAL_EVENTS = ['pull_request', 'pull_request_review', 'pull_request_review_comment']; +const REVIEW_STATES = ['COMMENTED', 'APPROVED', 'CHANGES_REQUESTED', 'DISMISSED']; +const FORMAL_STATES = ['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED']; + const statusOf = pr => pr.labels.map(label => label.name) .filter(name => STATUS.includes(name)).sort(); const active = pr => pr.state === 'open' && !pr.draft; @@ -35,28 +46,70 @@ 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; +function reviewOfThread(reply, byId) { + if (!reply.in_reply_to_id) return null; + const visited = new Set([reply.id]); + let root = reply; + while (root.in_reply_to_id) { + if (visited.has(root.in_reply_to_id)) return null; + visited.add(root.in_reply_to_id); + root = byId.get(root.in_reply_to_id); + if (!root) return null; + } + return root.pull_request_review_id; +} + +async function resolveWorkflowRunPrs({ github, context }) { + const { owner, repo } = context.repo; + const event = context.payload; + const run = event.workflow_run; + // Relay code and titles can be changed by a fork. Only GitHub-owned run + // associations select PRs; the receiver reconciles API history, not a title. + if (run.conclusion === 'skipped' + && ['PR label signal', 'PR activity signal'].includes(run.name)) return []; + if (!SIGNAL_EVENTS.includes(run.event)) return []; + if (run.name === 'PR label signal' + && (run.event !== 'pull_request' || run.path !== LABEL_WORKFLOW)) return []; + const sameRepo = pr => pr.base?.repo?.full_name + ? pr.base.repo.full_name === `${owner}/${repo}` + : pr.base?.repo?.id && pr.base.repo.id === event.repository?.id; + let prs = run.pull_requests?.length ? run.pull_requests.filter(sameRepo) : []; + if (!prs.length && run.head_sha) { + prs = (await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { + owner, repo, commit_sha: run.head_sha, per_page: 100, + })).filter(sameRepo); + } + const headOwner = run.head_repository?.owner?.login + || run.head_repository?.full_name?.split('/')[0]; + if (!prs.length && headOwner && run.head_branch) { + prs = (await github.paginate(github.rest.pulls.list, { + owner, repo, state: 'all', head: `${headOwner}:${run.head_branch}`, per_page: 100, + })).filter(pr => pr.head?.sha === run.head_sha || pr.state === 'open'); + } + if (!prs.length && run.head_sha) { + prs = (await github.paginate(github.rest.pulls.list, { + owner, repo, state: 'open', per_page: 100, + })).filter(pr => pr.head?.sha === run.head_sha); + } + if (!prs.length && run.head_sha && run.name !== 'PR label signal' + && github.rest.search?.issuesAndPullRequests) { + const { data } = await github.rest.search.issuesAndPullRequests({ + q: `repo:${owner}/${repo} is:pr ${run.head_sha}`, per_page: 20, + }); + prs = data.items || []; + } + return [...new Set(prs.map(pr => pr.number))]; +} + 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] : []; } - if (event.pull_request) return [event.pull_request.number]; - const { owner, repo } = context.repo; if (context.eventName === 'workflow_run') { - const run = event.workflow_run; - // Relay code and titles can be changed by a fork. Only GitHub-owned run - // associations select PRs; the receiver reconciles API history, not a title. - if (run.name === 'PR review signal' - && !['pull_request_review', 'pull_request_review_comment'].includes(run.event)) return []; - const prs = run.pull_requests?.length ? run.pull_requests - : await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { - owner, repo, commit_sha: run.head_sha, per_page: 100, - }); - return [...new Set(prs.filter(pr => pr.base?.repo?.full_name - ? pr.base.repo.full_name === `${owner}/${repo}` - : pr.base?.repo?.id && pr.base.repo.id === event.repository?.id) - .map(pr => pr.number))]; + return resolveWorkflowRunPrs({ github, context }); } + if (event.pull_request) return [event.pull_request.number]; const requested = event.inputs?.pr_number; if (requested) { const number = numberOf(requested); @@ -67,6 +120,7 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { if (!Number.isSafeInteger(days) || days <= 0) { throw new Error('PR_WORKFLOW_IDLE_DAYS must be a positive integer'); } + const { owner, repo } = context.repo; const cutoff = now - days * 86400000; const prs = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100 }); @@ -82,30 +136,146 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { return [...numbers.slice(start), ...numbers.slice(0, start)].slice(0, 20); } -async function sync({ github, context, core, number, now = Date.now() }) { - 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 permissions = new Map(); - const canDecide = async username => { +function createPermissionChecker(github, owner, repo) { + const cache = new Map(); + return async username => { if (!username) return false; - if (permissions.has(username)) return permissions.get(username); + if (cache.has(username)) return cache.get(username); try { const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username, }); const allowed = ['write', 'maintain', 'admin'].includes(data.permission); - permissions.set(username, allowed); + cache.set(username, allowed); return allowed; } catch (error) { if (error.status === 404) { - permissions.set(username, false); + cache.set(username, false); return false; } throw error; } }; +} + +// Label snapshots may be consumed only if GitHub executed this trusted +// default-branch signal definition. Either the triggering head already carries +// the exact blob, or the PR did not alter the workflow relative to its merge +// base with a base branch carrying it. No PR code or artifact is executed. +async function verifySignalDefinition({ github, owner, repo, pr, run, defaultBranch }) { + const blobSha = async ref => { + try { + const { data } = await github.rest.repos.getContent({ owner, repo, + path: LABEL_WORKFLOW, ref }); + return data.type === 'file' ? data.sha : undefined; + } catch (error) { + if (error.status !== 404) throw error; + return null; + } + }; + const content = readFileSync(join(__dirname, '../workflows/pr-label-signal.yml')); + const expected = createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex'); + const headBlob = await blobSha(run.head_sha); + if (headBlob === expected) return true; + if (headBlob === undefined) return false; + const baseRef = pr.base?.ref || defaultBranch; + if (!baseRef) return false; + if ((!defaultBranch || baseRef !== defaultBranch) + && await blobSha(pr.base?.sha || baseRef) !== expected) return false; + let mergeBase; + try { + const { data } = await github.rest.repos.compareCommitsWithBasehead({ + owner, repo, basehead: `${baseRef}...${run.head_sha}`, per_page: 1, + }); + mergeBase = data.merge_base_commit?.sha; + } catch (error) { + if (error.status !== 404) throw error; + return false; + } + return Boolean(mergeBase) && (await blobSha(mergeBase)) === headBlob; +} + +// Read conditions without writing labels: review classification and merge +// constraints must produce one decision, with unanswered feedback first. +async function checkMergeReadiness({ github, owner, repo, number, headSha }) { + const { repository: { pullRequest: merge } } = await github.graphql(` + query($owner:String!, $repo:String!, $number:Int!) { + repository(owner:$owner,name:$repo) { pullRequest(number:$number) { + headRefOid reviewDecision mergeStateStatus + baseRef { name branchProtectionRule { requiresStrictStatusChecks } } + potentialMergeCommit { oid statusCheckRollup { contexts(first:1) { totalCount } } } + } } + }`, { owner, repo, number }); + if (merge.headRefOid !== headSha) return null; + // GitHub evaluates test-merge checks when that commit has any statuses; + // otherwise the head is the source of required checks. + const checkSha = merge.potentialMergeCommit?.statusCheckRollup?.contexts?.totalCount > 0 + ? merge.potentialMergeCommit.oid : headSha; + let cursor = null; + let notPassing = false; + do { + const data = await github.graphql(` + query($owner:String!, $repo:String!, $number:Int!, $sha:GitObjectID!, $cursor:String) { + repository(owner:$owner,name:$repo) { object(oid:$sha) { ... on 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, sha: checkSha, cursor }); + if (!data.repository.object) return false; + const checks = data.repository.object.statusCheckRollup?.contexts; + notPassing ||= checks?.nodes.some(check => check.isRequired && + (check.status ? check.status !== 'COMPLETED' + || !['SUCCESS', 'NEUTRAL', 'SKIPPED'].includes(check.conclusion) + : check.state !== 'SUCCESS')); + cursor = checks?.pageInfo.hasNextPage ? checks.pageInfo.endCursor : null; + } while (cursor); + let behindRequired = false; + if (merge.mergeStateStatus === 'BEHIND') { + behindRequired = merge.baseRef?.branchProtectionRule?.requiresStrictStatusChecks === true; + if (!behindRequired && merge.baseRef) { + const rules = await github.paginate(github.rest.repos.getBranchRules, + { owner, repo, branch: merge.baseRef.name, per_page: 100 }); + behindRequired = rules.some(rule => rule.type === 'required_status_checks' + && rule.parameters?.strict_required_status_checks_policy === true); + } + } + return !(behindRequired || notPassing + || ['CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(merge.reviewDecision) + || ['BLOCKED', 'DIRTY'].includes(merge.mergeStateStatus)); +} + +function decideNextStatus({ + state, superseded, needsMaintainer, fresh, activeCurrentReviews, + unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, +}) { + if (state && !superseded && !needsMaintainer && !fresh.length + && !approvalWithdrawal && !dismissalWithdrawal + && !(state === AUTHOR && replyNeedsVerification)) return null; + if (unanswered) return AUTHOR; + if (superseded) return activeCurrentReviews.length ? MAINTAINER : REVIEWABLE; + if (state === READY) { + return needsMaintainer || fresh.some(review => ['COMMENTED', 'CHANGES_REQUESTED'].includes(review.state)) + ? MAINTAINER : null; + } + if (state === AUTHOR) { + return replyNeedsVerification || approvalWithdrawal || dismissalWithdrawal + ? MAINTAINER : null; + } + if (activeCurrentReviews.length) return MAINTAINER; + return !state ? REVIEWABLE : null; +} + +async function sync({ github, context, core, number, now = Date.now() }) { + 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 canDecide = createPermissionChecker(github, owner, repo); const readPr = async () => (await github.rest.pulls.get({ owner, repo, pull_number: number, })).data; @@ -117,28 +287,21 @@ async function sync({ github, context, core, number, now = Date.now() }) { const latestLabel = async name => (await timeline()).filter(item => item.event === 'labeled' && item.label?.name === name).sort((a, b) => (b.created_at || '').localeCompare(a.created_at || '') || b.id - a.id)[0]; - const progressRecords = async () => (await comments()).filter(comment => - comment.user?.login === 'github-actions[bot]' && PROGRESS_RECORD.test(comment.body.trim())); - const dropProgress = async () => { - for (const comment of await progressRecords()) { - await github.rest.issues.deleteComment({ owner, repo, comment_id: comment.id }); - } - }; - 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()) { + const markerComments = async pattern => (await comments()).filter(comment => + comment.user?.login === BOT && pattern.test(comment.body.trim())); + const deleteMarkers = async pattern => { + for (const comment of await markerComments(pattern)) { await github.rest.issues.deleteComment({ owner, repo, comment_id: comment.id }); } }; - const recordTracker = async sha => { + const upsertMarker = async (pattern, kind, sha, labelId) => { 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 (!numberOf(labelId)) throw new Error('Invalid label event ID'); + const existing = await markerComments(pattern); + const body = ``; + if (existing.length === 1 && existing[0].body.trim() === body) return; if (existing.length) { - await github.rest.issues.updateComment({ owner, repo, - comment_id: existing[0].id, body }); + await github.rest.issues.updateComment({ owner, repo, comment_id: existing[0].id, body }); } else { await github.rest.issues.createComment({ ...args, body }); } @@ -153,6 +316,7 @@ async function sync({ github, context, core, number, now = Date.now() }) { if (error.status !== 404) throw error; } }; + const pr = await readPr(); if (!active(pr)) { for (let attempt = 0; attempt < 3; attempt++) { @@ -160,148 +324,109 @@ async function sync({ github, context, core, number, now = Date.now() }) { if (active(latest)) return; const labels = statusOf(latest); if (!labels.length) { - await dropTracker(); - await dropProgress(); + await deleteMarkers(TRACKER); + await deleteMarkers(PROGRESS_RECORD); return; } for (const name of labels) await remove(name); } return; } - // Record exact event heads even during two-step label swaps. Ignore queued - // label applications superseded by another application on the same head. + + const run = context.eventName === 'workflow_run' ? event.workflow_run : null; + let verifiedDefinition; const latestApplication = async name => { - if (context.eventName !== 'pull_request_target' || event.action !== 'labeled' - || event.label?.name !== name || event.pull_request.head.sha !== pr.head.sha - || !statusOf(pr).includes(name)) return null; + if (run?.name !== 'PR label signal' || run.event !== 'pull_request' + || run.path !== LABEL_WORKFLOW || !statusOf(pr).includes(name)) return null; + const snapshot = LABEL_SIGNAL.exec(run.display_title || ''); + if (!snapshot || Number(snapshot[1]) !== number || snapshot[2] !== name + || snapshot[3] !== run.head_sha + || !(await collect({ github, context })).includes(number)) return null; + if (verifiedDefinition === undefined) { + verifiedDefinition = await verifySignalDefinition({ + github, owner, repo, pr, run, defaultBranch: event.repository?.default_branch, + }); + } + if (!verifiedDefinition) return null; const label = await latestLabel(name); - return label && label.actor?.login === event.sender?.login - && label.created_at <= event.pull_request.updated_at ? label : null; + const lag = Date.parse(snapshot[4]) - Date.parse(label?.created_at); + if (!label?.actor?.login || label.actor.login !== run.actor?.login + || !(lag >= 0 && lag <= 5000) + || (name === READY && !await canDecide(label.actor.login))) return null; + return { label, sha: snapshot[3] }; }; - const readyApplication = await latestApplication(READY); - const authorizedReady = readyApplication && await canDecide(event.sender?.login); - if (authorizedReady && unchanged(pr, await readPr())) await recordTracker(pr.head.sha); - const accepted = await latestApplication(PROGRESS); - if (accepted && unchanged(pr, await readPr())) { - await dropProgress(); - await github.rest.issues.createComment({ ...args, - body: `` }); + for (const [name, pattern, kind] of [ + [READY, TRACKER, 'ready-to-merge'], + [PROGRESS, PROGRESS_RECORD, 'review-in-progress'], + ]) { + const applied = await latestApplication(name); + if (applied && unchanged(pr, await readPr())) { + await upsertMarker(pattern, kind, applied.sha, applied.label.id); + } } + 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))) { + if (!(await comments()).some(comment => comment.user?.login === 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; + if (state === BLOCKED) return; // Only its owner can interpret the unblock condition. 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(); - if (state === PROGRESS) await dropProgress(); + if (state === READY) await deleteMarkers(TRACKER); + if (state === PROGRESS) await deleteMarkers(PROGRESS_RECORD); // 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); + if (!active(landed) || landed.head.sha !== pr.head.sha + || statusOf(landed).some(name => name !== next)) { + await remove(next); + return; + } + if (!statusOf(landed).includes(next)) return; core.info(`PR #${number}: ${state || 'none'} -> ${next}`); }; - 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 - baseRef { name branchProtectionRule { requiresStrictStatusChecks } } - 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')); - let behindRequired = false; - if (merge.mergeStateStatus === 'BEHIND') { - behindRequired = merge.baseRef?.branchProtectionRule?.requiresStrictStatusChecks === true; - if (!behindRequired && merge.baseRef) { - const rules = await github.paginate(github.rest.repos.getBranchRules, - { owner, repo, branch: merge.baseRef.name, per_page: 100 }); - behindRequired = rules.some(rule => rule.type === 'required_status_checks' - && rule.parameters?.strict_required_status_checks_policy === true); - } - } - if (behindRequired || 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 === 'status/blocked') return; // Only its owner can interpret the unblock condition. const handoff = await latestLabel(state); - const boundary = handoff?.created_at || ''; + let boundary = handoff?.created_at || ''; + let superseded = false; + let needsMaintainer = false; if (state === READY) { - if (readyApplication && !authorizedReady) { - await setStatus('status/awaiting-maintainer'); - return; - } - const records = await trackers(); - if (!records.some(comment => TRACKER.exec(comment.body.trim())[1] === pr.head.sha)) { - // Allow the authorized labeled job to record its exact event head when a - // label swap's other job wins the queue. Never invent that accepted head - // from the current head or from commit creation timestamps. - const pending = !records.length && handoff && await canDecide(handoff.actor?.login) - && now - Date.parse(boundary) < 10 * 60 * 1000; - if (pending && !(context.eventName === 'pull_request_target' - && event.action === 'synchronize')) { - await checkReadiness(); - return; - } - await setStatus(records.length ? 'status/ready-for-review' : 'status/awaiting-maintainer'); - return; + const records = await markerComments(TRACKER); + const matching = records.find(comment => Number(TRACKER.exec(comment.body.trim())[2]) === handoff?.id); + const authorized = Boolean(handoff?.actor?.login === BOT && matching) + || await canDecide(handoff?.actor?.login); + superseded = !!matching && TRACKER.exec(matching.body.trim())[1] !== pr.head.sha; + const pending = !matching && authorized && now - Date.parse(boundary) < 10 * 60 * 1000; + needsMaintainer = !authorized || !matching && !pending; + if (!superseded && !needsMaintainer) { + const passing = await checkMergeReadiness({ + github, owner, repo, number, headSha: pr.head.sha, + }); + if (passing === null) return; + needsMaintainer = !passing; } - await checkReadiness(); - if (!unchanged(pr, await readPr())) return; - } - if (state === PROGRESS) { - const records = await progressRecords(); - if (records.some(comment => { + } else if (state === PROGRESS) { + superseded = (await markerComments(PROGRESS_RECORD)).some(comment => { const [, sha, id] = PROGRESS_RECORD.exec(comment.body.trim()); return Number(id) === handoff?.id && sha !== pr.head.sha; - })) { - await setStatus('status/ready-for-review'); - return; - } + }); } + // Classify existing reviews on the new head before applying a new queue + // label; otherwise that label's timestamp would hide a completed review. + if (superseded) boundary = ''; // Every notification is only a wake-up. Durable API timestamps, bounded by // the current handoff, prevent replay and let scheduled scans recover work. @@ -309,49 +434,50 @@ async function sync({ github, context, core, number, now = Date.now() }) { const allReviews = await github.paginate(github.rest.pulls.listReviews, { owner, repo, pull_number: number, per_page: 100 }); const reviews = allReviews.filter(review => - review.user?.login !== pr.user.login && review.submitted_at - && ['COMMENTED', 'APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)) + review.user?.login && review.user.login !== pr.user?.login && review.submitted_at + && REVIEW_STATES.includes(review.state)) .sort((a, b) => a.submitted_at.localeCompare(b.submitted_at) || a.id - b.id); - const currentReviews = reviews.filter(review => review.commit_id === pr.head.sha); + const activeCurrentReviews = reviews.filter(review => + review.commit_id === pr.head.sha && review.state !== 'DISMISSED'); // Without a recorded handoff, do not reinterpret historical reviews over an // explicit state. Unlabeled PRs can still be classified from current facts. - if (state && !handoff) return; - const fresh = currentReviews.filter(review => review.state !== 'DISMISSED' - && review.submitted_at > boundary); + if (state && !handoff && !needsMaintainer) return; + const fresh = activeCurrentReviews.filter(review => review.submitted_at > boundary); const opinions = new Map(); for (const review of reviews) { - if (['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)) { - opinions.set(review.user.login, review); - } + if (FORMAL_STATES.includes(review.state)) opinions.set(review.user.login, review); } const requests = []; for (const review of opinions.values()) { if (review.state !== 'CHANGES_REQUESTED') continue; - if (state !== 'status/awaiting-author' && review.commit_id !== pr.head.sha) continue; - if (state === READY && review.submitted_at <= boundary) continue; + if (state !== AUTHOR && review.commit_id !== pr.head.sha) continue; + if (state === READY && !superseded && review.submitted_at <= boundary) continue; if (await canDecide(review.user.login)) requests.push(review); } + let allAuthorReplies = []; - if (state === 'status/awaiting-author' || requests.length) { + if (state === AUTHOR || requests.length) { const threadReplies = await github.paginate(github.rest.pulls.listReviewComments, { owner, repo, pull_number: number, per_page: 100 }); + const byId = new Map(threadReplies.map(reply => [reply.id, reply])); // Review bodies authored by the PR author are responses, not independent // review completions. Empty self-annotations cannot advance the workflow. - allAuthorReplies = [...await comments(), ...threadReplies, + allAuthorReplies = [...await comments(), + ...threadReplies.map(reply => ({ ...reply, thread: true, reviewId: reviewOfThread(reply, byId) })), ...allReviews.filter(review => review.state === 'COMMENTED').map(review => ({ ...review, created_at: review.submitted_at }))].filter(reply => - reply.user?.login === pr.user.login && reply.body?.trim() + reply.user?.login && reply.user.login === pr.user?.login && reply.body?.trim() && !reply.body.trim().startsWith('/') && reply.created_at); } - const authorReplies = allAuthorReplies.filter(reply => reply.created_at > boundary); + const replyNeedsVerification = allAuthorReplies.some(reply => reply.created_at > boundary); const unanswered = requests.some(review => !allAuthorReplies.some(reply => reply.created_at > review.submitted_at - && (state !== 'status/awaiting-author' || reply.created_at > boundary))); + && (reply.thread ? reply.reviewId === review.id : requests.length === 1) + && (state !== AUTHOR || reply.created_at > boundary))); + const priorOpinion = username => reviews.filter(review => review.user.login === username - && ['APPROVED', 'CHANGES_REQUESTED'].includes(review.state) - && review.submitted_at <= boundary).at(-1); - const automatedAuthorHandoff = state === 'status/awaiting-author' - && handoff?.actor?.login === 'github-actions[bot]'; + && FORMAL_STATES.includes(review.state) && review.submitted_at <= boundary).at(-1); + const automatedAuthorHandoff = state === AUTHOR && handoff?.actor?.login === BOT; let approvalWithdrawal = false; if (automatedAuthorHandoff) { for (const review of fresh) { @@ -367,32 +493,18 @@ async function sync({ github, context, core, number, now = Date.now() }) { const dismissed = reviews.find(review => review.id === item.dismissed_review.review_id); // REST preserves the dismissed review's original submission time. An // unrelated approval dismissal cannot withdraw the active blocking request. - if (!dismissed || dismissed.submitted_at > boundary) continue; - const previous = reviews.filter(review => review.user.login === dismissed.user.login - && ['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state) - && review.submitted_at <= boundary).at(-1); - if (previous?.id === dismissed.id && await canDecide(dismissed.user.login)) { + if (dismissed && dismissed.submitted_at <= boundary + && priorOpinion(dismissed.user.login)?.id === dismissed.id + && await canDecide(dismissed.user.login)) { dismissalWithdrawal = true; } } - const replyNeedsVerification = authorReplies.length > 0; - if (state && !fresh.length && !approvalWithdrawal && !dismissalWithdrawal - && !(state === 'status/awaiting-author' && replyNeedsVerification)) return; - if (unanswered) { - await setStatus('status/awaiting-author'); - } else if (state === READY) { - if (fresh.some(review => ['COMMENTED', 'CHANGES_REQUESTED'].includes(review.state))) { - await setStatus('status/awaiting-maintainer'); - } - } else if (state === 'status/awaiting-author') { - if (replyNeedsVerification || approvalWithdrawal || dismissalWithdrawal) { - await setStatus('status/awaiting-maintainer'); - } - } else if (currentReviews.length) { - await setStatus('status/awaiting-maintainer'); - } else if (!state) { - await setStatus('status/ready-for-review'); - } + + const next = decideNextStatus({ + state, superseded, needsMaintainer, fresh, activeCurrentReviews, + unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, + }); + if (next) await setStatus(next); } module.exports = { collect, sync }; diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 6ca45b13b8..25fddc2da2 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -18,6 +18,11 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); const { collect, sync } = require('./pr-status-label.cjs'); +const { readFileSync } = require('node:fs'); +const { join } = require('node:path'); +const { createHash } = require('node:crypto'); +const definition = readFileSync(join(__dirname, '../workflows/pr-label-signal.yml')); +const signalBlob = createHash('sha1').update(`blob ${definition.length}\0`).update(definition).digest('hex'); const HEAD = 'b'.repeat(40); const OLD = 'a'.repeat(40); @@ -27,27 +32,43 @@ const MAINTAINER = 'status/awaiting-maintainer'; const AUTHOR = 'status/awaiting-author'; const PROGRESS = 'status/review-in-progress'; const BLOCKED = 'status/blocked'; -const marker = sha => ``; +const marker = (sha, id = 1) => ``; 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' }, + head: { sha: HEAD }, base: options.base || { ref: 'master', sha: '0'.repeat(40) }, + user: Object.hasOwn(options, 'author') ? options.author : { login: 'author' }, labels: (options.labels || []).map(name => ({ name })) }; const comments = structuredClone(options.comments || []); const writes = []; let reads = 0; let checkPages = 0; + const checkShas = []; const context = { repo: { owner: 'apache', repo: 'brpc' }, - eventName: options.eventName || 'pull_request_target', + eventName: options.eventName || 'workflow_run', payload: { action: options.action || 'opened', pull_request: { number: 1, head: { sha: options.eventHead || HEAD }, updated_at: options.eventAt || options.timeline?.filter(item => item.event === 'labeled' && item.label?.name === options.eventLabel).at(-1)?.created_at || '2026-11-28T01:00:00Z' }, label: { name: options.eventLabel }, sender: { login: 'labeler' }, - repository: { default_branch: 'master' }, ...options.payload } }; + repository: { id: 1, default_branch: 'master' }, workflow_run: { + name: 'PR label signal', event: 'pull_request', + path: '.github/workflows/pr-label-signal.yml', + head_sha: options.eventHead || HEAD, + display_title: `PR label #1 ${options.eventLabel || 'area/http'} sha=${options.eventHead || HEAD} at=${options.eventAt + || options.timeline?.filter(item => item.event === 'labeled' + && item.label?.name === options.eventLabel).at(-1)?.created_at || '2026-11-28T01:00:00Z'}`, + actor: options.payload && Object.hasOwn(options.payload, 'sender') + ? options.payload.sender : { login: 'labeler' }, + created_at: options.action === 'labeled' ? options.eventAt + || options.timeline?.filter(item => item.event === 'labeled' + && item.label?.name === options.eventLabel).at(-1)?.created_at + || '2026-11-28T01:00:00Z' : '2026-11-28T00:00:00Z', + pull_requests: [{ number: 1, base: { repo: { full_name: 'apache/brpc' } } }], + }, ...options.payload } }; const issues = { listComments() {}, listEventsForTimeline() {}, async removeLabel({ name }) { @@ -57,6 +78,7 @@ function fixture(options = {}) { async addLabels({ labels }) { writes.push(['add', ...labels]); for (const name of labels) pr.labels.push({ name }); + options.onAdd?.(pr); }, async createComment({ body }) { writes.push(['comment', body]); @@ -77,14 +99,35 @@ function fixture(options = {}) { return { data: structuredClone(pr) }; } }; const repos = { listPullRequestsAssociatedWithCommit() {}, getBranchRules() {}, - async getCollaboratorPermissionLevel() { + async compareCommitsWithBasehead() { + if (options.compareError) throw Object.assign(new Error('Compare failed'), { status: options.compareError }); + return { data: { merge_base_commit: { sha: options.mergeBaseSha || '0'.repeat(40) } } }; + }, + async getContent({ ref }) { + if (options.contentByRef && Object.hasOwn(options.contentByRef, ref)) { + const entry = options.contentByRef[ref]; + if (entry === 404) throw Object.assign(new Error('Not found'), { status: 404 }); + return { data: { type: 'file', sha: entry } }; + } + if (options.contentError && ref === (options.eventHead || HEAD)) { + throw Object.assign(new Error('Content lookup failed'), { status: options.contentError }); + } + return { data: { type: 'file', + sha: options.tamperedSignal && ref === (options.eventHead || HEAD) ? 'modified' : signalBlob } }; + }, + async getCollaboratorPermissionLevel({ username }) { if (options.permissionError) throw Object.assign(new Error('Permission lookup failed'), { status: options.permissionError }); - return { data: { permission: options.permission || 'write' } }; + return { data: { permission: options.permissionByUser?.[username] || options.permission || 'write' } }; } }; + const search = options.searchItems ? { + async issuesAndPullRequests() { + return { data: { items: options.searchItems } }; + }, + } : undefined; const github = { - rest: { pulls, issues, repos }, - async paginate(method) { + rest: { pulls, issues, repos, ...(search ? { search } : {}) }, + async paginate(method, params = {}) { if (method === issues.listComments) return structuredClone(comments); if (method === issues.listEventsForTimeline) return options.timeline || (options.labels || []) .filter(name => name.startsWith('status/')).map((name, i) => ({ @@ -95,17 +138,26 @@ function fixture(options = {}) { if (method === repos.getBranchRules) return options.rules || []; if (method === repos.listPullRequestsAssociatedWithCommit) return options.associatedPrs || []; if (method === pulls.listReviews) return structuredClone(options.reviews || []); - if (method === pulls.list) return options.openPrs || []; + if (method === pulls.list) { + if (params.head) return options.pullsByHead?.[params.head] || []; + 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 } } } } }] }, - } } }; }, + async graphql(query, variables) { + if (!query.includes('object(oid:')) return { repository: { pullRequest: { + headRefOid: HEAD, reviewDecision: null, mergeStateStatus: 'CLEAN', ...options.merge, + } } }; + checkShas.push(variables.sha); + return { repository: { object: { statusCheckRollup: { contexts: + options.checkPages?.[checkPages++] || { + nodes: options.checksBySha?.[variables.sha] || options.checks || [], + pageInfo: { hasNextPage: false }, + }, + } } } }; + }, }; - return { pr, github, context, comments, writes, + return { pr, github, context, comments, writes, checkShas, async run() { await sync({ github, context, core: { info() {} }, number: 1, now: options.now }); return pr.labels.map(label => label.name).sort(); @@ -114,7 +166,7 @@ function fixture(options = {}) { function signalOptions(reviews, extra = {}) { return { labels: [PROGRESS], reviews, eventName: 'workflow_run', - payload: { workflow_run: { name: 'PR review signal', + payload: { workflow_run: { name: 'PR activity signal', event: 'pull_request_review', head_sha: HEAD, pull_requests: [{ number: 1, head: { sha: HEAD }, base: { repo: { full_name: 'apache/brpc' } } }], display_title: `PR review signal #1 review #${reviews[reviews.length - 1].id}` } }, ...extra }; @@ -179,7 +231,8 @@ test('new head invalidates readiness without using commit timestamps', async () }); test('stale push event does not invalidate a newer handoff', async () => { - const f = fixture({ labels: [READY], action: 'synchronize', eventHead: OLD }); + const f = fixture({ labels: [READY], action: 'synchronize', eventHead: OLD, + comments: [botRecord(marker(HEAD))] }); assert.deepEqual(await f.run(), [READY]); assert.equal(f.writes.length, 0); }); @@ -415,7 +468,7 @@ test('collection ignores issues and accepts PR comments without slash commands', test('relay collection ignores titles and uses only GitHub PR associations', async () => { const f = fixture({ eventName: 'workflow_run', payload: { pull_request: undefined, - workflow_run: { name: 'PR review signal', event: 'pull_request_review', head_sha: HEAD, + workflow_run: { name: 'PR activity signal', event: 'pull_request_review', head_sha: HEAD, display_title: 'PR review signal #999 review #10', pull_requests: [{ number: 1, base: { repo: { full_name: 'apache/brpc' } } }] } } }); assert.deepEqual(await collect(f), [1]); @@ -428,7 +481,7 @@ test('relay collection ignores titles and uses only GitHub PR associations', asy { number: 2, base: { repo: { full_name: 'apache/brpc' } } }, { number: 3, base: { repo: { full_name: 'other/brpc' } } }, ], payload: { pull_request: undefined, workflow_run: { - name: 'PR review signal', event: 'pull_request_review', head_sha: HEAD } } }); + name: 'PR activity signal', event: 'pull_request_review', head_sha: HEAD } } }); assert.deepEqual(await collect(fallback), [2]); f.context.payload.repository.id = 123; f.context.payload.workflow_run.pull_requests = [ @@ -488,7 +541,7 @@ test('a new relay cannot replay an edited review over a later handoff', async () const f = fixture(signalOptions([review('COMMENTED')], { labels: [state], timeline: [labelEvent(state, '03:00')], comments: state === READY ? [botRecord(marker(HEAD))] : [], - payload: { workflow_run: { name: 'PR review signal', + payload: { workflow_run: { name: 'PR activity signal', display_title: 'PR review signal #1 review #10', created_at: '2026-11-28T05:00:00Z' } }, })); assert.deepEqual(await f.run(), [state]); @@ -521,6 +574,7 @@ test('a fresh review-thread reply asks for verification and an old one does not' for (const [at, expected] of [['01:00', AUTHOR], ['04:00', MAINTAINER]]) { const f = fixture({ eventName: 'schedule', labels: [AUTHOR], reviews: [review('CHANGES_REQUESTED')], threadReplies: [ + { id: 123, user: { login: 'reviewer' }, pull_request_review_id: 10, body: 'Change this.' }, { user: { login: 'author' }, body: 'Addressed here.', in_reply_to_id: 123, created_at: `2026-11-28T${at}:00Z` }, ] }); @@ -543,35 +597,33 @@ test('readiness records survive either order of a maintainer label swap', async assert.equal(f.writes.length, 0); // The exact-head recording job is still pending. f.context.payload.action = 'labeled'; f.context.payload.label.name = READY; - f.context.payload.pull_request.updated_at = '2026-11-28T04:00:00Z'; + f.context.payload.workflow_run.display_title = `PR label #1 ${READY} sha=${HEAD} at=2026-11-28T04:00:00Z`; assert.deepEqual(await f.run(), [READY]); assert.equal(f.comments[0].body, marker(HEAD)); const swapped = fixture({ labels: [MAINTAINER, READY], action: 'labeled', eventLabel: READY }); await swapped.run(); - assert.ok(swapped.comments.some(comment => comment.body === marker(HEAD))); + assert.ok(swapped.comments.some(comment => comment.body === marker(HEAD, 2))); swapped.pr.labels = [{ name: READY }]; swapped.context.payload.action = 'unlabeled'; swapped.context.payload.label.name = MAINTAINER; assert.deepEqual(await swapped.run(), [READY]); }); -test('missing readiness confirmation expires and a push cannot borrow the grace period', async () => { - for (const [action, now] of [ - ['opened', '2026-11-28T04:11:00Z'], ['synchronize', '2026-11-28T04:01:00Z'], - ]) { - const f = fixture({ labels: [READY], action, now: Date.parse(now), - timeline: [labelEvent(READY, '04:00')] }); - assert.deepEqual(await f.run(), [MAINTAINER]); - assert.equal(f.comments.length, 0); - } +test('missing readiness confirmation expires and a recorded old head has no grace', async () => { + const expired = fixture({ labels: [READY], now: Date.parse('2026-11-28T04:11:00Z'), + timeline: [labelEvent(READY, '04:00')] }); + assert.deepEqual(await expired.run(), [MAINTAINER]); + const superseded = fixture({ labels: [READY], now: Date.parse('2026-11-28T04:01:00Z'), + comments: [botRecord(marker(OLD))], timeline: [labelEvent(READY, '04:00')] }); + assert.deepEqual(await superseded.run(), [REVIEWABLE]); }); test('accepted review head is recorded and only its superseded handoff is requeued', async () => { const accepted = fixture({ labels: [PROGRESS], action: 'labeled', eventLabel: PROGRESS }); assert.deepEqual(await accepted.run(), [PROGRESS]); assert.equal(accepted.comments[0].body, progressMarker(HEAD)); - for (const eventName of ['pull_request_target', 'schedule', 'workflow_run']) { + for (const eventName of ['issue_comment', 'schedule', 'workflow_run']) { const f = fixture({ labels: [PROGRESS], eventName, action: 'synchronize', comments: [botRecord(progressMarker(OLD))] }); assert.deepEqual(await f.run(), [REVIEWABLE]); @@ -639,7 +691,244 @@ test('a delayed unauthorized label application cannot undo a newer authorized re const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, eventAt: '2026-11-28T01:00:00Z', comments: [botRecord(marker(HEAD))], timeline: [labelEvent(READY, '03:00', { actor: { login: 'maintainer' } })], - permission: 'triage' }); + permission: 'triage', permissionByUser: { maintainer: 'write' } }); assert.deepEqual(await f.run(), [READY]); assert.equal(f.writes.length, 0); }); + + +test('ASF activity signals collect closed PRs and execute cleanup', async () => { + const f = fixture({ state: 'closed', labels: [READY], comments: [botRecord(marker(HEAD))], + associatedPrs: [{ number: 1, state: 'closed', base: { repo: { full_name: 'apache/brpc' } } }], + payload: { workflow_run: { name: 'PR activity signal', event: 'pull_request', + path: '.github/workflows/pr-review-signal.yml', head_sha: HEAD, pull_requests: [] } } }); + assert.deepEqual(await collect(f), [1]); + assert.deepEqual(await f.run(), []); + assert.equal(f.comments.length, 0); + f.context.payload.workflow_run.event = 'push'; + assert.deepEqual(await collect(f), []); +}); + +test('readiness confirmation is bound to its label application, including during conflicts', async () => { + for (const labels of [[READY], [READY, MAINTAINER]]) { + const f = fixture({ labels, eventName: 'schedule', permission: 'triage', + comments: [botRecord(marker(HEAD, 1))], timeline: [ + labelEvent(READY, '01:00', { id: 1, actor: { login: 'old-maintainer' } }), + labelEvent(READY, '03:00', { id: 2, actor: { login: 'triager' } }), + ] }); + if (labels.length > 1) { + await f.run(); + f.pr.labels = [{ name: READY }]; + } + assert.deepEqual(await f.run(), [MAINTAINER]); + } + const legacy = fixture({ labels: [READY], eventName: 'schedule', comments: [ + botRecord(``), + ] }); + assert.deepEqual(await legacy.run(), [MAINTAINER]); +}); + +test('superseded head classification consumes existing reviews before writing a queue label', async () => { + for (const oldState of [PROGRESS, READY]) { + for (const [state, expected] of [ + ['CHANGES_REQUESTED', AUTHOR], ['COMMENTED', MAINTAINER], ['APPROVED', MAINTAINER], + ]) { + const f = fixture({ labels: [oldState], eventName: 'schedule', + comments: [botRecord(oldState === READY ? marker(OLD) : progressMarker(OLD))], + reviews: [review(state)] }); + assert.deepEqual(await f.run(), [expected]); + assert.ok(!f.writes.some(write => write[0] === 'add' && write[1] === REVIEWABLE)); + } + } +}); + +test('new formal changes requests take precedence over a failing merge-readiness decision', async () => { + const f = fixture({ labels: [READY], comments: [botRecord(marker(HEAD))], + reviews: [review('CHANGES_REQUESTED')], + merge: { reviewDecision: 'CHANGES_REQUESTED', mergeStateStatus: 'BLOCKED' } }); + assert.deepEqual(await f.run(), [AUTHOR]); + assert.deepEqual(f.writes.filter(write => write[0] === 'add'), [['add', AUTHOR]]); +}); + +test('a thread reply can answer only the review owning its parent thread', async () => { + const requests = [review('CHANGES_REQUESTED'), review('CHANGES_REQUESTED', + { id: 11, user: { login: 'second-reviewer' } })]; + const roots = [ + { id: 101, pull_request_review_id: 10, user: { login: 'reviewer' }, body: 'First request.' }, + { id: 102, pull_request_review_id: 11, user: { login: 'second-reviewer' }, body: 'Second request.' }, + ]; + for (const [parents, expected] of [[[101], AUTHOR], [[101, 102], MAINTAINER]]) { + const f = fixture({ labels: [AUTHOR], reviews: requests, threadReplies: [...roots, + ...parents.map((id, i) => ({ id: 200 + i, in_reply_to_id: id, + user: { login: 'author' }, body: 'Please verify.', created_at: '2026-11-28T04:00:00Z' })), + ] }); + assert.deepEqual(await f.run(), [expected]); + } + const general = fixture({ labels: [AUTHOR], reviews: requests, comments: [ + { user: { login: 'author' }, body: 'Please verify.', created_at: '2026-11-28T04:00:00Z' }, + ] }); + assert.deepEqual(await general.run(), [AUTHOR]); +}); + +test('a delayed lifecycle signal records its original accepted head before classifying the new one', async () => { + const f = fixture({ labels: [PROGRESS], action: 'labeled', eventLabel: PROGRESS, + eventHead: OLD, reviews: [review('CHANGES_REQUESTED')] }); + assert.deepEqual(await f.run(), [AUTHOR]); + assert.ok(f.writes.some(write => write[0] === 'comment' && write[1] === progressMarker(OLD))); + assert.equal(f.comments.length, 0); +}); + +test('lifecycle confirmation rejects wrong actors, unrelated PR associations and stale runs', async () => { + for (const alter of [ + run => { run.actor = { login: 'other' }; }, + run => { run.display_title = `PR label #1 ${READY} sha=${HEAD} at=2026-11-28T01:02:00Z`; }, + run => { run.pull_requests[0].number = 2; }, + run => { run.path = '.github/workflows/other.yml'; }, + ]) { + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY }); + alter(f.context.payload.workflow_run); + assert.deepEqual(await f.run(), [MAINTAINER]); + assert.equal(f.comments.length, 0); + } +}); + +test('required checks prefer a populated test-merge rollup and otherwise use the head', async () => { + const mergeSha = 'c'.repeat(40); + for (const [count, headState, mergeState, expected, checked] of [ + [1, 'FAILURE', 'SUCCESS', READY, mergeSha], + [1, 'SUCCESS', 'FAILURE', MAINTAINER, mergeSha], + [0, 'FAILURE', 'SUCCESS', MAINTAINER, HEAD], + ]) { + const f = fixture({ labels: [READY], comments: [botRecord(marker(HEAD))], + merge: { potentialMergeCommit: { oid: mergeSha, + statusCheckRollup: { contexts: { totalCount: count } } } }, + checksBySha: { + [HEAD]: [{ isRequired: true, state: headState }], + [mergeSha]: [{ isRequired: true, state: mergeState }], + } }); + assert.deepEqual(await f.run(), [expected]); + assert.deepEqual(f.checkShas, [checked]); + } +}); + +test('missing review identities cannot crash grouping of historical opinions', async () => { + const f = fixture({ labels: [PROGRESS], reviews: [review('APPROVED', { user: null }), + review('COMMENTED', { id: 11 })] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('post-write reconciliation removes its own label while preserving a concurrent manual handoff', async () => { + const f = fixture({ onAdd(pr) { pr.labels.push({ name: BLOCKED }); } }); + assert.deepEqual(await f.run(), [BLOCKED]); + assert.ok(f.writes.some(write => write[0] === 'remove' && write[1] === REVIEWABLE)); +}); + +test('a modified or deleted signal definition cannot authenticate even an otherwise valid title', async () => { + for (const options of [ + { tamperedSignal: true }, + { contentError: 404 }, + { base: { ref: 'release-1.0', sha: '1'.repeat(40) }, + contentByRef: { [HEAD]: 'old-blob', ['1'.repeat(40)]: 'old-blob', ['0'.repeat(40)]: 'old-blob' } }, + ]) { + const f = fixture({ ...options, labels: [READY], action: 'labeled', eventLabel: READY }); + assert.deepEqual(await f.run(), [MAINTAINER]); + assert.equal(f.comments.length, 0); + } +}); + +test('un-rebased PRs that did not modify the signal workflow still confirm labels', async () => { + const mergeBaseSha = 'd'.repeat(40); + for (const blob of [404, 'older-default-blob']) { + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, mergeBaseSha, + contentByRef: { [HEAD]: blob, [mergeBaseSha]: blob } }); + assert.deepEqual(await f.run(), [READY]); + assert.equal(f.comments[0].body, marker(HEAD)); + } +}); + +test('triage reviewers record review-in-progress head while ready-to-merge still needs write permission', async () => { + const f = fixture({ labels: [PROGRESS], action: 'labeled', eventLabel: PROGRESS, + eventHead: OLD, permission: 'triage' }); + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.ok(f.writes.some(write => write[0] === 'comment' && write[1] === progressMarker(OLD))); +}); + +test('label confirmation tolerates small PR updated_at drift without accepting stale runs', async () => { + const ok = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + eventAt: '2026-11-28T01:00:02Z' }); + assert.deepEqual(await ok.run(), [READY]); + assert.equal(ok.comments[0].body, marker(HEAD)); + const stale = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + eventAt: '2026-11-28T00:59:59Z' }); + assert.deepEqual(await stale.run(), [MAINTAINER]); + assert.equal(stale.comments.length, 0); +}); + +test('fork workflow_run collection resolves open, pushed, closed and reviewed PRs without trusting search for labels', async () => { + const forkLabel = fixture({ eventName: 'workflow_run', pullsByHead: { + 'contrib:fix': [ + { number: 10, state: 'closed', head: { sha: 'c'.repeat(40) } }, + { number: 20, state: 'open', head: { sha: HEAD } }, + ], + }, payload: { pull_request: undefined, workflow_run: { + name: 'PR label signal', event: 'pull_request', path: '.github/workflows/pr-label-signal.yml', + head_sha: OLD, head_branch: 'fix', head_repository: { owner: { login: 'contrib' } }, + pull_requests: [], + } } }); + assert.deepEqual(await collect(forkLabel), [20]); + + const forkClosed = fixture({ eventName: 'workflow_run', pullsByHead: { + 'contrib:done': [{ number: 30, state: 'closed', head: { sha: HEAD } }], + }, payload: { pull_request: undefined, workflow_run: { + name: 'PR activity signal', event: 'pull_request', + head_sha: HEAD, head_branch: 'done', head_repository: { full_name: 'contrib/brpc' }, + pull_requests: [], + } } }); + assert.deepEqual(await collect(forkClosed), [30]); + + const forkReview = fixture({ eventName: 'workflow_run', openPrs: [ + { number: 40, state: 'open', head: { sha: HEAD } }, + { number: 41, state: 'open', head: { sha: OLD } }, + ], payload: { pull_request: undefined, workflow_run: { + name: 'PR activity signal', event: 'pull_request_review', + head_sha: HEAD, head_branch: 'fix', head_repository: { owner: { login: 'apache' } }, + pull_requests: [], + } } }); + assert.deepEqual(await collect(forkReview), [40]); + + const searchActivity = fixture({ eventName: 'workflow_run', searchItems: [{ number: 50 }], + payload: { pull_request: undefined, workflow_run: { + name: 'PR activity signal', event: 'pull_request_review', + head_sha: OLD, pull_requests: [], + } } }); + assert.deepEqual(await collect(searchActivity), [50]); + + const searchLabel = fixture({ eventName: 'workflow_run', searchItems: [{ number: 50 }], + payload: { pull_request: undefined, workflow_run: { + name: 'PR label signal', event: 'pull_request', path: '.github/workflows/pr-label-signal.yml', + head_sha: OLD, pull_requests: [], + } } }); + assert.deepEqual(await collect(searchLabel), []); + + const skipped = fixture({ eventName: 'workflow_run', payload: { pull_request: undefined, + workflow_run: { name: 'PR label signal', event: 'pull_request', conclusion: 'skipped', + path: '.github/workflows/pr-label-signal.yml', head_sha: HEAD, + pull_requests: [{ number: 1, base: { repo: { full_name: 'apache/brpc' } } }] } } }); + assert.deepEqual(await collect(skipped), []); +}); + +test('dismissed-only reviews on a superseded head requeue and deleted PR authors do not crash', async () => { + const f = fixture({ labels: [PROGRESS], eventName: 'schedule', author: null, + comments: [botRecord(progressMarker(OLD)), + { user: null, body: 'Orphaned comment', created_at: '2026-11-28T04:00:00Z' }], + reviews: [review('DISMISSED')] }); + assert.deepEqual(await f.run(), [REVIEWABLE]); +}); + +test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { + const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); + f.context.payload.workflow_run.name = 'PR activity signal'; + f.context.payload.workflow_run.display_title = `PR label #1 ${PROGRESS} sha=${HEAD} at=2026-11-28T01:00:00Z`; + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.ok(!f.writes.some(write => write[0] === 'comment')); +}); From bd56095bb9aaabd2024e9a36d5451c2983f5a94e Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 09:38:27 +0800 Subject: [PATCH 11/20] Document ASF signal workflow and handoff rules in PR skill Update .github/skills/pr-workflow/SKILL.md to document the read-only signal workflows, merge-base signal definition verification, fork PR association lookup, label-event-bound readiness records, test-merge check precedence, per-review thread replies, and post-write conflict rollback. --- .github/skills/pr-workflow/SKILL.md | 63 ++++++++++++++++++++++++----- 1 file changed, 52 insertions(+), 11 deletions(-) diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index bf58a2614e..086aaa4db4 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -123,22 +123,49 @@ The ordinary Action records the head when a maintainer sets ready-to-merge 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 -readiness for the old head regardless of commit creation time. +`GITHUB_TOKEN` does not trigger that event: after setting the label it must read +the actual label-event ID and record the verified full head as +``. +Only the workflow bot's exact record for the current label application is +trusted. Reapplying a label needs a new confirmation even on the same head; +legacy records containing only a SHA are not confirmations. A new head +invalidates readiness regardless of commit creation time. + +The GitHub adapter follows the +[ASF Actions policy](https://infra.apache.org/github-actions-policy.html#a-safer-replacement-for-pull_request_target): +no workflow uses `pull_request_target`. `PR label signal` handles `status/*` +label additions; `PR activity signal` handles the other lifecycle, review and +thread-reply events. Both have empty permissions and execute only a fixed +notification command. The default-branch `workflow_run` receiver performs +writes, including cleanup after closure. Fork PR lookup resolves GitHub-owned +head branch/SHA associations across open and closed PRs when +`workflow_run.pull_requests` is empty. + +For a label snapshot, the receiver first verifies that GitHub executed the +trusted default-branch signal definition: either the triggering head carries +the exact blob, or the PR did not alter the signal workflow relative to its +merge base with a base branch carrying that exact definition. Only then can it +use the GitHub-evaluated run name for the label, original head and event time. +These must also match the run's PR association, head and original actor, and +the current label event (plus write/maintain/admin permission for +`status/ready-to-merge`). Modified or deleted signal definitions cannot confirm +a label. Other signal titles remain untrusted and are ignored. This check reads +PR data without executing it; no artifact is used to authenticate a label. During a label swap, the recording job may run after the job that removes the previous label. An authorized readiness application gets up to ten minutes for its exact-head record to arrive; an unconfirmed application then returns to -awaiting maintainer. A push does not receive this grace period. Never merge -solely on an unconfirmed label. +awaiting maintainer. A recorded old head gets no grace period. Never merge solely +on an unconfirmed label. When review-in-progress is applied, the Action records the accepted head and the GitHub label-event ID as ``. A head change requeues that recorded review, while a newer label application -protects a newly accepted task. Automation that sets this label using +protects a newly accepted task. If the new head already has a completed review, +its feedback is classified before adding any new queue label. A queued signal +records the originally accepted head even if another push has already arrived. +Automation that sets this label using `GITHUB_TOKEN` must supply its own bot-owned record for the actual accepted head and label-event ID. An existing in-progress label without such a record needs human judgment about which head is being reviewed; the Action does not guess. @@ -149,8 +176,10 @@ human judgment about which head is being reviewed; the Action does not guess. - PR lifecycle events maintain the initial state, remove stale readiness and requeue a review whose recorded head has been superseded. -- Notifications only wake reconciliation. PR selection uses GitHub-owned run - associations, never a relay title or a claimed review ID. Review submissions +- Activity notifications only wake reconciliation. PR selection uses GitHub-owned + run associations, never a relay title or a claimed review ID. Label confirmation + additionally requires the definition and snapshot validation described above. + Review submissions and dismissal history are compared with the current label handoff; the relay run's time and edits to old reviews cannot replay an old completion. - A maintainer's formal changes @@ -163,13 +192,20 @@ human judgment about which head is being reviewed; the Action does not guess. bodies while awaiting author route to maintainer for verification. Replies predating the active handoff do not answer it. Author self-reviews never count as an independent review completion. Neither prose nor a push is acceptance. + A thread reply is associated with its original review through `in_reply_to_id`; + it cannot answer another reviewer's request. With several outstanding formal + requests, a general conversation reply does not automatically answer all of + them. Maintainers can evaluate general responses and hand off explicitly. - A withdrawal can return an automated author handoff to maintainer when it removes the corresponding trusted blocking opinion. Dismissing an unrelated approval does not clear feedback; manual author questions still need a reply. - CI completion checks whether an existing ready-to-merge state still satisfies GitHub's merge requirements. BEHIND revokes readiness only when branch protection or a ruleset requires an up-to-date branch. Optional failures do - not become blocking findings. + not become blocking findings. Required checks use the test merge commit when + it has checks/statuses, otherwise the head commit. Merge conditions and review + feedback produce one state decision; unanswered trusted feedback takes priority + over a generic return to maintainer. - 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 and activity newer than the current handoff. This recovers missed @@ -180,7 +216,7 @@ human judgment about which head is being reviewed; the Action does not guess. 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 and thread-reply events use a read-only notification workflow and a +Fork lifecycle, review and thread-reply events use read-only signal workflows and a default-branch receiver; no PR code or artifacts run with a write token. Per-PR writes are serialized with `queue: max` (up to 100 pending jobs); API-history reconciliation also recovers missed activity during batch scans. Services that @@ -189,3 +225,8 @@ should perform their authorized handoff for prompt updates rather than waiting for a batch scan. 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. + +After an automatic label write, the receiver checks the resulting head and status +labels. If a concurrent manual handoff added another state, it removes only its +own proposed label and retains the manual state. Label APIs still provide no +atomic compare-and-swap guarantee. From 5523cf1f77847c1183b9edabe147ba830f07f74d Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 09:42:55 +0800 Subject: [PATCH 12/20] Validate base branch signal blob and preserve current-head opinions Fix two edge cases in pr-status-label.cjs: - Verify the target base branch's pr-label-signal.yml blob before accepting a matching head blob, so a modified non-default base branch cannot supply an untrusted merge result. - Keep current-head formal opinions from being overwritten by a later approval or dismissal targeting an older commit, while preserving cross-head withdrawals submitted on the current head. --- .github/scripts/pr-status-label.cjs | 30 +++++++++++++++--------- .github/scripts/pr-status-label.test.cjs | 15 ++++++++++++ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 3adf738906..af2e218a16 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -59,6 +59,17 @@ function reviewOfThread(reply, byId) { return root.pull_request_review_id; } +function latestFormalOpinions(reviews, headSha) { + const opinions = new Map(); + for (const review of reviews) { + if (!FORMAL_STATES.includes(review.state)) continue; + const prev = opinions.get(review.user.login); + if (prev?.commit_id === headSha && review.commit_id !== headSha) continue; + opinions.set(review.user.login, review); + } + return opinions; +} + async function resolveWorkflowRunPrs({ github, context }) { const { owner, repo } = context.repo; const event = context.payload; @@ -175,13 +186,13 @@ async function verifySignalDefinition({ github, owner, repo, pr, run, defaultBra }; const content = readFileSync(join(__dirname, '../workflows/pr-label-signal.yml')); const expected = createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex'); - const headBlob = await blobSha(run.head_sha); - if (headBlob === expected) return true; - if (headBlob === undefined) return false; const baseRef = pr.base?.ref || defaultBranch; if (!baseRef) return false; if ((!defaultBranch || baseRef !== defaultBranch) && await blobSha(pr.base?.sha || baseRef) !== expected) return false; + const headBlob = await blobSha(run.head_sha); + if (headBlob === expected) return true; + if (headBlob === undefined) return false; let mergeBase; try { const { data } = await github.rest.repos.compareCommitsWithBasehead({ @@ -443,10 +454,7 @@ async function sync({ github, context, core, number, now = Date.now() }) { // explicit state. Unlabeled PRs can still be classified from current facts. if (state && !handoff && !needsMaintainer) return; const fresh = activeCurrentReviews.filter(review => review.submitted_at > boundary); - const opinions = new Map(); - for (const review of reviews) { - if (FORMAL_STATES.includes(review.state)) opinions.set(review.user.login, review); - } + const opinions = latestFormalOpinions(reviews, pr.head.sha); const requests = []; for (const review of opinions.values()) { if (review.state !== 'CHANGES_REQUESTED') continue; @@ -475,14 +483,14 @@ async function sync({ github, context, core, number, now = Date.now() }) { && (reply.thread ? reply.reviewId === review.id : requests.length === 1) && (state !== AUTHOR || reply.created_at > boundary))); - const priorOpinion = username => reviews.filter(review => review.user.login === username - && FORMAL_STATES.includes(review.state) && review.submitted_at <= boundary).at(-1); + const priorOpinions = latestFormalOpinions( + reviews.filter(review => review.submitted_at <= boundary), pr.head.sha); const automatedAuthorHandoff = state === AUTHOR && handoff?.actor?.login === BOT; let approvalWithdrawal = false; if (automatedAuthorHandoff) { for (const review of fresh) { if (review.state === 'APPROVED' - && priorOpinion(review.user.login)?.state === 'CHANGES_REQUESTED' + && priorOpinions.get(review.user.login)?.state === 'CHANGES_REQUESTED' && await canDecide(review.user.login)) approvalWithdrawal = true; } } @@ -494,7 +502,7 @@ async function sync({ github, context, core, number, now = Date.now() }) { // REST preserves the dismissed review's original submission time. An // unrelated approval dismissal cannot withdraw the active blocking request. if (dismissed && dismissed.submitted_at <= boundary - && priorOpinion(dismissed.user.login)?.id === dismissed.id + && priorOpinions.get(dismissed.user.login)?.id === dismissed.id && await canDecide(dismissed.user.login)) { dismissalWithdrawal = true; } diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 25fddc2da2..146eb1da87 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -829,6 +829,8 @@ test('a modified or deleted signal definition cannot authenticate even an otherw { contentError: 404 }, { base: { ref: 'release-1.0', sha: '1'.repeat(40) }, contentByRef: { [HEAD]: 'old-blob', ['1'.repeat(40)]: 'old-blob', ['0'.repeat(40)]: 'old-blob' } }, + { base: { ref: 'release-1.0', sha: '1'.repeat(40) }, + contentByRef: { [HEAD]: signalBlob, ['1'.repeat(40)]: 'modified-base-blob', ['0'.repeat(40)]: signalBlob } }, ]) { const f = fixture({ ...options, labels: [READY], action: 'labeled', eventLabel: READY }); assert.deepEqual(await f.run(), [MAINTAINER]); @@ -925,6 +927,19 @@ test('dismissed-only reviews on a superseded head requeue and deleted PR authors assert.deepEqual(await f.run(), [REVIEWABLE]); }); +test('an approval on an older head cannot override a current-head changes request', async () => { + const reviews = [ + review('CHANGES_REQUESTED', { id: 10, commit_id: HEAD, submitted_at: '2026-11-28T02:00:00Z' }), + review('APPROVED', { id: 11, commit_id: OLD, submitted_at: '2026-11-28T03:00:00Z' }), + ]; + assert.deepEqual(await fixture(signalOptions(reviews)).run(), [AUTHOR]); + const staying = fixture({ labels: [AUTHOR], eventName: 'schedule', reviews: [ + ...reviews, + review('COMMENTED', { id: 12, user: { login: 'other' }, submitted_at: '2026-11-28T04:00:00Z' }), + ] }); + assert.deepEqual(await staying.run(), [AUTHOR]); +}); + test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); f.context.payload.workflow_run.name = 'PR activity signal'; From 776656f8dd718320707d24363163a7d441f915a7 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 21:58:02 +0800 Subject: [PATCH 13/20] Skip root inline review comments in PR activity signal pull_request_review_comment: created fires once per root inline comment in addition to pull_request_review: submitted. Restrict the review comment signal to thread replies (in_reply_to_id != null) so multi- comment reviews do not flood the per-PR queue with redundant jobs. --- .github/workflows/pr-review-signal.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr-review-signal.yml b/.github/workflows/pr-review-signal.yml index fa86945f0e..d2e3dd629e 100644 --- a/.github/workflows/pr-review-signal.yml +++ b/.github/workflows/pr-review-signal.yml @@ -32,7 +32,7 @@ permissions: {} jobs: notify: - if: github.event_name != 'pull_request' || github.event.action != 'unlabeled' || startsWith(github.event.label.name, 'status/') + if: (github.event_name != 'pull_request' || github.event.action != 'unlabeled' || startsWith(github.event.label.name, 'status/')) && (github.event_name != 'pull_request_review_comment' || github.event.comment.in_reply_to_id != null) runs-on: ubuntu-latest timeout-minutes: 2 steps: From 2654a1ff8a545cc3a4a400edcf0d919a3020d6b9 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 21:58:22 +0800 Subject: [PATCH 14/20] Fix closed-PR recovery, handoff races, and renewed thread matching Address the remaining Copilot review findings on PR #3786: - Include a bounded single-page scan of recently updated closed PRs that still carry status/* labels so conflicted closed PRs are cleaned up. - Reject UNKNOWN (and DRAFT) mergeStateStatus in checkMergeReadiness(). - Refresh timeline events in setStatus() and compare handoff label IDs before removing a state so a reapplied same-head label is preserved. - Recover activity that raced an automatic bot handoff while preserving strict cutoffs for explicit manual handoffs. - Match thread replies against all non-author reviews contributing to the thread before the reply, and preserve per-request answers across automatic handoffs based on requests outstanding when each reply ran. - Update PR workflow skill docs and add regression tests. --- .github/scripts/pr-status-label.cjs | 124 +++++++++++++++++------ .github/scripts/pr-status-label.test.cjs | 103 ++++++++++++++++++- .github/skills/pr-workflow/SKILL.md | 26 +++-- 3 files changed, 210 insertions(+), 43 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index af2e218a16..6c7738987e 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -46,17 +46,61 @@ 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; -function reviewOfThread(reply, byId) { - if (!reply.in_reply_to_id) return null; - const visited = new Set([reply.id]); - let root = reply; - while (root.in_reply_to_id) { - if (visited.has(root.in_reply_to_id)) return null; - visited.add(root.in_reply_to_id); - root = byId.get(root.in_reply_to_id); - if (!root) return null; +function buildThreadReviewLookup(threadReplies, authorLogin) { + const byId = new Map(threadReplies.map(comment => [comment.id, comment])); + const rootIdOf = comment => { + const visited = new Set([comment.id]); + let root = comment; + while (root.in_reply_to_id) { + if (visited.has(root.in_reply_to_id)) return null; + visited.add(root.in_reply_to_id); + root = byId.get(root.in_reply_to_id); + if (!root) return null; + } + return root.id; + }; + const byRoot = new Map(); + for (const comment of threadReplies) { + const rootId = rootIdOf(comment); + if (!rootId) continue; + if (!byRoot.has(rootId)) byRoot.set(rootId, []); + byRoot.get(rootId).push(comment); + } + return reply => { + const ids = new Set(); + if (!reply.in_reply_to_id) return ids; + const rootId = rootIdOf(reply); + if (!rootId) return ids; + for (const comment of byRoot.get(rootId) || []) { + if (!comment.pull_request_review_id) continue; + if (authorLogin && comment.user?.login === authorLogin) continue; + if (!comment.created_at || !reply.created_at || comment.created_at <= reply.created_at) { + ids.add(comment.pull_request_review_id); + } + } + return ids; + }; +} + +function hasUnansweredRequest(requests, allAuthorReplies, manualCutoff) { + const replies = allAuthorReplies + .filter(reply => !manualCutoff || reply.created_at > manualCutoff) + .sort((a, b) => a.created_at.localeCompare(b.created_at) || (a.id || 0) - (b.id || 0)); + const answered = new Set(); + for (const reply of replies) { + if (reply.thread) { + for (const review of requests) { + if (reply.created_at > review.submitted_at && reply.reviewIds.has(review.id)) { + answered.add(review.id); + } + } + } else { + const pending = requests.filter(review => + review.submitted_at < reply.created_at && !answered.has(review.id)); + if (pending.length === 1) answered.add(pending[0].id); + } } - return root.pull_request_review_id; + return requests.some(review => !answered.has(review.id)); } function latestFormalOpinions(reviews, headSha) { @@ -135,6 +179,14 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { const cutoff = now - days * 86400000; const prs = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100 }); + // Include a bounded sample of recently updated closed PRs that still carry + // workflow labels (e.g. conflicted PRs whose pull_request signal did not run). + const closedResp = await github.rest.pulls.list({ + owner, repo, state: 'closed', sort: 'updated', direction: 'desc', per_page: 30, + }); + const closed = (closedResp?.data || []) + .filter(pr => (pr.labels || []).some(label => STATUS.includes(label.name))) + .map(pr => pr.number).sort((a, b) => a - b).slice(0, 5); // 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)) @@ -142,9 +194,13 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { .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(now / 1800000) * 20) % numbers.length; - return [...numbers.slice(start), ...numbers.slice(0, start)].slice(0, 20); + const openBudget = 20 - closed.length; + let openBatch = numbers; + if (numbers.length > openBudget) { + const start = (Math.floor(now / 1800000) * openBudget) % numbers.length; + openBatch = [...numbers.slice(start), ...numbers.slice(0, start)].slice(0, openBudget); + } + return [...new Set([...closed, ...openBatch])]; } function createPermissionChecker(github, owner, repo) { @@ -257,15 +313,19 @@ async function checkMergeReadiness({ github, owner, repo, number, headSha }) { } return !(behindRequired || notPassing || ['CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(merge.reviewDecision) - || ['BLOCKED', 'DIRTY'].includes(merge.mergeStateStatus)); + || ['BLOCKED', 'DIRTY', 'DRAFT', 'UNKNOWN'].includes(merge.mergeStateStatus)); } function decideNextStatus({ - state, superseded, needsMaintainer, fresh, activeCurrentReviews, + state, automatedHandoff, superseded, needsMaintainer, fresh, activeCurrentReviews, unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, }) { + const missedActivity = automatedHandoff && ( + (state === REVIEWABLE && activeCurrentReviews.length > 0) + || (state === MAINTAINER && unanswered) + ); if (state && !superseded && !needsMaintainer && !fresh.length - && !approvalWithdrawal && !dismissalWithdrawal + && !missedActivity && !approvalWithdrawal && !dismissalWithdrawal && !(state === AUTHOR && replyNeedsVerification)) return null; if (unanswered) return AUTHOR; if (superseded) return activeCurrentReviews.length ? MAINTAINER : REVIEWABLE; @@ -293,9 +353,14 @@ async function sync({ github, context, core, number, now = Date.now() }) { const comments = () => github.paginate(github.rest.issues.listComments, { ...args, per_page: 100 }); let history; - const timeline = () => history ||= github.paginate(github.rest.issues.listEventsForTimeline, - { ...args, per_page: 100 }); - const latestLabel = async name => (await timeline()).filter(item => + const timeline = (fresh = false) => { + if (fresh || !history) { + history = github.paginate(github.rest.issues.listEventsForTimeline, + { ...args, per_page: 100 }); + } + return history; + }; + const latestLabel = async (name, fresh = false) => (await timeline(fresh)).filter(item => item.event === 'labeled' && item.label?.name === name).sort((a, b) => (b.created_at || '').localeCompare(a.created_at || '') || b.id - a.id)[0]; const markerComments = async pattern => (await comments()).filter(comment => @@ -390,8 +455,10 @@ async function sync({ github, context, core, number, now = Date.now() }) { const state = current[0]; if (state === BLOCKED) return; // Only its owner can interpret the unblock condition. + const handoff = await latestLabel(state); const setStatus = async next => { if (state === next || !unchanged(pr, await readPr())) return; + if (state && handoff && (await latestLabel(state, true))?.id !== handoff.id) return; for (const name of current) await remove(name); if (state === READY) await deleteMarkers(TRACKER); if (state === PROGRESS) await deleteMarkers(PROGRESS_RECORD); @@ -410,7 +477,6 @@ async function sync({ github, context, core, number, now = Date.now() }) { core.info(`PR #${number}: ${state || 'none'} -> ${next}`); }; - const handoff = await latestLabel(state); let boundary = handoff?.created_at || ''; let superseded = false; let needsMaintainer = false; @@ -467,25 +533,25 @@ async function sync({ github, context, core, number, now = Date.now() }) { if (state === AUTHOR || requests.length) { const threadReplies = await github.paginate(github.rest.pulls.listReviewComments, { owner, repo, pull_number: number, per_page: 100 }); - const byId = new Map(threadReplies.map(reply => [reply.id, reply])); + const reviewIdsOf = buildThreadReviewLookup(threadReplies, pr.user?.login); // Review bodies authored by the PR author are responses, not independent // review completions. Empty self-annotations cannot advance the workflow. allAuthorReplies = [...await comments(), - ...threadReplies.map(reply => ({ ...reply, thread: true, reviewId: reviewOfThread(reply, byId) })), + ...threadReplies.map(reply => ({ ...reply, thread: true, reviewIds: reviewIdsOf(reply) })), ...allReviews.filter(review => review.state === 'COMMENTED').map(review => ({ ...review, created_at: review.submitted_at }))].filter(reply => reply.user?.login && reply.user.login === pr.user?.login && reply.body?.trim() && !reply.body.trim().startsWith('/') && reply.created_at); } - const replyNeedsVerification = allAuthorReplies.some(reply => reply.created_at > boundary); - const unanswered = requests.some(review => !allAuthorReplies.some(reply => - reply.created_at > review.submitted_at - && (reply.thread ? reply.reviewId === review.id : requests.length === 1) - && (state !== AUTHOR || reply.created_at > boundary))); + const automatedHandoff = handoff?.actor?.login === BOT; + const automatedAuthorHandoff = state === AUTHOR && automatedHandoff; + const manualCutoff = state === AUTHOR && !automatedAuthorHandoff ? boundary : ''; + const unanswered = hasUnansweredRequest(requests, allAuthorReplies, manualCutoff); + const replyNeedsVerification = allAuthorReplies.some(reply => reply.created_at > boundary) + || (automatedAuthorHandoff && requests.length > 0 && !unanswered); const priorOpinions = latestFormalOpinions( reviews.filter(review => review.submitted_at <= boundary), pr.head.sha); - const automatedAuthorHandoff = state === AUTHOR && handoff?.actor?.login === BOT; let approvalWithdrawal = false; if (automatedAuthorHandoff) { for (const review of fresh) { @@ -509,7 +575,7 @@ async function sync({ github, context, core, number, now = Date.now() }) { } const next = decideNextStatus({ - state, superseded, needsMaintainer, fresh, activeCurrentReviews, + state, automatedHandoff, superseded, needsMaintainer, fresh, activeCurrentReviews, unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, }); if (next) await setStatus(next); diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 146eb1da87..55946b7440 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -94,10 +94,15 @@ function fixture(options = {}) { if (index >= 0) comments.splice(index, 1); }, }; - const pulls = { list() {}, listReviews() {}, listReviewComments() {}, async get() { - options.onRead?.(pr, ++reads); - return { data: structuredClone(pr) }; - } }; + const pulls = { + async list(params) { + return { data: params?.state === 'closed' ? (options.closedPrs || []) : (options.openPrs || []) }; + }, + listReviews() {}, listReviewComments() {}, async get() { + options.onRead?.(pr, ++reads); + return { data: structuredClone(pr) }; + }, + }; const repos = { listPullRequestsAssociatedWithCommit() {}, getBranchRules() {}, async compareCommitsWithBasehead() { if (options.compareError) throw Object.assign(new Error('Compare failed'), { status: options.compareError }); @@ -940,6 +945,96 @@ test('an approval on an older head cannot override a current-head changes reques assert.deepEqual(await staying.run(), [AUTHOR]); }); +test('batch recovery scan includes recently closed PRs with stale workflow labels', async () => { + const f = fixture({ eventName: 'schedule', payload: { pull_request: undefined }, + openPrs: [{ number: 10, updated_at: '2026-11-28T00:00:00Z', labels: [] }], + closedPrs: [ + { number: 3, state: 'closed', labels: [{ name: READY }] }, + { number: 4, state: 'closed', labels: [{ name: 'area/http' }] }, + ] }); + assert.deepEqual(await collect({ ...f, now: Date.parse('2026-11-29T00:00:00Z') }), [3, 10]); +}); + +test('unknown mergeability does not preserve ready-to-merge', async () => { + const f = fixture({ labels: [READY], merge: { mergeStateStatus: 'UNKNOWN' }, + comments: [botRecord(marker(HEAD))] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('a reapplied label on the same head is not removed using a stale cached handoff', async () => { + const timeline = [labelEvent(PROGRESS, '01:00', { id: 1 })]; + const f = fixture(signalOptions([review('COMMENTED')], { timeline, onRead(_pr, count) { + if (count === 2) timeline.push(labelEvent(PROGRESS, '02:30', { id: 2 })); + } })); + assert.deepEqual(await f.run(), [PROGRESS]); + assert.equal(f.writes.length, 0); +}); + +test('automatic handoffs recover activity that raced the label write without overriding manual handoffs', async () => { + const missedReview = fixture({ eventName: 'schedule', labels: [REVIEWABLE], + timeline: [labelEvent(REVIEWABLE, '03:00', { actor: { login: 'github-actions[bot]' } })], + reviews: [review('COMMENTED', { submitted_at: '2026-11-28T02:59:59Z' })] }); + assert.deepEqual(await missedReview.run(), [MAINTAINER]); + + const missedRequest = fixture({ eventName: 'schedule', labels: [MAINTAINER], + timeline: [labelEvent(MAINTAINER, '03:00', { actor: { login: 'github-actions[bot]' } })], + reviews: [review('CHANGES_REQUESTED', { submitted_at: '2026-11-28T02:59:59Z' })] }); + assert.deepEqual(await missedRequest.run(), [AUTHOR]); + + const missedReply = fixture({ eventName: 'schedule', labels: [AUTHOR], + timeline: [labelEvent(AUTHOR, '03:00', { actor: { login: 'github-actions[bot]' } })], + reviews: [review('CHANGES_REQUESTED', { submitted_at: '2026-11-28T02:00:00Z' })], + comments: [{ id: 50, user: { login: 'author' }, body: 'Fixed before label write.', + created_at: '2026-11-28T02:59:59Z' }] }); + assert.deepEqual(await missedReply.run(), [MAINTAINER]); + + const manualCutoff = fixture({ eventName: 'schedule', labels: [AUTHOR], + timeline: [labelEvent(AUTHOR, '03:00', { actor: { login: 'maintainer' } })], + reviews: [review('CHANGES_REQUESTED', { submitted_at: '2026-11-28T02:00:00Z' })], + comments: [{ id: 50, user: { login: 'author' }, body: 'Old reply before manual send-back.', + created_at: '2026-11-28T02:30:00Z' }] }); + assert.deepEqual(await manualCutoff.run(), [AUTHOR]); +}); + +test('a thread reply matches renewed changes requests added to the same thread before the reply', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', reviews: [ + review('CHANGES_REQUESTED', { id: 10, submitted_at: '2026-11-28T02:00:00Z' }), + review('CHANGES_REQUESTED', { id: 20, submitted_at: '2026-11-28T04:00:00Z' }), + ], timeline: [labelEvent(AUTHOR, '04:05', { actor: { login: 'github-actions[bot]' } })], + threadReplies: [ + { id: 101, pull_request_review_id: 10, user: { login: 'reviewer' }, body: 'First issue.', + created_at: '2026-11-28T02:00:00Z' }, + { id: 102, in_reply_to_id: 101, user: { login: 'author' }, body: 'Tried fixing.', + created_at: '2026-11-28T03:00:00Z' }, + { id: 103, in_reply_to_id: 101, pull_request_review_id: 20, user: { login: 'reviewer' }, + body: 'Still broken here.', created_at: '2026-11-28T04:00:00Z' }, + { id: 104, in_reply_to_id: 101, user: { login: 'author' }, body: 'Fixed properly now.', + created_at: '2026-11-28T05:00:00Z' }, + ] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('earlier responses to reviewer A survive a later request from reviewer B across automatic handoffs', async () => { + const reviews = [ + review('CHANGES_REQUESTED', { id: 10, user: { login: 'rev-a' }, submitted_at: '2026-11-28T02:00:00Z' }), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'rev-b' }, submitted_at: '2026-11-28T04:00:00Z' }), + ]; + const comments = [{ id: 50, user: { login: 'author' }, body: 'Answered A.', + created_at: '2026-11-28T03:00:00Z' }]; + const timeline = [labelEvent(AUTHOR, '04:05', { actor: { login: 'github-actions[bot]' } })]; + const waitingForB = fixture({ labels: [AUTHOR], eventName: 'schedule', reviews, comments, timeline }); + assert.deepEqual(await waitingForB.run(), [AUTHOR]); + + const answeredBoth = fixture({ labels: [AUTHOR], eventName: 'schedule', reviews, comments, timeline, + threadReplies: [ + { id: 201, pull_request_review_id: 11, user: { login: 'rev-b' }, body: 'Please change B.', + created_at: '2026-11-28T04:00:00Z' }, + { id: 202, in_reply_to_id: 201, user: { login: 'author' }, body: 'Answered B.', + created_at: '2026-11-28T05:00:00Z' }, + ] }); + assert.deepEqual(await answeredBoth.run(), [MAINTAINER]); +}); + test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); f.context.payload.workflow_run.name = 'PR activity signal'; diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index 086aaa4db4..62069f5c45 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -190,26 +190,32 @@ human judgment about which head is being reviewed; the Action does not guess. review alone does not revoke it. - New author conversation replies, review-thread replies and nonempty self-review bodies while awaiting author route to maintainer for verification. Replies - predating the active handoff do not answer it. Author self-reviews never count + predating an explicit manual handoff do not answer it; for automatic handoffs, + per-request responses (including replies that raced the automatic label write) + are preserved based on the requests outstanding when each reply was posted. + Author self-reviews never count as an independent review completion. Neither prose nor a push is acceptance. - A thread reply is associated with its original review through `in_reply_to_id`; - it cannot answer another reviewer's request. With several outstanding formal - requests, a general conversation reply does not automatically answer all of - them. Maintainers can evaluate general responses and hand off explicitly. + A thread reply matches reviews that contributed to that thread before the + reply through `in_reply_to_id`; it cannot answer another reviewer's request. + With several outstanding formal requests at the time of a general conversation + reply, that single comment does not automatically answer all of them. + Maintainers can evaluate general responses and hand off explicitly. - A withdrawal can return an automated author handoff to maintainer when it removes the corresponding trusted blocking opinion. Dismissing an unrelated approval does not clear feedback; manual author questions still need a reply. - CI completion checks whether an existing ready-to-merge state still satisfies GitHub's merge requirements. BEHIND revokes readiness only when branch - protection or a ruleset requires an up-to-date branch. Optional failures do + protection or a ruleset requires an up-to-date branch; UNKNOWN mergeability + does not confirm readiness. Optional failures do not become blocking findings. Required checks use the test merge commit when it has checks/statuses, otherwise the head commit. Merge conditions and review feedback produce one state decision; unanswered trusted feedback takes priority over a generic return to maintainer. -- 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 and activity newer than the current handoff. This recovers missed - notifications without replaying older work over an explicit handoff. +- Every half hour, and on manual dispatch, a rotating batch of at most 20 PRs + (including a bounded check of recently updated closed PRs that still carry + workflow labels) is checked for lifecycle cleanup, missing/conflicting states, + stale readiness and activity newer than the current handoff. This recovers + missed notifications without replaying older work over an explicit handoff. 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 From 092ad0ac14d6704d0117800b696bda045a04df82 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 22:59:34 +0800 Subject: [PATCH 15/20] Avoid replaying old reviews on bot handoffs and filter closed PRs by label Fix two follow-up findings: - Remove the blanket automatedHandoff replay in decideNextStatus() so an agent-initiated status/ready-for-review on the same head is not immediately reverted by an earlier review. Recover activity that raced addLabels() via a single bounded post-write recheck using unseen review/reply IDs instead. - Query closed/merged PRs directly via GraphQL pullRequests(states: [CLOSED, MERGED], labels: STATUS, first: 5) so stale closed PRs beyond the first 30 recently updated closed PRs are always drained. --- .github/scripts/pr-status-label.cjs | 101 +++++++++++++++-------- .github/scripts/pr-status-label.test.cjs | 76 +++++++++++------ .github/skills/pr-workflow/SKILL.md | 9 +- 3 files changed, 123 insertions(+), 63 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 6c7738987e..f16bcc0995 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -82,9 +82,11 @@ function buildThreadReviewLookup(threadReplies, authorLogin) { }; } -function hasUnansweredRequest(requests, allAuthorReplies, manualCutoff) { +const replyKey = reply => `${reply.thread ? 't' : reply.submitted_at ? 'r' : 'c'}:${reply.id ?? reply.created_at}`; + +function hasUnansweredRequest(requests, allAuthorReplies, manualCutoff, racingReplies) { const replies = allAuthorReplies - .filter(reply => !manualCutoff || reply.created_at > manualCutoff) + .filter(reply => !manualCutoff || reply.created_at > manualCutoff || racingReplies?.has(replyKey(reply))) .sort((a, b) => a.created_at.localeCompare(b.created_at) || (a.id || 0) - (b.id || 0)); const answered = new Set(); for (const reply of replies) { @@ -179,14 +181,19 @@ async function collect({ github, context, idleDays = 90, now = Date.now() }) { const cutoff = now - days * 86400000; const prs = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'open', per_page: 100 }); - // Include a bounded sample of recently updated closed PRs that still carry - // workflow labels (e.g. conflicted PRs whose pull_request signal did not run). - const closedResp = await github.rest.pulls.list({ - owner, repo, state: 'closed', sort: 'updated', direction: 'desc', per_page: 30, - }); - const closed = (closedResp?.data || []) - .filter(pr => (pr.labels || []).some(label => STATUS.includes(label.name))) - .map(pr => pr.number).sort((a, b) => a - b).slice(0, 5); + // Query closed/merged PRs directly filtered by workflow labels so cleanup + // drains every stale closed PR regardless of how many others closed recently. + const closedData = await github.graphql(` + query($owner:String!, $repo:String!, $labels:[String!]) { + repository(owner:$owner, name:$repo) { + pullRequests(states:[CLOSED, MERGED], labels:$labels, first:5, + orderBy:{field:UPDATED_AT, direction:DESC}) { + nodes { number } + } + } + }`, { owner, repo, labels: STATUS }); + const closed = (closedData?.repository?.pullRequests?.nodes || []) + .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)) @@ -317,15 +324,11 @@ async function checkMergeReadiness({ github, owner, repo, number, headSha }) { } function decideNextStatus({ - state, automatedHandoff, superseded, needsMaintainer, fresh, activeCurrentReviews, + state, superseded, needsMaintainer, fresh, activeCurrentReviews, unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, }) { - const missedActivity = automatedHandoff && ( - (state === REVIEWABLE && activeCurrentReviews.length > 0) - || (state === MAINTAINER && unanswered) - ); if (state && !superseded && !needsMaintainer && !fresh.length - && !missedActivity && !approvalWithdrawal && !dismissalWithdrawal + && !approvalWithdrawal && !dismissalWithdrawal && !(state === AUTHOR && replyNeedsVerification)) return null; if (unanswered) return AUTHOR; if (superseded) return activeCurrentReviews.length ? MAINTAINER : REVIEWABLE; @@ -341,7 +344,10 @@ function decideNextStatus({ return !state ? REVIEWABLE : null; } -async function sync({ github, context, core, number, now = Date.now() }) { +async function sync({ + github, context, core, number, now = Date.now(), + _rechecked = false, _racingReviews = null, _racingReplies = null, +}) { if (!numberOf(number)) throw new Error('Invalid PR number'); const { owner, repo } = context.repo; const args = { owner, repo, issue_number: number }; @@ -457,24 +463,25 @@ async function sync({ github, context, core, number, now = Date.now() }) { if (state === BLOCKED) return; // Only its owner can interpret the unblock condition. const handoff = await latestLabel(state); const setStatus = async next => { - if (state === next || !unchanged(pr, await readPr())) return; - if (state && handoff && (await latestLabel(state, true))?.id !== handoff.id) return; + if (state === next || !unchanged(pr, await readPr())) return false; + if (state && handoff && (await latestLabel(state, true))?.id !== handoff.id) return false; for (const name of current) await remove(name); if (state === READY) await deleteMarkers(TRACKER); if (state === PROGRESS) await deleteMarkers(PROGRESS_RECORD); // 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; + if (!active(latest) || latest.head.sha !== pr.head.sha || statusOf(latest).length) return false; await github.rest.issues.addLabels({ ...args, labels: [next] }); const landed = await readPr(); if (!active(landed) || landed.head.sha !== pr.head.sha || statusOf(landed).some(name => name !== next)) { await remove(next); - return; + return false; } - if (!statusOf(landed).includes(next)) return; + if (!statusOf(landed).includes(next)) return false; core.info(`PR #${number}: ${state || 'none'} -> ${next}`); + return true; }; let boundary = handoff?.created_at || ''; @@ -519,7 +526,8 @@ async function sync({ github, context, core, number, now = Date.now() }) { // Without a recorded handoff, do not reinterpret historical reviews over an // explicit state. Unlabeled PRs can still be classified from current facts. if (state && !handoff && !needsMaintainer) return; - const fresh = activeCurrentReviews.filter(review => review.submitted_at > boundary); + const fresh = activeCurrentReviews.filter(review => + review.submitted_at > boundary || _racingReviews?.has(review.id)); const opinions = latestFormalOpinions(reviews, pr.head.sha); const requests = []; for (const review of opinions.values()) { @@ -529,26 +537,26 @@ async function sync({ github, context, core, number, now = Date.now() }) { if (await canDecide(review.user.login)) requests.push(review); } - let allAuthorReplies = []; - if (state === AUTHOR || requests.length) { + const readAuthorReplies = async reviewList => { const threadReplies = await github.paginate(github.rest.pulls.listReviewComments, { owner, repo, pull_number: number, per_page: 100 }); const reviewIdsOf = buildThreadReviewLookup(threadReplies, pr.user?.login); // Review bodies authored by the PR author are responses, not independent // review completions. Empty self-annotations cannot advance the workflow. - allAuthorReplies = [...await comments(), + return [...await comments(), ...threadReplies.map(reply => ({ ...reply, thread: true, reviewIds: reviewIdsOf(reply) })), - ...allReviews.filter(review => review.state === 'COMMENTED').map(review => + ...reviewList.filter(review => review.state === 'COMMENTED').map(review => ({ ...review, created_at: review.submitted_at }))].filter(reply => reply.user?.login && reply.user.login === pr.user?.login && reply.body?.trim() && !reply.body.trim().startsWith('/') && reply.created_at); - } - const automatedHandoff = handoff?.actor?.login === BOT; - const automatedAuthorHandoff = state === AUTHOR && automatedHandoff; + }; + const allAuthorReplies = (state === AUTHOR || requests.length) + ? await readAuthorReplies(allReviews) : []; + const automatedAuthorHandoff = state === AUTHOR && handoff?.actor?.login === BOT; const manualCutoff = state === AUTHOR && !automatedAuthorHandoff ? boundary : ''; - const unanswered = hasUnansweredRequest(requests, allAuthorReplies, manualCutoff); - const replyNeedsVerification = allAuthorReplies.some(reply => reply.created_at > boundary) - || (automatedAuthorHandoff && requests.length > 0 && !unanswered); + const unanswered = hasUnansweredRequest(requests, allAuthorReplies, manualCutoff, _racingReplies); + const replyNeedsVerification = allAuthorReplies.some(reply => + reply.created_at > boundary || _racingReplies?.has(replyKey(reply))); const priorOpinions = latestFormalOpinions( reviews.filter(review => review.submitted_at <= boundary), pr.head.sha); @@ -575,10 +583,33 @@ async function sync({ github, context, core, number, now = Date.now() }) { } const next = decideNextStatus({ - state, automatedHandoff, superseded, needsMaintainer, fresh, activeCurrentReviews, + state, superseded, needsMaintainer, fresh, activeCurrentReviews, unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, }); - if (next) await setStatus(next); + if (!next || !await setStatus(next) || _rechecked) return; + // Re-check once for reviews or author replies that arrived after our history + // read and before addLabels(), without replaying older history on future runs. + if (next === REVIEWABLE || next === MAINTAINER) { + const seenReviews = new Set(allReviews.map(review => review.id)); + const latestReviews = await github.paginate(github.rest.pulls.listReviews, + { owner, repo, pull_number: number, per_page: 100 }); + const racingReviews = new Set(latestReviews.filter(review => !seenReviews.has(review.id) + && review.user?.login && review.user.login !== pr.user?.login + && review.commit_id === pr.head.sha && review.submitted_at + && REVIEW_STATES.includes(review.state) && review.state !== 'DISMISSED').map(r => r.id)); + if (racingReviews.size) { + await sync({ github, context, core, number, now, _rechecked: true, _racingReviews: racingReviews }); + } + } else if (next === AUTHOR) { + const seenReplies = new Set(allAuthorReplies.map(replyKey)); + const latestReviews = await github.paginate(github.rest.pulls.listReviews, + { owner, repo, pull_number: number, per_page: 100 }); + const latestReplies = await readAuthorReplies(latestReviews); + const racingReplies = new Set(latestReplies.map(replyKey).filter(key => !seenReplies.has(key))); + if (racingReplies.size) { + await sync({ github, context, core, number, now, _rechecked: true, _racingReplies: racingReplies }); + } + } } module.exports = { collect, sync }; diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 55946b7440..b7793adfb4 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -42,6 +42,12 @@ function fixture(options = {}) { user: Object.hasOwn(options, 'author') ? options.author : { login: 'author' }, labels: (options.labels || []).map(name => ({ name })) }; const comments = structuredClone(options.comments || []); + const reviews = structuredClone(options.reviews || []); + const timeline = options.timeline || (options.labels || []) + .filter(name => name.startsWith('status/')).map((name, i) => ({ + id: i + 1, event: 'labeled', label: { name }, actor: { login: name === AUTHOR ? 'github-actions[bot]' : 'labeler' }, + created_at: name === AUTHOR ? '2026-11-28T02:30:00Z' : '2026-11-28T01:00:00Z', + })); const writes = []; let reads = 0; let checkPages = 0; @@ -77,8 +83,14 @@ function fixture(options = {}) { }, async addLabels({ labels }) { writes.push(['add', ...labels]); - for (const name of labels) pr.labels.push({ name }); - options.onAdd?.(pr); + for (const name of labels) { + pr.labels.push({ name }); + if (name.startsWith('status/')) { + timeline.push({ id: timeline.length + 10, event: 'labeled', label: { name }, + actor: { login: 'github-actions[bot]' }, created_at: '2026-11-28T06:00:00Z' }); + } + } + options.onAdd?.(pr, { reviews, comments, timeline }); }, async createComment({ body }) { writes.push(['comment', body]); @@ -134,15 +146,11 @@ function fixture(options = {}) { rest: { pulls, issues, repos, ...(search ? { search } : {}) }, async paginate(method, params = {}) { if (method === issues.listComments) return structuredClone(comments); - if (method === issues.listEventsForTimeline) return options.timeline || (options.labels || []) - .filter(name => name.startsWith('status/')).map((name, i) => ({ - id: i + 1, event: 'labeled', label: { name }, actor: { login: name === AUTHOR ? 'github-actions[bot]' : 'labeler' }, - created_at: name === AUTHOR ? '2026-11-28T02:30:00Z' : '2026-11-28T01:00:00Z', - })); + if (method === issues.listEventsForTimeline) return timeline; if (method === pulls.listReviewComments) return options.threadReplies || []; if (method === repos.getBranchRules) return options.rules || []; if (method === repos.listPullRequestsAssociatedWithCommit) return options.associatedPrs || []; - if (method === pulls.listReviews) return structuredClone(options.reviews || []); + if (method === pulls.listReviews) return structuredClone(reviews); if (method === pulls.list) { if (params.head) return options.pullsByHead?.[params.head] || []; return options.openPrs || []; @@ -150,6 +158,13 @@ function fixture(options = {}) { throw new Error('Unexpected API pagination'); }, async graphql(query, variables) { + if (query.includes('pullRequests(states:')) { + const nodes = (options.closedPrs || []) + .filter(item => (item.labels || []).some(label => variables.labels.includes(label.name))) + .slice(0, 5) + .map(item => ({ number: item.number })); + return { repository: { pullRequests: { nodes } } }; + } if (!query.includes('object(oid:')) return { repository: { pullRequest: { headRefOid: HEAD, reviewDecision: null, mergeStateStatus: 'CLEAN', ...options.merge, } } }; @@ -945,13 +960,14 @@ test('an approval on an older head cannot override a current-head changes reques assert.deepEqual(await staying.run(), [AUTHOR]); }); -test('batch recovery scan includes recently closed PRs with stale workflow labels', async () => { +test('batch recovery scan directly filters closed PRs carrying workflow labels beyond page one', async () => { + const closedPrs = [ + ...Array.from({ length: 35 }, (_, i) => ({ number: 100 + i, state: 'closed', labels: [{ name: 'area/http' }] })), + { number: 3, state: 'closed', labels: [{ name: READY }] }, + ]; const f = fixture({ eventName: 'schedule', payload: { pull_request: undefined }, openPrs: [{ number: 10, updated_at: '2026-11-28T00:00:00Z', labels: [] }], - closedPrs: [ - { number: 3, state: 'closed', labels: [{ name: READY }] }, - { number: 4, state: 'closed', labels: [{ name: 'area/http' }] }, - ] }); + closedPrs }); assert.deepEqual(await collect({ ...f, now: Date.parse('2026-11-29T00:00:00Z') }), [3, 10]); }); @@ -970,22 +986,34 @@ test('a reapplied label on the same head is not removed using a stale cached han assert.equal(f.writes.length, 0); }); -test('automatic handoffs recover activity that raced the label write without overriding manual handoffs', async () => { - const missedReview = fixture({ eventName: 'schedule', labels: [REVIEWABLE], +test('an automated ready-for-review request on the same head is not overwritten by an earlier review', async () => { + const f = fixture({ eventName: 'schedule', labels: [REVIEWABLE], timeline: [labelEvent(REVIEWABLE, '03:00', { actor: { login: 'github-actions[bot]' } })], - reviews: [review('COMMENTED', { submitted_at: '2026-11-28T02:59:59Z' })] }); + reviews: [review('APPROVED', { submitted_at: '2026-11-28T01:00:00Z' })] }); + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.equal(f.writes.length, 0); +}); + +test('post-write recheck recovers activity that raced an automatic label write without overriding manual handoffs', async () => { + const missedReview = fixture({ onAdd(_pr, { reviews }) { + if (!reviews.length) reviews.push(review('COMMENTED', { id: 21, submitted_at: '2026-11-28T05:59:59Z' })); + } }); assert.deepEqual(await missedReview.run(), [MAINTAINER]); - const missedRequest = fixture({ eventName: 'schedule', labels: [MAINTAINER], - timeline: [labelEvent(MAINTAINER, '03:00', { actor: { login: 'github-actions[bot]' } })], - reviews: [review('CHANGES_REQUESTED', { submitted_at: '2026-11-28T02:59:59Z' })] }); + const missedRequest = fixture(signalOptions([review('COMMENTED')], { onAdd(_pr, { reviews }) { + if (reviews.length === 1) { + reviews.push(review('CHANGES_REQUESTED', { id: 22, user: { login: 'other' }, + submitted_at: '2026-11-28T05:59:59Z' })); + } + } })); assert.deepEqual(await missedRequest.run(), [AUTHOR]); - const missedReply = fixture({ eventName: 'schedule', labels: [AUTHOR], - timeline: [labelEvent(AUTHOR, '03:00', { actor: { login: 'github-actions[bot]' } })], - reviews: [review('CHANGES_REQUESTED', { submitted_at: '2026-11-28T02:00:00Z' })], - comments: [{ id: 50, user: { login: 'author' }, body: 'Fixed before label write.', - created_at: '2026-11-28T02:59:59Z' }] }); + const missedReply = fixture(signalOptions([review('CHANGES_REQUESTED')], { onAdd(_pr, { comments }) { + if (!comments.length) { + comments.push({ id: 50, user: { login: 'author' }, body: 'Fixed before label write.', + created_at: '2026-11-28T05:59:59Z' }); + } + } })); assert.deepEqual(await missedReply.run(), [MAINTAINER]); const manualCutoff = fixture({ eventName: 'schedule', labels: [AUTHOR], diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index 62069f5c45..9a5f68b47c 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -212,10 +212,11 @@ human judgment about which head is being reviewed; the Action does not guess. feedback produce one state decision; unanswered trusted feedback takes priority over a generic return to maintainer. - Every half hour, and on manual dispatch, a rotating batch of at most 20 PRs - (including a bounded check of recently updated closed PRs that still carry - workflow labels) is checked for lifecycle cleanup, missing/conflicting states, - stale readiness and activity newer than the current handoff. This recovers - missed notifications without replaying older work over an explicit handoff. + (including a label-filtered batch of up to 5 closed or merged PRs that still + carry workflow labels) is checked for lifecycle cleanup, missing/conflicting + states, stale readiness and activity newer than the current handoff. This + recovers missed notifications without replaying older work over an explicit + handoff. 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 From 9cf232316323266961e210bbea47cb97965c0169 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Wed, 2 Dec 2026 23:21:50 +0800 Subject: [PATCH 16/20] Bind post-write recheck to the written head, state, and label event ID Have setStatus() return the bot-authored { headSha, state, handoffId } it just wrote, and pass it as _expected into the follow-up sync(). Abort the follow-up immediately if the head, status label, or label-event ID changed (e.g., due to a newer manual review-in-progress handoff), and skip label-application recording/conflict warnings during rechecks. --- .github/scripts/pr-status-label.cjs | 45 ++++++++++++++---------- .github/scripts/pr-status-label.test.cjs | 23 ++++++++++++ 2 files changed, 49 insertions(+), 19 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index f16bcc0995..653da1901a 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -346,7 +346,7 @@ function decideNextStatus({ async function sync({ github, context, core, number, now = Date.now(), - _rechecked = false, _racingReviews = null, _racingReplies = null, + _expected = null, _racingReviews = null, _racingReplies = null, }) { if (!numberOf(number)) throw new Error('Invalid PR number'); const { owner, repo } = context.repo; @@ -437,19 +437,21 @@ async function sync({ || (name === READY && !await canDecide(label.actor.login))) return null; return { label, sha: snapshot[3] }; }; - for (const [name, pattern, kind] of [ - [READY, TRACKER, 'ready-to-merge'], - [PROGRESS, PROGRESS_RECORD, 'review-in-progress'], - ]) { - const applied = await latestApplication(name); - if (applied && unchanged(pr, await readPr())) { - await upsertMarker(pattern, kind, applied.sha, applied.label.id); + if (!_expected) { + for (const [name, pattern, kind] of [ + [READY, TRACKER, 'ready-to-merge'], + [PROGRESS, PROGRESS_RECORD, 'review-in-progress'], + ]) { + const applied = await latestApplication(name); + if (applied && unchanged(pr, await readPr())) { + await upsertMarker(pattern, kind, applied.sha, applied.label.id); + } } } const current = statusOf(pr); if (current.length > 1) { - if (!unchanged(pr, await readPr())) return; + if (_expected || !unchanged(pr, await readPr())) return; if (!(await comments()).some(comment => comment.user?.login === BOT && comment.body.startsWith(WARNING))) { await github.rest.issues.createComment({ ...args, body: `${WARNING}\n` @@ -462,26 +464,30 @@ async function sync({ const state = current[0]; if (state === BLOCKED) return; // Only its owner can interpret the unblock condition. const handoff = await latestLabel(state); + if (_expected && (pr.head.sha !== _expected.headSha + || state !== _expected.state || handoff?.id !== _expected.handoffId)) return; const setStatus = async next => { - if (state === next || !unchanged(pr, await readPr())) return false; - if (state && handoff && (await latestLabel(state, true))?.id !== handoff.id) return false; + if (state === next || !unchanged(pr, await readPr())) return null; + if (state && handoff && (await latestLabel(state, true))?.id !== handoff.id) return null; for (const name of current) await remove(name); if (state === READY) await deleteMarkers(TRACKER); if (state === PROGRESS) await deleteMarkers(PROGRESS_RECORD); // 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 false; + if (!active(latest) || latest.head.sha !== pr.head.sha || statusOf(latest).length) return null; await github.rest.issues.addLabels({ ...args, labels: [next] }); const landed = await readPr(); if (!active(landed) || landed.head.sha !== pr.head.sha || statusOf(landed).some(name => name !== next)) { await remove(next); - return false; + return null; } - if (!statusOf(landed).includes(next)) return false; + if (!statusOf(landed).includes(next)) return null; core.info(`PR #${number}: ${state || 'none'} -> ${next}`); - return true; + const applied = await latestLabel(next, true); + return applied?.actor?.login === BOT && applied.id + ? { headSha: pr.head.sha, state: next, handoffId: applied.id } : null; }; let boundary = handoff?.created_at || ''; @@ -586,9 +592,10 @@ async function sync({ state, superseded, needsMaintainer, fresh, activeCurrentReviews, unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, }); - if (!next || !await setStatus(next) || _rechecked) return; + const written = next ? await setStatus(next) : null; + if (!written || _expected) return; // Re-check once for reviews or author replies that arrived after our history - // read and before addLabels(), without replaying older history on future runs. + // read and before addLabels(), bound strictly to this written handoff. if (next === REVIEWABLE || next === MAINTAINER) { const seenReviews = new Set(allReviews.map(review => review.id)); const latestReviews = await github.paginate(github.rest.pulls.listReviews, @@ -598,7 +605,7 @@ async function sync({ && review.commit_id === pr.head.sha && review.submitted_at && REVIEW_STATES.includes(review.state) && review.state !== 'DISMISSED').map(r => r.id)); if (racingReviews.size) { - await sync({ github, context, core, number, now, _rechecked: true, _racingReviews: racingReviews }); + await sync({ github, context, core, number, now, _expected: written, _racingReviews: racingReviews }); } } else if (next === AUTHOR) { const seenReplies = new Set(allAuthorReplies.map(replyKey)); @@ -607,7 +614,7 @@ async function sync({ const latestReplies = await readAuthorReplies(latestReviews); const racingReplies = new Set(latestReplies.map(replyKey).filter(key => !seenReplies.has(key))); if (racingReplies.size) { - await sync({ github, context, core, number, now, _rechecked: true, _racingReplies: racingReplies }); + await sync({ github, context, core, number, now, _expected: written, _racingReplies: racingReplies }); } } } diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index b7793adfb4..705e13cdb6 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -1024,6 +1024,29 @@ test('post-write recheck recovers activity that raced an automatic label write w assert.deepEqual(await manualCutoff.run(), [AUTHOR]); }); +test('post-write recheck aborts when a newer manual handoff replaces the written state or event ID', async () => { + for (const [nextLabel, expected] of [[PROGRESS, PROGRESS], [MAINTAINER, MAINTAINER]]) { + const timeline = [labelEvent(PROGRESS, '01:00', { id: 1 })]; + const f = fixture(signalOptions([review('COMMENTED')], { + timeline, + onAdd(_pr, { reviews }) { + if (reviews.length === 1) { + reviews.push(review('CHANGES_REQUESTED', { id: 22, user: { login: 'other' }, + submitted_at: '2026-11-28T05:59:59Z' })); + } + }, + onRead(pr, count) { + if (count === 5) { + pr.labels = [{ name: nextLabel }]; + timeline.push(labelEvent(nextLabel, '06:01', { id: 99, actor: { login: 'maintainer' } })); + } + }, + })); + assert.deepEqual(await f.run(), [expected]); + assert.deepEqual(f.writes.filter(write => write[0] === 'add'), [['add', MAINTAINER]]); + } +}); + test('a thread reply matches renewed changes requests added to the same thread before the reply', async () => { const f = fixture({ labels: [AUTHOR], eventName: 'schedule', reviews: [ review('CHANGES_REQUESTED', { id: 10, submitted_at: '2026-11-28T02:00:00Z' }), From f0d23db5c861bd4ff3a951c0ad84089ff57f02fa Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Thu, 3 Dec 2026 21:30:02 +0800 Subject: [PATCH 17/20] Verify PR commit associations and tighten handoff boundaries Address Copilot review comments and independent review findings: - Handle 404/422 from listPullRequestsAssociatedWithCommit, verify head-branch fallback candidates via pulls.listCommits when head SHA differs, and verify search fallback candidates against base repo and commit history via pulls.get / pulls.listCommits. - Prevent pre-handoff CHANGES_REQUESTED reviews from replaying over explicit MAINTAINER/PROGRESS/REVIEWABLE handoffs, and preserve earlier answers to pre-existing formal requests across manual AUTHOR handoffs. - Treat mergeStateStatus BEHIND directly as not ready (since GitHub only emits BEHIND when strict up-to-date checks are required and branchProtectionRule is null under GITHUB_TOKEN). - Extend post-write AUTHOR rechecks to also catch racing APPROVED reviews and review_dismissed withdrawals, ignore standalone root inline notes in readAuthorReplies, and update dispatch description. --- .github/scripts/pr-status-label.cjs | 113 +++++++++++++++-------- .github/scripts/pr-status-label.test.cjs | 110 +++++++++++++++++++--- .github/skills/pr-workflow/SKILL.md | 7 +- .github/workflows/pr-status-label.yml | 2 +- 4 files changed, 178 insertions(+), 54 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 653da1901a..2cad22bb8c 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -83,10 +83,10 @@ function buildThreadReviewLookup(threadReplies, authorLogin) { } const replyKey = reply => `${reply.thread ? 't' : reply.submitted_at ? 'r' : 'c'}:${reply.id ?? reply.created_at}`; +const dismissalKey = item => `${item.id ?? ''}:${item.created_at || ''}:${item.dismissed_review?.review_id ?? ''}`; -function hasUnansweredRequest(requests, allAuthorReplies, manualCutoff, racingReplies) { - const replies = allAuthorReplies - .filter(reply => !manualCutoff || reply.created_at > manualCutoff || racingReplies?.has(replyKey(reply))) +function hasUnansweredRequest(requests, allAuthorReplies) { + const replies = [...allAuthorReplies] .sort((a, b) => a.created_at.localeCompare(b.created_at) || (a.id || 0) - (b.id || 0)); const answered = new Set(); for (const reply of replies) { @@ -130,18 +130,39 @@ async function resolveWorkflowRunPrs({ github, context }) { const sameRepo = pr => pr.base?.repo?.full_name ? pr.base.repo.full_name === `${owner}/${repo}` : pr.base?.repo?.id && pr.base.repo.id === event.repository?.id; + const prHasCommit = async (prNumber, sha) => { + try { + const commits = await github.paginate(github.rest.pulls.listCommits, { + owner, repo, pull_number: prNumber, per_page: 100, + }); + return commits.some(commit => commit.sha === sha); + } catch (error) { + if (error.status === 404) return false; + throw error; + } + }; let prs = run.pull_requests?.length ? run.pull_requests.filter(sameRepo) : []; if (!prs.length && run.head_sha) { - prs = (await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { - owner, repo, commit_sha: run.head_sha, per_page: 100, - })).filter(sameRepo); + try { + prs = (await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { + owner, repo, commit_sha: run.head_sha, per_page: 100, + })).filter(sameRepo); + } catch (error) { + if (![404, 422].includes(error.status)) throw error; + } } const headOwner = run.head_repository?.owner?.login || run.head_repository?.full_name?.split('/')[0]; if (!prs.length && headOwner && run.head_branch) { - prs = (await github.paginate(github.rest.pulls.list, { + const byHead = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'all', head: `${headOwner}:${run.head_branch}`, per_page: 100, - })).filter(pr => pr.head?.sha === run.head_sha || pr.state === 'open'); + }); + prs = byHead.filter(pr => pr.head?.sha === run.head_sha); + if (!prs.length && run.head_sha) { + for (const candidate of byHead.filter(pr => pr.state === 'open')) { + if (await prHasCommit(candidate.number, run.head_sha)) prs.push(candidate); + } + } } if (!prs.length && run.head_sha) { prs = (await github.paginate(github.rest.pulls.list, { @@ -151,9 +172,22 @@ async function resolveWorkflowRunPrs({ github, context }) { if (!prs.length && run.head_sha && run.name !== 'PR label signal' && github.rest.search?.issuesAndPullRequests) { const { data } = await github.rest.search.issuesAndPullRequests({ - q: `repo:${owner}/${repo} is:pr ${run.head_sha}`, per_page: 20, + q: `repo:${owner}/${repo} is:pr ${run.head_sha}`, per_page: 5, }); - prs = data.items || []; + for (const item of data.items || []) { + try { + const { data: candidate } = await github.rest.pulls.get({ + owner, repo, pull_number: item.number, + }); + if (!sameRepo(candidate)) continue; + if (candidate.head?.sha === run.head_sha + || await prHasCommit(candidate.number, run.head_sha)) { + prs.push(candidate); + } + } catch (error) { + if (error.status !== 404) throw error; + } + } } return [...new Set(prs.map(pr => pr.number))]; } @@ -276,7 +310,6 @@ async function checkMergeReadiness({ github, owner, repo, number, headSha }) { query($owner:String!, $repo:String!, $number:Int!) { repository(owner:$owner,name:$repo) { pullRequest(number:$number) { headRefOid reviewDecision mergeStateStatus - baseRef { name branchProtectionRule { requiresStrictStatusChecks } } potentialMergeCommit { oid statusCheckRollup { contexts(first:1) { totalCount } } } } } }`, { owner, repo, number }); @@ -308,19 +341,11 @@ async function checkMergeReadiness({ github, owner, repo, number, headSha }) { : check.state !== 'SUCCESS')); cursor = checks?.pageInfo.hasNextPage ? checks.pageInfo.endCursor : null; } while (cursor); - let behindRequired = false; - if (merge.mergeStateStatus === 'BEHIND') { - behindRequired = merge.baseRef?.branchProtectionRule?.requiresStrictStatusChecks === true; - if (!behindRequired && merge.baseRef) { - const rules = await github.paginate(github.rest.repos.getBranchRules, - { owner, repo, branch: merge.baseRef.name, per_page: 100 }); - behindRequired = rules.some(rule => rule.type === 'required_status_checks' - && rule.parameters?.strict_required_status_checks_policy === true); - } - } - return !(behindRequired || notPassing + // GitHub only reports BEHIND when branch protection or a ruleset requires an + // up-to-date branch; non-strict out-of-date PRs report CLEAN or UNSTABLE. + return !(notPassing || ['CHANGES_REQUESTED', 'REVIEW_REQUIRED'].includes(merge.reviewDecision) - || ['BLOCKED', 'DIRTY', 'DRAFT', 'UNKNOWN'].includes(merge.mergeStateStatus)); + || ['BEHIND', 'BLOCKED', 'DIRTY', 'DRAFT', 'UNKNOWN'].includes(merge.mergeStateStatus)); } function decideNextStatus({ @@ -346,7 +371,7 @@ function decideNextStatus({ async function sync({ github, context, core, number, now = Date.now(), - _expected = null, _racingReviews = null, _racingReplies = null, + _expected = null, _racingReviews = null, _racingReplies = null, _racingDismissals = null, }) { if (!numberOf(number)) throw new Error('Invalid PR number'); const { owner, repo } = context.repo; @@ -539,7 +564,8 @@ async function sync({ for (const review of opinions.values()) { if (review.state !== 'CHANGES_REQUESTED') continue; if (state !== AUTHOR && review.commit_id !== pr.head.sha) continue; - if (state === READY && !superseded && review.submitted_at <= boundary) continue; + if (state && state !== AUTHOR && !superseded + && review.submitted_at <= boundary && !_racingReviews?.has(review.id)) continue; if (await canDecide(review.user.login)) requests.push(review); } @@ -548,9 +574,11 @@ async function sync({ { owner, repo, pull_number: number, per_page: 100 }); const reviewIdsOf = buildThreadReviewLookup(threadReplies, pr.user?.login); // Review bodies authored by the PR author are responses, not independent - // review completions. Empty self-annotations cannot advance the workflow. + // review completions. Empty self-annotations and standalone root notes + // cannot advance the workflow. return [...await comments(), - ...threadReplies.map(reply => ({ ...reply, thread: true, reviewIds: reviewIdsOf(reply) })), + ...threadReplies.filter(reply => reply.in_reply_to_id) + .map(reply => ({ ...reply, thread: true, reviewIds: reviewIdsOf(reply) })), ...reviewList.filter(review => review.state === 'COMMENTED').map(review => ({ ...review, created_at: review.submitted_at }))].filter(reply => reply.user?.login && reply.user.login === pr.user?.login && reply.body?.trim() @@ -559,13 +587,13 @@ async function sync({ const allAuthorReplies = (state === AUTHOR || requests.length) ? await readAuthorReplies(allReviews) : []; const automatedAuthorHandoff = state === AUTHOR && handoff?.actor?.login === BOT; - const manualCutoff = state === AUTHOR && !automatedAuthorHandoff ? boundary : ''; - const unanswered = hasUnansweredRequest(requests, allAuthorReplies, manualCutoff, _racingReplies); + const unanswered = hasUnansweredRequest(requests, allAuthorReplies); const replyNeedsVerification = allAuthorReplies.some(reply => reply.created_at > boundary || _racingReplies?.has(replyKey(reply))); const priorOpinions = latestFormalOpinions( - reviews.filter(review => review.submitted_at <= boundary), pr.head.sha); + reviews.filter(review => review.submitted_at <= boundary && !_racingReviews?.has(review.id)), + pr.head.sha); let approvalWithdrawal = false; if (automatedAuthorHandoff) { for (const review of fresh) { @@ -576,7 +604,8 @@ async function sync({ } let dismissalWithdrawal = false; for (const item of automatedAuthorHandoff ? await timeline() : []) { - if (item.event !== 'review_dismissed' || item.created_at <= boundary + if (item.event !== 'review_dismissed' + || (item.created_at <= boundary && !_racingDismissals?.has(dismissalKey(item))) || item.dismissed_review?.state?.toUpperCase() !== 'CHANGES_REQUESTED') continue; const dismissed = reviews.find(review => review.id === item.dismissed_review.review_id); // REST preserves the dismissed review's original submission time. An @@ -592,12 +621,15 @@ async function sync({ state, superseded, needsMaintainer, fresh, activeCurrentReviews, unanswered, replyNeedsVerification, approvalWithdrawal, dismissalWithdrawal, }); + const seenDismissals = next === AUTHOR && !_expected + ? new Set((await timeline()).filter(item => item.event === 'review_dismissed').map(dismissalKey)) + : null; const written = next ? await setStatus(next) : null; if (!written || _expected) return; - // Re-check once for reviews or author replies that arrived after our history - // read and before addLabels(), bound strictly to this written handoff. + // Re-check once for reviews, withdrawals or author replies that arrived after + // our history read and before addLabels(), bound strictly to this handoff. + const seenReviews = new Set(allReviews.map(review => review.id)); if (next === REVIEWABLE || next === MAINTAINER) { - const seenReviews = new Set(allReviews.map(review => review.id)); const latestReviews = await github.paginate(github.rest.pulls.listReviews, { owner, repo, pull_number: number, per_page: 100 }); const racingReviews = new Set(latestReviews.filter(review => !seenReviews.has(review.id) @@ -613,8 +645,17 @@ async function sync({ { owner, repo, pull_number: number, per_page: 100 }); const latestReplies = await readAuthorReplies(latestReviews); const racingReplies = new Set(latestReplies.map(replyKey).filter(key => !seenReplies.has(key))); - if (racingReplies.size) { - await sync({ github, context, core, number, now, _expected: written, _racingReplies: racingReplies }); + const racingReviews = new Set(latestReviews.filter(review => !seenReviews.has(review.id) + && review.state === 'APPROVED' && review.user?.login && review.user.login !== pr.user?.login + && review.commit_id === pr.head.sha && review.submitted_at).map(r => r.id)); + const racingDismissals = new Set((await timeline(true)) + .filter(item => item.event === 'review_dismissed' + && item.dismissed_review?.state?.toUpperCase() === 'CHANGES_REQUESTED' + && !seenDismissals.has(dismissalKey(item))) + .map(dismissalKey)); + if (racingReplies.size || racingReviews.size || racingDismissals.size) { + await sync({ github, context, core, number, now, _expected: written, + _racingReplies: racingReplies, _racingReviews: racingReviews, _racingDismissals: racingDismissals }); } } } diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 705e13cdb6..1b86f4c23e 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -110,7 +110,10 @@ function fixture(options = {}) { async list(params) { return { data: params?.state === 'closed' ? (options.closedPrs || []) : (options.openPrs || []) }; }, - listReviews() {}, listReviewComments() {}, async get() { + listCommits() {}, listReviews() {}, listReviewComments() {}, async get({ pull_number } = {}) { + if (options.pullsByNumber && pull_number && Object.hasOwn(options.pullsByNumber, pull_number)) { + return { data: structuredClone(options.pullsByNumber[pull_number]) }; + } options.onRead?.(pr, ++reads); return { data: structuredClone(pr) }; }, @@ -148,8 +151,14 @@ function fixture(options = {}) { if (method === issues.listComments) return structuredClone(comments); if (method === issues.listEventsForTimeline) return timeline; if (method === pulls.listReviewComments) return options.threadReplies || []; + if (method === pulls.listCommits) return options.commitsByPr?.[params.pull_number] || []; if (method === repos.getBranchRules) return options.rules || []; - if (method === repos.listPullRequestsAssociatedWithCommit) return options.associatedPrs || []; + if (method === repos.listPullRequestsAssociatedWithCommit) { + if (options.associatedPrError) { + throw Object.assign(new Error('Commit lookup failed'), { status: options.associatedPrError }); + } + return options.associatedPrs || []; + } if (method === pulls.listReviews) return structuredClone(reviews); if (method === pulls.list) { if (params.head) return options.pullsByHead?.[params.head] || []; @@ -676,16 +685,14 @@ test('unrelated dismissals and manual author questions cannot be cleared by with assert.deepEqual(await manual.run(), [AUTHOR]); }); -test('BEHIND blocks readiness only when legacy protection or rulesets require an up-to-date branch', async () => { - for (const [protection, rules, expected] of [ - [true, [], MAINTAINER], - [false, [{ type: 'required_status_checks', parameters: { - strict_required_status_checks_policy: true } }], MAINTAINER], - [false, [], READY], +test('BEHIND revokes readiness while CLEAN and UNSTABLE preserve it', async () => { + for (const [mergeStateStatus, expected] of [ + ['BEHIND', MAINTAINER], + ['CLEAN', READY], + ['UNSTABLE', READY], ]) { const f = fixture({ labels: [READY], comments: [botRecord(marker(HEAD))], - merge: { mergeStateStatus: 'BEHIND', baseRef: { name: 'master', - branchProtectionRule: { requiresStrictStatusChecks: protection } } }, rules }); + merge: { mergeStateStatus } }); assert.deepEqual(await f.run(), [expected]); } }); @@ -886,12 +893,16 @@ test('label confirmation tolerates small PR updated_at drift without accepting s assert.equal(stale.comments.length, 0); }); -test('fork workflow_run collection resolves open, pushed, closed and reviewed PRs without trusting search for labels', async () => { - const forkLabel = fixture({ eventName: 'workflow_run', pullsByHead: { +test('fork workflow_run collection verifies commit associations and search candidates', async () => { + const forkLabel = fixture({ eventName: 'workflow_run', associatedPrError: 422, pullsByHead: { 'contrib:fix': [ { number: 10, state: 'closed', head: { sha: 'c'.repeat(40) } }, { number: 20, state: 'open', head: { sha: HEAD } }, + { number: 21, state: 'open', head: { sha: 'd'.repeat(40) } }, ], + }, commitsByPr: { + 20: [{ sha: OLD }, { sha: HEAD }], + 21: [{ sha: 'd'.repeat(40) }], }, payload: { pull_request: undefined, workflow_run: { name: 'PR label signal', event: 'pull_request', path: '.github/workflows/pr-label-signal.yml', head_sha: OLD, head_branch: 'fix', head_repository: { owner: { login: 'contrib' } }, @@ -899,7 +910,7 @@ test('fork workflow_run collection resolves open, pushed, closed and reviewed PR } } }); assert.deepEqual(await collect(forkLabel), [20]); - const forkClosed = fixture({ eventName: 'workflow_run', pullsByHead: { + const forkClosed = fixture({ eventName: 'workflow_run', associatedPrError: 404, pullsByHead: { 'contrib:done': [{ number: 30, state: 'closed', head: { sha: HEAD } }], }, payload: { pull_request: undefined, workflow_run: { name: 'PR activity signal', event: 'pull_request', @@ -918,7 +929,14 @@ test('fork workflow_run collection resolves open, pushed, closed and reviewed PR } } }); assert.deepEqual(await collect(forkReview), [40]); - const searchActivity = fixture({ eventName: 'workflow_run', searchItems: [{ number: 50 }], + const searchActivity = fixture({ eventName: 'workflow_run', + searchItems: [{ number: 50 }, { number: 51 }, { number: 52 }], + pullsByNumber: { + 50: { number: 50, head: { sha: OLD }, base: { repo: { full_name: 'apache/brpc' } } }, + 51: { number: 51, head: { sha: HEAD }, base: { repo: { full_name: 'apache/brpc' } } }, + 52: { number: 52, head: { sha: OLD }, base: { repo: { full_name: 'other/brpc' } } }, + }, + commitsByPr: { 51: [{ sha: HEAD }] }, payload: { pull_request: undefined, workflow_run: { name: 'PR activity signal', event: 'pull_request_review', head_sha: OLD, pull_requests: [], @@ -926,6 +944,9 @@ test('fork workflow_run collection resolves open, pushed, closed and reviewed PR assert.deepEqual(await collect(searchActivity), [50]); const searchLabel = fixture({ eventName: 'workflow_run', searchItems: [{ number: 50 }], + pullsByNumber: { + 50: { number: 50, head: { sha: OLD }, base: { repo: { full_name: 'apache/brpc' } } }, + }, payload: { pull_request: undefined, workflow_run: { name: 'PR label signal', event: 'pull_request', path: '.github/workflows/pr-label-signal.yml', head_sha: OLD, pull_requests: [], @@ -1086,6 +1107,67 @@ test('earlier responses to reviewer A survive a later request from reviewer B ac assert.deepEqual(await answeredBoth.run(), [MAINTAINER]); }); +test('pre-handoff changes requests do not replay over explicit maintainer or review handoffs', async () => { + for (const state of [MAINTAINER, PROGRESS, REVIEWABLE]) { + const f = fixture({ labels: [state], eventName: 'schedule', + timeline: [labelEvent(state, '03:00')], + reviews: [ + review('CHANGES_REQUESTED', { id: 10, user: { login: 'rev-a' }, submitted_at: '2026-11-28T02:00:00Z' }), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'rev-b' }, submitted_at: '2026-11-28T02:05:00Z' }), + review('COMMENTED', { id: 12, user: { login: 'rev-c' }, submitted_at: '2026-11-28T04:00:00Z' }), + ], + comments: [{ id: 50, user: { login: 'author' }, body: 'Answered both.', created_at: '2026-11-28T02:30:00Z' }] }); + assert.deepEqual(await f.run(), [MAINTAINER]); + } +}); + +test('manual awaiting-author handoff preserves earlier answers to pre-existing formal requests', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', + timeline: [labelEvent(AUTHOR, '02:00', { actor: { login: 'maintainer' } })], + reviews: [ + review('CHANGES_REQUESTED', { id: 10, user: { login: 'rev-a' }, submitted_at: '2026-11-28T01:00:00Z' }), + review('COMMENTED', { id: 20, user: { login: 'rev-b' }, submitted_at: '2026-11-28T02:00:00Z' }), + ], + threadReplies: [ + { id: 101, pull_request_review_id: 10, user: { login: 'rev-a' }, body: 'Fix A.', created_at: '2026-11-28T01:00:00Z' }, + { id: 102, in_reply_to_id: 101, user: { login: 'author' }, body: 'Fixed A.', created_at: '2026-11-28T01:10:00Z' }, + { id: 201, pull_request_review_id: 20, user: { login: 'rev-b' }, body: 'Question B?', created_at: '2026-11-28T02:00:00Z' }, + { id: 202, in_reply_to_id: 201, user: { login: 'author' }, body: 'Answer B.', created_at: '2026-11-28T02:10:00Z' }, + ] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('post-write recheck after awaiting-author recovers racing approval and dismissal withdrawals', async () => { + const approvedRace = fixture(signalOptions([review('CHANGES_REQUESTED')], { + onAdd(_pr, { reviews }) { + if (reviews.length === 1) { + reviews.push(review('APPROVED', { id: 11, submitted_at: '2026-11-28T05:59:59Z' })); + } + }, + })); + assert.deepEqual(await approvedRace.run(), [MAINTAINER]); + + const dismissedRace = fixture(signalOptions([review('CHANGES_REQUESTED')], { + onAdd(_pr, { reviews, timeline }) { + if (reviews[0].state === 'CHANGES_REQUESTED') { + reviews[0].state = 'DISMISSED'; + timeline.push({ id: 88, event: 'review_dismissed', created_at: '2026-11-28T05:59:59Z', + dismissed_review: { review_id: 10, state: 'changes_requested' } }); + } + }, + })); + assert.deepEqual(await dismissedRace.run(), [MAINTAINER]); +}); + +test('standalone author root inline diff notes do not advance manual awaiting-author', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', + timeline: [labelEvent(AUTHOR, '02:00', { actor: { login: 'maintainer' } })], + threadReplies: [ + { id: 301, user: { login: 'author' }, body: 'Self note on diff.', created_at: '2026-11-28T03:00:00Z' }, + ] }); + assert.deepEqual(await f.run(), [AUTHOR]); +}); + test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); f.context.payload.workflow_run.name = 'PR activity signal'; diff --git a/.github/skills/pr-workflow/SKILL.md b/.github/skills/pr-workflow/SKILL.md index 9a5f68b47c..bb53f7bfeb 100644 --- a/.github/skills/pr-workflow/SKILL.md +++ b/.github/skills/pr-workflow/SKILL.md @@ -204,9 +204,10 @@ human judgment about which head is being reviewed; the Action does not guess. removes the corresponding trusted blocking opinion. Dismissing an unrelated approval does not clear feedback; manual author questions still need a reply. - CI completion checks whether an existing ready-to-merge state still satisfies - GitHub's merge requirements. BEHIND revokes readiness only when branch - protection or a ruleset requires an up-to-date branch; UNKNOWN mergeability - does not confirm readiness. Optional failures do + GitHub's merge requirements. BEHIND and UNKNOWN mergeability do not confirm + readiness (GitHub reports BEHIND only when branch protection or a ruleset + requires an up-to-date branch; non-strict out-of-date PRs report CLEAN or + UNSTABLE). Optional failures do not become blocking findings. Required checks use the test merge commit when it has checks/statuses, otherwise the head commit. Merge conditions and review feedback produce one state decision; unanswered trusted feedback takes priority diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index 689df95900..12dbdb473c 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -36,7 +36,7 @@ on: workflow_dispatch: inputs: pr_number: - description: 'PR number; leave empty for a rotating batch of up to 20 open PRs' + description: 'PR number; leave empty for a batch of up to 20 PRs (including stale closed PRs)' required: false type: string From fc7a4adfe297ce705283382673a0d586c4565f3a Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Thu, 3 Dec 2026 22:42:26 +0800 Subject: [PATCH 18/20] Identify PR signal workflows by workflow_run.path instead of name GitHub overwrites workflow_run.name with the evaluated run-name when run-name is set (observed live on PR #3786 run 47128750401), so checks comparing workflow_run.name against 'PR label signal' fail in production. Identify signal runs by GitHub-owned workflow_run.path instead, and align the test fixture's workflow_run.name with real GitHub run payloads. --- .github/scripts/pr-status-label.cjs | 17 ++++++++++------- .github/scripts/pr-status-label.test.cjs | 11 +++++++---- .github/workflows/pr-status-label.yml | 2 +- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 2cad22bb8c..613144e70a 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -23,6 +23,7 @@ const { createHash } = require('node:crypto'); const BOT = 'github-actions[bot]'; const LABEL_WORKFLOW = '.github/workflows/pr-label-signal.yml'; +const ACTIVITY_WORKFLOW = '.github/workflows/pr-review-signal.yml'; const LABEL_SIGNAL = /^PR label #(\d+) (status\/(?:ready-to-merge|review-in-progress)) sha=([0-9a-f]{40}) at=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)$/; const REVIEWABLE = 'status/ready-for-review'; const PROGRESS = 'status/review-in-progress'; @@ -122,11 +123,13 @@ async function resolveWorkflowRunPrs({ github, context }) { const run = event.workflow_run; // Relay code and titles can be changed by a fork. Only GitHub-owned run // associations select PRs; the receiver reconciles API history, not a title. + // Note: GitHub overwrites workflow_run.name with evaluated run-name, so + // identify signal workflows by their GitHub-owned workflow_run.path. + const isLabelSignal = run.path === LABEL_WORKFLOW; if (run.conclusion === 'skipped' - && ['PR label signal', 'PR activity signal'].includes(run.name)) return []; + && [LABEL_WORKFLOW, ACTIVITY_WORKFLOW].includes(run.path)) return []; if (!SIGNAL_EVENTS.includes(run.event)) return []; - if (run.name === 'PR label signal' - && (run.event !== 'pull_request' || run.path !== LABEL_WORKFLOW)) return []; + if (isLabelSignal && run.event !== 'pull_request') return []; const sameRepo = pr => pr.base?.repo?.full_name ? pr.base.repo.full_name === `${owner}/${repo}` : pr.base?.repo?.id && pr.base.repo.id === event.repository?.id; @@ -169,7 +172,7 @@ async function resolveWorkflowRunPrs({ github, context }) { owner, repo, state: 'open', per_page: 100, })).filter(pr => pr.head?.sha === run.head_sha); } - if (!prs.length && run.head_sha && run.name !== 'PR label signal' + if (!prs.length && run.head_sha && !isLabelSignal && github.rest.search?.issuesAndPullRequests) { const { data } = await github.rest.search.issuesAndPullRequests({ q: `repo:${owner}/${repo} is:pr ${run.head_sha}`, per_page: 5, @@ -443,9 +446,9 @@ async function sync({ const run = context.eventName === 'workflow_run' ? event.workflow_run : null; let verifiedDefinition; const latestApplication = async name => { - if (run?.name !== 'PR label signal' || run.event !== 'pull_request' - || run.path !== LABEL_WORKFLOW || !statusOf(pr).includes(name)) return null; - const snapshot = LABEL_SIGNAL.exec(run.display_title || ''); + if (run?.path !== LABEL_WORKFLOW || run.event !== 'pull_request' + || !statusOf(pr).includes(name)) return null; + const snapshot = LABEL_SIGNAL.exec(run.display_title || run.name || ''); if (!snapshot || Number(snapshot[1]) !== number || snapshot[2] !== name || snapshot[3] !== run.head_sha || !(await collect({ github, context })).includes(number)) return null; diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 1b86f4c23e..8c6a533ed9 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -52,6 +52,9 @@ function fixture(options = {}) { let reads = 0; let checkPages = 0; const checkShas = []; + const labelRunName = `PR label #1 ${options.eventLabel || 'area/http'} sha=${options.eventHead || HEAD} at=${options.eventAt + || options.timeline?.filter(item => item.event === 'labeled' + && item.label?.name === options.eventLabel).at(-1)?.created_at || '2026-11-28T01:00:00Z'}`; const context = { repo: { owner: 'apache', repo: 'brpc' }, eventName: options.eventName || 'workflow_run', payload: { action: options.action || 'opened', pull_request: { @@ -61,12 +64,11 @@ function fixture(options = {}) { label: { name: options.eventLabel }, sender: { login: 'labeler' }, repository: { id: 1, default_branch: 'master' }, workflow_run: { - name: 'PR label signal', event: 'pull_request', + // GitHub sets workflow_run.name to the evaluated run-name when defined. + name: labelRunName, event: 'pull_request', path: '.github/workflows/pr-label-signal.yml', head_sha: options.eventHead || HEAD, - display_title: `PR label #1 ${options.eventLabel || 'area/http'} sha=${options.eventHead || HEAD} at=${options.eventAt - || options.timeline?.filter(item => item.event === 'labeled' - && item.label?.name === options.eventLabel).at(-1)?.created_at || '2026-11-28T01:00:00Z'}`, + display_title: labelRunName, actor: options.payload && Object.hasOwn(options.payload, 'sender') ? options.payload.sender : { login: 'labeler' }, created_at: options.action === 'labeled' ? options.eventAt @@ -1171,6 +1173,7 @@ test('standalone author root inline diff notes do not advance manual awaiting-au test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); f.context.payload.workflow_run.name = 'PR activity signal'; + f.context.payload.workflow_run.path = '.github/workflows/pr-review-signal.yml'; f.context.payload.workflow_run.display_title = `PR label #1 ${PROGRESS} sha=${HEAD} at=2026-11-28T01:00:00Z`; assert.deepEqual(await f.run(), [REVIEWABLE]); assert.ok(!f.writes.some(write => write[0] === 'comment')); diff --git a/.github/workflows/pr-status-label.yml b/.github/workflows/pr-status-label.yml index 12dbdb473c..000412e3b7 100644 --- a/.github/workflows/pr-status-label.yml +++ b/.github/workflows/pr-status-label.yml @@ -44,7 +44,7 @@ permissions: {} jobs: collect: - if: ${{ !(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'skipped' && (github.event.workflow_run.name == 'PR label signal' || github.event.workflow_run.name == 'PR activity signal')) }} + if: ${{ !(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'skipped' && (github.event.workflow_run.path == '.github/workflows/pr-label-signal.yml' || github.event.workflow_run.path == '.github/workflows/pr-review-signal.yml')) }} permissions: contents: read pull-requests: read From 847525a7b624ccd325408301034651f052248635 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Fri, 4 Dec 2026 09:20:56 +0800 Subject: [PATCH 19/20] Harden signal history, request attribution, and same-second ordering Address the latest review feedback on PR #3786: - Verify the base branch's pr-label-signal.yml version at run.created_at via repos.listCommits so queued signals from older definitions are not validated against a newer workflow. - Always check headOwner:head_branch when workflow_run.pull_requests is empty even if commit association already matched an older merged PR. - Reject ambiguous multi-candidate label applications within the 5s window and keep already-confirmed label event IDs immutable. - Evaluate general comment attribution against the formal requests that were actually pending when the comment was posted, and exclude old-head requests predating a later non-AUTHOR handoff. - Check that the latest label event still belongs to github-actions[bot] before rolling back on a concurrent head change, and resolve same-second submitted_at === boundary ordering using GitHub timeline positions. --- .github/scripts/pr-status-label.cjs | 129 ++++++++++++++++++----- .github/scripts/pr-status-label.test.cjs | 98 +++++++++++++++++ 2 files changed, 203 insertions(+), 24 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index 613144e70a..a63f5f59f3 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -86,20 +86,27 @@ function buildThreadReviewLookup(threadReplies, authorLogin) { const replyKey = reply => `${reply.thread ? 't' : reply.submitted_at ? 'r' : 'c'}:${reply.id ?? reply.created_at}`; const dismissalKey = item => `${item.id ?? ''}:${item.created_at || ''}:${item.dismissed_review?.review_id ?? ''}`; -function hasUnansweredRequest(requests, allAuthorReplies) { +function hasUnansweredRequest(requests, allAuthorReplies, trustedFormalReviews, headSha, dismissedAt = new Map()) { const replies = [...allAuthorReplies] .sort((a, b) => a.created_at.localeCompare(b.created_at) || (a.id || 0) - (b.id || 0)); const answered = new Set(); for (const reply of replies) { if (reply.thread) { - for (const review of requests) { - if (reply.created_at > review.submitted_at && reply.reviewIds.has(review.id)) { + for (const review of trustedFormalReviews) { + if (review.state === 'CHANGES_REQUESTED' + && reply.created_at > review.submitted_at + && reply.reviewIds.has(review.id)) { answered.add(review.id); } } } else { - const pending = requests.filter(review => - review.submitted_at < reply.created_at && !answered.has(review.id)); + const priorReviews = trustedFormalReviews + .filter(review => review.submitted_at < reply.created_at) + .map(review => (review.state === 'DISMISSED' && dismissedAt.get(review.id) > reply.created_at + ? { ...review, state: 'CHANGES_REQUESTED' } : review)); + const atReply = latestFormalOpinions(priorReviews, headSha); + const pending = [...atReply.values()].filter(review => + review.state === 'CHANGES_REQUESTED' && !answered.has(review.id)); if (pending.length === 1) answered.add(pending[0].id); } } @@ -144,24 +151,28 @@ async function resolveWorkflowRunPrs({ github, context }) { throw error; } }; - let prs = run.pull_requests?.length ? run.pull_requests.filter(sameRepo) : []; - if (!prs.length && run.head_sha) { + const directPrs = run.pull_requests?.length ? run.pull_requests.filter(sameRepo) : []; + let prs = [...directPrs]; + if (!directPrs.length && run.head_sha) { try { - prs = (await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { + prs.push(...(await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { owner, repo, commit_sha: run.head_sha, per_page: 100, - })).filter(sameRepo); + })).filter(sameRepo)); } catch (error) { if (![404, 422].includes(error.status)) throw error; } } const headOwner = run.head_repository?.owner?.login || run.head_repository?.full_name?.split('/')[0]; - if (!prs.length && headOwner && run.head_branch) { + // Even when commit association matches an older merged PR (e.g. backporting + // an existing commit to a release branch), also check the run's source branch. + if (!directPrs.length && headOwner && run.head_branch) { const byHead = await github.paginate(github.rest.pulls.list, { owner, repo, state: 'all', head: `${headOwner}:${run.head_branch}`, per_page: 100, }); - prs = byHead.filter(pr => pr.head?.sha === run.head_sha); - if (!prs.length && run.head_sha) { + const exact = byHead.filter(pr => pr.head?.sha === run.head_sha); + prs.push(...exact); + if (!exact.length && run.head_sha) { for (const candidate of byHead.filter(pr => pr.state === 'open')) { if (await prHasCommit(candidate.number, run.head_sha)) prs.push(candidate); } @@ -290,6 +301,17 @@ async function verifySignalDefinition({ github, owner, repo, pr, run, defaultBra if (!baseRef) return false; if ((!defaultBranch || baseRef !== defaultBranch) && await blobSha(pr.base?.sha || baseRef) !== expected) return false; + if (run.created_at && github.rest.repos.listCommits) { + try { + const { data } = await github.rest.repos.listCommits({ + owner, repo, sha: baseRef, path: LABEL_WORKFLOW, until: run.created_at, per_page: 1, + }); + if (!data?.length || await blobSha(data[0].sha) !== expected) return false; + } catch (error) { + if (error.status !== 404) throw error; + return false; + } + } const headBlob = await blobSha(run.head_sha); if (headBlob === expected) return true; if (headBlob === undefined) return false; @@ -408,6 +430,11 @@ async function sync({ if (!/^[0-9a-f]{40}$/.test(sha || '')) throw new Error('Invalid head SHA'); if (!numberOf(labelId)) throw new Error('Invalid label event ID'); const existing = await markerComments(pattern); + // Never overwrite a confirmed SHA already bound to the same label event ID. + if (existing.some(comment => { + const match = pattern.exec(comment.body.trim()); + return Number(match?.[2]) === labelId && match[1] !== sha; + })) return; const body = ``; if (existing.length === 1 && existing[0].body.trim() === body) return; if (existing.length) { @@ -459,9 +486,13 @@ async function sync({ } if (!verifiedDefinition) return null; const label = await latestLabel(name); - const lag = Date.parse(snapshot[4]) - Date.parse(label?.created_at); - if (!label?.actor?.login || label.actor.login !== run.actor?.login - || !(lag >= 0 && lag <= 5000) + const matches = (await timeline()).filter(item => { + if (item.event !== 'labeled' || item.label?.name !== name) return false; + if (!item.actor?.login || item.actor.login !== run.actor?.login) return false; + const lag = Date.parse(snapshot[4]) - Date.parse(item.created_at); + return lag >= 0 && lag <= 5000; + }); + if (!label || matches.length !== 1 || matches[0].id !== label.id || (name === READY && !await canDecide(label.actor.login))) return null; return { label, sha: snapshot[3] }; }; @@ -504,13 +535,21 @@ async function sync({ // 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 null; + const beforeAddId = (await latestLabel(next, true))?.id || 0; await github.rest.issues.addLabels({ ...args, labels: [next] }); const landed = await readPr(); - if (!active(landed) || landed.head.sha !== pr.head.sha - || statusOf(landed).some(name => name !== next)) { + if (!active(landed)) { await remove(next); return null; } + if (landed.head.sha !== pr.head.sha + || statusOf(landed).some(name => name !== next)) { + const latestNext = await latestLabel(next, true); + if (!latestNext || (latestNext.actor?.login === BOT && latestNext.id >= beforeAddId)) { + await remove(next); + } + return null; + } if (!statusOf(landed).includes(next)) return null; core.info(`PR #${number}: ${state || 'none'} -> ${next}`); const applied = await latestLabel(next, true); @@ -560,15 +599,35 @@ async function sync({ // Without a recorded handoff, do not reinterpret historical reviews over an // explicit state. Unlabeled PRs can still be classified from current facts. if (state && !handoff && !needsMaintainer) return; + const timelineEvents = state && handoff ? await timeline() : []; + const handoffIndex = handoff + ? timelineEvents.findIndex(item => item.event === 'labeled' && item.id === handoff.id) + : -1; + const afterBoundary = review => { + if (review.submitted_at > boundary) return true; + if (review.submitted_at !== boundary || handoffIndex < 0) return false; + return timelineEvents.findIndex(item => item.event === 'reviewed' && item.id === review.id) > handoffIndex; + }; const fresh = activeCurrentReviews.filter(review => - review.submitted_at > boundary || _racingReviews?.has(review.id)); + afterBoundary(review) || _racingReviews?.has(review.id)); + const prevNonAuthor = state === AUTHOR && handoff + ? timelineEvents.filter(item => item.event === 'labeled' + && STATUS.includes(item.label?.name) && item.label.name !== AUTHOR + && ((item.created_at || '') < (handoff.created_at || '') + || (item.created_at === handoff.created_at && item.id < handoff.id))) + .sort((a, b) => (b.created_at || '').localeCompare(a.created_at || '') || b.id - a.id)[0] + : null; + const prevStateAt = prevNonAuthor?.created_at || ''; + const inRequestScope = review => (state === AUTHOR + ? review.commit_id === pr.head.sha || !prevStateAt || review.submitted_at > prevStateAt + : review.commit_id === pr.head.sha); const opinions = latestFormalOpinions(reviews, pr.head.sha); const requests = []; for (const review of opinions.values()) { if (review.state !== 'CHANGES_REQUESTED') continue; - if (state !== AUTHOR && review.commit_id !== pr.head.sha) continue; + if (!inRequestScope(review)) continue; if (state && state !== AUTHOR && !superseded - && review.submitted_at <= boundary && !_racingReviews?.has(review.id)) continue; + && !afterBoundary(review) && !_racingReviews?.has(review.id)) continue; if (await canDecide(review.user.login)) requests.push(review); } @@ -589,13 +648,35 @@ async function sync({ }; const allAuthorReplies = (state === AUTHOR || requests.length) ? await readAuthorReplies(allReviews) : []; + let unanswered = false; + if (requests.length) { + const trustedFormalReviews = []; + for (const review of reviews) { + if (!FORMAL_STATES.includes(review.state) || !inRequestScope(review)) continue; + if (await canDecide(review.user.login)) trustedFormalReviews.push(review); + } + const dismissedAt = new Map(); + if (trustedFormalReviews.some(review => review.state === 'DISMISSED')) { + for (const item of await timeline()) { + if (item.event === 'review_dismissed' + && item.dismissed_review?.state?.toUpperCase() === 'CHANGES_REQUESTED' + && item.dismissed_review.review_id) { + dismissedAt.set(item.dismissed_review.review_id, item.created_at); + } + } + } + unanswered = hasUnansweredRequest(requests, allAuthorReplies, trustedFormalReviews, pr.head.sha, dismissedAt); + } const automatedAuthorHandoff = state === AUTHOR && handoff?.actor?.login === BOT; - const unanswered = hasUnansweredRequest(requests, allAuthorReplies); - const replyNeedsVerification = allAuthorReplies.some(reply => - reply.created_at > boundary || _racingReplies?.has(replyKey(reply))); + const replyNeedsVerification = allAuthorReplies.some(reply => { + if (reply.created_at > boundary || _racingReplies?.has(replyKey(reply))) return true; + if (reply.created_at !== boundary || handoffIndex < 0) return false; + const eventType = reply.submitted_at ? 'reviewed' : 'commented'; + return timelineEvents.findIndex(item => item.event === eventType && item.id === reply.id) > handoffIndex; + }); const priorOpinions = latestFormalOpinions( - reviews.filter(review => review.submitted_at <= boundary && !_racingReviews?.has(review.id)), + reviews.filter(review => !afterBoundary(review) && !_racingReviews?.has(review.id)), pr.head.sha); let approvalWithdrawal = false; if (automatedAuthorHandoff) { diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 8c6a533ed9..7003df5690 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -121,6 +121,10 @@ function fixture(options = {}) { }, }; const repos = { listPullRequestsAssociatedWithCommit() {}, getBranchRules() {}, + async listCommits() { + if (options.baseWorkflowCommits) return { data: options.baseWorkflowCommits }; + return { data: [{ sha: 'e'.repeat(40) }] }; + }, async compareCommitsWithBasehead() { if (options.compareError) throw Object.assign(new Error('Compare failed'), { status: options.compareError }); return { data: { merge_base_commit: { sha: options.mergeBaseSha || '0'.repeat(40) } } }; @@ -1170,6 +1174,100 @@ test('standalone author root inline diff notes do not advance manual awaiting-au assert.deepEqual(await f.run(), [AUTHOR]); }); +test('default branch workflow updated while signal was queued cannot confirm the older run', async () => { + const oldCommit = 'f'.repeat(40); + const f = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + baseWorkflowCommits: [{ sha: oldCommit }], + contentByRef: { [HEAD]: 'old-blob', ['0'.repeat(40)]: 'old-blob', [oldCommit]: 'old-blob' } }); + assert.deepEqual(await f.run(), [MAINTAINER]); + assert.equal(f.comments.length, 0); +}); + +test('backported commit matching an older merged PR still collects the source branch PR', async () => { + const f = fixture({ eventName: 'workflow_run', + associatedPrs: [{ number: 100, state: 'closed', base: { repo: { full_name: 'apache/brpc' } } }], + pullsByHead: { 'contrib:release-1.10': [{ number: 200, state: 'open', head: { sha: HEAD } }] }, + payload: { pull_request: undefined, workflow_run: { + name: 'PR label #200 status/ready-to-merge', event: 'pull_request', + path: '.github/workflows/pr-label-signal.yml', head_sha: HEAD, + head_branch: 'release-1.10', head_repository: { owner: { login: 'contrib' } }, + pull_requests: [], + } } }); + assert.deepEqual(await collect(f), [100, 200]); +}); + +test('same-second multi-candidate label applications are rejected and confirmed event IDs are immutable', async () => { + const ambiguous = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + eventHead: OLD, eventAt: '2026-11-28T01:00:00Z', timeline: [ + labelEvent(READY, '01:00', { id: 1 }), + labelEvent(READY, '01:00', { id: 2 }), + ] }); + assert.deepEqual(await ambiguous.run(), [MAINTAINER]); + assert.equal(ambiguous.comments.length, 0); + + const protectedMarker = fixture({ labels: [READY], action: 'labeled', eventLabel: READY, + eventHead: OLD, comments: [botRecord(marker(HEAD, 1))], + timeline: [labelEvent(READY, '01:00', { id: 1 })] }); + assert.deepEqual(await protectedMarker.run(), [READY]); + assert.equal(protectedMarker.comments[0].body, marker(HEAD, 1)); +}); + +test('a general comment posted while two requests were pending cannot retroactively answer one after the other approves', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', + timeline: [labelEvent(AUTHOR, '02:05', { actor: { login: 'github-actions[bot]' } })], + reviews: [ + review('CHANGES_REQUESTED', { id: 10, user: { login: 'rev-a' }, submitted_at: '2026-11-28T02:00:00Z' }), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'rev-b' }, submitted_at: '2026-11-28T02:01:00Z' }), + review('APPROVED', { id: 12, user: { login: 'rev-a' }, submitted_at: '2026-11-28T04:00:00Z' }), + ], + comments: [{ id: 50, user: { login: 'author' }, body: 'Updated.', created_at: '2026-11-28T03:00:00Z' }] }); + assert.deepEqual(await f.run(), [AUTHOR]); +}); + +test('old-head change requests predating a later non-author handoff do not block a newer awaiting-author handoff', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', + timeline: [ + labelEvent(MAINTAINER, '02:00', { id: 1 }), + labelEvent(AUTHOR, '03:05', { id: 2, actor: { login: 'github-actions[bot]' } }), + ], + reviews: [ + review('CHANGES_REQUESTED', { id: 10, user: { login: 'rev-a' }, commit_id: OLD, submitted_at: '2026-11-28T01:00:00Z' }), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'rev-b' }, commit_id: HEAD, submitted_at: '2026-11-28T03:00:00Z' }), + ], + threadReplies: [ + { id: 201, pull_request_review_id: 11, user: { login: 'rev-b' }, body: 'Fix B.', created_at: '2026-11-28T03:00:00Z' }, + { id: 202, in_reply_to_id: 201, user: { login: 'author' }, body: 'Fixed B.', created_at: '2026-11-28T04:00:00Z' }, + ] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('head-change rollback preserves a label manually reapplied on the new head', async () => { + const f = fixture({ onAdd(pr, { timeline }) { + pr.head.sha = 'c'.repeat(40); + timeline.push(labelEvent(REVIEWABLE, '06:01', { id: 99, actor: { login: 'maintainer' } })); + } }); + assert.deepEqual(await f.run(), [REVIEWABLE]); + assert.ok(!f.writes.some(write => write[0] === 'remove' && write[1] === REVIEWABLE)); +}); + +test('same-second reviews use timeline order to distinguish post-handoff reviews from earlier ones', async () => { + const after = fixture({ labels: [PROGRESS], eventName: 'schedule', + reviews: [review('COMMENTED', { id: 10, submitted_at: '2026-11-28T01:00:00Z' })], + timeline: [ + labelEvent(PROGRESS, '01:00', { id: 1 }), + { id: 10, event: 'reviewed', submitted_at: '2026-11-28T01:00:00Z' }, + ] }); + assert.deepEqual(await after.run(), [MAINTAINER]); + + const before = fixture({ labels: [PROGRESS], eventName: 'schedule', + reviews: [review('COMMENTED', { id: 10, submitted_at: '2026-11-28T01:00:00Z' })], + timeline: [ + { id: 10, event: 'reviewed', submitted_at: '2026-11-28T01:00:00Z' }, + labelEvent(PROGRESS, '01:00', { id: 1 }), + ] }); + assert.deepEqual(await before.run(), [PROGRESS]); +}); + test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); f.context.payload.workflow_run.name = 'PR activity signal'; From afab15073266205d58e7f9977daa30ce52162a74 Mon Sep 17 00:00:00 2001 From: Wang Xiaofeng Date: Fri, 4 Dec 2026 21:08:04 +0800 Subject: [PATCH 20/20] Replay thread replies at reply time and scope same-head requests to handoff Fix two edge cases in PR #3786 review 6182186760: - Apply stateAt(review, reply.created_at) consistently to both thread replies and general comments in hasUnansweredRequest() so an earlier thread reply to a later-dismissed request still counts when resolving subsequent general comments. - Drop the pr.head.sha bypass in inRequestScope() under AUTHOR so requests predating a later non-AUTHOR handoff (including same-head requests with no intervening push) do not re-block a newer handoff. --- .github/scripts/pr-status-label.cjs | 17 ++++++++--- .github/scripts/pr-status-label.test.cjs | 36 ++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/.github/scripts/pr-status-label.cjs b/.github/scripts/pr-status-label.cjs index a63f5f59f3..0ba0691df1 100644 --- a/.github/scripts/pr-status-label.cjs +++ b/.github/scripts/pr-status-label.cjs @@ -87,13 +87,15 @@ const replyKey = reply => `${reply.thread ? 't' : reply.submitted_at ? 'r' : 'c' const dismissalKey = item => `${item.id ?? ''}:${item.created_at || ''}:${item.dismissed_review?.review_id ?? ''}`; function hasUnansweredRequest(requests, allAuthorReplies, trustedFormalReviews, headSha, dismissedAt = new Map()) { + const stateAt = (review, at) => (review.state === 'DISMISSED' && dismissedAt.get(review.id) > at + ? 'CHANGES_REQUESTED' : review.state); const replies = [...allAuthorReplies] .sort((a, b) => a.created_at.localeCompare(b.created_at) || (a.id || 0) - (b.id || 0)); const answered = new Set(); for (const reply of replies) { if (reply.thread) { for (const review of trustedFormalReviews) { - if (review.state === 'CHANGES_REQUESTED' + if (stateAt(review, reply.created_at) === 'CHANGES_REQUESTED' && reply.created_at > review.submitted_at && reply.reviewIds.has(review.id)) { answered.add(review.id); @@ -102,8 +104,7 @@ function hasUnansweredRequest(requests, allAuthorReplies, trustedFormalReviews, } else { const priorReviews = trustedFormalReviews .filter(review => review.submitted_at < reply.created_at) - .map(review => (review.state === 'DISMISSED' && dismissedAt.get(review.id) > reply.created_at - ? { ...review, state: 'CHANGES_REQUESTED' } : review)); + .map(review => ({ ...review, state: stateAt(review, reply.created_at) })); const atReply = latestFormalOpinions(priorReviews, headSha); const pending = [...atReply.values()].filter(review => review.state === 'CHANGES_REQUESTED' && !answered.has(review.id)); @@ -618,8 +619,16 @@ async function sync({ .sort((a, b) => (b.created_at || '').localeCompare(a.created_at || '') || b.id - a.id)[0] : null; const prevStateAt = prevNonAuthor?.created_at || ''; + const prevStateIndex = prevNonAuthor + ? timelineEvents.findIndex(item => item.event === 'labeled' && item.id === prevNonAuthor.id) + : -1; + const afterPrevState = review => { + if (!prevStateAt || review.submitted_at > prevStateAt) return true; + if (review.submitted_at !== prevStateAt || prevStateIndex < 0) return false; + return timelineEvents.findIndex(item => item.event === 'reviewed' && item.id === review.id) > prevStateIndex; + }; const inRequestScope = review => (state === AUTHOR - ? review.commit_id === pr.head.sha || !prevStateAt || review.submitted_at > prevStateAt + ? afterPrevState(review) : review.commit_id === pr.head.sha); const opinions = latestFormalOpinions(reviews, pr.head.sha); const requests = []; diff --git a/.github/scripts/pr-status-label.test.cjs b/.github/scripts/pr-status-label.test.cjs index 7003df5690..3d928bf220 100644 --- a/.github/scripts/pr-status-label.test.cjs +++ b/.github/scripts/pr-status-label.test.cjs @@ -1268,6 +1268,42 @@ test('same-second reviews use timeline order to distinguish post-handoff reviews assert.deepEqual(await before.run(), [PROGRESS]); }); +test('thread reply to a later-dismissed request still counts when attributing a subsequent general comment', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', + timeline: [ + labelEvent(AUTHOR, '02:05', { id: 1, actor: { login: 'github-actions[bot]' } }), + { id: 2, event: 'review_dismissed', created_at: '2026-11-28T05:00:00Z', + dismissed_review: { review_id: 10, state: 'changes_requested' } }, + ], + reviews: [ + review('DISMISSED', { id: 10, user: { login: 'rev-a' }, submitted_at: '2026-11-28T02:00:00Z' }), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'rev-b' }, submitted_at: '2026-11-28T02:01:00Z' }), + ], + threadReplies: [ + { id: 101, pull_request_review_id: 10, user: { login: 'rev-a' }, body: 'Fix A.', created_at: '2026-11-28T02:00:00Z' }, + { id: 102, in_reply_to_id: 101, user: { login: 'author' }, body: 'Fixed A.', created_at: '2026-11-28T03:00:00Z' }, + ], + comments: [{ id: 50, user: { login: 'author' }, body: 'Fixed B as well.', created_at: '2026-11-28T04:00:00Z' }] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + +test('same-head change requests predating a later non-author handoff do not block a newer awaiting-author handoff', async () => { + const f = fixture({ labels: [AUTHOR], eventName: 'schedule', + timeline: [ + labelEvent(MAINTAINER, '02:00', { id: 1 }), + labelEvent(AUTHOR, '03:05', { id: 2, actor: { login: 'github-actions[bot]' } }), + ], + reviews: [ + review('CHANGES_REQUESTED', { id: 10, user: { login: 'rev-a' }, commit_id: HEAD, submitted_at: '2026-11-28T01:00:00Z' }), + review('CHANGES_REQUESTED', { id: 11, user: { login: 'rev-b' }, commit_id: HEAD, submitted_at: '2026-11-28T03:00:00Z' }), + ], + threadReplies: [ + { id: 201, pull_request_review_id: 11, user: { login: 'rev-b' }, body: 'Fix B.', created_at: '2026-11-28T03:00:00Z' }, + { id: 202, in_reply_to_id: 201, user: { login: 'author' }, body: 'Fixed B.', created_at: '2026-11-28T04:00:00Z' }, + ] }); + assert.deepEqual(await f.run(), [MAINTAINER]); +}); + test('ordinary lifecycle activity cannot rewrite a previous label confirmation for a newer head', async () => { const f = fixture({ labels: [PROGRESS], comments: [botRecord(progressMarker(OLD))] }); f.context.payload.workflow_run.name = 'PR activity signal';