diff --git a/.github/workflows/ai-pr-review.yml b/.github/workflows/ai-pr-review.yml new file mode 100644 index 0000000..751e932 --- /dev/null +++ b/.github/workflows/ai-pr-review.yml @@ -0,0 +1,16 @@ +name: AI PR review + +on: + pull_request: + types: [opened, ready_for_review] + +jobs: + review: + uses: ./.github/workflows/pr-review.yml + permissions: + contents: read + pull-requests: write + secrets: inherit + with: + # Load the script from the PR branch so changes to it are tested here. + tools_ref: ${{ github.head_ref }} diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml new file mode 100644 index 0000000..5b26cd5 --- /dev/null +++ b/.github/workflows/pr-review.yml @@ -0,0 +1,74 @@ +name: AI PR review + +# Reusable workflow. Repos opt in by adding a caller workflow, e.g.: +# +# on: +# pull_request: +# types: [opened] +# jobs: +# review: +# uses: fraymio/.github/.github/workflows/pr-review.yml@main +# permissions: +# contents: read +# pull-requests: write +# secrets: inherit +# +# See workflow-templates/ai-pr-review.yml for the full template. + +on: + workflow_call: + inputs: + model: + description: "OpenAI model ID" + type: string + default: gpt-6-astra + reasoning_effort: + description: "low | medium | high | xhigh | max" + type: string + default: medium + tools_ref: + description: "Fallback ref of fraymio/.github to load the review script from (only used if job.workflow_sha is unavailable)" + type: string + default: main + secrets: + OPENAI_API_KEY: + required: true + +jobs: + review: + # Skip drafts (reviewed on ready_for_review), bots, and fork PRs (no secrets there). + if: >- + !github.event.pull_request.draft && + github.event.pull_request.user.type != 'Bot' && + github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + pull-requests: write + steps: + # Load the script from the same commit this reusable workflow runs from, so + # a caller pinned to a branch/tag/SHA gets the matching script. Falls back + # to tools_ref where the job.workflow_* context isn't available. + - uses: actions/checkout@v7 + with: + repository: ${{ job.workflow_repository || 'fraymio/.github' }} + ref: ${{ job.workflow_sha || inputs.tools_ref }} + sparse-checkout: pr_review + persist-credentials: false + + - uses: actions/setup-python@v7 + with: + python-version: "3.14" + + - run: pip install -r pr_review/requirements.txt + + - name: Review PR + run: python pr_review/review.py + env: + GITHUB_TOKEN: ${{ github.token }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + OPENAI_MODEL: ${{ inputs.model }} + REASONING_EFFORT: ${{ inputs.reasoning_effort }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} diff --git a/.gitignore b/.gitignore index 4c49bd7..4ae5be0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,223 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +*.lcov +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +# Pipfile.lock + +# uv +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +# poetry.lock +# poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +# pdm.lock +# pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +# pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi/* +!.pixi/config.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule* +celerybeat.pid + +# Redis +*.rdb +*.aof +*.pid + +# RabbitMQ +mnesia/ +rabbitmq/ +rabbitmq-data/ + +# ActiveMQ +activemq-data/ + +# SageMath parsed files +*.sage.py + +# Environments .env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Conda environments +conda-meta/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs/Zensical documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +# .idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that +# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, you +# could uncomment the following to ignore the entire vscode folder +# .vscode/ +# Temporary file for partial code execution +tempCodeRunnerFile.py + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ + +# Streamlit +.streamlit/secrets.toml \ No newline at end of file diff --git a/README.md b/README.md index a46ae92..ca8ea98 100644 --- a/README.md +++ b/README.md @@ -1 +1,39 @@ -# .github \ No newline at end of file +# .github + +Org-wide GitHub config and tooling for fraymio. + +## AI PR review + +[`.github/workflows/pr-review.yml`](.github/workflows/pr-review.yml) is a reusable workflow that posts an OpenAI review (`gpt-6-astra` by default) as a comment on a PR as soon as it's opened, or when a draft is marked ready. It never approves or blocks. Bot PRs and PRs from forks are skipped. + +**Opting a repo in:** add `.github/workflows/ai-pr-review.yml` to the repo. Either copy [`workflow-templates/ai-pr-review.yml`](workflow-templates/ai-pr-review.yml), or pick **AI PR review** under Actions → New workflow. Delete the file to opt out. + +```yaml +on: + pull_request: + types: [opened, ready_for_review] +jobs: + review: + uses: fraymio/.github/.github/workflows/pr-review.yml@main + permissions: + contents: read + pull-requests: write + secrets: inherit + # with: + # model: gpt-6-astra + # reasoning_effort: medium # low | medium | high | xhigh | max +``` + +**Secret:** `OPENAI_API_KEY` as an org secret (Org settings → Secrets → Actions), shared with the opted-in repos. No other token is needed: each repo's built-in `GITHUB_TOKEN` posts the review. + +**Local dry run:** + +```sh +pip install -r pr_review/requirements.txt +GITHUB_TOKEN=... OPENAI_API_KEY=... REPOSITORY=fraymio/tessera PR_NUMBER=123 DRY_RUN=true \ + python pr_review/review.py +``` + +## Stale PR report + +`stale_prs/pr_tracker.py` writes a CSV of PRs that have been open past the review SLA. diff --git a/pr_review/requirements.txt b/pr_review/requirements.txt new file mode 100644 index 0000000..535409c --- /dev/null +++ b/pr_review/requirements.txt @@ -0,0 +1 @@ +requests>=2.31 diff --git a/pr_review/review.py b/pr_review/review.py new file mode 100644 index 0000000..62cb29b --- /dev/null +++ b/pr_review/review.py @@ -0,0 +1,130 @@ +""" +Reviews one pull request with an OpenAI model and posts the result as a PR +review comment. Called by .github/workflows/pr-review.yml. + +Env vars: + GITHUB_TOKEN token with pull-request write on the repo (required) + OPENAI_API_KEY OpenAI API key (required) + REPOSITORY owner/name, e.g. fraymio/tessera (required) + PR_NUMBER pull request number (required) + OPENAI_MODEL model ID (default: gpt-6-astra) + REASONING_EFFORT low | medium | high | xhigh | max (default: medium) + DRY_RUN if "true", print the review instead of posting it +""" + +import os + +import requests + +MAX_DIFF_CHARS = 400_000 + +GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN") +OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") +REPOSITORY = os.environ.get("REPOSITORY") +PR_NUMBER = os.environ.get("PR_NUMBER") +OPENAI_MODEL = os.environ.get("OPENAI_MODEL") or "gpt-6-astra" +REASONING_EFFORT = os.environ.get("REASONING_EFFORT") or "medium" +DRY_RUN = os.environ.get("DRY_RUN", "").lower() == "true" + +GH = "https://api.github.com" +gh_headers = { + "Authorization": f"Bearer {GITHUB_TOKEN}", + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", +} + +SYSTEM_PROMPT = """You are a senior engineer reviewing a pull request. +Focus on real problems: bugs, incorrect logic, security issues, data loss, +race conditions, broken error handling, and missing tests for risky changes. +Skip style nits and anything a linter would catch. Do not praise the PR. + +Format your answer in GitHub markdown: +- Start with a 1-2 sentence summary of what the PR does. +- Then a "Findings" list, most severe first. For each: `path:line`, what is + wrong, and a concrete fix. If there are no meaningful problems, say so plainly. +Keep it short.""" + + +def get_pr(pr_url: str) -> dict: + resp = requests.get(pr_url, headers=gh_headers, timeout=60) + resp.raise_for_status() + return resp.json() + + +def get_diff(pr_url: str) -> str: + resp = requests.get( + pr_url, + headers={**gh_headers, "Accept": "application/vnd.github.diff"}, + timeout=60, + ) + resp.raise_for_status() + return resp.text + + +def ask_model(pr: dict, diff: str) -> str: + truncated = len(diff) > MAX_DIFF_CHARS + if truncated: + diff = diff[:MAX_DIFF_CHARS] + user_input = ( + f"Repository: {REPOSITORY}\n" + f"Title: {pr['title']}\n\n" + f"Description:\n{pr.get('body') or '(none)'}\n\n" + f"Diff{' (truncated)' if truncated else ''}:\n```diff\n{diff}\n```" + ) + resp = requests.post( + "https://api.openai.com/v1/responses", + headers={"Authorization": f"Bearer {OPENAI_API_KEY}"}, + json={ + "model": OPENAI_MODEL, + "instructions": SYSTEM_PROMPT, + "input": user_input, + "reasoning": {"effort": REASONING_EFFORT}, + "max_output_tokens": 64_000, + }, + timeout=1500, + ) + if resp.status_code != 200: + raise RuntimeError(f"OpenAI error {resp.status_code}: {resp.text}") + data = resp.json() + text = "".join( + part["text"] + for item in data.get("output", []) + if item.get("type") == "message" + for part in item.get("content", []) + if part.get("type") == "output_text" + ).strip() + if not text: + raise RuntimeError(f"OpenAI returned no text: {data}") + return text + + +def post_review(pr_url: str, pr: dict, review: str) -> None: + body = ( + f"### AI review ({OPENAI_MODEL})\n\n{review}\n\n" + f"Reviewed at `{pr['head']['sha'][:7]}`. " + f"Automated review; use your judgment." + ) + if DRY_RUN: + print(body) + return + resp = requests.post( + f"{pr_url}/reviews", + headers=gh_headers, + json={"body": body, "event": "COMMENT", "commit_id": pr["head"]["sha"]}, + timeout=60, + ) + resp.raise_for_status() + + +def main() -> None: + for name in ("GITHUB_TOKEN", "OPENAI_API_KEY", "REPOSITORY", "PR_NUMBER"): + assert os.environ.get(name), f"{name} is required" + + pr_url = f"{GH}/repos/{REPOSITORY}/pulls/{PR_NUMBER}" + pr = get_pr(pr_url) + print(f"Reviewing {REPOSITORY}#{PR_NUMBER}: {pr['title']}") + post_review(pr_url, pr, ask_model(pr, get_diff(pr_url))) + + +if __name__ == "__main__": + main() diff --git a/workflow-templates/ai-pr-review.properties.json b/workflow-templates/ai-pr-review.properties.json new file mode 100644 index 0000000..2b2aeaa --- /dev/null +++ b/workflow-templates/ai-pr-review.properties.json @@ -0,0 +1,6 @@ +{ + "name": "AI PR review", + "description": "Posts an OpenAI (gpt-6-astra) review comment on every new pull request.", + "iconName": "octicon code-review", + "categories": ["Automation"] +} diff --git a/workflow-templates/ai-pr-review.yml b/workflow-templates/ai-pr-review.yml new file mode 100644 index 0000000..012c339 --- /dev/null +++ b/workflow-templates/ai-pr-review.yml @@ -0,0 +1,17 @@ +name: AI PR review + +on: + pull_request: + types: [opened, ready_for_review] + +jobs: + review: + uses: fraymio/.github/.github/workflows/pr-review.yml@main + permissions: + contents: read + pull-requests: write + secrets: inherit + # Optional overrides: + # with: + # model: gpt-6-astra + # reasoning_effort: medium