Skip to content

About

Project created during IBM BOB 2.0 Hackathon by LABLAB

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DevGuardAI — AI-Powered Code Review Assistant

An automated code review system that accepts a GitHub repository and pull request number, dispatches a parallel fleet of specialized AI agents to analyze the diff, and delivers a structured report with findings ranked by severity — posted back to the PR as a comment. This project was created during the IBM BOB 2.0 Hackathon by LABLAB.


Table of Contents

  1. Overview
  2. Architecture
  3. Repository Structure
  4. Backend
  5. Frontend
  6. Data Flow
  7. Database Schema
  8. API Reference
  9. Getting Started
  10. Key Design Decisions

Overview

DevGuardAI is a full-stack application built for the LabLabAI hackathon. When a review is requested, the backend:

  1. Fetches the PR metadata and all changed file contents from the GitHub API.
  2. Runs three specialized LLM agents in parallel (Code Quality, Security, Test Coverage).
  3. Passes all raw findings to a fourth Aggregator Agent that deduplicates, prioritizes, and computes an overall PR status (PASS, NEEDS_ATTENTION, or BLOCKED).
  4. Persists every finding and the final report to PostgreSQL.
  5. Posts a formatted Markdown report back to the GitHub PR as a comment.

Architecture

┌──────────────────────────────────────────────────────────────────────┐
│                            Docker Compose                            │
│                                                                      │
│  ┌─────────────┐   HTTP    ┌──────────────────────────────────────┐  │
│  │   Frontend  │ ◄──────► │           Backend (FastAPI)          │  │
│  │  React/TS   │  :3000    │              port 8000               │  │
│  │   (nginx)   │           │                                      │  │
│  └─────────────┘           │  ┌──────────┐   ┌─────────────────┐ │  │
│                            │  │  Review  │   │   Orchestrator  │ │  │
│                            │  │ Service  │──►│                 │ │  │
│                            │  └──────────┘   │  ┌───────────┐  │ │  │
│                            │       │         │  │CodeAgent  │  │ │  │
│                            │       │         │  ├───────────┤  │ │  │
│                            │  ┌────▼─────┐   │  │SecurityAg.│  │ │  │
│                            │  │ GitHub   │   │  ├───────────┤  │ │  │
│                            │  │ Service  │   │  │ TestAgent │  │ │  │
│                            │  └──────────┘   │  └─────┬─────┘  │ │  │
│                            │       │         │        │         │ │  │
│                            │  GitHub API     │  ┌─────▼──────┐  │ │  │
│                            │                 │  │ Aggregator │  │ │  │
│                            │                 │  │   Agent    │  │ │  │
│                            │                 │  └────────────┘  │ │  │
│                            │                 └─────────────────┘ │  │
│                            │                                      │  │
│                            │  ┌──────────────────────────────┐   │  │
│                            │  │   PostgreSQL (SQLAlchemy +   │   │  │
│                            │  │   asyncpg + Alembic)         │   │  │
│                            │  └──────────────────────────────┘   │  │
│                            └──────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────────────┘

Key technology choices:

Layer Technology
Backend framework FastAPI 0.136 (async)
LLM provider Google Gemini (google-genai 2.25)
Database PostgreSQL 15
ORM SQLAlchemy 2.0 (async)
Migrations Alembic
HTTP client httpx (async)
Frontend React 19 + TypeScript + Vite
Container runtime Docker Compose

Repository Structure

├── docker-compose.yml          # Orchestrates db, backend, frontend
├── backend/
│   ├── Dockerfile
│   ├── requirements.txt
│   ├── alembic.ini
│   ├── .env.example
│   ├── migrations/
│   │   └── versions/
│   │       ├── 0001_init.py            # Initial schema
│   │       └── 0002_report_column_add_report_in_review.py
│   └── src/
│       ├── main.py                     # FastAPI app + lifespan
│       ├── core/config.py              # Pydantic settings
│       ├── agents/                     # LLM agent implementations
│       ├── api/
│       │   ├── endpoints/              # FastAPI routers
│       │   └── schemas/                # Pydantic request/response models
│       ├── clients/github_client.py    # Async GitHub REST client
│       ├── database/
│       │   ├── db.py                   # Session factory
│       │   └── models.py               # SQLAlchemy ORM models + enums
│       ├── exception_handlers/         # Typed HTTP exceptions
│       ├── repositories/               # Data-access layer
│       └── services/                   # Business logic
└── frontend/
    ├── Dockerfile                      # Multi-stage: Vite build → nginx
    └── src/
        ├── api/                        # Typed API client wrappers
        ├── components/                 # Reusable UI components
        ├── pages/                      # Home, Review, History
        └── types/review.ts             # Shared TypeScript interfaces

