# Project export: DiffSense

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: UC Berkeley AI Hackathon 2025
- Tagline: Every ‘simple’ code change risks breaking your app. DiffSense’s AI catches breakages early—and lets you query your entire code history with an LLM powered by retrieval-augmented generation (RAG).
- Devpost: https://devpost.com/software/diffsense
- GitHub: https://github.com/jalenfran/DiffSense/
- Video: https://www.youtube.com/embed/P__UXiXExbY?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 3 GitHub contributor(s) — Jayson Clark (11 commits), Jalen Francis (11 commits), Farhan Sadeek (2 commits)

## Devpost submission (written by the team)

### Overview

AI-Powered Code Change Intelligence & Breaking Change Detection Turning code deployment from Russian roulette into predictable science

### Inspiration

Every developer has that one commit that haunts their dreams. A "simple" function rename that crashes the mobile app. A "harmless" API update that locks out millions of users. A database schema change that wipes data forever. The inspiration for DiffSense came from watching brilliant engineering teams repeatedly fall into the same trap: invisible breaking changes. We realized that these disasters aren't random—they're predictable. The connections between code changes and their cascading effects follow patterns that human eyes miss but AI can see.

### What it does

DiffSense is like having a crystal ball for your code changes. It's an AI-powered platform that: Predictive Breaking Change Detection Analyzes every code change using advanced ML models Predicts ripple effects across your entire codebase Provides impact severity scoring and affected user estimates Intelligent Context Analysis Uses RAG (Retrieval-Augmented Generation) to understand your codebase Leverages Claude AI for natural language explanations Performs deep AST analysis and pattern detection Maintains historical context of previous breaking changes Smart Recommendations Generates actionable suggestions to prevent disasters Provides migration strategies for necessary breaking changes Prioritizes fixes by business impact and technical risk Real-time Integration GitHub OAuth integration for seamless repository access WebSocket support for real-time change monitoring RESTful API for integration with existing CI/CD pipelines Vector embeddings for semantic code similarity analysis

### How we built it

Architecture We built DiffSense using a modern, AI-first architecture: Frontend: React with Vite, TailwindCSS for beautiful, responsive UI Backend: FastAPI with Python for high-performance API endpoints AI/ML Stack: Claude AI for natural language understanding CodeBERT for code semantic analysis SentenceTransformers for vector embeddings Custom ML models for breaking change prediction Data Layer: SQLite for development with vector caching for embeddings Infrastructure: Layered architecture supporting future microservices migration Key Technical Innovations Semantic Code Analysis: Combined AST parsing with ML embeddings Intelligent RAG System: Context-aware retrieval for better AI responses Predictive Breaking Change Models: Custom ML pipeline trained on git history patterns Real-time Change Tracking: WebSocket-based live monitoring system Development Process AI-first design philosophy from day one Extensive testing with real-world repositories User-centered design for developer experience

### Challenges we ran into

Technical Challenges Scale of Code Analysis: Analyzing entire repositories efficiently without overwhelming resources Context Window Limitations: Working within AI model token limits while maintaining comprehensive analysis False Positive Management: Balancing sensitivity with practical usability Real-time Performance: Delivering instant feedback without sacrificing accuracy Integration Challenges GitHub API Rate Limits: Efficiently managing API calls for large repositories Cross-platform Compatibility: Supporting diverse development environments Security & Privacy: Handling sensitive code data with enterprise-grade security Performance Optimization: Maintaining speed while processing complex codebases

### Accomplishments we're proud of

Technical Achievements Built a working AI system that can actually predict breaking changes Utilized a breaking change detector to power our web app Fine tuned a RAG model to smart prompt a Claude API Innovation First-of-its-kind predictive breaking change detection Novel combination of static analysis, ML, and AI reasoning Beautiful, intuitive UX that makes complex AI accessible

### What we learned

Technical Insights AI works best with structure: Combining traditional static analysis with AI gives better results than pure AI Context is everything: The quality of our RAG system directly impacts AI accuracy User feedback is gold: Real developer usage patterns taught us what actually matters

### What's next

