# Project export: Github Time Machine

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: OpenAI Build Week
- Tagline: GitHub Time Machine helps developers understand how a GitHub repository has evolved over time. Instead of scrolling through hundreds of commits, users can explore code changes, contributor activity.
- Devpost: https://devpost.com/software/github-time-machine
- GitHub: https://github.com/sai-karthik-dev/github-time-machine
- Demo: https://github-time-machine-delta.vercel.app/
- Video: https://www.youtube.com/embed/56b4bIlUa8w?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 4 GitHub contributor(s) — Fernando (80 commits), Sai Karthik (9 commits), foysalpranto121 (3 commits), Vijay Babu (1 commits)

## Devpost submission (written by the team)

### Inspiration

Every GitHub repository tells a story, but that story is often buried beneath thousands of commits, pull requests, and code changes. Understanding how a project evolved can take hours, especially for new contributors or developers exploring open-source projects.

### What it does

GitHub Time Machine is an AI that transforms a repository's commit history into a clear, easy to understand timeline.

### How we built it

We built GitHub Time Machine using OpenAI Codex and GPT-5.6 as the core intelligence behind the project. By integrating with the GitHub API, our application analyzes repository history and uses AI to generate summaries and insights.

### Challenges we ran into

One of our biggest challenges was designing a clean user interface that could present complex repository information in a simple way. We also faced backend integration issues while processing GitHub data efficiently.

### Accomplishments we're proud of

We're proud of successfully building a working AI that can simplify repository history for developers. Overcoming backend challenges, fixing critical bugs within the hackathon timeline were significant achievements for our team.

### What we learned

Throughout this project, we gained hands-on experience integrating with the GitHub API, working with real-world repository data, and AI models like GPT-5.6 and Codex to solve practical developer problems.

### What's next

for GitHub Time Machine This is just the beginning. We plan to make GitHub Time Machine even more intelligent by adding features. Our goal is to become the easiest way for developers to understand any GitHub repository in minutes instead of hours.

## README (from the GitHub repository)

# GitHub Time Machine

> *"Every codebase has a story. Most teams just can't read it."*

We built GitHub Time Machine because we've all been there — staring at a legacy codebase with zero documentation, wondering why that one file has 47 commits by someone who left two years ago. Engineering knowledge gets lost in commit messages, stale wikis, and tribal memory. We wanted to fix that.

## What it does

GitHub Time Machine is an engineering intelligence dashboard. You point it at any public GitHub repo, and it builds a living map of your codebase:

- **Ask questions about the architecture** — the AI reads the actual source files, README, and commit history to answer
- **See the dependency graph** — a force-directed visual showing how files and modules connect
- **Travel through time** — a commit timeline that highlights fixes, merges, and architectural shifts
- **Find the debt** — a heatmap ranking every file by complexity, churn, and risk
- **Simulate changes** — "What happens if I refactor this file?" with blast radius analysis
- **Trace bugs to their origin** — the AI analyzes fix commits and points to the likely culprit
- **Get a refactoring plan** — based on actual commit patterns in your repo

Everything runs on real data. No mocks. No demos. You submit a GitHub URL, the pipeline clones it, parses every file with Tree-sitter, extracts functions and import edges, indexes commits, and stores it all in Supabase.

## How we built it

### The stack

| Layer | Tech | Why |
|-------|------|-----|
| Frontend | Next.js 15, React 19, Tailwind, Canvas | Fast SSR, glass-morphism UI, force-directed graph rendering |
| Backend | FastAPI | Single service handling repos, analysis, auth, and AI — no microservice complexity |
| Database | Supabase (PostgreSQL) | Real-time, RLS, serverless — perfect for a hackathon |
| AI | GPT-5.6 via OpenAI | Powers every intelligent feature |
| Deployment | Railway (backend) + Vercel (frontend) | Zero-config deploys from git pushes |

### How we used Codex + GPT-5.6

**Codex (GitHub Copilot / OpenAI Codex) was our sixth team member.** Throughout the entire hackathon, we used Codex to:

- **Scaffold the FastAPI routes** — Copilot generated the initial endpoint structure, parameter validation with Pydantic, and async patterns. We then refined each route for our specific Supabase schema.
- **Write the Tree-sitter integration** — symbol extraction for Python and JavaScript is complex. Codex handled the grammar queries while we focused on the pipeline orchestration.
- **Debug database queries** — when edge case Supabase queries failed, Copilot suggested the correct OR filters and upsert strategies.
- **Generate the Canvas force-directed graph** — the physics simulation (repulsion, attraction, gravity) was pair-programmed with Codex, iterating on damping coefficients and layout quality.
- **Handle CORS and auth edge cases** — the GitHub OAuth flow with state validation, redirect URI matching, and Supabase session exchange was built alongside Copilot suggestions.
- **Write tests and error handling** — every endpoint has fallback responses. Codex helped ensure no unhandled exceptions would crash the deployed service.

**GPT-5.6 powers the product itself:**

| Feature | GPT-5.6 Role |
|---------|-------------|
| Architect's Memory (Chat) | Grounded Q&A using real repository context — files, README, commits |
| Change Intelligence | Analyzes dependency edges and computes blast radius with risk scoring |
| Bug Origin | Reads fix commits, correlates patterns, identifies the culprit SHA |
| Refactor Planner | Studies commit history and generates actionable step-by-step plans |
| Impact Simulation | Combines graph traversal + AI analysis for "what breaks?" scenarios |

The key insight: we didn't bolt AI onto an existing tool. **The product cannot exist without GPT-5.6.** Every analysis panel that adds real value depends on the model's ability to understand code structure, infer relationships from commit messages, and generate engineering insights that a static analysis tool alone could never produce.

### Architecture

```
┌─────────────────────────────────────────┐
│             Vercel (Frontend)             │
│  Next.js 15 · glass UI · Canvas graph    │
│  Landing page · Dashboard · Auth         │
└──────────────┬──────────────────────────┘
               │  HTTPS
┌──────────────▼──────────────────────────┐
│           Railway (Backend)               │
│  FastAPI · tree-sitter · GitPython       │
│  15 endpoints · rate limiting · CORS     │
└──────────────┬──────────────────────────┘
               │  PostgreSQL
┌──────────────▼──────────────────────────┐
│           Supabase (Database)             │
│  users · repos · commits · files          │
│  edges · chat_history · analyses         │
└──────────────┬──────────────────────────┘
               │  API
┌──────────────▼──────────────────────────┐
│         OpenAI (GPT-5.6 + Codex)          │
│  chat · impact · bug_origin · refactor   │
└─────────────────────────────────────────┘
```

## Getting started

### Prerequisites

- Node.js 18+, Python 3.10+
- OpenAI API key (GPT-5.6)
- Supabase project
- GitHub OAuth App (for login)

### Backend

```bash
cd backend
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Set SUPABASE_URL, SUPABASE_SERVICE_KEY, OPENAI_API_KEY
uvicorn app.main:app --reload --port 8000
```

Then run `backend/database/complete_schema.sql` in the Supabase SQL Editor.

### Frontend

```bash
cd frontend
npm install
cp .env.example .env.local
# Set NEXT_PUBLIC_API_URL=http://localhost:8000
npm run dev
```

### Live deployments

- **Backend**: `https://github-time-machine-production.up.railway.app`
- **Frontend**: `https://github-time-machine-taupe.vercel.app`

## API Endpoints

| Method | Path | Purpose |
|--------|------|---------|
| `POST` | `/repositories/` | Submit a repo for analysis |
| `GET` | `/repositories/` | List analyzed repos |
| `GET` | `/repositories/{id}` | Status + metadata |
| `GET` | `/repositories/{id}/graph` | Dependency graph |
| `GET` | `/repositories/{id}/timeline` | Commit timeline |
| `GET` | `/repositories/{id}/heatmap` | Technical debt |
| `GET` | `/repositories/{id}/file_health` | Per-file health |
| `POST` | `/repositories/{id}/chat` | AI chat |
| `POST` | `/repositories/{id}/impact` | Change simulation |
| `POST` | `/repositories/{id}/bug_origin` | Bug tracker |
| `POST` | `/repositories/{id}/refactor_plan` | Refactor planner |
| `POST` | `/repos/connect` | GitHub OAuth sync |

## What makes this a strong submission

- **AI is the core, not an add-on** — remove GPT-5.6 and the product loses chat, impact analysis, bug origin, and refactor planning. Those four panels are what make the dashboard useful.
- **Codex was used throughout development** — scaffolding, debugging, optimization, edge cases. We coded alongside it, not against it.
- **It's real and working** — deployed on Railway and Vercel. Demo with any public GitHub repo. No smoke and mirrors.
- **It solves a genuine problem** — every engineer has struggled with undocumented codebases. This gives you answers, not just data.
- **Polished UX** — glass-morphism dark theme, force-directed graph, smooth animations. It feels like a product, not a proof of concept.

## Team

We built this in 48 hours for the OpenAI Build Week Hackathon.

| Name | Role | GitHub |
|------|------|--------|
| Sai Karthik | PM — architecture, AI prompt design, testing, demo | @sai-karthik-dev |
| Anmol | Frontend — components, auth, responsive design | @pvtt-anmol2 |
| Pranto | Backend — FastAPI, AI orchestration, Railway | @foysalpranto121 |
| Fernando | Backend — Git analysis, API architecture, endpoints, Vercel | @FerLpz55 |
| Vijay | Database — Supabase, schema, RLS, indexes | @vjbabu3 |
| Rachana | Frontend — UI redesign, landing page, theming | @adhikaryrachana00428-hash |

## License

MIT


## Detected evidence (automated analysis)

Indexed codebase: 97 recognized source files, 351 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- Next.js (technology) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- SQL (language) — detected in the code
- Supabase (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code
- PostgreSQL (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (120 of 427)

```
.gitignore
.idea/.gitignore
.idea/discord.xml
ai/app/__init__.py
ai/app/config.py
ai/app/dependencies.py
ai/app/main.py
ai/app/mock/__init__.py
ai/app/mock/data_provider.py
ai/app/mock/sample_repo.py
ai/app/models/__init__.py
ai/app/models/bug_origin.py
ai/app/models/chat.py
ai/app/models/graph.py
ai/app/models/health.py
ai/app/models/heatmap.py
ai/app/models/impact.py
ai/app/models/refactor_plan.py
ai/app/models/repository.py
ai/app/models/timeline.py
ai/app/prompts/architecture_explain.j2
ai/app/prompts/bug_origin.j2
ai/app/prompts/file_history.j2
ai/app/prompts/impact_analysis.j2
ai/app/prompts/refactor_plan.j2
ai/app/prompts/system.j2
ai/app/routers/__init__.py
ai/app/routers/bug_origin.py
ai/app/routers/chat.py
ai/app/routers/graph.py
ai/app/routers/health.py
ai/app/routers/heatmap.py
ai/app/routers/impact.py
ai/app/routers/refactor_plan.py
ai/app/routers/timeline.py
ai/app/services/__init__.py
ai/app/services/cache.py
ai/app/services/health_analyzer.py
ai/app/services/openai_client.py
ai/app/services/prompt_engine.py
ai/Dockerfile
ai/railway.json
ai/README.md
ai/requirements.txt
backend/.env.example
backend/.gitignore
backend/app/__init__.py
backend/app/core/__init__.py
backend/app/core/config.py
backend/app/core/rate_limit.py
backend/app/core/supabase.py
backend/app/dependencies.py
backend/app/main.py
backend/app/models/__init__.py
backend/app/models/bug_origin.py
backend/app/models/embeddings.py
backend/app/models/health.py
backend/app/models/heatmap.py
backend/app/models/impact.py
backend/app/models/refactor_plan.py
backend/app/models/schemas.py
backend/app/models/tables.py
backend/app/prompts/bug_origin.j2
backend/app/prompts/impact_analysis.j2
backend/app/prompts/refactor_plan.j2
backend/app/routes/__init__.py
backend/app/routes/admin.py
backend/app/routes/ai_endpoints.py
backend/app/routes/health.py
backend/app/routes/repos.py
backend/app/routes/repositories.py
backend/app/services/__init__.py
backend/app/services/chat_service.py
backend/app/services/commit_analyzer.py
backend/app/services/debt_scorer.py
backend/app/services/embedding_generator.py
backend/app/services/file_walker.py
backend/app/services/repo_analyzer.py
backend/app/services/repo_cloner.py
backend/app/services/symbol_extractor.py
backend/app/utils.py
backend/database/complete_schema.sql
backend/database/migration_functions_edges.sql
backend/main.py
backend/nixpacks.toml
backend/pre_seed.py
backend/Procfile
backend/railway.json
backend/README.md
backend/requirements.txt
data/.gitkeep
docs/README.md
frontend/.env.example
frontend/.gitignore
frontend/app/api/auth/github/route.ts
frontend/app/api/auth/signout/route.ts
frontend/app/auth/callback/route.ts
frontend/app/components/ChatPanel.tsx
frontend/app/components/DashboardShell.tsx
frontend/app/components/desert.tsx
frontend/app/components/DesertTimeMachineScroll.tsx
frontend/app/components/ExperienceEnhancements.tsx
frontend/app/components/FileHealthBadge.tsx
frontend/app/components/GraphPanel.tsx
frontend/app/components/HeatmapPanel.tsx
frontend/app/components/ImpactPanel.tsx
frontend/app/components/RefactorPlanner.tsx
frontend/app/components/TimelinePanel.tsx
frontend/app/globals.css
frontend/app/layout.tsx
frontend/app/login/page.tsx
frontend/app/page.tsx
frontend/app/repo/[id]/page.tsx
frontend/app/ui-effects.css
frontend/app/utils/supabase/server.ts
frontend/middleware.ts
frontend/next-env.d.ts
frontend/next.config.ts
frontend/package.json
frontend/postcss.config.mjs
[307 more files omitted for size]
```

### Dependencies

- ai/requirements.txt: fastapi@>=0.115.0, httpx@>=0.27.0, jinja2@>=3.1.0, openai@>=1.50.0, pydantic-settings@>=2.5.0, python-dotenv@>=1.0.0, sse-starlette@>=2.0.0, uvicorn[standard]@>=0.32.0
- backend/requirements.txt: annotated-doc@==0.0.4, annotated-types@==0.7.0, anyio@==4.14.2, certifi@==2026.6.17, cffi@==2.1.0, click@==8.4.2, cryptography@==49.0.0, deprecation@==2.1.0, distro@==1.9.0, fastapi@==0.139.0, gitdb@==4.0.12, GitPython@==3.1.52, h11@==0.16.0, h2@==4.3.0, hpack@==4.2.0, httpcore@==1.0.9, httpx@==0.28.1, hyperframe@==6.1.0, idna@==3.18, jinja2@>=3.1.0, jiter@==0.16.0, multidict@==6.7.1, openai@==2.45.0, packaging@==26.2, postgrest@==2.31.0, propcache@==0.5.2, pycparser@==3.0, pydantic@==2.13.4, pydantic_core@==2.46.4, PyJWT@==2.13.0, python-dotenv@==1.2.2, realtime@==2.31.0, smmap@==5.0.3, sniffio@==1.3.1, starlette@==1.3.1, storage3@==2.31.0, StrEnum@==0.4.15, supabase@==2.31.0, supabase-auth@==2.31.0, supabase-functions@==2.31.0, tqdm@==4.68.4, tree-sitter@==0.26.0, tree-sitter-javascript@==0.25.0, tree-sitter-python@==0.25.0, typing_extensions@==4.16.0, typing-inspection@==0.4.2, uvicorn@==0.51.0, websockets@==15.0.1, yarl@==1.24.2
- frontend/package.json: @heroicons/react@^2.2.0, @supabase/ssr@^0.12.3, @supabase/supabase-js@^2.110.6, @tailwindcss/postcss@^4.1.4, @types/node@^22.15.2, @types/react@^19.1.2, @types/react-dom@^19.1.2, framer-motion@^12.42.2, next@^15.3.1, react@^19.1.0, react-dom@^19.1.0, tailwindcss@^4.1.4, typescript@^5.8.3

### Recent commits (newest first)

- chore: force vercel rebuild with NEXT_PUBLIC_API_URL
- chore: force real rebuild 1784579044
- chore: force Vercel rebuild 1784578932
- fix: backend fixes — rate limiter 429, since_days fix, graph schema total_nodes/edges, unified debt scoring, admin auth, removed debug endpoint
- fix: improve chat system prompt — more conversational, handles limited context better
- Revert "chore: trigger Vercel rebuild"
- chore: trigger Vercel rebuild
- feat: add admin endpoints to list/delete users
- fix: catch Supabase APIError on duplicate repo insert, return existing repo
- fix: return 409 for duplicate repos + frontend handles it gracefully
- fix: hardcode Railway URL fallback in all frontend components, fix chat history
- fix: revert to original submit handler — remove broken duplicate check
- fix: return RepositoryPending (not plain dict) for existing repos to match response_model
- fix: simplify duplicate check — return plain dict to avoid Pydantic validation issues
- fix: add error handling around duplicate repo checks
- fix: handle duplicate repo submission — return existing repo instead of 500
- docs: rewrite README with Codex/GPT-5.6 usage, human tone, submission-ready
- docs: update READMEs with current architecture, endpoints, team roles, and deployment
- fix: restore security filters, prevent blocked messages from persisting in chat
- fix: simplify injection filter, remove NON_CODE_TOPICS, concise system prompt

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

### ai/requirements.txt

```
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
openai>=1.50.0
pydantic-settings>=2.5.0
jinja2>=3.1.0
python-dotenv>=1.0.0
sse-starlette>=2.0.0
httpx>=0.27.0

```

### ai/Dockerfile

```
FROM python:3.12-slim

WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY . .

# Expose port
EXPOSE 8001

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD python -c "import httpx; r = httpx.get('http://localhost:8001/health'); r.raise_for_status()"

# Run with uvicorn
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8001"]

```

### frontend/package.json

```
{
  "name": "github-time-machine",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@heroicons/react": "^2.2.0",
    "@supabase/ssr": "^0.12.3",
    "@supabase/supabase-js": "^2.110.6",
    "framer-motion": "^12.42.2",
    "next": "^15.3.1",
    "react": "^19.1.0",
    "react-dom": "^19.1.0"
  },
  "devDependencies": {
    "@tailwindcss/postcss": "^4.1.4",
    "@types/node": "^22.15.2",
    "@types/react": "^19.1.2",
    "@types/react-dom": "^19.1.2",
    "tailwindcss": "^4.1.4",
    "typescript": "^5.8.3"
  }
}

```

### backend/requirements.txt

```
annotated-doc==0.0.4
annotated-types==0.7.0
anyio==4.14.2
certifi==2026.6.17
cffi==2.1.0
click==8.4.2
cryptography==49.0.0
deprecation==2.1.0
distro==1.9.0
fastapi==0.139.0
gitdb==4.0.12
GitPython==3.1.52
h11==0.16.0
h2==4.3.0
hpack==4.2.0
httpcore==1.0.9
httpx==0.28.1
hyperframe==6.1.0
idna==3.18
jiter==0.16.0
multidict==6.7.1
openai==2.45.0
packaging==26.2
postgrest==2.31.0
propcache==0.5.2
pycparser==3.0
pydantic==2.13.4
pydantic_core==2.46.4
PyJWT==2.13.0
python-dotenv==1.2.2
realtime==2.31.0
smmap==5.0.3
sniffio==1.3.1
starlette==1.3.1
storage3==2.31.0
StrEnum==0.4.15
supabase==2.31.0
supabase-auth==2.31.0
supabase-functions==2.31.0
tqdm==4.68.4
tree-sitter==0.26.0
tree-sitter-javascript==0.25.0
tree-sitter-python==0.25.0
typing-inspection==0.4.2
typing_extensions==4.16.0
uvicorn==0.51.0
websockets==15.0.1
yarl==1.24.2
jinja2>=3.1.0

```

### backend/main.py

```python
from app.main import app

```

### frontend/app/layout.tsx

```typescript
import type { Metadata } from "next";
import { Inter, JetBrains_Mono } from "next/font/google";
import "./globals.css";
import "./ui-effects.css";

const inter = Inter({ variable: "--font-inter", subsets: ["latin"] });
const mono = JetBrains_Mono({ variable: "--font-mono", subsets: ["latin"] });

export const metadata: Metadata = {
  title: "GitHub Time Machine — Engineering Intelligence",
  description: "Understand how your codebase became what it is.",
};

export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
  return <html lang="en"><body className={`${inter.variable} ${mono.variable}`}>{children}</body></html>;
}
// force rebuild 1784578932
// force rebuild 1784579044
// rebuild trigger lun 20 jul 2026 14:45:32 CST

```

### backend/app/main.py

```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.core.config import CORS_ORIGINS
from app.core.rate_limit import rate_limit_middleware
from app.routes.health import router as health_router
from app.routes.repositories import router as repositories_router
from app.routes.repos import router as repos_router
from app.routes.ai_endpoints import router as ai_endpoints_router
from app.routes.admin import router as admin_router

app = FastAPI(title="GitHub Time Machine API", version="0.2.0")

_cors_origins = [o.strip() for o in CORS_ORIGINS.split(",")]
# Browsers reject credentialed requests against a wildcard origin, and CORS
# middleware that advertises both is a common misconfiguration (OWASP).
_allow_credentials = "*" not in _cors_origins

app.add_middleware(
    CORSMiddleware,
    allow_origins=_cors_origins,
    allow_credentials=_allow_credentials,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.middleware("http")(rate_limit_middleware())

app.include_router(health_router)
app.include_router(repositories_router)
app.include_router(repos_router)
app.include_router(ai_endpoints_router)
app.include_router(admin_router)

```

### ai/app/main.py

```python
"""
GitHub Time Machine — AI Orchestration Service

FastAPI application entry point.
Run with: uvicorn app.main:app --reload --port 8001
"""

from __future__ import annotations

import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.config import settings
from app.routers import chat, graph, impact, timeline, heatmap, health, bug_origin, refactor_plan

# ── Logging ─────────────────────────────────────────────────────────────

logging.basicConfig(
    level=logging.DEBUG if settings.debug else logging.INFO,
    format="%(asctime)s │ %(levelname)-7s │ %(name)s │ %(message)s",
    datefmt="%H:%M:%S",
)
logger = logging.getLogger("github-time-machine")


# ── Lifespan ────────────────────────────────────────────────────────────

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Startup / shutdown events."""
    logger.info("🚀  GitHub Time Machine AI service starting…")

    if not settings.openai_api_key:
        logger.warning("⚠️  OPENAI_API_KEY not set — AI endpoints will fail")
    else:
        logger.info("✅  OpenAI key configured (model: %s)", settings.openai_model)

    logger.info("📡  CORS origins: %s", settings.cors_origin_list)
    logger.info("🧪  Using MockDataProvider (demo repo available at repo_id='demo')")

    yield

    logger.info("👋  Shutting down…")


# ── App ─────────────────────────────────────────────────────────────────

app = FastAPI(
    title="GitHub Time Machine — AI Service",
    description="AI-powered engineering intelligence: architecture explanation, "
                "impact simulation, knowledge graph, timeline, and debt heatmap.",
    version="0.1.0",
    lifespan=lifespan,
    docs_url="/docs",
    redoc_url="/redoc",
)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origin_list,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ── Routers ─────────────────────────────────────────────────────────────

app.include_router(chat.router)
app.include_router(graph.router)
app.include_router(impact.router)
app.include_router(timeline.router)
app.include_router(heatmap.router)
app.include_router(health.router)
app.include_router(bug_origin.router)
app.include_router(refactor_plan.router)


# ── Health Check ────────────────────────────────────────────────────────

@app.get("/health", tags=["system"])
async def health():
    """Health check endpoint."""
    return {
        "status": "healthy",
        "service": "github-time-machine-ai",
        "version": "0.1.0",
        "openai_configured": bool(settings.openai_api_key),
        "model": settings.openai_model,
        "data_provider": "mock",
    }


@app.get("/", tags=["system"])
async def root():
    """Root endpoint with API info."""
    return {
        "service": "GitHub Time Machine — AI Orchestration",
        "version": "0.1.0",
        "docs": "/docs",
        "endpoints": {
            "chat": "POST /repos/{repo_id}/chat",
            "graph": "GET /repos/{repo_id}/graph",
            "impact": "POST /repos/{repo_id}/impact",
            "timeline": "GET /repos/{repo_id}/timeline",
            "heatmap": "GET /repos/{repo_id}/heatmap",
            "file_health": "GET /repos/{repo_id}/file_health",
            "bug_origin": "POST /repos/{repo_id}/bug_origin",
            "refactor_plan": "POST /repos/{repo_id}/refactor_plan",
            "health": "GET /health",
        },
    }


```

### frontend/app/page.tsx

```typescript
"use client";

import { useRouter } from "next/navigation";
import Link from "next/link";
import { ArrowRightIcon } from "@heroicons/react/24/outline";
import DesertTimeMachineScroll from "./components/DesertTimeMachineScroll";

export default function Home() {
  const router = useRouter();

  // WIRING UP EVENT HANDLERS TO ORIGINAL SITE DESTINATIONS
  const handleConnectRepository = () => {
    router.push("/login");
  };

  const handleExplorePlatform = () => {
    // Smooth scroll down to the last page (100% scroll depth / Panel 3)
    if (typeof window !== "undefined") {
      window.scrollTo({
        top: window.innerHeight * 8,
        behavior: "smooth",
      });
    }
  };

  const handleTraceDecision = () => {
    // Smooth scroll down to Panel 2 (Platform Feature Trio)
    // 87.5% of 900vh is roughly 7.0 * Viewport Height
    if (typeof window !== "undefined") {
      window.scrollTo({
        top: window.innerHeight * 7.0,
        behavior: "smooth",
      });
    }
  };

  const handleExploreFeature = (index: number) => {
    // Smooth scroll down to the last page (100% scroll depth / Panel 3)
    if (typeof window !== "undefined") {
      window.scrollTo({
        top: window.innerHeight * 8,
        behavior: "smooth",
      });
    }
  };

  const handleConnectGithub = () => {
    router.push("/login");
  };

  const handleMapSystem = () => {
    router.push("/login");
  };

  const handleBuildContext = () => {
    router.push("/login");
  };

  // Nav bar scroll shortcuts
  const handleNavPlatform = (e: React.MouseEvent) => {
    e.preventDefault();
    if (typeof window !== "undefined") {
      window.scrollTo({
        top: window.innerHeight * 7.8,
        behavior: "smooth",
      });
    }
  };

  const handleNavHowItWorks = (e: React.MouseEvent) => {
    e.preventDefault();
    if (typeof window !== "undefined") {
      window.scrollTo({
        top: window.innerHeight * 9,
        behavior: "smooth",
      });
    }
  };

  return (
    <main className="bg-[#0A0A0B] min-h-screen text-white/90 font-sans tracking-tight antialiased selection:bg-white selection:text-black">
      
      {/* Sleek Vercel/Linear-inspired floating glass header */}
      <header className="fixed top-0 left-0 right-0 h-20 flex items-center justify-between px-8 md:px-16 z-50 backdrop-blur-md bg-[#0A0A0B]/20 border-b border-white/10">
        <Link href="/" className="flex items-center gap-2 font-mono text-xs font-bold tracking-widest text-white">
          <span className="flex items-center justify-center w-6 h-6 border border-white/20 rounded text-sm text-white/90">⌁</span>
          GITHUB <span className="text-white/50 font-light">TIME MACHINE</span>
        </Link>
        <nav className="flex items-center gap-8">
          <a 
            href="#platform" 
            onClick={handleNavPlatform}
            className="text-xs text-white/60 hover:text-white transition-colors font-mono tracking-wider"
          >
            PLATFORM
          </a>
          <a 
            href="#how-it-works" 
            onClick={handleNavHowItWorks}
            className="text-xs text-white/60 hover:text-white transition-colors font-mono tracking-wider"
          >
            HOW IT WORKS
          </a>
          <Link 
            href="/login" 
            className="inline-flex items-center gap-1.5 bg-white/5 hover:bg-white/10 text-white text-xs px-4 py-2 rounded-full transition-all border border-white/10 font-mono"
          >
            SIGN IN <ArrowRightIcon className="w-3 h-3" />
          </Link>
        </nav>
      </header>

      {/* Synchronized Canvas Image Scrollytelling visual flow */}
      <DesertTimeMachineScroll 
        onConnectRepository={handleConnectRepository}
        onExplorePlatform={handleExplorePlatform}
        onTraceDecision={handleTraceDecision}
        onExploreFeature={handleExploreFeature}
        onConnectGithub={handleConnectGithub}
        onMapSystem={handleMapSystem}
        onBuildContext={handleBuildContext}
      />

      {/* Restyled Vercel/Linear-inspired Minimalist Footer */}
      <footer className="w-full bg-[#0A0A0B] py-10 px-8 border-t border-white/10 flex flex-col sm:flex-row items-center justify-between gap-4 z-20 relative font-mono text-[10px] text-white/40">
        <div className="flex items-center gap-2">
          <span className="flex items-center justify-center w-5 h-5 border border-white/10 rounded text-[10px]">⌁</span>
          <span>GITHUB TIME MACHINE</span>
        </div>
        <span>Built for engineers who inherit the future.</span>
      </footer>
    </main>
  );
}

```

### frontend/app/login/page.tsx

```typescript
import Link from "next/link";
import { ArrowLeftIcon, ArrowRightIcon, CheckIcon, CircleStackIcon, LockClosedIcon, SparklesIcon } from "@heroicons/react/24/outline";
import { ToastNotification } from "../components/ExperienceEnhancements";
import { Suspense } from "react";

function GitHubMark() { 
  return (
    <svg viewBox="0 0 24 24" className="w-full h-full" aria-hidden="true">
      <path fill="currentColor" d="M12 .7a11.3 11.3 0 0 0-3.57 22.02c.56.1.77-.24.77-.54v-2.1c-3.13.68-3.8-1.33-3.8-1.33-.5-1.3-1.25-1.65-1.25-1.65-1.02-.7.08-.69.08-.69 1.13.08 1.72 1.16 1.72 1.16 1 1.71 2.63 1.22 3.27.94.1-.73.39-1.22.71-1.5-2.5-.29-5.13-1.25-5.13-5.57 0-1.23.44-2.23 1.16-3.02-.12-.28-.5-1.43.11-2.98 0 0 .95-.3 3.1 1.15A10.7 10.7 0 0 1 12 6.9c.96 0 1.93.13 2.83.38 2.16-1.46 3.1-1.15 3.1-1.15.62 1.55.23 2.7.12 2.98.72.8 1.16 1.8 1.16 3.02 0 4.33-2.64 5.27-5.15 5.55.4.35.76 1.03.76 2.08v2.99c0 .3.2.65.78.54A11.3 11.3 0 0 0 12 .7Z"/>
    </svg>
  ); 
}

export default function LoginPage() {
  return (
    <main className="min-h-screen grid grid-cols-1 md:grid-cols-12 bg-[#090D1A] font-sans antialiased text-white selection:bg-indigo-500 selection:text-white select-none">
      
      {/* LEFT COLUMN: DEEP DARK MODE SIDE */}
      <aside className="md:col-span-5 bg-[#090D1A] border-b-4 border-black md:border-b-0 md:border-r-4 md:border-black p-8 md:p-12 flex flex-col justify-between relative overflow-hidden">
        
        {/* Background Grid Pattern for Neobrutalist Depth */}
        <div className="absolute inset-0 bg-[linear-gradient(to_right,#1e293b_1px,transparent_1px),linear-gradient(to_bottom,#1e293b_1px,transparent_1px)] bg-[size:4rem_4rem] [mask-image:radial-gradient(ellipse_60%_50%_at_50%_0%,#000_70%,transparent_100%)] opacity-20 pointer-events-none" />

        {/* Logo/Branding Header */}
        <div className="relative z-10">
          <Link href="/" className="inline-flex items-center gap-2.5 font-mono text-xs font-black tracking-widest text-indigo-300 bg-indigo-950/45 border-2 border-indigo-500/40 p-2.5 shadow-[3px_3px_0px_0px_#6366F1] hover:translate-x-[-1px] hover:translate-y-[-1px] hover:shadow-[4px_4px_0px_0px_#6366F1] active:translate-x-[1px] active:translate-y-[1px] transition-all">
            <span className="text-indigo-400 font-bold text-sm">⌁</span>GITHUB <em className="text-slate-400 font-normal font-sans not-italic">TIME MACHINE</em>
          </Link>
        </div>

        {/* Story & Branding */}
        <div className="my-auto py-10 relative z-10 flex flex-col gap-6">
          <div className="inline-flex items-center gap-1.5 bg-violet-950/50 border-2 border-violet-400/40 px-3 py-1.5 text-[9px] font-mono font-bold tracking-widest text-violet-300 shadow-[2px_2px_0px_0px_rgba(139,92,246,0.3)] w-fit uppercase">
            <SparklesIcon className="w-3.5 h-3.5 text-violet-400" /> Repository Intelligence
          </div>
          
          <h2 className="text-4xl lg:text-5xl font-black tracking-tight leading-none text-white uppercase border-b-4 border-indigo-500/10 pb-4">
            Every pull request<br/>
            has a <span className="text-indigo-400 font-serif italic font-normal lowercase">past.</span>
          </h2>
          
          <p className="text-xs md:text-sm text-slate-400 leading-relaxed max-w-sm font-medium">
            Turn thousands of commits into the context your team needs to make its next move.
          </p>

          {/* Repository Preview Card: Hard Neobrutalist design */}
          <div className="mt-4 bg-[#0D1326] border-4 border-indigo-500 p-6 rounded-none shadow-[8px_8px_0px_0px_#6366F1] flex flex-col gap-5 relative group">
            
            {/* Top row */}
            <div className="flex items-center justify-between border-b-2 border-indigo-950/60 pb-3">
              <span className="flex items-center gap-2 text-xs font-mono font-bold text-indigo-200">
                <span className="w-4 h-4 text-indigo-400"><GitHubMark /></span>
                octo-labs / <strong className="font-extrabold text-white">atlas</strong>
              </span>
              <span className="bg-emerald-950/90 border-2 border-emerald-400 text-emerald-300 rounded-none px-2 py-0.5 text-[9px] font-mono font-black flex items-center gap-1.5 shadow-[2px_2px_0px_0px_#10B981]">
                <i className="w-1.5 h-1.5 rounded-full bg-emerald-400 shadow-[0_0_8px_#34d399] animate-pulse" />
                Analysis ready
              </span>
            </div>

            {/* Branch info */}
            <div className="text-[10px] font-mono text-indigo-300 flex items-center gap-2 bg-indigo-950/30 px-3 py-1.5 border border-indigo-900/40 w-fit">
              <span className="w-1.5 h-1.5 rounded-full border border-emerald-400 bg-transparent inline-block" />
              main <span className="text-indigo-600">·</span> 1,248 commits mapped
            </div>

            {/* Architecture Map Stat */}
            <div className="bg-[#111A35] border-2 border-indigo-500 p-4 flex items-center justify-between gap-3 shadow-[4px_4px_0px_0px_rgba(99,102,241,0.25)] transition-transform group-hover:translate-x-[-1px] group-hover:translate-y-[-1px]">
              <div className="flex items-center gap-3">
                <CircleStackIcon className="w-5 h-5 text-indigo-400 flex-shrink-0" />
                <div className="text-left font-mono">
                  <span className="text-[11px] font-black text-indigo-200 block uppercase tracking-wider">Architecture map</span>
                  <span className="text-[10px] text-slate-400 block mt-0.5">86 modules · 312 dependencies</span>
                </div>
              </div>
              <ArrowRightIcon className="w-4 h-4 text-indigo-400" />
            </div>

            {/* Neobrutalist custom loading progress overlay */}
            <div className="border-2 border-indigo-950 bg-[#070B16] p-4 flex flex-col gap-2.5 font-mono">
              <div className="flex justify-between items-center text-[10px]">
     
[truncated — 6716 more characters]
```

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