# Project export: Brydge

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: Cal Hacks 12.0
- Tagline: Presenting Brydge: the AI orchestration platform that turns scattered engineering knowledge into automated workflows, transforming hours of context-switching into just minutes of autonomous execution
- Devpost: https://devpost.com/software/brydge
- GitHub: https://github.com/aprabu/BrydgeCalhacks
- Demo: https://youtu.be/I7pkua3iYAs
- Video: https://www.youtube.com/embed/I7pkua3iYAs?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Y Combinator: Build an Iconic YC Company - 1st Place)
- Team: 1 GitHub contributor(s) — Aadhav Prabu (2 commits)

## Devpost submission (written by the team)

### Overview

The Problem I Witnessed During my internship at NVIDIA, I was surrounded by cutting-edge AI tools: ChatGPT for brainstorming, Cursor for coding, Confluence for documentation, Jira for tracking, Slack for communication. Every tool was powerful individually, but my day became an endless cycle of context-switching: copy error logs from Datadog, paste into ChatGPT, get suggestions, search Confluence for architecture docs, check Jira for related tickets, update GitHub, notify the team in Slack. A simple bug fix that should take just minutes stretched into 2+ hours...not because of coding complexity, but because of coordination overhead. I realized the problem wasn't the tools themselves. It was that they existed in isolation. Each one held a piece of the puzzle, but no one was connecting them. Engineers were spending 50-60% of their time being "human middleware, "manually shuttling information between systems. The Insight What if AI agents could do the context-switching for us? Not just answer questions, but actively orchestrate workflows across tools. Not just search documentation, but pull relevant context from everywhere, synthesize it, and take action. The key was multi-agent orchestration: specialized agents that understood each tool deeply (GitHub, Jira, Slack, Confluence) coordinated by a reasoning agent that understood the bigger picture. The Project Brydge is an AI orchestration platform where one command triggers a cascade of intelligent agents working in parallel: The Architecture: Orchestrator Agent (NVIDIA llama Nemotron reasoning model): Plans multi-step workflows, coordinates sub-agents, handles failures Tool-Specific Agents: GitHub Agent (code analysis + PR creation), Jira Agent (ticket context), Confluence Agent (docs), Slack Agent (notifications), Weaviate Query Agent (semantic search across all sources) Specialized Agents: Analysis Agent (root cause identification), Code Generation Agent (fixes via Claude Code SDK) Human-in-the-Loop Gates: Approval checkpoints before any write action Sample Flow: Manager pings in Slack: "Checkout flow is broken for mobile users" Orchestrator creates execution plan, shows it for approval Agents fan out in parallel: fetch Jira ticket, analyze recent commits, search Confluence docs, semantic search across codebase Analysis Agent synthesizes root cause from all sources Code Generation Agent writes fix using Claude Code SDK User reviews diff → approves GitHub Agent creates PR Confluence Agent updates docs → user approves Slack Agent notifies manager → user approves What took 2 hours manually now takes 3 minutes of orchestrated agent work + 2 minutes of human review. Technical Challenges 1. Multi-Agent Coordination The hardest part was getting agents to work together without stepping on each other. For this, a DAG-based execution model where the Orchestrator determines dependencies (e.g., Code Generation can't start until Analysis completes) and runs independent tasks in parallel. Used asyncio for concurrent execution and Redis for inter-agent communication. 2. Real-Time Streaming Users needed to see what agents were thinking in real-time (chain-of-thought transparency). Implemented WebSocket streaming where each agent broadcasts thoughts, actions, and results. The Claude Agent SDK's built-in streaming callbacks (on_thought, on_tool_use) made this much cleaner than expected. 3. Context Window Management Claude's context limits were a big issue when processing large codebases. Solution: Weaviate Query Agent with semantic search to intelligently retrieve only relevant documents (solving the "retrieve top 25 docs" limitation by using Weaviate's agentic search modes that auto-refine queries). 4. Approval Gate Design Needed human approval before any write action (code changes, PRs, notifications) without blocking the entire workflow. Implemented async approval gates: agent pauses execution, creates approval record in PostgreSQL, sends preview via WebSocket, waits for user decision, then continues or rolls back. The Claude Agent SDK's on_approval_needed hook was perfect for this. 5. Error Handling Across Distributed Agents When one agent fails mid-workflow, how do you recover gracefully? Implemented checkpoint system: each agent step is logged to agent_steps table with status. If Analysis Agent fails, Orchestrator retries up to 3 times. If Code Generation fails, repo clone is cleaned up. If user rejects at any gate, all downstream steps are cancelled and changes are rolled back. Learnings Technical: Multi-agent systems require different architecture than single-agent systems (stateful orchestration, not stateless requests) Real-time streaming is non-negotiable for transparency in agentic systems Human-in-the-loop is essential for trust (fully autonomous is scary, fully manual defeats the purpose) Vector databases (Weaviate) are crucial for context retrieval at scale Sub-agent delegation (Claude Code SDK's feature) mirrors how humans delegate tasks to specialists Product: Engineers don't want "AI magic" they want transparent, controllable automation The value isn't eliminating human judgment, it's eliminating human busywork Showing the agent's reasoning ("chain-of-thought") builds trust Approval gates feel slow but are necessary for adoption What's Next Short-term (next 3 months): Add Datadog and PagerDuty agents for incident response workflows Implement scheduled agent runs (e.g., weekly digest of PR activity) Build admin dashboard for monitoring agent performance across teams Long-term vision: Marketplace for custom agents (let companies build tool-specific agents for internal systems) Agent learning from feedback (when users reject changes, agents learn what patterns to avoid) Proactive agents (not just reactive to user commands, but monitoring for issues and suggesting fixes) The future of engineering isn't replacing developers with AI; it's giving developers AI teammates that handle the coordination busywork so they can focus on creative problem-solving. Brydge is the operating system for that future.

## README (from the GitHub repository)

# Brydge - AI Knowledge Hub

A comprehensive AI-powered knowledge management platform that integrates with various tools (GitHub, Jira, Confluence, Slack) to provide intelligent search and chat capabilities across your organization's data.

## 🚀 Current Status Report

### ✅ Completed Features

#### 1. **Authentication System**
- **User Authentication**: Email/password login with JWT tokens
- **Password Security**: PBKDF2-SHA256 hashing (avoids bcrypt 72-byte limit)
- **Session Management**: JWT tokens with configurable expiration (30 minutes)
- **User Isolation**: All data is user-specific and properly isolated
- **Protected Routes**: Frontend routes require authentication
- **Auto-redirect**: Unauthenticated users redirected to login

#### 2. **OAuth Integration Framework**
- **GitHub OAuth**: Complete OAuth 2.0 flow implementation
- **Extensible Framework**: Base classes for adding new providers (Jira, Confluence, Slack)
- **Security**: CSRF protection via secure state tokens
- **Token Management**: Secure storage and refresh handling
- **User-Specific Brydges**: Each user's integrations are isolated

#### 3. **Brydge Management**
- **CRUD Operations**: Create, read, update, delete brydges
- **Real-time Sync**: Progress tracking during data synchronization
- **Document Cleanup**: Automatic duplicate prevention
- **Enhanced Content**: Metadata-enriched content for better searchability
- **User Isolation**: Users can only access their own brydges

#### 4. **Data Synchronization**
- **GitHub Integration**: Syncs repositories, issues, PRs, commits, code files
- **Vector Storage**: Documents stored in Weaviate for semantic search
- **Database Storage**: Metadata stored in PostgreSQL
- **Progress Tracking**: Real-time sync progress with UI updates
- **Error Handling**: Comprehensive error handling and logging

#### 5. **AI Chat Interface**
- **RAG Implementation**: Retrieval Augmented Generation for contextual answers
- **NVIDIA Nemotron**: Advanced LLM with enhanced reasoning capabilities
- **Semantic Search**: Vector-based document retrieval
- **Source Citations**: Automatic source attribution in responses
- **User Context**: Search limited to user's connected brydges

#### 6. **Frontend Application**
- **React Router**: Client-side navigation with protected routes
- **Dark Mode**: Persistent theme preference across sessions
- **Responsive Design**: Modern UI with Tailwind CSS
- **Real-time Updates**: Live sync progress and status updates
- **User Management**: Profile display and logout functionality

#### 7. **Database Architecture**
- **PostgreSQL**: User data, brydge metadata, document records
- **Weaviate**: Vector database for semantic search and embeddings
- **Redis**: Caching and message broker (configured for Celery)
- **User Isolation**: All data properly scoped to users

#### 8. **Settings & User Management**
- **Settings Page**: Complete user settings interface with profile and password management
- **User Profile Updates**: Update name, email with proper validation
- **Password Management**: Secure password changes with current password verification
- **Brydges Integration**: Direct access to brydge management from settings
- **Consistent UI**: Matches existing design patterns and dark mode support

### 🔄 Current Implementation Details

#### Sync Architecture
- **Hybrid Approach**: Currently uses threading-based sync for immediate response
- **Document Processing**: Enhanced content generation combining title, metadata, and content
- **Vector Storage**: Documents stored with embeddings for semantic search
- **Database Storage**: Original content stored in PostgreSQL for reference
- **Cleanup Process**: Automatic removal of existing documents before sync

#### Authentication Flow
1. User provides email/password on login page
2. Backend validates credentials and issues JWT token
3. Frontend stores token and includes in API requests
4. Protected routes validate token and extract user context
5. All API operations are scoped to the authenticated user

#### OAuth Flow (GitHub)
1. User clicks "Connect" on GitHub brydge
2. Frontend calls backend to initiate OAuth
3. Backend generates secure state token and redirects to GitHub
4. GitHub redirects back with authorization code
5. Backend exchanges code for access token
6. Backend fetches user info and creates brydge
7. User can now sync GitHub data

## 🚧 Pending Features & Improvements

### 1. **Celery Integration for Async Processing**
- **Current**: Threading-based sync (immediate but blocking)
- **Needed**: Celery workers for background processing
- **Benefits**: Non-blocking syncs, better scalability, periodic syncing
- **Implementation**: Configure Celery workers and beat scheduler

### 2. **Weaviate Query Limits**
- **Current**: Limited to 25 documents per query (server-side limit)
- **Issue**: Not all documents are retrievable in search results
- **Solution**: Implement pagination or increase server limits
- **Impact**: Affects search quality and context retrieval

### 3. **Chat History & Context**
- **Current**: No chat history persistence
- **Needed**: Store chat conversations in database
- **Features**: Chat history, conversation context, message threading
- **Implementation**: Chat messages table and context management

### 4. **Enhanced Search Capabilities**
- **Current**: Basic semantic search with limited results
- **Needed**: Hybrid search (semantic + keyword), better ranking
- **Features**: Advanced filters, search suggestions, result highlighting
- **Implementation**: Enhanced vector search and keyword matching

### 5. **Additional Brydge Providers**
- **Current**: Only GitHub implemented
- **Needed**: Jira, Confluence, Slack integrations
- **Framework**: OAuth utilities already created for easy implementation
- **Priority**: High for enterprise adoption

### 6. **Google Sign-In Integration**
- **Current**: Email/password authentication only
- **Needed**: Google OAuth authentication for existing users
- **Features**: Google Sign-In button, account connection in settings
- **Implementation**: Google OAuth endpoints, email matching validation
- **Security**: Google email must match existing user email

### 7. **User Registration & Management**
- **Current**: Manual user creation only
- **Needed**: User registration, password reset, profile management
- **Features**: Self-registration, email verification, password policies
- **Implementation**: Registration endpoints and email service

### 8. **Admin Dashboard**
- **Current**: No admin functionality
- **Needed**: System monitoring, user management, brydge oversight
- **Features**: Usage analytics, error monitoring, system health
- **Implementation**: Admin routes and dashboard UI

## 🤖 Brydge Agents: Multi-Agent Orchestration Platform

### Vision: Agentic MapReduce for Technical Knowledge

Brydge is evolving from a simple RAG chatbot into a **multi-agent orchestration platform** that solves distributed systems challenges in knowledge workflows. Our platform implements "agentic MapReduce" - fanning out hundreds of sub-agents in parallel to search, filter, and synthesize information across multiple tools.

### Current Multi-Agent Architecture

#### Orchestrator Agents
- **Parent Orchestrator**: Coordinates overall sync and query processes
- **Sync Orchestrator**: Manages data synchronization workflows
- **Query Orchestrator**: Handles search and response generation

#### Source-Specific Sub-Agents
- **GitHub Agent**: Repository, issue, PR, and commit processing
- **Jira Agent**: Ticket and project management data extraction
- **Confluence Agent**: Documentation and knowledge base processing
- **Slack Agent**: Message and channel content analysis

#### Processing Sub-Agents
- **Document Parser Agent**: Content extraction and normalization
- **Embedding Agent**: Vector generation for semantic search
- **Deduplication Agent**: Content deduplication and cleanup
- **Enhancement Agent**: Metadata enrichment and context building

#### Que

[README truncated for size]

## Detected evidence (automated analysis)

Indexed codebase: 121 recognized source files, 1544 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
- JavaScript (language) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Redis (technology) — detected in the code
- Streamlit (technology) — detected in the code
- Tailwind CSS (technology) — detected in the code
- TypeScript (language) — detected in the code

## Codebase structure (from repository index)

### Files (120 of 147)

```
.DS_Store
alembic.ini
alembic/__init__.py
alembic/env.py
app.json
Aptfile
backend/alembic.ini
backend/alembic/__init__.py
backend/alembic/env.py
backend/alembic/script.py.mako
backend/alembic/versions/2025_01_15_1200-change_doc_metadata_to_jsonb.py
backend/alembic/versions/2025_10_23_1002-bfa6d7a6d839_add_agent_execution_models.py
backend/app/__init__.py
backend/app/agents/__init__.py
backend/app/agents/analysis_agent.py
backend/app/agents/approval.py
backend/app/agents/base.py
backend/app/agents/code_gen_agent.py
backend/app/agents/confluence_agent.py
backend/app/agents/github_agent.py
backend/app/agents/jira_agent.py
backend/app/agents/nat_bridge.py
backend/app/agents/orchestrator.py
backend/app/agents/README.md
backend/app/agents/slack_agent.py
backend/app/agents/weaviate_agent.py
backend/app/api/__init__.py
backend/app/api/auth.py
backend/app/api/brydges.py
backend/app/api/chat.py
backend/app/api/mcp_server.py
backend/app/api/oauth_base.py
backend/app/api/oauth_unified.py
backend/app/api/oauth.py
backend/app/api/query.py
backend/app/api/websocket.py
backend/app/brydges/__init__.py
backend/app/brydges/base.py
backend/app/brydges/confluence.py
backend/app/brydges/github.py
backend/app/brydges/jira.py
backend/app/brydges/slack.py
backend/app/config.py
backend/app/db/__init__.py
backend/app/db/database.py
backend/app/db/seed_demo_data.py
backend/app/db/vector_store.py
backend/app/main.py
backend/app/main.py.bak
backend/app/middleware/websocket_auth.py
backend/app/models/__init__.py
backend/app/models/agent_execution.py
backend/app/models/agent_step.py
backend/app/models/approval_gate.py
backend/app/models/base.py
backend/app/models/brydge.py
backend/app/models/chat.py
backend/app/models/document.py
backend/app/models/user.py
backend/app/providers/__init__.py
backend/app/providers/confluence_provider.py
backend/app/providers/github_provider.py
backend/app/providers/jira_provider.py
backend/app/providers/README.md
backend/app/providers/registry.py
backend/app/providers/slack_provider.py
backend/app/schemas/__init__.py
backend/app/services/__init__.py
backend/app/services/embeddings.py
backend/app/services/llm.py
backend/app/services/search.py
backend/app/utils/__init__.py
backend/app/utils/oauth_utils.py
backend/app/workers/__init__.py
backend/app/workers/celery_app.py
backend/app/workers/embedding_tasks.py
backend/app/workers/sync_tasks.py
backend/celerybeat-schedule
backend/DEPLOYMENT.md
backend/Dockerfile
backend/package.json
backend/README.md
backend/requirements.txt
backend/static/assets/index-BYI9Wfa2.js
backend/static/assets/index-iHA-jWYG.css
backend/static/index.html
backend/static/site-BwHFeIBa.webmanifest
backend/tests/__init__.py
backend/verify_claude.sh
debug_dashboard.py
deploy.sh
DEPLOYMENT.md
docker-compose.yml
Dockerfile
frontend-v2/.gitignore
frontend-v2/eslint.config.js
frontend-v2/index.html
frontend-v2/package.json
frontend-v2/postcss.config.js
frontend-v2/public/site-BwHFeIBa.webmanifest
frontend-v2/README.md
frontend-v2/src/App.tsx
frontend-v2/src/components/ChatInterface.tsx
frontend-v2/src/components/Message.tsx
frontend-v2/src/components/ProtectedRoute.tsx
frontend-v2/src/components/Sidebar.tsx
frontend-v2/src/components/SourceCard.tsx
frontend-v2/src/contexts/AuthContext.tsx
frontend-v2/src/contexts/DarkModeContext.tsx
frontend-v2/src/hooks/useTypingAnimation.ts
frontend-v2/src/index.css
frontend-v2/src/lib/api.ts
frontend-v2/src/main.tsx
frontend-v2/src/pages/BrydgesPage.tsx
frontend-v2/src/pages/ChatPage.tsx
frontend-v2/src/pages/DashboardPage.tsx
frontend-v2/src/pages/LandingPage.tsx
frontend-v2/src/pages/LoginPage.tsx
frontend-v2/src/pages/SearchPage.tsx
frontend-v2/src/pages/SettingsPage.tsx
[27 more files omitted for size]
```

### Dependencies

- backend/package.json: @anthropic-ai/claude-code@latest
- backend/requirements.txt: aiohttp@>=3.13.0, alembic@==1.13.1, anthropic@==0.18.0, asyncpg@==0.29.0, bcrypt@==4.0.1, black@==24.1.1, celery@==5.3.6, claude-agent-sdk@==0.1.5, email-validator@==2.1.0, fastapi@>=0.115.0, flake8@==7.0.0, httpx@>=0.28.0, mypy@==1.8.0, numpy@==1.26.3, nvidia-nat@>=1.2.0, nvidia-nat-mcp@>=1.0.0, openai@>=2.6.0, pandas@==2.1.4, passlib[bcrypt]@==1.7.4, psycopg2-binary@==2.9.9, pydantic@>=2.10.0, pydantic-settings@>=2.5.2, pytest@==7.4.4, pytest-asyncio@==0.23.3, python-dateutil@==2.8.2, python-dotenv@>=1.1.1, python-jose[cryptography]@==3.3.0, python-multipart@>=0.0.20, PyYAML@==6.0.1, redis@==5.0.1, sqlalchemy@==2.0.25, tiktoken@>=0.12.0, uvicorn[standard]@>=0.32.0, weaviate-client@>=4.17.0, websockets@>=12.0
- frontend-v2/package.json: @eslint/js@^9.36.0, @tailwindcss/postcss@^4.1.14, @types/node@^24.7.1, @types/react@^19.1.16, @types/react-dom@^19.1.9, @vitejs/plugin-react@^5.0.4, autoprefixer@^10.4.21, axios@^1.12.2, eslint@^9.36.0, eslint-plugin-react-hooks@^5.2.0, eslint-plugin-react-refresh@^0.4.22, globals@^16.4.0, lucide-react@^0.545.0, postcss@^8.5.6, react@^19.1.1, react-dom@^19.1.1, react-markdown@^10.1.0, react-router-dom@^7.9.4, remark-gfm@^4.0.1, tailwindcss@^4.1.14, typescript@~5.9.3, typescript-eslint@^8.45.0, vite@^7.1.7
- frontend/requirements.txt: pandas@==2.1.4, python-dotenv@==1.0.0, requests@==2.31.0, streamlit@==1.31.0
- requirements.txt: aiohttp@==3.9.1, alembic@==1.13.1, anthropic@==0.18.0, asyncpg@==0.29.0, bcrypt@==4.0.1, black@==24.1.1, celery@==5.3.6, email-validator@==2.1.0, fastapi@==0.109.0, flake8@==7.0.0, gunicorn@==21.2.0, httpx@==0.26.0, mypy@==1.8.0, numpy@==1.26.3, openai@==1.10.0, pandas@==2.1.4, passlib[bcrypt]@==1.7.4, psycopg2-binary@==2.9.9, pydantic@==2.5.3, pydantic-settings@==2.1.0, pytest@==7.4.4, pytest-asyncio@==0.23.3, python-dateutil@==2.8.2, python-dotenv@==1.0.0, python-jose[cryptography]@==3.3.0, python-multipart@==0.0.6, PyYAML@==6.0.1, redis@==5.0.1, sqlalchemy@==2.0.25, tiktoken@==0.5.2, uvicorn[standard]@==0.27.0, weaviate-client@==4.4.0

### Recent commits (newest first)

- Calhacks submission
- Calhacks submission

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

### DEPLOYMENT.md

```markdown
# Brydge Heroku Deployment Guide

This guide will help you deploy Brydge to Heroku.

## Prerequisites

1. **Heroku CLI** installed and logged in
2. **Git** repository initialized
3. **Required API Keys**:
   - NVIDIA API key (for LLM)
   - GitHub OAuth credentials
   - Weaviate instance URL (or use Weaviate Cloud Services)

## Step 1: Prepare Your Repository

Make sure your code is committed to Git:

```bash
git add .
git commit -m "Prepare for Heroku deployment"
```

## Step 2: Create Heroku App

```bash
# Create the app
heroku create your-app-name

# Add required addons
heroku addons:create heroku-postgresql:mini
heroku addons:create heroku-redis:mini
```

## Step 3: Set Environment Variables

Set all required environment variables:

```bash
# Core settings
heroku config:set SECRET_KEY="$(openssl rand -base64 32)"
heroku config:set ENVIRONMENT=production
heroku config:set LLM_PROVIDER=nvidia

# NVIDIA API
heroku config:set NVIDIA_API_KEY="your_nvidia_api_key"
heroku config:set NVIDIA_BASE_URL="https://integrate.api.nvidia.com/v1"
heroku config:set NVIDIA_MODEL="nvidia/llama-3_3-nemotron-super-49b-v1_5"
heroku config:set NVIDIA_EMBEDDING_MODEL="nvidia/nv-embedqa-e5-v5"

# GitHub OAuth
heroku config:set GITHUB_CLIENT_ID="your_github_client_id"
heroku config:set GITHUB_CLIENT_SECRET="your_github_client_secret"

# Slack OAuth
heroku config:set SLACK_CLIENT_ID="your_slack_client_id"
heroku config:set SLACK_CLIENT_SECRET="your_slack_client_secret"
heroku config:set SLACK_SIGNING_SECRET="your_slack_signing_secret"

# Weaviate (use Weaviate Cloud Services or self-hosted)
heroku config:set WEAVIATE_URL="https://your-weaviate-instance.weaviate.network"

# Application URLs
heroku config:set FRONTEND_URL="https://your-app-name.herokuapp.com"
heroku config:set BACKEND_URL="https://your-app-name.herokuapp.com"
```

## Step 4: Configure OAuth Providers

### GitHub OAuth
1. Go to GitHub Developer Settings
2. Create a new OAuth App
3. Set Authorization callback URL to: `https://your-app-name.herokuapp.com/api/oauth/github/callback`
4. Copy the Client ID and Secret to Heroku config

### Slack OAuth
1. Go to [Slack API](https://api.slack.com/apps)
2. Create a new app and configure OAuth
3. Set redirect URL to: `https://your-app-name.herokuapp.com/api/oauth/slack/callback`
4. Add required scopes (see SLACK_SETUP.md for details)
5. Copy the Client ID and Secret to Heroku config

## Step 5: Set Up Weaviate

### Option A: Weaviate Cloud Services (Recommended)
1. Sign up at [Weaviate Cloud Services](https://console.weaviate.cloud/)
2. Create a new cluster
3. Get the cluster URL and set it as `WEAVIATE_URL`

### Option B: Self-hosted Weaviate
You'll need to deploy Weaviate separately (not on Heroku due to resource constraints).

## Step 6: Deploy to Heroku

```bash
# Deploy the app
git push heroku main

# Run database migrations
heroku run "cd backend && alembic upgrade head"

# Scale the dynos
heroku ps:scale web=1 worker=1 beat=1
```

## Step 7: Create Initial User


[truncated — 2032 more characters]
```

### SLACK_SETUP.md

```markdown
# Slack OAuth Setup Guide

This guide will help you set up Slack OAuth integration for Brydge.

## Prerequisites

1. A Slack workspace where you have admin permissions
2. Access to your Heroku app configuration
3. Your Brydge app deployed and running

## Step 1: Create a Slack App

1. Go to [Slack API](https://api.slack.com/apps)
2. Click "Create New App"
3. Choose "From scratch"
4. Enter app name: "Brydge AI Knowledge Hub"
5. Select your workspace
6. Click "Create App"

## Step 2: Configure OAuth & Permissions

### Basic Information
1. Go to "Basic Information" in the left sidebar
2. Note down your **Client ID** and **Client Secret**
3. Add a description: "AI-powered knowledge orchestration for engineering teams"

### OAuth & Permissions
1. Go to "OAuth & Permissions" in the left sidebar
2. Add the following redirect URLs:
   - `https://your-app-name.herokuapp.com/api/oauth/slack/callback`
   - Replace `your-app-name` with your actual Heroku app name

3. Scroll down to "Scopes" and add these **User Token Scopes**:
   ```
   channels:read      # View basic information about public channels
   groups:read        # View basic information about private channels  
   im:read           # View basic information about direct messages
   mpim:read         # View basic information about group direct messages
   users:read        # View people in a workspace
   channels:history  # View messages in public channels
   groups:history    # View messages in private channels
   im:history        # View messages in direct messages
   mpim:history      # View messages in group direct messages
   im:write          # Start direct messages with people
   ```

4. **Important**: Do NOT add any Bot Token Scopes for this integration

## Step 3: Configure Heroku Environment Variables

Set the following environment variables in your Heroku app:

```bash
# Slack OAuth credentials
heroku config:set SLACK_CLIENT_ID="your_slack_client_id"
heroku config:set SLACK_CLIENT_SECRET="your_slack_client_secret"

# Optional: Slack signing secret (for webhooks if you add them later)
heroku config:set SLACK_SIGNING_SECRET="your_slack_signing_secret"
```

## Step 4: Test the Integration

1. Deploy your updated code to Heroku
2. Go to your Brydge app
3. Navigate to the Brydges page
4. Click "Connect" on the Slack brydge
5. Complete the OAuth flow
6. Check the sync status

## Troubleshooting

### Common Issues

#### 1. "Invalid redirect URI" error
- Ensure the redirect URI in your Slack app exactly matches: `https://your-app-name.herokuapp.com/api/oauth/slack/callback`
- Check for typos in the URL
- Make sure you're using HTTPS

#### 2. "Missing scope" error
- Verify all required scopes are added in your Slack app
- Make sure you're using **User Token Scopes**, not Bot Token Scopes
- Reinstall the app to your workspace after adding scopes

#### 3. "No conversations found" warning
- Check if your Slack token has access to channels
- Verify the user has joined some channels
- Check if the work
[truncated — 2158 more characters]
```

### package.json

```
{
  "name": "brydge-fullstack",
  "version": "1.0.0",
  "description": "Brydge AI Knowledge Hub - Full Stack Application",
  "scripts": {
    "build": "cd frontend-v2 && npm ci && npm run build",
    "postinstall": "npm run build"
  },
  "engines": {
    "node": ">=20.0.0",
    "npm": ">=8.0.0"
  }
}

```

### requirements.txt

```
# FastAPI and web framework
fastapi==0.109.0
uvicorn[standard]==0.27.0
python-multipart==0.0.6
pydantic==2.5.3
pydantic-settings==2.1.0

# Database
sqlalchemy==2.0.25
alembic==1.13.1
psycopg2-binary==2.9.9
asyncpg==0.29.0
gunicorn==21.2.0

# Redis and Celery
redis==5.0.1
celery==5.3.6

# Vector Database
weaviate-client==4.4.0

# LLM and Embeddings
openai==1.10.0
anthropic==0.18.0
# claude-agent-sdk  # TODO: Re-enable when Node.js buildpack is working
tiktoken==0.5.2

# HTTP clients
httpx==0.26.0
aiohttp==3.9.1

# Authentication
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
bcrypt==4.0.1
python-dotenv==1.0.0

# Data processing
pandas==2.1.4
numpy==1.26.3

# Utilities
python-dateutil==2.8.2
PyYAML==6.0.1

# Testing (optional, but recommended)
pytest==7.4.4
pytest-asyncio==0.23.3
httpx==0.26.0

# Code quality (optional)
black==24.1.1
flake8==7.0.0
mypy==1.8.0

email-validator==2.1.0

```

### Dockerfile

```
# Multi-stage build for Brydge AI Knowledge Hub
FROM node:20-alpine AS frontend-builder

# Build frontend
WORKDIR /app/frontend
COPY frontend-v2/package*.json ./
RUN npm ci --only=production
COPY frontend-v2/ ./
RUN npm run build

# Python backend stage
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    libpq-dev \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copy backend requirements and install Python dependencies
COPY backend/requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copy backend code
COPY backend/ ./

# Copy built frontend from previous stage
COPY --from=frontend-builder /app/frontend/dist ./static

# Create necessary directories
RUN mkdir -p /app/logs

# Expose port (Heroku will set PORT env var)
EXPOSE 8000

# Default command
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

```

### docker-compose.yml

```yaml
#version: '3.8'

services:
  # PostgreSQL Database
  postgres:
    image: postgres:15-alpine
    container_name: knowledge_postgres
    environment:
      POSTGRES_USER: knowledge_user
      POSTGRES_PASSWORD: knowledge_pass
      POSTGRES_DB: knowledge_db
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U knowledge_user"]
      interval: 10s
      timeout: 5s
      retries: 5

  # Redis for Celery
  redis:
    image: redis:7-alpine
    container_name: knowledge_redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

  # Weaviate Vector Database (alternative to Pinecone for local)
  weaviate:
    image: semitechnologies/weaviate:1.24.1
    container_name: knowledge_weaviate
    ports:
      - "8080:8080"
    environment:
      QUERY_DEFAULTS_LIMIT: 25
      AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
      PERSISTENCE_DATA_PATH: '/var/lib/weaviate'
      DEFAULT_VECTORIZER_MODULE: 'none'
      CLUSTER_HOSTNAME: 'node1'
    volumes:
      - weaviate_data:/var/lib/weaviate

  # FastAPI Backend
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: knowledge_backend
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://knowledge_user:knowledge_pass@postgres:5432/knowledge_db
      - REDIS_URL=redis://redis:6379/0
      - WEAVIATE_URL=http://weaviate:8080
      - LLM_PROVIDER=${LLM_PROVIDER}
      - NVIDIA_API_KEY=${NVIDIA_API_KEY}
      - NVIDIA_BASE_URL=${NVIDIA_BASE_URL}
      - NVIDIA_MODEL=${NVIDIA_MODEL}
      - NVIDIA_EMBEDDING_MODEL=${NVIDIA_EMBEDDING_MODEL}
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - GITHUB_CLIENT_ID=${GITHUB_CLIENT_ID}
      - GITHUB_CLIENT_SECRET=${GITHUB_CLIENT_SECRET}
      - SLACK_CLIENT_ID=${SLACK_CLIENT_ID}
      - SLACK_CLIENT_SECRET=${SLACK_CLIENT_SECRET}
      - BACKEND_URL=${BACKEND_URL}
      - FRONTEND_URL=${FRONTEND_URL}
      - SECRET_KEY=${SECRET_KEY:-your-secret-key-change-in-production}
      - ENVIRONMENT=development
    volumes:
      - ./backend:/app
      - backend_cache:/root/.cache
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
      weaviate:
        condition: service_started
    command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload

  # Celery Worker
  celery_worker:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: knowledge_celery_worker
    environment:
      - DATABASE_URL=postgresql://knowledge_user:knowledge_pass@postgres:5432/knowledge_db
      - REDIS_URL=redis://redis:6379/0
      - WEAVIATE_URL=http://weaviate:8080
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - ENVIRONMENT=development
    volumes:
      - ./backend:/app
    depends_on:
      - redis
      - postgres
    command: celery -A app.workers.celery_app worker --loglevel=info

  # Celery Beat (for scheduled tasks)
  celery_beat:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: knowledge_celery_beat
    environment:
      - DATABASE_URL=postgresql://knowledge_user:knowledge_pass@postgres:5432/knowledge_db
      - REDIS_URL=redis://redis:6379/0
      - WEAVIATE_URL=http://weaviate:8080
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - ENVIRONMENT=development
    volumes:
      - ./backend:/app
    depends_on:
      - redis
      - postgres
    command: celery -A app.workers.celery_app beat --loglevel=info

  # Streamlit Frontend (Simple MVP UI)
  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    container_name: knowledge_frontend
    ports:
      - "8501:8501"
    environment:
      - BACKEND_URL=http://backend:8000
    volumes:
      - ./frontend:/app
    depends_on:
      - backend
    command: streamlit run app.py --server.address=0.0.0.0

  # New React frontend
  frontend-v2:
    image: node:20-alpine
    container_name: knowledge_frontend_v2
    working_dir: /app
    ports:
      - "5173:5173"
    environment:
      - VITE_API_URL=http://localhost:8000
    volumes:
      - ./frontend-v2:/app
      - /app/node_modules
    command: sh -c "npm install && npm run dev -- --host"
    depends_on:
      - backend

volumes:
  postgres_data:
  redis_data:
  weaviate_data:
  backend_cache:
```

### frontend/requirements.txt

```
streamlit==1.31.0
requests==2.31.0
python-dotenv==1.0.0
pandas==2.1.4
```

### frontend/Dockerfile

```
FROM python:3.11-slim

WORKDIR /app

# Copy requirements
COPY requirements.txt .

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

# Copy application
COPY . .

# Expose Streamlit port
EXPOSE 8501

# Change this line:
CMD ["python", "-m", "streamlit", "run", "app.py", "--server.address=0.0.0.0"]
```

### backend/package.json

```
{
  "name": "brydge-backend",
  "version": "1.0.0",
  "description": "Brydge AI Knowledge Hub - Backend Services",
  "engines": {
    "node": "18.x",
    "npm": "8.x"
  },
  "dependencies": {
    "@anthropic-ai/claude-code": "latest"
  },
  "scripts": {
    "postinstall": "echo 'Claude CLI installed successfully'"
  }
}

```

### backend/requirements.txt

```
# FastAPI and web framework
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
python-multipart>=0.0.20
pydantic>=2.10.0
pydantic-settings>=2.5.2
websockets>=12.0

# Database
sqlalchemy==2.0.25
alembic==1.13.1
psycopg2-binary==2.9.9
asyncpg==0.29.0

# Redis and Celery
redis==5.0.1
celery==5.3.6

# Vector Database
weaviate-client>=4.17.0

# LLM and Embeddings
openai>=2.6.0
anthropic==0.18.0
claude-agent-sdk==0.1.5
tiktoken>=0.12.0

# NVIDIA NeMo Agent Toolkit
nvidia-nat>=1.2.0
nvidia-nat-mcp>=1.0.0

# HTTP clients
httpx>=0.28.0
aiohttp>=3.13.0

# Authentication
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
bcrypt==4.0.1
python-dotenv>=1.1.1

# Data processing
pandas==2.1.4
numpy==1.26.3

# Utilities
python-dateutil==2.8.2
PyYAML==6.0.1

# Testing (optional, but recommended)
pytest==7.4.4
pytest-asyncio==0.23.3

# Code quality (optional)
black==24.1.1
flake8==7.0.0
mypy==1.8.0

email-validator==2.1.0
# Trigger deployment for claude-agent-sdk dependency

```

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