VS Code Extension with inline risk alerts and code search Fine-tune models on commit-level breaking changes Improve code embeddings & retrieval quality (RAG) Add context retention for multi-turn queries Scale backend infrastructure for faster, larger repo support The Future is Predictable DiffSense represents a fundamental shift in how we think about code changes. Instead of crossing our fingers and hoping for the best, we're moving toward a world where every change is analyzed, understood, and deployed with confidence. We're not just preventing bugs. We're preventing disasters. The future of software isn't about writing perfect code—it's about knowing exactly what your imperfect code will do before it's too late. Welcome to the future of predictable code deployment. Welcome to DiffSense.

## README (from the GitHub repository)

# DiffSense: Feature Drift Detector

> 🏆 **AI Berkeley Hackathon Project** - Semantic drift detection using embedding-powered analysis of git history

[![Demo](https://img.shields.io/badge/Demo-Ready-brightgreen)](./setup.sh)
[![Documentation](https://img.shields.io/badge/Docs-Complete-blue)](./TECHNICAL_ROADMAP.md)
[![Presentation](https://img.shields.io/badge/Presentation-Guide-purple)](./DEMO_GUIDE.md)

## 🚀 Quick Start for Judges

### **Instant Demo** (2 minutes)
```bash
./setup.sh demo
```
*Shows semantic drift analysis on a generated repository*

### **Full Web Application** (5 minutes)
```bash
./setup.sh full
# Open http://localhost:3000
```
*Complete interface for analyzing any GitHub repository*

### **Help & Options**
```bash
./setup.sh help
```

## 🎯 The Problem

Modern software development moves fast. Features change, APIs evolve, and sometimes small commits create huge unexpected impacts—whether breaking downstream functionality, causing subtle bugs, or violating intended product behavior. Teams lose track of why things were changed or when something started behaving differently.

## 💡 Solution: DiffSense

**DiffSense** solves this by using embedding-powered semantic drift detection over git diffs, commit messages, issue tickets, and changelogs.

→ You input a function, file, or API you want to audit  
→ The system retrieves its historical versions, compares the semantic meaning of changes over time via embeddings  
→ Generates clear, human-readable explanations of how and why that feature changed  

## 🚀 Quick Start

### Option 1: One-Command Start (Recommended)
```bash
./start.sh
```

### Option 2: Manual Setup

**Backend Setup:**
```bash
cd backend
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python main.py
```

**Frontend Setup:**
```bash
cd frontend
npm install
npm run dev
```

**Demo Script:**
```bash
cd backend
python demo.py
```

## 🏗️ Architecture

### Technology Stack
- **Backend**: Python FastAPI with ML pipeline
- **Frontend**: React with Recharts visualization
- **ML Models**: 
  - CodeBERT for code embeddings
  - sentence-transformers for text embeddings
  - Hybrid embedding approach
- **Git Analysis**: GitPython for repository parsing
- **API**: RESTful endpoints with real-time analysis

### Core Components
1. **Git Analyzer** (`git_analyzer.py`) - Extract and parse git history
2. **Embedding Engine** (`embedding_engine.py`) - Generate semantic embeddings
3. **Drift Detector** (`drift_detector.py`) - Analyze semantic changes over time
4. **FastAPI Backend** (`main.py`) - REST API for frontend integration
5. **React Frontend** - Interactive visualization and analysis interface

## ✨ Core Features

### 1. **Semantic Drift Detection**
- Track how code meaning changes over time using AI embeddings
- Identify gradual vs sudden semantic shifts
- Measure cumulative drift from original implementation

### 2. **Breaking Change Prediction**
- ML-powered risk scoring for commits
- Predict potentially risky changes before they impact users
- Historical pattern analysis for risk assessment

### 3. **Interactive Timeline Visualization**
- Visual drift timeline with commit details
- Identify significant change events
- Hover details with commit messages and metrics

### 4. **Multi-Level Analysis**
- **File-level**: Analyze entire file evolution
- **Function-level**: Track specific function changes
- **Repository-level**: Overall project health metrics

## 🎮 Demo Flow

1. **Repository Input**: Enter GitHub repository URL
2. **File Selection**: Choose file or function to analyze  
3. **Semantic Analysis**: AI processes git history and generates embeddings
4. **Drift Visualization**: Interactive timeline showing semantic changes
5. **Risk Assessment**: Breaking change prediction with explanations
6. **Export Results**: Summary reports and recommendations

## 📊 Use Cases

### For Development Teams
- **Detect undocumented breaking changes** before a release
- **Help new developers** quickly catch up on why parts of the codebase evolved
- **Trace regressions** back to their origins, even in noisy or badly documented projects

### For Project Managers
- **Risk assessment** for releases
- **Technical debt tracking** over time
- **API stability monitoring**

### For Open Source Maintainers
- **Contributor onboarding** with feature evolution stories
- **Impact analysis** for proposed changes
- **Documentation gap identification**

## 🛠️ Technical Implementation

### Embedding Strategy
```python
# Hybrid approach combining code and text semantics
code_embedding = CodeBERT.encode(code_diff)
text_embedding = SentenceTransformer.encode(commit_message)
hybrid_embedding = 0.7 * code_embedding + 0.3 * text_embedding
```

### Drift Calculation
```python
# Semantic similarity tracking over time
def calculate_drift(embeddings_timeline):
    drift_scores = []
    for i in range(1, len(embeddings_timeline)):
        similarity = cosine_similarity(embeddings_timeline[0], embeddings_timeline[i])
        drift_scores.append(1 - similarity)  # Higher = more drift
    return drift_scores
```

### Breaking Change Prediction
- **Feature Engineering**: Code metrics + semantic embeddings + commit metadata
- **Heuristic Model**: Risk scoring based on drift patterns and change magnitude
- **Contextual Analysis**: Related issues, commit message sentiment, file importance

## 📁 Project Structure

```
DiffSense/
├── README.md                 # This file
├── TECHNICAL_ROADMAP.md      # Detailed implementation guide
├── start.sh                  # One-command startup script
├── backend/
│   ├── main.py              # FastAPI server
│   ├── demo.py              # Standalone demo script
│   ├── requirements.txt     # Python dependencies
│   └── src/
│       ├── git_analyzer.py     # Git repository analysis
│       ├── embedding_engine.py # AI embedding generation
│       └── drift_detector.py   # Semantic drift detection
└── frontend/
    ├── package.json         # Node.js dependencies
    ├── vite.config.js       # Vite configuration
    ├── tailwind.config.js   # Tailwind CSS config
    └── src/
        ├── App.jsx              # Main React application
        └── components/
            ├── RepositoryCloner.jsx  # Repository input interface
            ├── DriftAnalyzer.jsx     # Main analysis interface
            ├── FileSelector.jsx      # File selection component
            ├── DriftSummary.jsx      # Analysis results summary
            └── DriftTimeline.jsx     # Interactive timeline chart
```

## 🎯 Hackathon Demo Points

### **Technical Innovation**
- Novel application of code embeddings for semantic drift detection
- Hybrid embedding approach combining code and natural language understanding
- Real-time git history analysis with visual feedback

### **Practical Value**
- Addresses real pain points in software development
- Scalable to any git repository
- Immediate actionable insights for development teams

### **User Experience**
- Intuitive web interface with beautiful visualizations
- One-click repository analysis
- Interactive timeline exploration
- Clear risk assessments and explanations

## 🔄 Future Enhancements

- **LLM Integration**: Use Claude/GPT for natural language explanations
- **Advanced ML**: Train custom models for breaking change prediction
- **Integration**: GitHub Apps, VS Code extensions, CI/CD webhooks
- **Collaboration**: Team insights, change approval workflows
- **Scale**: Enterprise deployment, multi-repository analysis

## 🏃‍♂️ Getting Started for Judges

1. **Quick Demo**: `./start.sh` → Open http://localhost:3000
2. **Standalone Demo**: `cd backend && python demo.py`
3. **Example Repository**: Try with `https://github.com/microsoft/vscode`
4. **Explore**: Select a file like `src/vs/editor/editor.api.ts`

## 🤝 Team & Acknowledgments

Built for the AI Berkeley Hackathon. Special thanks to the open-source community for the foundational tools that make this possible.

---

**Ready to detect f

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 60 recognized source files, 2019 KB.
- Anthropic (technology) — detected in the code
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- Hugging Face (technology) — detected in the code
- JavaScript (language) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- PyTorch (technology) — detected in the code
- React (technology) — detected in the code
- Redis (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code

## Codebase structure (from repository index)

### Files (76 of 76)

```
.gitignore
backend/API.md
backend/main.py
backend/README.md
backend/requirements.txt
backend/src/__init__.py
backend/src/breaking_change_detector.py
backend/src/claude_analyzer.py
backend/src/code_analyzer.py
backend/src/config.py
backend/src/database.py
backend/src/embedding_engine.py
backend/src/git_analyzer.py
backend/src/github_service.py
backend/src/rag_system.py
backend/src/storage_manager.py
backend/src/suggestions_engine.py
code-extension/.vscode-test.mjs
code-extension/.vscode/extensions.json
code-extension/.vscode/launch.json
code-extension/.vscode/settings.json
code-extension/.vscode/tasks.json
code-extension/.vscodeignore
code-extension/esbuild.js
code-extension/eslint.config.mjs
code-extension/media/chat.css
code-extension/media/chat.js
code-extension/media/ChatApp.tsx
code-extension/media/index.js
code-extension/media/index.js.map
code-extension/media/index.tsx
code-extension/package.json
code-extension/README.md
code-extension/src/extension.ts
code-extension/tsconfig.json
frontend/.env.example
frontend/.gitignore
frontend/DEMO.md
frontend/FILE_VIEWER_IMPLEMENTATION.md
frontend/index.html
frontend/package.json
frontend/postcss.config.js
frontend/README.md
frontend/src/App.jsx
frontend/src/components/AddRepositoryDialog.jsx
frontend/src/components/BreakingChangeAnalyzer.jsx
frontend/src/components/ChatInterface.jsx
frontend/src/components/CommitViewer.jsx
frontend/src/components/Dashboard.jsx
frontend/src/components/FileContentRenderer.jsx
frontend/src/components/FileExplorer.jsx
frontend/src/components/FileViewer.jsx
frontend/src/components/FileViewer/index.js
frontend/src/components/FileViewerModal.jsx
frontend/src/components/Header.jsx
frontend/src/components/LandingPage.jsx
frontend/src/components/LinkifiedMarkdown.jsx
frontend/src/components/LinkifyContent.jsx
frontend/src/components/LoadingSpinner.jsx
frontend/src/components/MainContent.jsx
frontend/src/components/MarkdownRenderer.jsx
frontend/src/components/PortableFileViewer.jsx
frontend/src/components/Sidebar.jsx
frontend/src/components/SimpleFileViewer.jsx
frontend/src/config/index.js
frontend/src/contexts/CommitViewerContext.jsx
frontend/src/contexts/DarkModeContext.jsx
frontend/src/contexts/FileViewerContext.jsx
frontend/src/contexts/RepositoryContext.jsx
frontend/src/index.css
frontend/src/main.jsx
frontend/src/services/api.js
frontend/tailwind.config.js
frontend/vite.config.js
pyproject.toml
README.md
```

### Dependencies

- backend/requirements.txt: alembic@==1.13.0, anthropic@==0.7.7, black@==23.11.0, chromadb@==0.4.18, fastapi@==0.104.1, flake8@==6.1.0, gitpython@==3.1.40, mypy@==1.7.1, numpy@==1.24.3, openai@==1.3.7, pydantic@==2.5.0, pytest@==7.4.3, python-dotenv@==1.0.0, python-multipart@==0.0.6, redis@==5.0.1, scikit-learn@==1.3.2, sentence-transformers@==2.2.2, sqlalchemy@==2.0.23, torch@==2.1.1, transformers@==4.36.0, uvicorn[standard]@==0.24.0
- code-extension/package.json: @types/mocha@^10.0.10, @types/node@20.x, @types/react@^19.1.8, @types/react-dom@^19.1.6, @types/vscode@^1.101.0, @typescript-eslint/eslint-plugin@^8.31.1, @typescript-eslint/parser@^8.31.1, @vscode/test-cli@^0.0.10, @vscode/test-electron@^2.5.2, esbuild@^0.25.3, eslint@^9.25.1, npm-run-all@^4.1.5, react@^19.1.0, react-dom@^19.1.0, typescript@^5.8.3
- frontend/package.json: @types/react@^18.2.15, @types/react-dom@^18.2.7, @vitejs/plugin-react@^4.0.3, autoprefixer@^10.4.14, axios@^1.5.0, highlight.js@^11.11.1, lucide-react@^0.263.1, postcss@^8.4.27, react@^18.2.0, react-dom@^18.2.0, react-markdown@^10.1.0, react-syntax-highlighter@^15.6.1, rehype-highlight@^7.0.2, remark-gfm@^4.0.1, tailwindcss@^3.3.3, vite@^4.4.5

### Recent commits (newest first)

- Merge pull request #1 from jalenfran/local-work
- improvements in model
- Merge branch 'main' of https://github.com/jalenfran/DiffSense
- More complete frontend
- integrated change deteciton in further models.
- added advanced breaking_change_detection
- greatly improved rag model.
- Merge branch 'main' of https://github.com/jalenfran/DiffSense
- updates to database to support caching and accessing specific files and commits.
- Merge branch 'main' of https://github.com/jalenfran/DiffSense
- Integrated api 2.0
- Merge branch 'main' of https://github.com/jalenfran/DiffSense
- integrated github oauth  and chat/analysis persistence
- Merge branch 'main' of https://github.com/jalenfran/DiffSense
- Fixed bugs
- Merge branch 'main' of https://github.com/jalenfran/DiffSense
- major updates to architecture
- Markdown on chat implementation
- Frontend updates
- Integrated API into web app

## Key source files (fetched from GitHub, selected and truncated for size)

### backend/API.md

```markdown
# DiffSense API Documentation

## Overview

DiffSense provides repository cloning, breaking-change analysis, RAG-based queries, persistent chat, and GitHub OAuth authentication.

---

## Health Check

GET `/`
- Returns service status and configuration health.

Response:
```json
{ "message": "DiffSense API is running", "timestamp": "2025-06-22T...Z", "config_status": true }
```

---

## Authentication

### Initiate GitHub OAuth
GET `/api/auth/github`
- Returns OAuth URL and state.

### OAuth Callback
GET `/api/auth/github/callback?code=<code>&state=<state>`
- GitHub redirects here after user authorization
- Uses Referer header to determine frontend origin for redirect
- Redirects to frontend with session_id: `{frontend_origin}/auth/callback?session_id={session_id}&success=true`
- On error: `{frontend_origin}/auth/callback?error={message}&success=false`

### Get Current User
GET `/api/auth/user`
- Header: `Authorization: Bearer <session_id>`
- Returns user profile.

### Logout
POST `/api/auth/logout`
- Header: `Authorization: Bearer <session_id>`
- Invalidates session.

---

## Repository Management

### Clone Repository
POST `/api/clone-repository`
```json
{ "repo_url": "https://github.com/user/repo", "use_auth": false }
```
- Clones (supports private repos), returns `{ repo_id, status, stats, message }`.

### List Files
GET `/api/repository/{repo_id}/files`
- Lists code files.

### Repository Stats
GET `/api/repository/{repo_id}/stats`
- Returns stats: total_commits, contributors, branches, file_count.

### List Commits
GET `/api/repository/{repo_id}/commits?limit=50`
- Returns recent commits with metadata.

### Get Commit Files
GET `/api/repository/{repo_id}/commit/{commit_hash}/files?include_diff_stats=false`
- Lists all files changed in a specific commit with optional diff statistics.

### Cleanup Repository
DELETE `/api/repository/{repo_id}`
- Deletes local clone and resources.

---

## Breaking Change Analysis

### Analyze Single Commit
POST `/api/analyze-commit/{repo_id}`
```json
{ "commit_hash": "<hash>", "include_claude_analysis": true }
```
- Returns risk score, breaking_changes, optional Claude analysis.

### Analyze Commit Range
POST `/api/analyze-commit-range/{repo_id}`
```json
{ "start_commit": "<hash>", "end_commit": "<hash>", "max_commits": 100, "include_claude_analysis": false }
```
- Batch analysis with trends.

---

## RAG Queries & Intelligent Search

### Repository Query
POST `/api/query-repository/{repo_id}`
```json
{ "query": "...", "max_results": 10 }
```
- QA over repository, returns `{ query, response, confidence, sources, context_used, suggestions, claude_enhanced }`.

### Enhanced RAG Query
POST `/api/repository/{repo_id}/query/enhanced`
```json
{ "query": "...", "max_results": 10 }
```
- RAG + Claude-enhanced response with related content.

### Search Commits
GET `/api/repository/{repo_id}/commits/search?query=...&max_results=10`

### Search Files
GET `/api/repository/{repo_id}/files/search?query=...&max_results=10`

-
[truncated — 1726 more characters]
```

### frontend/DEMO.md

```markdown
# DiffSense Frontend Demo

This document provides a quick demo of the new DiffSense frontend features.

## Demo Setup

1. **DiffSense API Server**
   ```bash
   # The DiffSense API is running on http://76.125.217.28:8080
   # You should see endpoints like:
   # - POST /api/clone-repository
   # - GET /api/repository/{id}/stats
   # - POST /api/query-repository/{id}
   ```

2. **Start the Frontend**
   ```bash
   cd frontend
   npm run dev
   # Visit http://localhost:5173
   # OAuth server (if needed) runs on localhost:3000
   ```

## Demo Walkthrough

### Step 1: Add a Repository via URL

1. Open the application (auth is optional for this demo)
2. Click "Add Repository" in the sidebar
3. Switch to "Add by URL" tab
4. Enter a repository URL like: `https://github.com/octocat/Hello-World`
5. Click "Add Repository"

**What happens:**
- The frontend calls the DiffSense API to clone and analyze the repository
- Repository stats, files, and risk analysis are fetched
- The repository appears in the sidebar

### Step 2: Explore the Risk Dashboard

Once a repository is selected, you'll see:

1. **Repository Header**
   - Basic stats (stars, forks, language, file count)
   - Links to GitHub

2. **Risk Analysis Panel**
   - Overall risk score with visual indicator
   - High-risk commits count
   - Total commits analyzed
   - Breaking changes by category

3. **Error Handling**
   - If the API is not running, you'll see connection errors
   - Repository analysis failures are displayed clearly

### Step 3: Use the Chat Interface

The bottom panel contains an interactive chat:

1. **Quick Prompts**: Click any of the predefined prompts:
   - "Analyze recent changes"
   - "Find breaking changes"  
   - "Code structure overview"
   - "Security concerns"

2. **Custom Questions**: Type your own questions like:
   - "What files handle authentication?"
   - "Are there any deprecated functions?"
   - "What are the main dependencies?"

3. **File Context**: 
   - Click "Select files" to choose specific files
   - The AI responses will focus on those files

**Chat Response Features:**
- Confidence scores for AI responses
- Source citations with relevance ratings
- Expandable sections for detailed information
- Copy functionality for responses

### Step 4: Breaking Change Analysis

When the API detects breaking changes, you'll see:

1. **Risk Indicators**: Color-coded risk levels (green/yellow/red)
2. **Change Categories**: 
   - Function removals
   - API signature changes
   - Parameter modifications
   - Dependency changes
3. **AI Analysis**: Claude-powered insights and suggestions

## Sample API Responses

### Repository Query Response
```json
{
  "response": "This project appears to be a simple Hello World repository...",
  "confidence": 0.85,
  "sources": [
    {
      "type": "file",
      "path": "README.md",
      "relevance": 0.9
    }
  ],
  "claude_enhanced": true
}
```

### Commit Analysis Response
```json
{
  "commit_hash": "abc123",
  "overall_risk_score": 0.
[truncated — 2005 more characters]
```

### backend/requirements.txt

```
# Core dependencies
fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==2.5.0
python-multipart==0.0.6
python-dotenv==1.0.0
gitpython==3.1.40

# ML/AI Dependencies
torch==2.1.1
transformers==4.36.0
sentence-transformers==2.2.2
scikit-learn==1.3.2
numpy==1.24.3

# Claude API Integration
anthropic==0.8.1

# Vector/Embedding Storage
chromadb==0.4.18

# Optional: CUDA support
# torch==2.1.1+cu118 -f https://download.pytorch.org/whl/torch_stable.html

# Database (for production)
sqlalchemy==2.0.23
alembic==1.13.0

# Caching
redis==5.0.1

# API clients
anthropic==0.7.7
openai==1.3.7

# Development
pytest==7.4.3
black==23.11.0
flake8==6.1.0
mypy==1.7.1

```

### frontend/package.json

```
{
    "name": "diffsense-frontend",
    "private": true,
    "version": "0.0.0",
    "type": "module",
    "scripts": {
        "dev": "vite",
        "build": "vite build",
        "preview": "vite preview"
    },
    "dependencies": {
        "axios": "^1.5.0",
        "highlight.js": "^11.11.1",
        "lucide-react": "^0.263.1",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-markdown": "^10.1.0",
        "react-syntax-highlighter": "^15.6.1",
        "rehype-highlight": "^7.0.2",
        "remark-gfm": "^4.0.1"
    },
    "devDependencies": {
        "@types/react": "^18.2.15",
        "@types/react-dom": "^18.2.7",
        "@vitejs/plugin-react": "^4.0.3",
        "autoprefixer": "^10.4.14",
        "postcss": "^8.4.27",
        "tailwindcss": "^3.3.3",
        "vite": "^4.4.5"
    }
}

```

### code-extension/package.json

```
{
    "name": "diffsense-extension",
    "displayName": "DiffSense",
    "description": "AI-powered Git diff analysis and code insights",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.101.0"
    },
    "categories": [
        "Other"
    ],
    "activationEvents": [],
    "main": "./dist/extension.js",
    "scripts": {
        "vscode:prepublish": "npm run package",
        "compile": "npm run check-types && npm run lint && node esbuild.js",
        "watch": "npm-run-all -p watch:*",
        "watch:esbuild": "node esbuild.js --watch",
        "watch:tsc": "tsc --noEmit --watch --project tsconfig.json",
        "package": "npm run check-types && npm run lint && node esbuild.js --production",
        "compile-tests": "tsc -p . --outDir out",
        "watch-tests": "tsc -p . -w --outDir out",
        "pretest": "npm run compile-tests && npm run compile && npm run lint",
        "check-types": "tsc --noEmit",
        "lint": "eslint src",
        "test": "vscode-test"
    },
    "devDependencies": {
        "@types/mocha": "^10.0.10",
        "@types/node": "20.x",
        "@types/react": "^19.1.8",
        "@types/react-dom": "^19.1.6",
        "@types/vscode": "^1.101.0",
        "@typescript-eslint/eslint-plugin": "^8.31.1",
        "@typescript-eslint/parser": "^8.31.1",
        "@vscode/test-cli": "^0.0.10",
        "@vscode/test-electron": "^2.5.2",
        "esbuild": "^0.25.3",
        "eslint": "^9.25.1",
        "npm-run-all": "^4.1.5",
        "typescript": "^5.8.3"
    },
    "contributes": {
        "commands": [
            {
                "command": "myChatView.focus",
                "title": "Focus DiffSense Chat"
            }
        ],
        "viewsContainers": {
            "activitybar": [
                {
                    "id": "myChatContainer",
                    "title": "DiffSense",
                    "icon": "resources/chat.svg"
                }
            ]
        },
        "views": {
            "myChatContainer": [
                {
                    "id": "myChatView",
                    "name": "DiffSense AI",
                    "type": "webview"
                }
            ]
        }
    },
    "dependencies": {
        "react": "^19.1.0",
        "react-dom": "^19.1.0"
    }
}
```

### frontend/src/main.jsx

```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
)

```

### code-extension/media/index.tsx

```typescript
import React from 'react';
import { createRoot } from 'react-dom/client';
import ChatApp from './ChatApp';

// Acquire VS Code API
declare global {
  interface Window {
    acquireVsCodeApi: () => any;
  }
}

const vscode = window.acquireVsCodeApi();

const container = document.getElementById('root');
if (container) {
  const root = createRoot(container);
  root.render(<ChatApp vscode={vscode} />);
}

```

### frontend/src/App.jsx

```javascript
import { useState, useEffect } from 'react'
import { diffSenseAPI } from './services/api'
import LandingPage from './components/LandingPage'
import Dashboard from './components/Dashboard'
import LoadingSpinner from './components/LoadingSpinner'
import { DarkModeProvider } from './contexts/DarkModeContext'
import { RepositoryProvider } from './contexts/RepositoryContext'
import { FileViewerProvider } from './contexts/FileViewerContext'
import { CommitViewerProvider } from './contexts/CommitViewerContext'

function App() {
    const [user, setUser] = useState(null)
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        checkAuthStatus()
        handleOAuthCallback()
    }, [])

    const checkAuthStatus = async () => {
        try {
            // Check if we have a session token
            if (diffSenseAPI.isAuthenticated()) {
                const userData = await diffSenseAPI.getCurrentUser()
                console.log('Auth status response:', userData)
                setUser(userData)
            }
        } catch (error) {
            console.log('Not authenticated:', error)
            // Clear invalid token
            diffSenseAPI.setSessionToken(null)
        } finally {
            setLoading(false)
        }
    }

    const handleOAuthCallback = async () => {
        // Check if we're returning from GitHub OAuth
        const urlParams = new URLSearchParams(window.location.search)
        const code = urlParams.get('code')
        const state = urlParams.get('state')
        const sessionId = urlParams.get('session_id')
        const authSuccess = urlParams.get('auth_success')

        // Handle different callback patterns
        if (sessionId) {
            // Backend redirected with session_id in URL
            try {
                setLoading(true)
                diffSenseAPI.setSessionToken(sessionId)
                const userData = await diffSenseAPI.getCurrentUser()
                console.log('OAuth success with session_id:', userData)
                setUser(userData)

                // Clean up URL
                window.history.replaceState({}, document.title, window.location.pathname)
            } catch (error) {
                console.error('Failed to get user with session_id:', error)
                diffSenseAPI.setSessionToken(null)
            } finally {
                setLoading(false)
            }
        } else if (authSuccess === 'true') {
            // Backend set session via cookie or other method
            try {
                setLoading(true)
                const userData = await diffSenseAPI.getCurrentUser()
                console.log('OAuth success via cookie:', userData)
                setUser(userData)

                // Clean up URL
                window.history.replaceState({}, document.title, window.location.pathname)
            } catch (error) {
                console.error('Failed to get user after auth_success:', error)
            } finally {
                setLoading(false)
            }
        } else if (code && state) {
            // Frontend needs to handle the OAuth callback (original pattern)
            try {
                setLoading(true)
                const authResult = await diffSenseAPI.handleGitHubCallback(code, state)
                console.log('OAuth callback result:', authResult)

                if (authResult.user) {
                    setUser(authResult.user)
                }

                // Clean up URL
                window.history.replaceState({}, document.title, window.location.pathname)
            } catch (error) {
                console.error('OAuth callback error:', error)
            } finally {
                setLoading(false)
            }
        }
    }

    const handleLogout = async () => {
        try {
            await diffSenseAPI.logout()
        } catch (error) {
            console.error('Logout error:', error)
        } finally {
            setUser(null)
        }
    }

    if (loading) {
        return <LoadingSpinner />
    }    return (
        <DarkModeProvider>
            <RepositoryProvider>
                <FileViewerProvider>
                    <CommitViewerProvider>
                        <div className="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors">
                            {user ? (
                                <Dashboard
                                    user={user}
                                    onLogout={handleLogout}
                                />
                            ) : (
                                <LandingPage />
                            )}
                        </div>
                    </CommitViewerProvider>
                </FileViewerProvider>
            </RepositoryProvider>
        </DarkModeProvider>
    )
}

export default App

```

### frontend/src/config/index.js

```javascript
// API Configuration
export const config = {
  API_BASE_URL: import.meta.env.VITE_API_BASE_URL || 'http://76.125.217.28:8080/api',
  API_TIMEOUT: 120000, // 120 seconds
  
  // Default values for API calls
  DEFAULT_MAX_COMMITS: 50,
  DEFAULT_MAX_RESULTS: 10,
  
  // Risk level thresholds
  RISK_LEVELS: {
    LOW: 0.3,
    MEDIUM: 0.6,
    HIGH: 0.8
  }
}

export default config

```

### frontend/src/components/FileViewer/index.js

```javascript
// Export all portable file viewer components
export { default as PortableFileViewer } from './PortableFileViewer'
export { default as FileViewerModal } from './FileViewerModal'
export { default as FileContentRenderer } from './FileContentRenderer'
export { default as FileViewerDemo } from './FileViewerDemo'

// Export example components
export {
    InlineFileViewer,
    CompactFilePreview,
    FullSizeFileViewer,
    FileLink,
    CommitLink,
    DiffComparison,
    CustomFileViewer
} from './FileViewerExamples'

// Export context and hooks
export { FileViewerProvider, useFileViewer } from '../contexts/FileViewerContext'

// Usage example:
// import { PortableFileViewer, useFileViewer, FileLink } from './components/FileViewer'

```

[43 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]