Backend

Entry Point & Middleware

src/main.py

  • Creates the FastAPI application titled "AI Code Review Assistant".
  • Uses an asynccontextmanager lifespan to create a single shared GitHubClient instance on startup and gracefully close it on shutdown.
  • Applies CORSMiddleware with origins driven by configuration.
  • Mounts the review_router under /api/v1.
  • Exposes GET /_info as a lightweight health/info probe (used by the Docker healthcheck).

Configuration

src/core/config.py

A pydantic-settings BaseSettings class that reads from backend/.env:

Variable Default Purpose
DB_HOST db PostgreSQL host
DB_PORT 5432 PostgreSQL port
DB_USER admin DB username
DB_PASS admin_123 DB password
DB_NAME code_reviewer_db Database name
GITHUB_TOKEN (required) GitHub Personal Access Token
GITHUB_API_URL https://api.github.com GitHub API base URL
GEMINI_API_KEY (required) Google Gemini API key
GEMINI_MODEL gemini-3.5-flash Gemini model identifier
APP_NAME Code_reviewer Application name
DEBUG True Debug flag
cors_origins ["*"] CORS allowed origins

A computed URL_DATABASE property returns the full postgresql+asyncpg://… connection string.


API Layer

All routes are prefixed /api/v1 and tagged reviews.

Method Path Description
POST /reviews Trigger a new AI code review
GET /reviews List all past reviews
GET /reviews/{review_id} Get review status + agent statuses
GET /reviews/{review_id}/findings Get all raw findings for a review
GET /reviews/{review_id}/report Get the aggregated report summary
GET /reviews/{review_id}/markdown Get the full Markdown report (plain text)

ReviewService is injected via Depends, itself depending on an AsyncSession and a GitHubClient.

Schemas — src/api/schemas/

Schema Purpose
ReviewCreate Input: repository (owner/repo) + pull_request (int)
ReviewResponse Full review record with embedded agent statuses
ReviewFindingsResponse Review ID + list of FindingResponse
ReviewReportResponse Aggregated report: status, summary, statistics, key issues, recommendations
ReviewReport Internal Pydantic model for the LLM response from AggregatorAgent
AgentResult LLM response schema for the three specialized agents: agent_type + findings[]
FindingCreate / FindingResponse Individual finding data
ReviewContextResponse PR context passed into agents: metadata + changed files + README
ChangedFile / PullRequestData GitHub API response shapes

Services

Central business logic class. Key methods:

Method Description
create_review Full end-to-end flow: fetch GitHub context → run orchestrator → persist findings → post PR comment
get_review_by_id Returns review + agent statuses
get_review_with_findings Returns review + individual findings
get_review_report Returns structured aggregated report from stored JSONB
get_review_markdown Returns formatted Markdown report
list_reviews Returns all reviews ordered by creation date

The create_review flow:

  1. Fetches PR context from GitHub (GitHubService).
  2. Creates a Review row with status=RUNNING.
  3. Calls ReviewOrchestrator.run_analysis() — the most time-intensive step.
  4. Persists one ReviewAgent row per agent type.
  5. Persists all individual Finding rows.
  6. Updates the Review row to status=COMPLETED, storing the full report as JSONB.
  7. Posts the formatted Markdown report as a PR comment (failure is non-fatal — logged as a warning).

ReviewOrchestrator — src/services/orchestrator.py

Coordinates the multi-agent pipeline:

  1. Runs CodeAgent, SecurityAgent, and TestAgent concurrently with asyncio.gather(return_exceptions=True).
  2. Filters out any agent that raised an exception (partial failure resilience).
  3. Passes valid results to AggregatorAgent.aggregate().
  4. Returns a final ReviewReport.

