Migrate review automation to OpenCode
This commit is contained in:
1 parent
27db22cd78
commit
8aaecb4dc7
21 files changed
+2703
-713
No files matched your search
@@ -1,249 +1,176 @@
|
||||
# ghbot
|
||||
|
||||
GitHub Actions bot that reviews pull requests by calling Codex CLI, leaves inline review comments for problems, approves clean PRs, and can merge them when repository checks are green.
|
||||
[中文文档](README-zh.md)
|
||||
|
||||
## Behavior
|
||||
GitHub Actions bot that uses OpenCode to review pull requests, triage issues and pull requests, flag likely duplicates, and optionally merge approved changes.
|
||||
|
||||
- Triggers on `pull_request_target`: `opened`, `synchronize`, `reopened`, `ready_for_review`.
|
||||
- When a new PR is opened, posts an immediate comment that review has started.
|
||||
- Fetches changed files and patches from the pull request.
|
||||
- Asks Codex CLI to review the PR and write a structured JSON result to `.review-result.json`:
|
||||
- `safeToMerge=true` only when there are no blocking findings.
|
||||
- `blocking` findings become request-changes reviews.
|
||||
- `suggestion` findings are included as non-blocking suggestions.
|
||||
- Supports a lenient pass when a repository administrator comments `/lenient-check`.
|
||||
- If no repository administrator has commented or reviewed within the last 24 hours, the lenient trigger automatically broadens to users with `write`, `maintain`, or `admin` permission.
|
||||
- A scheduled recheck runs hourly so the 24-hour fallback can take effect even if no new PR event arrives after the window expires.
|
||||
- In lenient mode, only blocks dangerous changes, runtime-impacting issues, errors, crashes, broken builds, data-loss risks, and security risks.
|
||||
- A PR that passes lenient mode is not auto-merged until an eligible reviewer approves the current head commit.
|
||||
- Eligible reviewers for lenient merge approval are:
|
||||
- repository administrators when an administrator has commented or reviewed on the PR within the last 24 hours
|
||||
- otherwise any repository user with `write`, `maintain`, or `admin` permission
|
||||
- If the reviewer detects clearly malicious code, the bot comments with the reason and closes the pull request.
|
||||
- Posts inline comments only on valid added diff lines.
|
||||
- Approves clean pull requests.
|
||||
- Retries transient Codex CLI and GitHub API request failures up to 5 times before giving up.
|
||||
- Deletes any stale `.review-result.json` before each run and again after each review attempt.
|
||||
- If `AUTO_MERGE=true`, merges only after:
|
||||
- the AI reviewer says the PR is safe,
|
||||
- GitHub reports the PR as mergeable,
|
||||
- checks/statuses are green when `REQUIRE_CHECKS=true`.
|
||||
## Pull request review
|
||||
|
||||
## GitHub Actions setup
|
||||
OpenCode returns exactly four sections:
|
||||
|
||||
Add these repository secrets:
|
||||
- `review`: concrete non-blocking inline review notes.
|
||||
- `change`: required inline changes that block merge.
|
||||
- `comment`: an overall comment for the pull request author.
|
||||
- `result`: the maintainer-facing merge decision, summary, and malicious-code close decision.
|
||||
|
||||
- `CODEX_API_KEY`
|
||||
- Optional for GitHub App identity:
|
||||
- `GH_APP_ID`
|
||||
- `GH_APP_PRIVATE_KEY`
|
||||
- `GH_APP_INSTALLATION_ID`
|
||||
Only `change` is always a required change. How ordinary `review` notes affect merge is configured with `REVIEW_POLICY`:
|
||||
|
||||
Optional repository variables:
|
||||
- `allow`: review notes do not block merge. A clean result is submitted as `APPROVE`.
|
||||
- `require_approval` (default): review notes are submitted as `COMMENT`; the `ghbot review` check remains `action_required` until a repository administrator approves the current head commit.
|
||||
- `reject`: any review note is submitted as `REQUEST_CHANGES` and blocks merge.
|
||||
|
||||
- `CODEX_BASE_URL`: defaults to `https://api.openai.com/v1`
|
||||
- `CODEX_MODEL`: defaults to `gpt-5.4`
|
||||
- `CODEX_REASONING_EFFORT`: `minimal`, `low`, `medium`, `high`, or `xhigh`, defaults to `high`
|
||||
- `AUTO_MERGE`: defaults to `false`
|
||||
- `MERGE_METHOD`: `merge`, `squash`, or `rebase`, defaults to `squash`
|
||||
- `REQUIRE_CHECKS`: defaults to `true`
|
||||
- `MAX_PATCH_CHARS`: defaults to `120000`
|
||||
Required changes and malicious code block under every policy. Clearly malicious pull requests can be commented on and closed automatically. Start with `AUTO_MERGE=false` until the review behavior is trusted.
|
||||
|
||||
The workflow automatically receives `github.token` from GitHub Actions, so you do not need to create a repository secret named `GITHUB_TOKEN`.
|
||||
If you do nothing else, ghbot uses that workflow token for comments, reviews, checks, and merges.
|
||||
If you configure a GitHub App, ghbot prefers the App installation token for those GitHub write operations and falls back to the workflow token if App auth fails.
|
||||
It installs Codex CLI inside the GitHub Actions runner and uses that CLI for the review itself. The workflow writes an isolated Codex `config.toml` at runtime with the configured model, provider base URL, and reasoning setting, then asks Codex CLI to persist its final review result into `.review-result.json`.
|
||||
### Repository-specific rules
|
||||
|
||||
## GitHub App setup
|
||||
Use repository Actions variables to customize a caller repository:
|
||||
|
||||
You only need this if you want the bot to act as your GitHub App instead of `github-actions[bot]`.
|
||||
- `REVIEW_INSTRUCTIONS`: additional repository-specific review requirements, such as testing, compatibility, architecture, or release rules.
|
||||
- `REVIEW_BRANCHES`: comma-separated base-branch globs. Empty reviews all target branches. Example: `main,develop,release/**`.
|
||||
- `MAX_PATCH_CHARS`: maximum total patch text sent for review; default `120000`.
|
||||
|
||||
1. Create a GitHub App at `Settings -> Developer settings -> GitHub Apps -> New GitHub App`
|
||||
2. Recommended fields:
|
||||
- `GitHub App name`: any unique name, for example `ghbot`
|
||||
- `Homepage URL`: your repository URL or project URL
|
||||
- `Webhook`: disabled, this workflow-based setup does not need a webhook
|
||||
3. App permissions:
|
||||
- Repository permissions:
|
||||
- `Contents`: `Read and write`
|
||||
- `Pull requests`: `Read and write`
|
||||
- `Checks`: `Read and write`
|
||||
- `Issues`: `Read and write`
|
||||
- `Metadata`: `Read-only`
|
||||
4. Subscribe to no webhook events unless you need them for something else
|
||||
5. Create and download the private key
|
||||
6. Install the App on the target repository
|
||||
7. In the target repository, add these Actions secrets:
|
||||
- `GH_APP_ID`: the numeric App ID
|
||||
- `GH_APP_PRIVATE_KEY`: the full PEM private key content
|
||||
- Optional `GH_APP_INSTALLATION_ID`: the numeric installation ID
|
||||
`REVIEW_BRANCHES` matches the pull request's target (base) branch. `*` does not cross `/`; `**` does. The workflow file must be present on the repository's default branch for `pull_request_target`, but that does not limit reviews to PRs targeting the default branch. A workflow installed on `main` can review PRs targeting `develop` or release branches. The bot fetches each PR and its diff by PR number and never executes code from the PR head.
|
||||
|
||||
Notes:
|
||||
To make `require_approval` or `reject` prevent manual merges, add the `ghbot review` check as a required status check in the target branch's ruleset or branch protection settings. Without that repository rule, ghbot still reports `action_required`, but GitHub may allow an administrator or collaborator to merge manually.
|
||||
|
||||
- GitHub Actions secrets and variables cannot start with `GITHUB_`, so use the `GH_APP_*` names above in repository settings.
|
||||
- `GH_APP_INSTALLATION_ID` is optional. ghbot can resolve it automatically from the repository if the App is installed there.
|
||||
- Keep `CODEX_API_KEY` as a separate secret. The App only replaces GitHub write identity; it does not replace Codex authentication.
|
||||
- The repository still gets `github.token` automatically from GitHub Actions, and ghbot uses it as a fallback if App authentication is unavailable or broken.
|
||||
### Incremental review cache
|
||||
|
||||
Each successful review stores this metadata in GitHub Actions cache:
|
||||
|
||||
- repository and PR number
|
||||
- reviewed head SHA and timestamp
|
||||
- the structured `review/change/comment/result` output
|
||||
|
||||
When a new commit triggers `synchronize`, or PR metadata/base changes trigger `edited`, the latest cache for that PR is restored. OpenCode receives an earlier-head result plus the current complete PR patch, revalidates old findings, removes fixed findings, and checks the newest content. The previous merge decision is never reused without a fresh review. An `edited` event on the same head still runs a fresh complete review so title, description, and base-branch changes are respected.
|
||||
|
||||
Cache keys are isolated by repository ID and PR number. A `closed` event, including a merged PR, deletes all remote caches for that PR and removes the local cache file. Cache data contains no API keys, full diff, or prompt.
|
||||
|
||||
## Issue and PR triage
|
||||
|
||||
On `issues` and `pull_request_target` open/edit/reopen events, ghbot can:
|
||||
|
||||
- apply one or more labels from the configured allowlist
|
||||
- compare an issue only with other issues, and a PR only with other PRs
|
||||
- comment with a possible or likely duplicate and a link to the earlier item
|
||||
- add the duplicate label only for a high-confidence (`likely`) match
|
||||
|
||||
The bot does not automatically close duplicates. Duplicate comments contain a hidden marker so repeated triage does not post the same candidate twice. Human labels outside the configured managed label set are preserved.
|
||||
|
||||
Triage variables:
|
||||
|
||||
- `TRIAGE_ENABLED`: default `true`.
|
||||
- `TRIAGE_LABELS`: default `bug,enhancement,documentation,question,maintenance`.
|
||||
- `TRIAGE_DUPLICATE_LABEL`: default `duplicate`.
|
||||
- `TRIAGE_CANDIDATE_LIMIT`: recent same-type items supplied to OpenCode, default `50`, maximum `100`.
|
||||
- `TRIAGE_INSTRUCTIONS`: optional repository-specific classification rules.
|
||||
|
||||
Missing configured labels are created automatically.
|
||||
|
||||
## PR comment chat
|
||||
|
||||
Mention `@bot` in a pull request conversation to ask about the current PR. The configured `BOT_NAME` is also accepted as a mention; for example, `BOT_NAME=github-actions[bot]` accepts both `@github-actions` and `@github-actions[bot]`. Because this agent can execute commands, only repository collaborators with `write`, `maintain`, or `admin` permission may invoke it.
|
||||
|
||||
This restriction does not affect automatic review. Pull requests from forks and contributors without repository access still receive the normal `review/change/comment/result` review on every configured PR event. When an external contributor needs repository-agent investigation, a maintainer can mention `@bot` on that contributor's PR; the agent then analyzes the contributor's current PR head in isolation and posts the answer to the same conversation.
|
||||
|
||||
ghbot checks out the current PR head without persisted GitHub credentials and gives OpenCode a sanitized temporary snapshot plus the PR title, description, branches, and bounded complete diff. OpenCode runs in a dedicated disposable Docker container with every OpenCode tool allowed. It can execute commands and tests, edit the temporary workspace, install dependencies, and use the network, but the container mounts only the sanitized PR snapshot and receives no GitHub token, GitHub App credentials, or real OpenCode API key. A short-lived local proxy exchanges the container's one-run token for the real provider credential and closes with the container. The agent cannot commit or push, and resource/time limits still apply. The named container is forcibly removed on success, failure, or timeout.
|
||||
|
||||
The snapshot excludes Git metadata, repository OpenCode/agent instruction files, `.env`, and symbolic links, then is deleted after the reply. This prevents PR-controlled OpenCode configuration and common credential paths from entering the agent workspace; the container boundary protects the Actions runner and ghbot runtime while preserving full permissions inside the analysis environment.
|
||||
|
||||
Replies are keyed to the source comment so a workflow rerun does not post the same answer twice, and bot-authored replies are ignored to prevent loops.
|
||||
|
||||
## OpenCode configuration
|
||||
|
||||
Required secret:
|
||||
|
||||
- `OPENCODE_API_KEY`
|
||||
|
||||
Repository variables:
|
||||
|
||||
- `OPENCODE_BASE_URL`: default `https://api.openai.com/v1`.
|
||||
- `OPENCODE_MODEL`: default `gpt-5.4`.
|
||||
- `OPENCODE_REASONING_EFFORT`: `minimal`, `low`, `medium`, `high`, or `xhigh`; default `high` in the workflow.
|
||||
|
||||
The workflow installs the tested `opencode-ai@1.18.14`. At runtime ghbot creates an isolated inline OpenCode provider using `@ai-sdk/openai-compatible`, so requests use the OpenAI-compatible `/v1/chat/completions` API. It invokes:
|
||||
|
||||
```text
|
||||
opencode run --pure --format json --model ghbot/<model> --variant <effort>
|
||||
```
|
||||
|
||||
The OpenCode process gets an isolated home/data/state directory, disables plugins, model fetching, LSP downloads, and auto-update, and denies every tool permission. It receives the PR patch as data and returns JSON through the CLI NDJSON event stream; it does not edit or execute the reviewed repository.
|
||||
|
||||
## GitHub authentication and permissions
|
||||
|
||||
The workflow always receives `github.token`, so no `GITHUB_TOKEN` repository secret is needed. ghbot optionally prefers a GitHub App installation token and falls back to the workflow token when App authentication fails. The OpenCode key remains a separate secret.
|
||||
|
||||
Workflow permissions:
|
||||
|
||||
- `actions: write`: save/restore Actions cache and delete PR caches on close or merge.
|
||||
- `contents: write`: optional merge and repository operations.
|
||||
- `pull-requests: write`: list PRs, create reviews, and merge.
|
||||
- `issues: write`: list issues/PRs, add labels, create labels, and post comments.
|
||||
- `checks: write`: publish and update the `ghbot review` check.
|
||||
- `statuses: read`: verify commit statuses before auto-merge.
|
||||
|
||||
For a GitHub App, configure these repository permissions:
|
||||
|
||||
- Actions: read and write
|
||||
- Contents: read and write
|
||||
- Pull requests: read and write
|
||||
- Issues: read and write
|
||||
- Checks: read and write
|
||||
- Commit statuses: read-only
|
||||
- Metadata: read-only
|
||||
|
||||
Add App credentials as optional repository secrets:
|
||||
|
||||
- `GH_APP_ID`
|
||||
- `GH_APP_PRIVATE_KEY`
|
||||
- `GH_APP_INSTALLATION_ID` (optional; ghbot can resolve it)
|
||||
|
||||
GitHub Actions secret names cannot start with `GITHUB_`, so use the `GH_APP_*` names above.
|
||||
|
||||
## Reuse from another repository
|
||||
|
||||
This repository now exposes a reusable workflow at:
|
||||
Create a workflow on the caller repository's default branch. A complete wrapper is available in [.github/workflows/review.yml](.github/workflows/review.yml); the central reusable workflow is:
|
||||
|
||||
```text
|
||||
lezi-fun/ghbot/.github/workflows/review-reusable.yml@main
|
||||
```
|
||||
|
||||
In another repository, create a thin wrapper workflow such as:
|
||||
The caller must forward `issues`, `pull_request_target`, `issue_comment`, `pull_request_review`, and optional schedule events, declare the permissions above, and pass:
|
||||
|
||||
```yaml
|
||||
name: PR Review Bot
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, ready_for_review]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_review:
|
||||
types: [submitted]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
checks: write
|
||||
statuses: read
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
review:
|
||||
if: |
|
||||
github.event_name == 'pull_request_target' ||
|
||||
(github.event_name == 'issue_comment' && github.event.issue.pull_request != null) ||
|
||||
github.event_name == 'pull_request_review'
|
||||
uses: lezi-fun/ghbot/.github/workflows/review-reusable.yml@main
|
||||
secrets:
|
||||
CODEX_API_KEY: ${{ secrets.CODEX_API_KEY }}
|
||||
GH_APP_ID: ${{ secrets.GH_APP_ID }}
|
||||
GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
|
||||
with:
|
||||
event_name: ${{ github.event_name }}
|
||||
event_action: ${{ github.event.action }}
|
||||
repository_owner: ${{ github.repository_owner }}
|
||||
repository_name: ${{ github.event.repository.name }}
|
||||
pull_number: ${{ github.event.pull_request.number || github.event.issue.number }}
|
||||
commenter_login: ${{ github.event.comment.user.login || '' }}
|
||||
comment_body: ${{ github.event.comment.body || '' }}
|
||||
reviewer_login: ${{ github.event.review.user.login || '' }}
|
||||
review_state: ${{ github.event.review.state || '' }}
|
||||
review_commit_id: ${{ github.event.review.commit_id || '' }}
|
||||
bot_name: github-actions[bot]
|
||||
codex_base_url: ${{ vars.CODEX_BASE_URL || 'https://api.openai.com/v1' }}
|
||||
codex_model: ${{ vars.CODEX_MODEL || 'gpt-5.4' }}
|
||||
codex_reasoning_effort: ${{ vars.CODEX_REASONING_EFFORT || 'high' }}
|
||||
auto_merge: ${{ vars.AUTO_MERGE || 'false' }}
|
||||
merge_method: ${{ vars.MERGE_METHOD || 'squash' }}
|
||||
require_checks: ${{ vars.REQUIRE_CHECKS || 'true' }}
|
||||
max_patch_chars: ${{ vars.MAX_PATCH_CHARS || '120000' }}
|
||||
log_level: info
|
||||
secrets:
|
||||
OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }}
|
||||
GH_APP_ID: ${{ secrets.GH_APP_ID }}
|
||||
GH_APP_PRIVATE_KEY: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
GH_APP_INSTALLATION_ID: ${{ secrets.GH_APP_INSTALLATION_ID }}
|
||||
```
|
||||
|
||||
The caller repository still needs to configure:
|
||||
See the checked-in wrapper for all `with:` inputs and repository-variable mappings.
|
||||
|
||||
- `CODEX_API_KEY` as a secret
|
||||
- optional `GH_APP_ID`, `GH_APP_PRIVATE_KEY`, and `GH_APP_INSTALLATION_ID` secrets if you want GitHub App identity
|
||||
- `CODEX_BASE_URL`, `CODEX_MODEL`, `CODEX_REASONING_EFFORT`, `AUTO_MERGE`, `MERGE_METHOD`, `REQUIRE_CHECKS`, and `MAX_PATCH_CHARS` as repository variables as needed
|
||||
## Lenient review
|
||||
|
||||
## Required workflow permissions
|
||||
|
||||
Repository Actions permissions must allow the workflow token to:
|
||||
|
||||
- `contents: write`
|
||||
- `pull-requests: write`
|
||||
- `checks: write`
|
||||
- `issues: write`
|
||||
- `statuses: read`
|
||||
|
||||
These permissions are declared in [.github/workflows/review.yml](/Users/home/Projects/ghbot/.github/workflows/review.yml:1).
|
||||
|
||||
## Lenient check
|
||||
|
||||
If a strict review leaves findings that are not practical to change, a repository administrator can comment this on the PR:
|
||||
An eligible repository user can comment:
|
||||
|
||||
```text
|
||||
/lenient-check
|
||||
```
|
||||
|
||||
That reruns the AI in lenient mode.
|
||||
|
||||
If no administrator has commented or reviewed within the last 24 hours on that PR, the command is also accepted from users with `write` or `maintain` permission.
|
||||
|
||||
If lenient mode passes, the bot still requires an eligible reviewer to approve the current head commit before merge.
|
||||
|
||||
Approval eligibility follows the same rule as lenient triggering:
|
||||
|
||||
- if a repository administrator has commented or reviewed on that PR within the last 24 hours, only an administrator approval can unlock merge
|
||||
- otherwise any user with `write`, `maintain`, or `admin` permission can unlock merge
|
||||
- an hourly scheduled recheck reevaluates this fallback window for already-approved PRs
|
||||
The bot reruns review with runtime, build, data-loss, and security focus. If an administrator has responded within the previous 24 hours, only an administrator may request or approve the lenient result; otherwise users with `write`, `maintain`, or `admin` permission are eligible. An hourly scheduled job rechecks pending approvals.
|
||||
|
||||
## Local development
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run build
|
||||
npm run typecheck
|
||||
npm run build
|
||||
```
|
||||
|
||||
To simulate the workflow locally, export the same env vars that the GitHub Action uses and run:
|
||||
For local event simulation, install OpenCode and export the variables in [.env.example](.env.example), plus `GITHUB_EVENT_NAME` and `GITHUB_EVENT_PATH`, then run:
|
||||
|
||||
```bash
|
||||
node dist/src/actions/runReview.js
|
||||
```
|
||||
|
||||
You must also provide:
|
||||
|
||||
- `GITHUB_EVENT_NAME`
|
||||
- `GITHUB_EVENT_PATH`
|
||||
- either `GITHUB_TOKEN`, or `GH_APP_ID` plus `GH_APP_PRIVATE_KEY`
|
||||
|
||||
## Configuration
|
||||
|
||||
See [.env.example](/Users/home/Projects/ghbot/.env.example:1) for local testing values.
|
||||
|
||||
Important variables:
|
||||
|
||||
- `GITHUB_TOKEN`: optional in GitHub Actions because `github.token` is automatic; still useful for local simulation or as a fallback
|
||||
- `GH_APP_ID`: optional GitHub App ID
|
||||
- `GH_APP_PRIVATE_KEY`: optional GitHub App private key
|
||||
- `GH_APP_INSTALLATION_ID`: optional GitHub App installation ID
|
||||
- `CODEX_API_KEY`: API key used by Codex CLI
|
||||
- `CODEX_BASE_URL`: optional Codex/OpenAI-compatible base URL
|
||||
- `CODEX_MODEL`: defaults to `gpt-5.4`
|
||||
- `CODEX_REASONING_EFFORT`: optional, one of `minimal`, `low`, `medium`, `high`, `xhigh`
|
||||
- `BOT_NAME`: defaults to `ghbot`, but the workflow sets it to `github-actions[bot]`
|
||||
- `AUTO_MERGE`: defaults to `false`
|
||||
- `MERGE_METHOD`: defaults to `squash`
|
||||
- `REQUIRE_CHECKS`: defaults to `true`
|
||||
- `MAX_PATCH_CHARS`: defaults to `120000`
|
||||
|
||||
The generated Codex CLI config is intentionally close to a working local setup:
|
||||
|
||||
```toml
|
||||
model = "gpt-5.4"
|
||||
model_provider = "bot"
|
||||
approvals_reviewer = "user"
|
||||
model_reasoning_effort = "high"
|
||||
|
||||
[model_providers.bot]
|
||||
name = "bot"
|
||||
base_url = "https://api.openai.com/v1"
|
||||
env_key = "CODEX_API_KEY"
|
||||
wire_api = "responses"
|
||||
```
|
||||
|
||||
The workflow invokes Codex CLI with `--dangerously-bypass-approvals-and-sandbox`, relies on `.review-result.json` for the final machine-readable result, and streams Codex CLI stdout/stderr into the GitHub Actions log for debugging.
|
||||
|
||||
## Safety notes
|
||||
|
||||
Start with `AUTO_MERGE=false`. Let the bot comment and approve first, then enable auto-merge after you trust the behavior on your repositories.
|
||||
|
||||
This bot does not execute untrusted PR code. It reviews diffs and checks GitHub check/status results. Keep repository branch protection enabled so required CI and human override rules still apply.
|
||||
The bot reviews GitHub-provided diffs and status data. It intentionally does not check out or execute untrusted pull request code under `pull_request_target`.
|
||||
Reference in new issue
Block a user