Skip to content

Latest commit

 

History

History
314 lines (253 loc) · 10.7 KB

File metadata and controls

314 lines (253 loc) · 10.7 KB

🤖 AI Code Reviewer (CodePulse AI)

An intelligent, full-stack automated code review workspace powered by Large Language Models via OpenRouter. The application performs in-depth security, performance, and bug analysis on source code across multiple programming languages and delivers structured feedback, ratings, industry best practices, and refactored code through an interactive split-view dashboard.


🚦 Workflow & System Status

All project workflows have been verified and tested end-to-end:

Workflow Scope Status Notes
Frontend Linting frontend PASSED ESLint 10 verification clean across all JSX components
Frontend Build frontend PASSED Vite 8 production build bundles clean assets to dist/
Backend API Server backend PASSED Express 5 REST API running on port 8000 (supports /api and /ai routes)
3-Stage LLM Pipeline backend/services PASSED Multi-stage analysis, refactoring, and JSON report synthesis verified with live OpenRouter model (google/gemini-2.5-flash)

🌟 Key Features

  • Multi-Stage AI Analysis Pipeline:
    • Phase 1: Deep Code Analysis — Scans specifically for security vulnerabilities, logic defects, edge cases, and performance bottlenecks.
    • Phase 2: Intelligent Refactoring — Generates clean, idiomatic, type-safe, and bug-free code based on Phase 1 findings.
    • Phase 3: Structured Report Synthesis — Formats insights into a reliable JSON schema for seamless UI rendering.
  • Interactive Tabbed Review Dashboard:
    • Overview: Executive summary, rating score (1–10 stars), and key code strengths.
    • Issues: Itemized security flaws, runtime risks, and algorithmic issues.
    • Improvements: Actionable recommendations for code maintainability, type safety, and scalability.
    • Best Practices: Industry-standard engineering tips tailored to the submitted code.
    • Refactored Code: Ready-to-use refactored code snippet with one-click clipboard copying.
  • Multi-Language Support: Editor selector with preset support for JavaScript, TypeScript, Python, and Java.
  • Provider Agnostic (OpenRouter): Easily switch between LLM models (e.g., Google Gemini 2.5 Flash, OpenAI GPT-4o, Anthropic Claude 3.5 Sonnet) via environment variable configuration.
  • Modern Split-Screen Interface: Code editor panel on the left with live character counters, real-time loading feedback with skeleton cards, and formatted AI review panel on the right.