Higher-level abstraction over GitHubClient:

  • get_review_context — assembles a ReviewContextResponse by:
    1. Fetching PR metadata.
    2. Fetching changed file list (filtered to max 30 files; skips binaries/lock files/minified assets).
    3. Concurrently fetching full file contents and the repo README.
  • post_pr_comment — posts the Markdown report as a PR comment.
  • File filtering ignores: .png, .jpg, .gif, .webp, .ico, .zip, .pdf, .lock, .min.js, .map, .exe, .bin.

generate_markdown_report — src/services/helper.py

Pure function that formats a Review ORM object (with its JSONB report and related findings) into a rich Markdown string, including a statistics table, findings sorted by severity, key issues, and recommendations. Used both for the API response and the GitHub PR comment.


AI Agents

All agents live in src/agents/ and share the same async LLM call mechanism.

BaseAgent — src/agents/base.py

Abstract base class defining the contract:

  • Abstract property agent_type: AgentType
  • Abstract async method analyze(context: ReviewContextResponse) -> AgentResult

call_llm_with_schema — src/agents/call_llm.py

Shared async helper that calls Gemini with:

  • response_mime_type="application/json" — forces structured JSON output.
  • response_schema=response_model — constrains the output to the provided Pydantic model.
  • temperature=0.2 — low temperature for deterministic, factual analysis.

Returns the response.parsed object — a fully hydrated Pydantic model instance.

Specialized Agents

Agent Class agent_type Focus Areas
Code Quality CodeAgent code Bugs, bad practices, code duplication, complexity, N+1 queries, incorrect async usage, resource leaks
Security SecurityAgent security SQL injection, command injection, missing authorization, exposed secrets, unsafe file ops, SSRF, IDOR
Test Coverage TestAgent test Missing tests, insufficient coverage, missing edge cases, missing integration/negative tests

Each agent concatenates all changed file paths and contents into a single user prompt and calls call_llm_with_schema with its system prompt and AgentResult as the response schema.

AggregatorAgent — src/agents/aggregator_agent.py

Receives all AgentResult objects, formats them into a structured text block, and calls Gemini again with a Tech Lead persona. Rules enforced in the system prompt:

  • Never invent new findings — only work from what the specialized agents reported.
  • May merge duplicates, group related findings, prioritize, summarize.
  • Determines overall_status:
    • PASS — no critical/high issues.
    • NEEDS_ATTENTION — medium/low issues or minor gaps.
    • BLOCKED — critical/high security vulnerabilities or severe bugs.

Returns a ReviewReport (summary, status, statistics, key_issues, recommendations, findings).


GitHub Integration

src/clients/github_client.py

Async HTTP client built on httpx.AsyncClient. Initialized with a Bearer token and Accept: application/vnd.github+json headers.

Method GitHub Endpoint
get_pull_request GET /repos/{owner}/{repo}/pulls/{pull_number}
get_all_pull_request_files GET /repos/{owner}/{repo}/pulls/{pull_number}/files (paginated, 100/page)
get_file_content GET /repos/{owner}/{repo}/contents/{path}?ref={sha} (base64-decoded)
post_pr_comment POST /repos/{owner}/{repo}/issues/{pull_number}/comments

Error mapping:

  • 401/403 → GitHubAuthenticationError (or GitHubRateLimitError if rate limit message present)
  • 404 → GitHubNotFoundError
  • 429 → GitHubRateLimitError
  • Other → GitHubException

Database

src/database/models.py

SQLAlchemy 2.0 declarative models with UUID primary keys and automatic created_at/updated_at timestamps on the shared Base.

Enums:

Enum Values
Status queued, running, completed, failed
AgentType code, security, test
SeverityStatus critical, high, medium, low, info
CategoryStatus bug, security, performance, architecture, test, style

src/database/db.py provides the async session factory and get_session dependency.

Migrations are managed by Alembic with two versions:

  • 0001_init.py — creates reviews, findings, review_agents tables.
  • 0002_… — adds the report JSONB column to reviews.

At container start, docker-compose.yml runs alembic upgrade head before launching uvicorn.


Repositories

src/repositories/ implements the repository pattern.

BaseRepository (base_repository.py) provides generic create, get, get_all, update, delete, and add_all methods for any SQLAlchemy model.

Specialized repositories:

Repository Extra Methods
ReviewRepository get_review_with_agents, get_review_with_findings, get_all_with_agents
ReviewAgentRepository Inherits BaseRepository
FindingRepository Inherits BaseRepository

All queries use SQLAlchemy's selectinload for eager-loading relationships to avoid N+1 problems.


Exception Handling

src/exception_handlers/ defines a typed exception hierarchy:

BaseAppException
├── DatabaseException
└── NotFoundException
    GitHubException
    ├── GitHubNotFoundError   (404)
    ├── GitHubAuthenticationError (401)
    └── GitHubRateLimitError  (429)

Frontend

A React 19 + TypeScript SPA built with Vite, served by nginx in production.

Pages:

Page File Description
Home src/pages/Home.tsx Input form for owner/repo + PR number; triggers review creation and navigates to Review page
Review src/pages/Review.tsx Displays review status, per-agent status cards, report summary, and findings
History src/pages/History.tsx Paginated list of all past reviews

Components:

Component Purpose
AgentStatus Renders per-agent status badge (queued / running / completed / failed)
FindingCard Displays a single finding with severity icon, category, file path, and recommendation
Statistics Renders the severity breakdown table

API client (src/api/reviews.ts) wraps all backend calls using typed helper functions (createReview, getReview, getReviewFindings, getReviewReport, getReviewMarkdown, listReviews).


Data Flow

User submits owner/repo + PR number
        │
        ▼
POST /api/v1/reviews
        │
        ▼
ReviewService.create_review()
        │
        ├─ GitHubService.get_review_context()
        │       ├─ get_pull_request()           ──► GitHub API
        │       ├─ get_pull_request_files()     ──► GitHub API (paginated)
        │       └─ get_file_content() × N       ──► GitHub API (concurrent)
        │
        ├─ ReviewRepository.create()            ──► INSERT reviews (status=RUNNING)
        │
        └─ ReviewOrchestrator.run_analysis()
                │
                ├─ asyncio.gather(
                │       CodeAgent.analyze()     ──► Gemini API
                │       SecurityAgent.analyze() ──► Gemini API
                │       TestAgent.analyze()     ──► Gemini API
                │  )
                │
                └─ AggregatorAgent.aggregate()  ──► Gemini API
                        │
                        ▼
                   ReviewReport
                        │
        ┌───────────────┘
        │
        ├─ ReviewAgentRepository.create() × 3   ──► INSERT review_agents
        ├─ FindingRepository.create() × N        ──► INSERT findings
        ├─ ReviewRepository.update()             ──► UPDATE reviews (status=COMPLETED, report=JSONB)
        └─ GitHubService.post_pr_comment()       ──► GitHub API
                │
                ▼
        ReviewResponse returned to client

Database Schema

┌─────────────────────────────────────────────────────────┐
│                         reviews                          │
├──────────────────┬──────────────────────────────────────┤
│ id               │ UUID (PK)                            │
│ repository       │ VARCHAR                              │
│ pull_request     │ INTEGER                              │
│ commit_sha       │ VARCHAR (nullable)                   │
│ status           │ ENUM(queued,running,completed,failed)│
│ progress         │ INTEGER (0–100)                      │
│ summary          │ TEXT (nullable)                      │
│ report           │ JSONB (nullable)                     │
│ started_at       │ TIMESTAMPTZ                          │
│ completed_at     │ TIMESTAMPTZ                          │
│ created_at       │ TIMESTAMPTZ                          │
│ updated_at       │ TIMESTAMPTZ                          │
└─────────────────────────────────────────────────────────┘
           │ 1                               1 │
           │ CASCADE DELETE          CASCADE DELETE │
           ▼ N                               ▼ N
┌────────────────────────────┐   ┌───────────────────────────────┐
│       review_agents        │   │           findings             │
├──────────┬─────────────────┤   ├────────────┬──────────────────┤
│ id       │ UUID (PK)       │   │ id         │ UUID (PK)        │
│ review_id│ UUID (FK)       │   │ review_id  │ UUID (FK)        │
│ agent_type│ ENUM           │   │ agent_type │ ENUM             │
│ status   │ ENUM            │   │ severity   │ ENUM             │
│ started_at│ TIMESTAMPTZ    │   │ category   │ ENUM             │
│ completed_at│ TIMESTAMPTZ  │   │ file_path  │ VARCHAR          │
│ error    │ TEXT (nullable) │   │ line       │ INTEGER (nullable)│
│ created_at│ TIMESTAMPTZ    │   │ title      │ VARCHAR          │
│ updated_at│ TIMESTAMPTZ    │   │ description│ TEXT             │
└────────────────────────────┘   │ recommendation│ TEXT (nullable)│
                                 │ created_at │ TIMESTAMPTZ      │
                                 │ updated_at │ TIMESTAMPTZ      │
                                 └───────────────────────────────┘

API Reference

POST /api/v1/reviews

Trigger a new review. The request is synchronous — the response is returned only after all agents complete.

Request body:

{
  "repository": "owner/repo",
  "pull_request": 42
}

Response 202: ReviewResponse


GET /api/v1/reviews

List all reviews ordered by creation date (newest first).

Response 200: ReviewResponse[]


GET /api/v1/reviews/{review_id}

Response 200: ReviewResponse with embedded agents[]


GET /api/v1/reviews/{review_id}/findings

Response 200: ReviewFindingsResponse — { id, findings[] }


GET /api/v1/reviews/{review_id}/report

Response 200: ReviewReportResponse

{
  "review_id": "…",
  "repository": "owner/repo",
  "pull_request": 42,
  "status": "NEEDS_ATTENTION",
  "summary": "…",
  "statistics": { "total": 5, "critical": 0, "high": 1, "medium": 2, "low": 2, "info": 0 },
  "key_issues": ["…"],
  "recommendations": ["…"]
}

GET /api/v1/reviews/{review_id}/markdown

Response 200 (plain text): Full Markdown report (same content posted to GitHub PR).


Getting Started

Prerequisites

  • Docker and Docker Compose
  • A GitHub Personal Access Token with repo scope (read PR data and post comments)
  • A Google Gemini API key

Environment Variables

Copy the example file and fill in your secrets:

cp backend/.env.example backend/.env
# backend/.env
DB_HOST=db
DB_PORT=5432
DB_NAME=code_reviewer_db
DB_USER=postgres
DB_PASS=secret

APP_NAME=Code_reviewer
DEBUG=True

GITHUB_TOKEN=ghp_your_token_here
GITHUB_API_URL=https://api.github.com

GEMINI_API_KEY=your_gemini_api_key_here

Running with Docker Compose

docker compose up --build

This will:

  1. Start PostgreSQL on port 5432.
  2. Run alembic upgrade head to apply all migrations.
  3. Start the FastAPI backend on port 8000.
  4. Build the React frontend and serve it via nginx on port 3000.

Open http://localhost:3000 to use the UI, or call the API directly at http://localhost:8000.

The OpenAPI docs are available at http://localhost:8000/docs.

Running Locally (Development)

Backend:

cd backend
python -m venv venv
# Windows
.\venv\Scripts\activate
# Linux/macOS
source venv/bin/activate

pip install -r requirements.txt

# Apply migrations (PostgreSQL must be running)
alembic upgrade head

uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

Frontend:

cd frontend
npm install
VITE_API_URL=http://localhost:8000/api/v1 npm run dev

Key Design Decisions

Decision Rationale
Parallel agent execution asyncio.gather runs Code, Security, and Test agents concurrently, cutting total LLM latency to ~1× instead of 3×.
Structured LLM output Gemini's response_schema + response_mime_type="application/json" guarantees each agent returns a valid, fully typed Pydantic model — no prompt-engineering fragility or post-processing needed.
Aggregator as a fourth LLM call Separating aggregation from analysis keeps individual agent prompts focused, and gives the aggregator a global view to deduplicate and reprioritize.
JSONB report column The full ReviewReport is stored as JSONB alongside the normalized findings rows, enabling fast report retrieval without a JOIN while keeping individual findings queryable.
Repository pattern Decouples database access from business logic, making the service layer testable without a live database.
Non-fatal PR comment posting GitHub comment posting errors are caught and logged as warnings so a transient API failure doesn't roll back an otherwise successful review.
File filtering in GitHubService Binary files, lock files, and minified assets are excluded before sending content to the LLM to reduce token usage and avoid irrelevant noise in findings.

About

Project created during IBM BOB 2.0 Hackathon by LABLAB

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages