# Vibn Architecture

## System Overview

Vibn is an AI-powered development platform that helps developers (especially "vibe coders") manage their projects, track AI usage, monitor costs, and maintain living documentation. The system integrates with multiple tools (Cursor, GitHub, ChatGPT, v0) and provides a unified interface for project management.

---

## Core Components

### 1. **Frontend (Next.js 15 + React 19)**
- User interface for project management
- Real-time AI chat interface
- Design iteration with v0
- Session monitoring & cost tracking

### 2. **Backend (Firebase + GCP)**
- **Firestore**: NoSQL database for projects, users, sessions, analyses
- **Firebase Auth**: User authentication (Email, Google, GitHub)
- **Cloud Storage**: File uploads (logos, documents, exports)
- **Cloud Functions**: Serverless backend logic
- **Data Sovereignty**: Regional deployment (Canada for compliance)

### 3. **Cursor Extension** (Existing)
- Tracks coding sessions in real-time
- Captures AI conversations
- Logs file changes
- Sends data to PostgreSQL (current) → Will migrate to Firebase

### 4. **AI Analysis Pipeline**
- Analyzes code repositories (GitHub)
- Processes ChatGPT conversations
- Extracts tech stack, features, architecture
- Generates project summaries

### 5. **Integrations**
- **GitHub**: Repository access, code analysis
- **ChatGPT (MCP)**: Conversation sync, project docs
- **v0**: UI generation and iteration
- **Railway/GCP**: Deployment automation (future)

---

## Data Architecture

### Firestore Collections

#### `users`
```typescript
{
  uid: string;                    // Firebase Auth UID
  email: string;
  displayName?: string;
  photoURL?: string;
  workspace: string;              // e.g., "marks-account"
  createdAt: Timestamp;
  updatedAt: Timestamp;
}
```

#### `projects`
```typescript
{
  id: string;                     // Auto-generated
  name: string;                   // Project name
  slug: string;                   // URL-friendly slug
  userId: string;                 // Owner
  workspace: string;              // User's workspace
  
  // Product Details
  productName: string;
  productVision?: string;
  isForClient: boolean;
  
  // Connected Services
  hasLogo: boolean;
  hasDomain: boolean;
  hasWebsite: boolean;
  hasGithub: boolean;
  hasChatGPT: boolean;
  githubRepo?: string;
  chatGPTProjectId?: string;
  
  // Metadata
  createdAt: Timestamp;
  updatedAt: Timestamp;
}
```

#### `sessions`
```typescript
{
  id: string;
  projectId: string;
  userId: string;
  
  // Session Data
  startTime: Timestamp;
  endTime?: Timestamp;
  duration?: number;              // seconds
  
  // AI Usage
  model: string;                  // e.g., "claude-sonnet-4"
  tokensUsed: number;
  cost: number;                   // USD
  
  // Context
  filesModified: string[];
  conversationSummary?: string;
  
  createdAt: Timestamp;
}
```

#### `analyses`
```typescript
{
  id: string;
  projectId: string;
  type: 'code' | 'chatgpt' | 'github' | 'combined';
  
  // Analysis Results
  summary: string;
  techStack?: string[];
  features?: string[];
  architecture?: object;
  
  // Raw Data
  rawData?: any;
  
  createdAt: Timestamp;
}
```

#### `designs` (for v0 iterations)
```typescript
{
  id: string;
  projectId: string;
  userId: string;
  
  // Design Details
  pageName: string;
  pageSlug: string;
  v0ChatId: string;
  
  // Versions
  versions: {
    id: string;
    code: string;
    timestamp: Timestamp;
    prompt: string;
  }[];
  
  // Collaboration
  comments: {
    id: string;
    userId: string;
    text: string;
    timestamp: Timestamp;
  }[];
  
  createdAt: Timestamp;
  updatedAt: Timestamp;
}
```

---

## Data Flow Architecture

### 1. **User Onboarding Flow**

```
User signs up
    ↓
Firebase Auth creates user
    ↓
Create Firestore user document
    ↓
Generate workspace (e.g., "john-account")
    ↓
Redirect to /{workspace}/projects
```

### 2. **New Project Flow**

```
User creates project
    ↓
Step 1: Project name + type
    ↓
Step 2: Product vision (optional)
    ↓
Step 3: Product details (logo, domain, GitHub, etc.)
    ↓
Generate slug, check availability
    ↓
Create project document in Firestore
    ↓
Redirect to /{workspace}/{slug}/getting-started
```

### 3. **Project Onboarding Flow**

```
/{workspace}/{slug}/getting-started/connect
    ↓
- Install Cursor Extension
- Connect GitHub (OAuth)
- Connect ChatGPT (MCP) [optional]
    ↓
/{workspace}/{slug}/getting-started/analyze
    ↓
AI analyzes:
- GitHub repository structure & code
- ChatGPT conversations & docs
- Cursor extension session data
    ↓
/{workspace}/{slug}/getting-started/summarize
    ↓
Display AI-generated summary:
- Product vision
- Tech stack
- Key features
    ↓
/{workspace}/{slug}/getting-started/setup
    ↓
Confirmation & redirect to /{workspace}/{slug}/product
```

### 4. **Session Tracking Flow (Cursor Extension)**

```
Developer codes in Cursor
    ↓
Extension tracks in real-time:
- AI model used
- Tokens consumed
- Files modified
- Time elapsed
    ↓
CURRENT: Sends to PostgreSQL
FUTURE: Send to Firebase Cloud Function
    ↓
Cloud Function processes & stores in Firestore
    ↓
Real-time updates in Vibn dashboard
```

### 5. **AI Analysis Pipeline**

```
User connects GitHub + ChatGPT
    ↓
Trigger analysis (Cloud Function or API route)
    ↓
Step 1: Fetch GitHub repository
    - Clone or fetch file tree
    - Identify key files (package.json, etc.)
    - Extract imports, dependencies
    ↓
Step 2: Fetch ChatGPT conversations (via MCP)
    - Access project-specific chats
    - Extract product requirements
    - Identify feature discussions
    ↓
Step 3: Process with AI (Claude/Gemini)
    - Analyze code structure
    - Extract tech stack
    - Identify features
    - Summarize product vision
    ↓
Step 4: Store in Firestore (analyses collection)
    ↓
Display in UI (/{workspace}/{slug}/getting-started/summarize)
```

### 6. **Design Iteration Flow (v0)**

```
User navigates to /{workspace}/{slug}/design
    ↓
Click on a page or create new
    ↓
v0 SDK initializes chat
    ↓
User provides prompt or selects element (Design Mode)
    ↓
v0 generates/updates UI
    ↓
Code rendered in preview
    ↓
User can:
- Comment
- Create version
- Push to Cursor (send code to IDE)
    ↓
All stored in Firestore (designs collection)
```

---

## Integration Architecture

### GitHub Integration

**OAuth Flow:**
```
User clicks "Connect GitHub"
    ↓
Redirect to GitHub OAuth
    ↓
User authorizes Vibn
    ↓
Callback receives access token
    ↓
Store token in Firestore (encrypted)
    ↓
Use token to access repositories
```

**Repository Analysis:**
```
User selects repository
    ↓
Fetch file tree via GitHub API
    ↓
Identify key files:
- package.json / requirements.txt
- README.md
- Config files
    ↓
Extract:
- Dependencies
- Project structure
- Documentation
    ↓
Send to AI for analysis
    ↓
Store results in analyses collection
```

### ChatGPT (MCP) Integration

**Setup:**
```
User installs MCP server for Vibn
    ↓
Vibn MCP server provides resources:
- Project conversations
- Documentation
- Product requirements
    ↓
ChatGPT can read/write via MCP
    ↓
Vibn can also read ChatGPT data via MCP
```

**Data Sync:**
```
User connects ChatGPT project
    ↓
Vibn MCP client fetches conversations
    ↓
Extract product vision, features, requirements
    ↓
AI processes and summarizes
    ↓
Store in analyses collection
```

### v0 Integration

**UI Generation:**
```
User provides design prompt
    ↓
v0 SDK sends to v0 API
    ↓
v0 generates React component
    ↓
Return code + chat ID
    ↓
Store in Firestore (designs collection)
    ↓
Render in preview using @v0-sdk/react
```

**Iteration:**
```
User modifies design (text or Design Mode)
    ↓
Send iteration request with chat ID
    ↓
v0 updates component
    ↓
Create new version
    ↓
Store in versions array
    ↓
Update preview
```

---

## Migration Strategy

### Phase 1: Dual Database (Current)
- PostgreSQL: Existing extension data
- Firebase: New user/project data
- Read from both, write to both

### Phase 2: Firebase Primary
- New sessions → Firebase
- Old sessions → PostgreSQL (read-only)
- Gradually migrate historical data

### Phase 3: Firebase Only
- Deprecate PostgreSQL
- All data in Firebase
- Extension sends directly to Firebase

---

## Security Architecture

### Authentication
- Firebase Auth for user login
- JWT tokens for API authentication
- Session management via Firebase

### Authorization
- Firestore security rules enforce user ownership
- Users can only access their own projects
- Admin SDK for server-side operations

### Data Protection
- Sensitive tokens encrypted in Firestore
- API keys in environment variables
- Regional data storage (Canada for compliance)

### API Security
- CORS configuration for frontend
- Rate limiting on Cloud Functions
- Input validation on all endpoints

---

## Cost Architecture

### Tracking
```
Session started
    ↓
Track: model, start time
    ↓
AI usage captured
    ↓
Calculate cost:
- Input tokens × model price
- Output tokens × model price
    ↓
Store in session document
    ↓
Aggregate by project/user
    ↓
Display in /costs dashboard
```

### Pricing Model (Future)
- Free tier: Limited sessions, basic features
- Pro: Unlimited sessions, all integrations
- Enterprise: Team features, custom deployment, data sovereignty

---

## Deployment Architecture

### Frontend (Next.js)
- **Development**: Local (`npm run dev`)
- **Preview**: Vercel (automatic from GitHub)
- **Production**: Vercel or Cloud Run (GCP credits)

### Backend (Firebase)
- **Firestore**: Canada region (northamerica-northeast1)
- **Cloud Functions**: Same region as Firestore
- **Cloud Storage**: Same region as Firestore

### Cursor Extension
- **Current**: Connects to local PostgreSQL
- **Future**: Connects to Firebase Cloud Function endpoint

### AI Services
- **Claude (Anthropic)**: API calls for analysis
- **Gemini (Google)**: Alternative AI model
- **v0 (Vercel)**: UI generation

---

## Scalability Considerations

### Database
- Firestore scales automatically
- Indexes for common queries
- Denormalization where needed (e.g., project summaries)

### Compute
- Cloud Functions scale to zero
- Pay only for actual usage
- Can migrate to Cloud Run for heavy workloads

### Storage
- Cloud Storage for large files
- CDN for static assets
- Efficient file compression

### Caching
- Firebase SDK caches locally
- API responses cached when appropriate
- Static pages cached at CDN edge

---

## Monitoring & Observability

### Metrics
- Session count per project
- Token usage per model
- Cost tracking per user
- API response times

### Logging
- Firebase logs for all operations
- Cloud Function logs
- Error tracking (Sentry)

### Analytics
- User behavior (Posthog/Mixpanel)
- Feature usage
- Conversion funnels

---

## Next Steps for Implementation

1. ✅ **Auth System** (Complete)
2. **Connect New Project Form to Firebase**
3. **Build AI Analysis Pipeline**
4. **Migrate Cursor Extension to Firebase**
5. **Implement Session Tracking**
6. **Build Cost Dashboard**
7. **GitHub Integration**
8. **ChatGPT MCP Integration**
9. **v0 Design System**
10. **Deployment Automation**

---

## Tech Stack Summary

**Frontend:**
- Next.js 15, React 19, TypeScript
- Tailwind CSS, shadcn/ui
- v0-sdk for design iteration

**Backend:**
- Firebase (Auth, Firestore, Storage, Functions)
- Google Cloud Platform ($100K credits)
- Regional deployment (Canada)

**AI:**
- Claude Sonnet 4 (Anthropic)
- Google Gemini (alternative)
- v0 (UI generation)

**Integrations:**
- GitHub API (repositories)
- ChatGPT MCP (conversations)
- Cursor Extension (sessions)
- Railway API (deployment, future)

**Database:**
- Firestore (primary)
- PostgreSQL (legacy, migration)

**Deployment:**
- Vercel (frontend)
- Cloud Run / Cloud Functions (backend)
- Cloud Storage (files)

---

## Questions to Address

1. **ChatGPT MCP**: How deep should the integration be?
2. **Cursor Extension**: Modify existing or build new?
3. **AI Analysis**: Use Claude, Gemini, or both?
4. **Deployment**: Manual or fully automated?
5. **Pricing**: When to start charging users?
6. **Data Migration**: Automated or manual from PostgreSQL?

---

This architecture is designed to be:
- **Scalable**: Handles growth from 1 to 10,000+ users
- **Cost-effective**: Leverages GCP credits, scales to zero
- **Secure**: Data sovereignty, encryption, proper auth
- **Developer-friendly**: Clean APIs, good DX
- **User-friendly**: Fast, intuitive, beautiful UI

Let's build this! 🚀