🏗️ Architecture & Data Flow

  ┌────────────────────────┐
  │   React 19 Frontend    │  (Vite 8 Dev Server @ http://localhost:5173)
  │  (Source Code Editor)  │
  └───────────┬────────────┘
              │  POST /api/review { "code": "..." }
              ▼
  ┌────────────────────────┐
  │   Express 5 Backend    │  (Node.js REST Server @ http://localhost:8000)
  │  (Controller & Router) │
  └───────────┬────────────┘
              │
              ├───► Step 1: Deep Code Analysis (Security & Bugs)
              ├───► Step 2: Code Refactoring based on Analysis Findings
              └───► Step 3: Report Synthesis into Structured JSON Schema
                      │
                      ▼
            [ OpenRouter API ]
      (e.g., google/gemini-2.5-flash)

📁 Project Structure

ai-code-reviewer/
├── backend/                     # Express.js REST API Backend
│   ├── controllers/             # Endpoint controllers
│   │   └── ai.controller.js     # Express request handler for code reviews
│   ├── middleware/              # Express middlewares
│   │   └── errorHandler.js      # Global error and OpenRouter response handler
│   ├── prompts/                 # Prompt engineering templates
│   │   └── reviewPrompt.js      # 3-stage prompts & JSON output schema definition
│   ├── routes/                  # API routing definitions
│   │   └── ai.routes.js         # Express router for /review and /get-review
│   ├── services/                # Business logic & LLM service integration
│   │   └── openai.service.js    # OpenRouter API client & 3-stage execution pipeline
│   ├── .env.example             # Backend environment template
│   ├── .env                     # Local environment file (API keys & port config)
│   ├── package.json             # Backend dependencies & npm scripts
│   ├── server.js                # Express app entry point
│   └── test.http                # REST Client test request collection
│
├── frontend/                    # React 19 Frontend Application (Vite 8)
│   ├── public/                  # Favicons and SVG assets
│   ├── src/
│   │   ├── components/
│   │   │   ├── CodeInput.jsx    # Split-screen code editor input component
│   │   │   ├── Loader.jsx       # Animated loading state with skeleton UI
│   │   │   ├── Navbar.jsx       # Header bar & branding component
│   │   │   └── ReviewOutput.jsx # Tabbed review dashboard & refactored code view
│   │   ├── services/
│   │   │   └── api.js           # Axios API client pointing to backend
│   │   ├── App.jsx              # Workspace layout manager
│   │   ├── App.css              # Dashboard and component styling
│   │   ├── index.css            # Base design system tokens and typography
│   │   └── main.jsx             # React DOM root render
│   ├── eslint.config.js         # ESLint 10 flat configuration
│   ├── package.json             # Frontend dependencies & npm scripts
│   └── vite.config.js           # Vite 8 project configuration
│
└── README.md                    # System documentation & project overview

🛠️ Tech Stack

Frontend

  • Framework: React 19
  • Build Tool: Vite 8
  • HTTP Client: Axios
  • Linting: ESLint 10
  • Styling: Modern CSS variables & responsive split-grid layout system

Backend


🚀 Getting Started

Prerequisites

  • Node.js (>= v18.0.0)
  • npm (>= v9.0.0)
  • OpenRouter API Key (Obtain from openrouter.ai)

1. Backend Setup

  1. Open your terminal and navigate to the backend directory:

    cd backend
  2. Install dependencies:

    npm install
  3. Configure environment variables: Create a .env file in backend/ (or copy .env.example):

    PORT=8000
    OPENROUTER_API_KEY=your_actual_openrouter_api_key
    MODEL=google/gemini-2.5-flash
    MAX_TOKENS=800
  4. Run the backend server:

    • Development mode (with auto-restart via nodemon):
      npm run dev
    • Production mode:
      npm start

    The backend API will start on http://localhost:8000.


2. Frontend Setup

  1. Open a second terminal window and navigate to the frontend directory:

    cd frontend
  2. Install dependencies:

    npm install
  3. Run linting and build checks:

    npm run lint
    npm run build
  4. Start the Vite development server:

    npm run dev
  5. Open your browser and navigate to http://localhost:5173.


⚙️ Environment Variables Reference

The backend requires the following keys in backend/.env:

Variable Description Default / Recommended
PORT Port number for Express API server 8000
OPENROUTER_API_KEY Authentication bearer token from OpenRouter sk-or-v1-...
MODEL OpenRouter model identifier google/gemini-2.5-flash
MAX_TOKENS Maximum completion token limit per pipeline step 800

📡 API Reference

1. Server Health Check

GET /

Response (200 OK):

{
  "success": true,
  "message": "AI Code Reviewer API is running 🚀"
}

2. Submit Code for Review

POST /api/review

(Also aliased at POST /ai/review and POST /api/get-review)

Request Headers:

Content-Type: application/json

Request Body:

{
  "code": "function add(a, b) { return a + b; }"
}

Response (200 OK):

{
  "success": true,
  "data": {
    "review": {
      "summary": "The function performs basic addition but lacks type checking for JavaScript's dynamic typing.",
      "rating": 7,
      "strengths": [
        "Concise implementation",
        "Clean functional logic"
      ],
      "issues": [
        "Lack of input validation allows unexpected string concatenation"
      ],
      "improvements": [
        "Add explicit typeof validation or switch to TypeScript",
        "Include JSDoc documentation"
      ],
      "bestPractices": [
        "Validate input arguments before performing arithmetic operations",
        "Document function contracts with JSDoc parameters"
      ],
      "refactoredCode": "/**\n * Adds two numbers.\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\nfunction add(a, b) {\n  if (typeof a !== 'number' || typeof b !== 'number') {\n    throw new TypeError('Both arguments must be numbers.');\n  }\n  return a + b;\n}"
    }
  },
  "review": { ... }
}

🧪 Testing

Frontend Workflow Tests

  • Run ESLint check:
    cd frontend && npm run lint
  • Run Vite production bundle build:
    cd frontend && npm run build

Backend API Tests

  • Use the included REST Client file backend/test.http in VS Code / Cursor.
  • Or send a test request via curl:
    curl -X POST http://localhost:8000/api/review \
      -H "Content-Type: application/json" \
      -d '{"code": "function calculate(x, y) { return x / y; }"}'

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add AmazingFeature')
  4. Push to your branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

📄 License

Distributed under the ISC License.