Skip to content
Prakhar007PathakPublic

About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

Repository files navigation

CodeDNA

AI-powered repository intelligence — understand why code exists, what it connects to, and what breaks if you touch it.

CodeDNA clones any GitHub repository and gives you a living memory of it: commit timelines, function-level dependency graphs, change-impact risk assessments, and a Gemini-powered chat agent that answers questions grounded in the actual code and history.


Features

Feature Description
Repository Analysis Clone any public GitHub repo and extract its full file tree, functions, and commit history
Timeline View Commit history grouped by year, categorised by type (feature, bugfix, security, optimization, milestone, test)
File Explorer Browse every file and function with JSDoc/comment-extracted descriptions
Why Does This Exist? Gemini analyses a function's source + commit history and explains its origin with evidence and confidence level
Dependency Graph Real static-analysis graph of every file that calls a function, its sibling functions, and related test files
Impact Analysis Pre-change risk assessment across Security, API, Database, Performance, Testing, and Architecture dimensions
Ask CodeDNA (Chat) Multi-turn AI chat agent with full repo context — file tree, commits, stats, and persistent conversation memory per session
Demo Mode Try every feature without a live repository using built-in mock data

Architecture

codedna/
├── client/                  # React 18 + Vite frontend
│   └── src/
│       ├── pages/           # OverviewPage, TimelinePage, ExplorePage, ImpactPage
│       ├── components/
│       │   ├── analysis/    # WhyAnalysisView, DependencyGraph, ChangeImpactView
│       │   ├── chat/        # AskCodeDNAModal (AI chat interface)
│       │   ├── explore/     # FileExplorer, FunctionCard
│       │   ├── timeline/    # Timeline
│       │   ├── repository/  # RepositoryInput
│       │   └── common/      # Button, Card, Badge, EmptyState, ErrorState
│       ├── services/        # api.js — all REST calls to the backend
│       ├── context/         # RepositoryContext (global repo state)
│       └── utils/           # demoChatResponses, helpers
│
└── server/                  # Express backend
    ├── index.js             # App entrypoint, middleware, route mounting
    ├── config/db.js         # MongoDB Atlas connection
    ├── routes/
    │   ├── repositories.js  # POST /analyze, GET /:id, /timeline, /files
    │   ├── analysis.js      # POST /why, /dependencies, /impact
    │   └── chat.js          # POST /chat — Gemini AI chat with history
    ├── services/
    │   ├── aiService.js     # All Gemini interactions (why, impact, chat)
    │   ├── gitService.js    # Clone/update repos, commit history (simple-git)
    │   ├── parserService.js # File tree builder + function extractor (JS/TS/Python)
    │   ├── codeSearchService.js  # Static reference finder + source extractor
    │   ├── timelineService.js    # Commit → yearly grouped timeline builder
    │   └── statsService.js       # Health score + repo statistics
    ├── models/
    │   ├── Repository.js    # Repo metadata, stats, health, insights
    │   ├── FileTree.js      # Parsed file + function tree
    │   ├── Timeline.js      # Yearly grouped commit events
    │   ├── Analysis.js      # Cached why/dependency/impact results
    │   └── ChatHistory.js   # Per-session conversation history
    ├── middleware/
    │   └── errorHandler.js  # Global error handler + asyncHandler wrapper
    └── utils/
        └── repoLookup.js    # Find repo by ObjectId or slug

Getting Started

Prerequisites

  • Node.js v18 or later
  • MongoDB Atlas account (free tier works fine)
  • Gemini API key — get one free at Google AI Studio
  • (Optional) GitHub Personal Access Token — needed for private repos or to avoid rate limits

1 — Clone the repository

git clone https://github.com/your-username/codedna.git
cd codedna

2 — Install dependencies

npm run install:all

This installs packages for the root, client, and server in a single command.

3 — Configure environment variables

Create a .env file in the project root (next to package.json):

# ── Required ─────────────────────────────────────────────
MONGODB_URI=mongodb+srv://<user>:<password>@cluster0.xxxxx.mongodb.net/
GEMINI_API_KEY=your_gemini_api_key_here

# ── Optional ─────────────────────────────────────────────
GEMINI_MODEL=gemini-1.5-flash        # default: gemini-1.5-flash
GITHUB_TOKEN=ghp_your_token_here     # for private repos / higher rate limits
PORT=5000                            # default: 5000

MongoDB Atlas tip: If you see a connection error about IP whitelisting, go to
Atlas → Network Access → Add IP Address → Add your current IP (or 0.0.0.0/0 for development).

4 — Run in development

npm run dev

This starts both the backend and frontend concurrently:

Service URL
Frontend (Vite) http://localhost:5173
Backend (Express) http://localhost:5000
API health check http://localhost:5000/api/health

API Reference

Repositories

Method Endpoint Description
POST /api/repositories/analyze Clone + analyze a GitHub repo
GET /api/repositories/:id Get repository metadata
GET /api/repositories/:id/timeline Get yearly grouped commit timeline
GET /api/repositories/:id/files Get parsed file tree with functions

POST /api/repositories/analyze

{ "url": "https://github.com/owner/repo" }

Analysis

Method Endpoint Description
POST /api/analysis/why "Why does this function exist?" (Gemini + commits)
POST /api/analysis/dependencies Static dependency graph for a function
POST /api/analysis/impact Change impact risk assessment (Gemini)

All analysis endpoints share this request body:

{
  "repositoryId": "<ObjectId or slug>",
  "filePath": "src/utils/auth.js",
  "functionName": "verifyToken"
}

Results are cached in MongoDB — the first call generates via Gemini, subsequent calls return the cached result instantly.


Chat

Method Endpoint Description
POST /api/chat AI chat with full repo context and session memory
{
  "repositoryId": "<ObjectId or slug>",
  "message": "What changed in the auth module recently?",
  "sessionId": "sess-1234567890-abc123"
}

The chat agent is given the repository's file tree, recent commit history, and the full conversation history for the session — enabling multi-turn, grounded answers.


How the AI Works

generateWhyAnalysis

Passes the function's source code and commit history for its file to Gemini with a strict prompt instructing it to only reference real commit hashes. Returns a JSON object with summary, history, evidence (with verified commit hashes), and a confidence level.

buildDependencyGraph

100% deterministic — no AI. Uses static regex scanning across the entire repo to find every real call-site of the function, classifies them as consumers or test files, and places sibling functions. No hallucination possible.

generateImpactAnalysis

Combines the real dependency counts from the graph with Gemini narrative generation. The prompt explicitly passes in verified numbers and tells the model not to contradict them. Returns risks, consequences, and evidence.

generateChatResponse

The chat agent receives:

  • Repository metadata (name, language, file count, commit count, contributors)
  • A compact file tree summary (up to 40 files with function counts)
  • Up to 20 recent commit titles
  • The last 8 messages of the conversation session
  • The user's current message

Conversation history is persisted to MongoDB ChatHistory per sessionId, so context survives page refreshes.


Tech Stack

Layer Technology
Frontend React 18, React Router v6, Vite 5
Backend Node.js, Express 4
Database MongoDB Atlas via Mongoose 8
AI Google Gemini (@google/generative-ai)
Git simple-git
Dev tooling concurrently, dotenv, morgan

Key npm Scripts

Script What it does
npm run dev Start frontend + backend concurrently
npm run client Start only the Vite frontend
npm run server Start only the Express backend
npm run build:client Build the frontend for production
npm run install:all Install all dependencies (root + client + server)

Data Models

Repository

Stores metadata, stats (files, commits, languages, contributors, branches), a health score, and AI-generated architectural insights.

FileTree

The full parsed file and function tree for a repository. Each file node has path, type, and a functions array with name, line, and description.

Timeline

Commit history grouped by year into typed events (milestone, feature, bugfix, optimization, security, test) with affected area inference (Auth, API, Database, Frontend, etc.).

Analysis

Cache document per { repositoryId, filePath, functionName } storing the why, dependencies, and impact sub-documents to avoid redundant Gemini calls.

ChatHistory

Conversation messages stored per { repositoryId, sessionId } — enables multi-turn memory across requests.


Environment Variables Reference

Variable Required Default Description
MONGODB_URI ✅ — MongoDB Atlas connection string
GEMINI_API_KEY ✅ — Google Gemini API key
GEMINI_MODEL ❌ gemini-1.5-flash Gemini model name
GITHUB_TOKEN ❌ — GitHub PAT for private repos / rate limits
PORT ❌ 5000 Express server port

Troubleshooting

MongoDB connection fails
Your IP may not be whitelisted. Go to Atlas → Network Access → Add Current IP Address.

Gemini returns errors
Verify GEMINI_API_KEY is set correctly in .env at the project root. The server loads it from ../.env relative to server/.

Chat always returns "AI service unavailable"
Check the server logs — the error message is printed to console. Most common causes: missing API key, invalid model name, or Gemini quota exceeded.

Repository analysis is slow on first run
The repo is being cloned fresh. Subsequent analyses of the same repo use git pull instead and are much faster.

Functions not appearing in a file
The parser supports JS, JSX, TS, TSX, MJS, CJS, and Python. Other languages (Go, Java, Rust, etc.) are indexed as files but functions are not extracted.


About

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages