feat(ci): show the AI review among the PR's checks

Comment-triggered runs belong to main, so GitHub never lists them in the
PR's checks and the only sign of a running review is a reaction on the
comment. Set an informational "AI PR Review" commit status on the PR
head, linking to the run: pending when the gate accepts, then success or
error. A run cancelled by a newer review of the same commit leaves the
newer run's status alone.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Ramon Roche <mrpollo@gmail.com>
This commit is contained in:
Ramon Roche committed 2026-10-02 19:38:09 -07:00
1 parent 1ca4506927
commit a9a86dad76
5 files changed
+135 -15

No files matched your search

+16 -5
View File
@@ -13,7 +13,9 @@ name: AI PR Review
# pr-review-poster.yml (never approve or request changes), replacing the
# previous one from this workflow; the full report also goes to the job
# summary and the ai-review-report artifact. The triggering comment gets
# 👀 when accepted, then 🚀 or 😕 when the review finishes.
# 👀 when accepted, then 🚀 or 😕 when the review finishes. The PR head
# also gets an "AI PR Review" commit status linking to the run, so the
# review shows among the PR's checks (informational, never required).
#
# Credentials: the review job assumes the px4-ai-review IAM role through
# GitHub OIDC. That role's trust policy only accepts this file running
@@ -65,9 +67,11 @@ jobs:
# reacting to a comment on a pull request needs pull-requests, not
# issues, permission
pull-requests: write
statuses: write # "AI PR Review" status on the PR head
outputs:
run: ${{ steps.decide.outputs.run }}
pr: ${{ steps.decide.outputs.pr }}
head_sha: ${{ steps.decide.outputs.head_sha }}
model: ${{ steps.decide.outputs.model }}
effort: ${{ steps.decide.outputs.effort }}
comment_id: ${{ steps.decide.outputs.comment_id }}
@@ -197,16 +201,15 @@ jobs:
retention-days: 30
finish:
name: Report back on the comment
name: Report back on the PR
needs: [gate, review]
if: >-
always() && needs.gate.outputs.run == 'true'
&& needs.gate.outputs.comment_id != '0'
if: always() && needs.gate.outputs.run == 'true'
runs-on: [runs-on,runner=1cpu-linux-x64,image=ubuntu24-full-x64,"run-id=${{ github.run_id }}"]
timeout-minutes: 5
permissions:
contents: read
pull-requests: write # react to the triggering comment
statuses: write # final "AI PR Review" status on the PR head
steps:
- uses: runs-on/action@v2
- name: Checkout review tooling
@@ -214,7 +217,15 @@ jobs:
with:
persist-credentials: false
sparse-checkout: Tools/ci
- name: Status
working-directory: Tools/ci
env:
GITHUB_TOKEN: ${{ github.token }}
HEAD_SHA: ${{ needs.gate.outputs.head_sha }}
RESULT: ${{ needs.review.result }}
run: python3 -m ai_review status "$HEAD_SHA" "$RESULT"
- name: React
if: needs.gate.outputs.comment_id != '0'
working-directory: Tools/ci
env:
GITHUB_TOKEN: ${{ github.token }}
+6
View File
@@ -25,6 +25,12 @@ in either of two ways:
- **Run the workflow manually** (Actions, AI PR Review, Run workflow) with
the PR number.
Either way, the PR head gets an "AI PR Review" commit status linking to
the run: pending while it works, then success or error. The workflow runs
from `main`, so without it the review would not show among the PR's
checks. The status is informational and must never be made a required
check.
## Pipeline
1. **Gather** (`context.py`): PR metadata, linked issues, commits, CI
+6
View File
@@ -204,6 +204,12 @@ def parser() -> argparse.ArgumentParser:
rct.add_argument('content', choices=['eyes', 'rocket', 'confused'])
rct.set_defaults(func=lambda a: trigger.main(
['react', a.comment_id, a.content]))
sts = sub.add_parser('status', help='set the final commit status on the '
'PR head from the review job result')
sts.add_argument('sha')
sts.add_argument('result')
sts.set_defaults(func=lambda a: trigger.main(
['status', a.sha, a.result]))
chk = sub.add_parser('models-check', help='send a one-token request to '
'every model in models.json with the current '
+40 -6
View File
@@ -1,5 +1,7 @@
"""Only people with write access may start a review from a comment, and a
malformed command must never start a default review by accident."""
"""Only people with write access may start a review from a comment, a
malformed command must never start a default review by accident, and a
cancelled run must not overwrite the status of the review that replaced
it."""
import os
import tempfile
@@ -24,14 +26,24 @@ def event(body: str = '!ai-review', login: str = 'alice',
class FakeApi:
def __init__(self, permission: Optional[str]) -> None:
def __init__(self, permission: Optional[str],
statuses: Optional[List[Dict[str, Any]]] = None) -> None:
self.permission = permission
self.statuses = statuses or []
self.calls: List[Tuple[str, str]] = []
self.posted: List[Dict[str, Any]] = []
def __call__(self, method: str, path: str,
body: Optional[Dict[str, Any]]) -> Any:
self.calls.append((method, path))
return {'permission': self.permission}
if path.endswith('/permission'):
return {'permission': self.permission}
if '/pulls/' in path:
return {'head': {'sha': 'abc123'}}
if method == 'GET' and path.endswith('/statuses'):
return self.statuses
self.posted.append(body or {})
return None
def decide(ev: Dict[str, Any], permission: Optional[str] = 'write',
@@ -87,8 +99,12 @@ class TestDecide(unittest.TestCase):
api = FakeApi('write')
trigger.decide('issue_comment', event(login='bob'), {}, ALIASES, api,
'PX4/PX4-Autopilot')
self.assertEqual(api.calls, [
('GET', 'repos/PX4/PX4-Autopilot/collaborators/bob/permission')])
self.assertEqual(api.calls[0], (
'GET', 'repos/PX4/PX4-Autopilot/collaborators/bob/permission'))
def test_accepted_run_resolves_the_head_commit(self) -> None:
# the status must land on the commit being reviewed
self.assertEqual(decide(event()).head_sha, 'abc123')
def test_ignored_events(self) -> None:
cases = [(event(on_pr=False), 'not on a pull request'),
@@ -118,5 +134,23 @@ class TestDecide(unittest.TestCase):
self.assertIn('pr=42\n', text)
class TestStatus(unittest.TestCase):
RUN = 'https://github.com/r/actions/runs/1'
def test_final_status_replaces_this_runs_pending(self) -> None:
api = FakeApi(None, [{'context': trigger.STATUS_CONTEXT,
'target_url': self.RUN}])
trigger.set_status(api, 'r', 'abc123', 'success', 'done', self.RUN,
only_if_ours=True)
self.assertEqual(api.posted[0]['state'], 'success')
def test_cancelled_run_leaves_a_newer_review_alone(self) -> None:
api = FakeApi(None, [{'context': trigger.STATUS_CONTEXT,
'target_url': 'https://github.com/r/runs/2'}])
trigger.set_status(api, 'r', 'abc123', 'error', 'cancelled',
self.RUN, only_if_ours=True)
self.assertEqual(api.posted, [])
if __name__ == '__main__':
unittest.main()
+67 -4
View File
@@ -9,8 +9,14 @@ Two ways in:
maintain or admin. author_association is not used: an organization
member can have read-only access to this repository.
Writes the decision to $GITHUB_OUTPUT as run, pr, model, effort,
comment_id and reason. Invoked by pr-ai-review.yml; never runs PR code.
Writes the decision to $GITHUB_OUTPUT as run, pr, head_sha, model,
effort, comment_id and reason. Invoked by pr-ai-review.yml; never runs PR
code.
An accepted run also sets an "AI PR Review" commit status on the PR head,
linking to the run, so it shows in the PR's checks while it works: the
run itself is a default-branch workflow and would not appear there
otherwise. The status is informational, never a required check.
"""
import json
@@ -19,7 +25,7 @@ import re
import sys
import urllib.error
import urllib.request
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import Any, Callable, Dict, Mapping, Optional
from .models import EFFORTS
@@ -28,6 +34,13 @@ from .models import EFFORTS
COMMAND_RE = re.compile(r'!ai-review(?P<args>(?:[ \t]+\S+)*)')
ARG_RE = re.compile(r'^(model|effort)=([a-z0-9-]+)$')
WRITE_PERMISSIONS = ('admin', 'maintain', 'write')
STATUS_CONTEXT = 'AI PR Review'
# review job result -> (commit status state, description)
OUTCOMES = {
'success': ('success', 'Review finished; posted on the PR'),
'failure': ('error', 'Review failed; see the run'),
'cancelled': ('error', 'Review cancelled'),
}
Api = Callable[[str, str, Optional[Dict[str, Any]]], Any]
@@ -37,6 +50,7 @@ class Decision:
run: bool
reason: str
pr: int = 0
head_sha: str = ''
model: str = 'default'
effort: str = 'default'
comment_id: int = 0
@@ -44,6 +58,7 @@ class Decision:
def outputs(self) -> Dict[str, str]:
return {'run': 'true' if self.run else 'false',
'reason': self.reason, 'pr': str(self.pr),
'head_sha': self.head_sha,
'model': self.model, 'effort': self.effort,
'comment_id': str(self.comment_id)}
@@ -76,6 +91,16 @@ def parse_command(body: str, aliases: Any) -> Optional[Dict[str, str]]:
def decide(event_name: str, event: Mapping[str, Any],
inputs: Mapping[str, str], aliases: Any, api: Api,
repo: str) -> Decision:
d = _decide(event_name, event, inputs, aliases, api, repo)
if not d.run:
return d
pull = api('GET', f'repos/{repo}/pulls/{d.pr}', None) or {}
return replace(d, head_sha=(pull.get('head') or {}).get('sha') or '')
def _decide(event_name: str, event: Mapping[str, Any],
inputs: Mapping[str, str], aliases: Any, api: Api,
repo: str) -> Decision:
if event_name == 'workflow_dispatch':
try:
pr = int(inputs.get('pr_number', ''))
@@ -120,7 +145,7 @@ def write_outputs(decision: Decision, path: Optional[str]) -> None:
def _client_api() -> Api:
"""The two GitHub REST calls this module needs, stdlib only."""
"""The few GitHub REST calls this module needs, stdlib only."""
token = os.environ['GITHUB_TOKEN']
def api(method: str, path: str, body: Optional[Dict[str, Any]]) -> Any:
@@ -154,6 +179,36 @@ def react(api: Api, repo: str, comment_id: int, content: str) -> None:
file=sys.stderr)
def set_status(api: Api, repo: str, sha: str, state: str, description: str,
run_url: str, only_if_ours: bool = False) -> None:
"""Best-effort commit status on the PR head; never fails a run.
With only_if_ours, the status is left alone when the latest one for
this context links to another run: a newer review of the same commit
has taken over, and this run being cancelled must not overwrite it.
"""
if not sha:
return
try:
if only_if_ours:
latest = next((st for st in api(
'GET', f'repos/{repo}/commits/{sha}/statuses', None) or []
if st.get('context') == STATUS_CONTEXT), None)
if latest and latest.get('target_url') != run_url:
return
api('POST', f'repos/{repo}/statuses/{sha}',
{'state': state, 'context': STATUS_CONTEXT,
'description': description[:140], 'target_url': run_url})
except RuntimeError as e:
print(f'warning: could not set the commit status: {e}',
file=sys.stderr)
def _run_url(repo: str) -> str:
server = os.environ.get('GITHUB_SERVER_URL', 'https://github.com')
return f'{server}/{repo}/actions/runs/{os.environ["GITHUB_RUN_ID"]}'
def main(argv: Any = None) -> int:
from .models import load
args = sys.argv[1:] if argv is None else argv
@@ -162,6 +217,12 @@ def main(argv: Any = None) -> int:
# react <comment_id> <content>
react(_client_api(), repo, int(args[1] or 0), args[2])
return 0
if args and args[0] == 'status':
# status <sha> <result of the review job>
state, description = OUTCOMES.get(args[2], OUTCOMES['failure'])
set_status(_client_api(), repo, args[1], state, description,
_run_url(repo), only_if_ours=True)
return 0
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as fh:
event = json.load(fh)
inputs = {k: os.environ.get(f'INPUT_{k.upper()}', '')
@@ -171,4 +232,6 @@ def main(argv: Any = None) -> int:
write_outputs(decision, os.environ.get('GITHUB_OUTPUT'))
if decision.run:
react(_client_api(), repo, decision.comment_id, 'eyes')
set_status(_client_api(), repo, decision.head_sha, 'pending',
f'Reviewing: {decision.reason}', _run_url(repo))
return 0