Repository navigation
Add event-driven PR workflow labels #3786
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
ca683f2
1c30885
a99d8e8
3a1cfd6
df536cf
a94bad6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| --- | ||
| 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'] | ||
| --- | ||
|
|
||
| <!-- | ||
| 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. | ||
| --> | ||
|
|
||
| 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. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,305 @@ | ||
| // 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 = /^<!-- pr-status-label:ready-to-merge sha=([0-9a-f]{40}) -->$/; | ||
| const WARNING = '<!-- pr-status-label -->'; | ||
| 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, 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; | ||
| 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 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 }); | ||
| // 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(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 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; | ||
| 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 = `<!-- pr-status-label:ready-to-merge sha=${sha} -->`; | ||
| 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; | ||
| if (!await canDecide(event.sender?.login)) { | ||
| await setStatus('status/awaiting-maintainer'); | ||
| 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; | ||
| 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)); | ||
| 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(); | ||
|
Comment on lines
+296
to
+297
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in a94bad6. A validated current-head COMMENTED review now moves an already-ready PR to awaiting-maintainer and removes its readiness record. It requires interpretation rather than preserving readiness solely because required checks still pass. Optional APPROVED reviews continue to preserve readiness. |
||
| } 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 }; | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in df536cf. The label event sender must have write, maintain or admin permission before a readiness record is created; triage/read/none and missing senders hand off to awaiting-maintainer. Write is intentionally accepted because the workflow uses repository write access as its maintainer decision boundary, rather than requiring GitHub's specifically named Maintain role. The skill now states this boundary explicitly, with functional coverage for each role.