Skip to content

feat: add AI code review integration (#1067)#1068

Closed
myakove wants to merge 3 commits intomainfrom
feat/issue-1067-ai-code-review
Closed

feat: add AI code review integration (#1067)#1068
myakove wants to merge 3 commits intomainfrom
feat/issue-1067-ai-code-review

Conversation

@myakove
Copy link
Copy Markdown
Collaborator

@myakove myakove commented Apr 13, 2026

Summary

Add AI-powered code review integration via the external pr-ai-reviewer service. Same architecture as the existing test-oracle integration — thin HTTP client in the webhook server, heavy logic in the external service.

What Changed

New Files

File Purpose
webhook_server/libs/ai_review.py Thin HTTP client (~100 lines) — health check → payload → /review → log
webhook_server/tests/test_ai_review.py 11 tests for the client

Modified Files

File Change
webhook_server/config/schema.yaml ai-review top-level config + repo-level (server-url, providers, triggers)
webhook_server/libs/github_api.py Extract ai_review_config from config
webhook_server/libs/handlers/pull_request_handler.py Fire call_ai_reviewer on opened + synchronize (non-clean)
AGENTS.md Document AI review integration
examples/config.yaml Config example
3 test files Added ai_review_config = None to mocks + 4 handler scheduling tests

Configuration

ai-review:
  server-url: "http://localhost:8001"
  providers:
    - ai-provider: claude
      ai-model: claude-sonnet-4-20250514
  triggers:
    - pr-opened
    - pr-synchronized

Testing

  • 1508 tests pass, 90.67% coverage
  • Peer reviewed with Cursor (3 rounds, all findings addressed)

Related

Closes #1067

Summary by CodeRabbit

Release Notes

  • New Features

    • Added AI-powered code review integration with automatic triggering on PR events (open, update).
    • Support for multiple configurable AI providers with customizable execution rounds and timeouts.
    • Built-in health checks and error handling for robust service integration.
  • Documentation

    • Extended documentation with AI Code Review Integration workflow and configuration guide.
  • Tests

    • Added comprehensive test coverage for AI review triggering and error scenarios.

Add thin HTTP client that calls the external pr-ai-reviewer service
for AI-powered code review on PRs.

- New ai-review top-level config (server-url, providers, triggers)
- Thin HTTP client in webhook_server/libs/ai_review.py (~100 lines)
- Fire-and-forget on PR opened and synchronize (non-clean rebase)
- Same pattern as test-oracle integration
- 15 new tests, all 1508 tests pass, 90.67% coverage

Closes #1067
@myakove-bot
Copy link
Copy Markdown
Collaborator

Report bugs in Issues

Welcome! 🎉

This pull request will be automatically processed with the following features:

🔄 Automatic Actions

  • Reviewer Assignment: Reviewers are automatically assigned based on the OWNERS file in the repository root
  • Size Labeling: PR size labels (XS, S, M, L, XL, XXL) are automatically applied based on changes
  • Issue Creation: Disabled for this repository
  • Pre-commit Checks: pre-commit runs automatically if .pre-commit-config.yaml exists
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified
  • Labels: All label categories are enabled (default configuration)

📋 Available Commands

PR Status Management

  • /wip - Mark PR as work in progress (adds WIP: prefix to title)
  • /wip cancel - Remove work in progress status
  • /hold - Block PR merging (approvers only)
  • /hold cancel - Unblock PR merging
  • /verified - Mark PR as verified
  • /verified cancel - Remove verification status
  • /reprocess - Trigger complete PR workflow reprocessing (useful if webhook failed or configuration changed)
  • /regenerate-welcome - Regenerate this welcome message

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (approvers only)
  • /automerge - Enable automatic merging when all requirements are met (maintainers and approvers only)
  • /assign-reviewers - Assign reviewers based on OWNERS file
  • /assign-reviewer @username - Assign specific reviewer
  • /check-can-merge - Check if PR meets merge requirements

Testing & Validation

  • /retest tox - Run Python test suite with tox
  • /retest build-container - Rebuild and test container image
  • /retest python-module-install - Test Python package installation
  • /retest pre-commit - Run pre-commit hooks and checks
  • /retest conventional-title - Validate commit message format
  • /retest all - Run all available tests

Container Operations

  • /build-and-push-container - Build and push container image (tagged with PR number)
    • Supports additional build arguments: /build-and-push-container --build-arg KEY=value

Cherry-pick Operations

  • /cherry-pick <branch> - Schedule cherry-pick to target branch when PR is merged
    • Multiple branches: /cherry-pick branch1 branch2 branch3

Label Management

  • /<label-name> - Add a label to the PR
  • /<label-name> cancel - Remove a label from the PR

✅ Merge Requirements

This PR will be automatically approved when the following conditions are met:

  1. Approval: /approve from at least one approver
  2. LGTM Count: Minimum 1 /lgtm from reviewers
  3. Status Checks: All required status checks must pass
  4. No Blockers: No wip, hold, has-conflicts labels and PR must be mergeable (no conflicts)
  5. Verified: PR must be marked as verified

📊 Review Process

Approvers and Reviewers

Approvers:

  • myakove
  • rnetser

Reviewers:

  • myakove
  • rnetser
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
  • automerge
AI Features
  • Conventional Title: Mode: fix (claude/claude-opus-4-6[1m])
  • Cherry-Pick Conflict Resolution: Enabled (claude/claude-opus-4-6[1m])
  • Test Oracle: Triggers: approved (claude/claude-opus-4-6[1m]); /test-oracle can be used anytime

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is removed on new commits unless the push is detected as a clean rebase
  • Cherry-picking: Cherry-pick labels are processed when the PR is merged
  • Container Builds: Container images are automatically tagged with the PR number
  • Permission Levels: Some commands require approver permissions
  • Auto-verified Users: Certain users have automatic verification and merge privileges

For more information, please refer to the project documentation or contact the maintainers.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 13, 2026

Warning

Rate limit exceeded

@myakove has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 26 minutes and 44 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 26 minutes and 44 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3fac285a-8eeb-4019-aa91-a2470335a99b

📥 Commits

Reviewing files that changed from the base of the PR and between 2f05fe5 and 5f05db8.

📒 Files selected for processing (7)
  • examples/config.yaml
  • webhook_server/config/schema.yaml
  • webhook_server/libs/ai_review.py
  • webhook_server/libs/handlers/pull_request_handler.py
  • webhook_server/tests/test_ai_review.py
  • webhook_server/tests/test_pull_request_handler.py
  • webhook_server/utils/constants.py

Walkthrough

This PR implements AI-powered code review functionality that analyzes pull requests via an external AI review service. It adds configuration schema for AI review settings, a new module for orchestrating asynchronous review requests, integration into the PR handler to trigger reviews on PR opened and synchronized events, and comprehensive test coverage.

Changes

Cohort / File(s) Summary
Documentation & Examples
CLAUDE.md, examples/config.yaml
Added documentation describing the AI code review integration workflow, configuration structure (server-url, providers, max-rounds, timeout-minutes, triggers), and multi-agent/provider behavior including health checks and error handling.
Configuration Schema
webhook_server/config/schema.yaml
Defined ai-review config schema at global and repository-override levels with required fields server-url and providers (supporting claude/gemini/cursor), optional max-rounds (1–5, default 3), timeout-minutes (min 1, default 30), and triggers (default: pr-opened, pr-synchronized).
Core AI Review Module
webhook_server/libs/ai_review.py
Introduced call_ai_reviewer() async function that performs health checks (5s timeout), constructs review request payloads from PR context and config, POSTs to /review endpoint with computed timeouts, handles HTTP errors by logging warnings and posting PR comments, and gracefully handles JSON parsing and cancellation errors without interrupting webhook processing.
Configuration Integration
webhook_server/libs/github_api.py
Extended GithubWebhook._repo_data_from_config() to read and store ai_review_config from the ai-review configuration key.
PR Handler Integration
webhook_server/libs/handlers/pull_request_handler.py
Added background task scheduling for call_ai_reviewer() when PR is opened (trigger: pr-opened) or synchronized with non-clean rebase (trigger: pr-synchronized), using asyncio.create_task() pattern with proper cleanup callbacks.
Test Coverage
webhook_server/tests/test_ai_review.py
Added comprehensive test suite covering control flow (early returns, trigger filtering, command-triggered bypass), health check failure handling with PR comments, HTTP errors, JSON parsing errors, cancellation handling, and provider configuration conversion.
Test Fixtures
webhook_server/tests/test_clean_rebase_detection.py, webhook_server/tests/test_pull_request_handler.py, webhook_server/tests/test_runner_handler.py
Updated mock webhook fixtures to include ai_review_config = None and modified existing tests to explicitly set this attribute when representing "no AI features" scenarios.

Sequence Diagram(s)

sequenceDiagram
    actor GitHub
    participant WebhookHandler as PR Handler
    participant AIReview as ai_review.py
    participant AIService as AI Review Service
    participant GitHubAPI as GitHub API

    GitHub->>WebhookHandler: PR opened/synchronized webhook
    WebhookHandler->>WebhookHandler: Validate trigger & config
    WebhookHandler->>AIReview: call_ai_reviewer() [async background]
    
    AIReview->>AIService: GET /health (5s timeout)
    alt Health Check Fails
        AIService-->>AIReview: Connection error / HTTP error
        AIReview->>GitHubAPI: Post issue comment (review skipped)
        AIReview-->>WebhookHandler: Return (log warning)
    else Health Check Passes
        AIService-->>AIReview: 200 OK
        AIReview->>AIReview: Build review request payload<br/>(pr_url, providers, token, timeouts)
        AIReview->>AIService: POST /review (computed timeout)
        AIService-->>AIReview: Review response (comments, summary)
        alt Review Success
            AIReview->>AIReview: Log completion details
            AIReview-->>WebhookHandler: Return (fire-and-forget)
        else Review/Parsing Errors
            AIReview->>AIReview: Log error (no PR comment)
            AIReview-->>WebhookHandler: Return (no interrupt)
        end
    end
    
    WebhookHandler-->>GitHub: Webhook response 200
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

The diff introduces new business logic across multiple files with heterogeneous purposes (schema, async orchestration, integration, tests), but follows consistent patterns. The call_ai_reviewer() function contains moderate logic density with clear error handling. Test coverage is comprehensive and well-structured. Review complexity stems from understanding the async orchestration flow, error-handling semantics (health-check comment posting vs. review error logging), and verification that trigger filtering works correctly across the handler integration points.

Possibly related PRs

Suggested labels

Review effort 3/5

Suggested reviewers

  • rnetser
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: add AI code review integration' accurately and concisely summarizes the main change—introducing AI-powered code review functionality as described in issue #1067.
Linked Issues check ✅ Passed All coding requirements from issue #1067 are met: ai-review schema added [schema.yaml], ai_review.py created with HTTP client [ai_review.py], ai_review_config extracted [github_api.py], triggers integrated for opened/synchronize/clean-rebase logic [pull_request_handler.py], comprehensive tests added [test_ai_review.py + handler tests], CLAUDE.md updated with design docs, and 90%+ coverage achieved.
Out of Scope Changes check ✅ Passed All changes are tightly scoped to AI code review integration. Config schema, HTTP client, handler triggering, test fixtures, and documentation all directly address issue #1067 requirements without extraneous modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/issue-1067-ai-code-review

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@webhook_server/config/schema.yaml`:
- Around line 216-282: The ai-review object schema is duplicated; extract the
shared schema into a single reusable definition under $defs (e.g., define
aiReview object with properties server-url, providers, max-rounds,
timeout-minutes, triggers, required and additionalProperties) and replace both
inline ai-review occurrences with a $ref to that $defs entry; ensure that
properties like providers (with its ai-provider/ai-model items and constraints),
default values, min/max constraints, required fields, and additionalProperties:
false are preserved exactly in the $defs so both references validate
identically.

In `@webhook_server/libs/ai_review.py`:
- Around line 70-77: The code is using asyncio.to_thread to read
pull_request.html_url which is a cached webhook property and doesn't need a
thread hop; replace the async to_thread call with a direct property access
(assign pr_url = pull_request.html_url) and remove the unnecessary
asyncio.to_thread wrapper where pr_url is set in ai_review.py so the rest of the
logic (providers_config, providers_payload) remains unchanged.

In `@webhook_server/tests/test_ai_review.py`:
- Around line 176-180: Combine the nested context managers in the
test_cancelled_error_reraised test into a single with statement: replace the
nested "with patch(...): with pytest.raises(...):" with "with
patch('webhook_server.libs.ai_review.httpx.AsyncClient',
side_effect=asyncio.CancelledError), pytest.raises(asyncio.CancelledError):" so
the call to call_ai_reviewer(mock_github_webhook, mock_pull_request,
trigger='pr-opened') runs inside one combined context.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e89544b2-2b9b-427e-9c84-ddab56929c29

📥 Commits

Reviewing files that changed from the base of the PR and between 12a4a0d and 2f05fe5.

📒 Files selected for processing (10)
  • CLAUDE.md
  • examples/config.yaml
  • webhook_server/config/schema.yaml
  • webhook_server/libs/ai_review.py
  • webhook_server/libs/github_api.py
  • webhook_server/libs/handlers/pull_request_handler.py
  • webhook_server/tests/test_ai_review.py
  • webhook_server/tests/test_clean_rebase_detection.py
  • webhook_server/tests/test_pull_request_handler.py
  • webhook_server/tests/test_runner_handler.py

Comment thread webhook_server/config/schema.yaml Outdated
Comment thread webhook_server/libs/ai_review.py
Comment thread webhook_server/tests/test_ai_review.py Outdated
myakove added 2 commits April 13, 2026 13:31
- Extract ai-review schema to $defs, use $ref in both locations
- Remove unnecessary asyncio.to_thread for cached html_url property
- Combine nested with statements (SIM117)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: AI-powered code review for pull requests

2 participants