---
name: supabase-rag-knowledge
status: backlog
created: 2025-10-23T08:20:11Z
progress: 0%
prd: .claude/prds/supabase-rag-knowledge.md
github: [Will be updated when synced to GitHub]
---

# Epic: Supabase RAG Knowledge Base System

## Overview

Build a minimal RAG (Retrieval-Augmented Generation) system that enables Vapi voice agents to answer customer-specific questions by querying ingested website content. The system uses Supabase's native pgvector for semantic search, Firecrawl for web scraping, and provides an admin-managed CLI workflow.

**Key Simplification**: Leverage existing Supabase infrastructure and standard Nx patterns. No new deployment targets - CLI runs on admin laptop, Edge Function deploys to Supabase (already configured).

## Architecture Decisions

### 1. Leverage Existing Infrastructure ✅
- **Supabase Already Configured**: Connection string, service role key, storage already in use
- **No New Services**: CLI is local-only (no Railway deployment), Edge Function uses existing Supabase
- **Existing Patterns**: Follow slide-system's Supabase integration patterns

### 2. Minimal CLI Design
- **Node.js CLI**: Simple Nx app (like existing scripts in `apps/`)
- **Run Locally**: Admin executes from laptop (no deployment complexity)
- **Dependencies**: Firecrawl SDK, OpenAI SDK, Supabase JS client, Langchain text splitters
- **Single Command**: `pnpm nx run knowledge-cli:ingest --url=<url> --customer=<id>`

### 3. Supabase Edge Function with Hybrid Search
- **Already Know How**: Follow existing Edge Function patterns from proxy-server
- **Hybrid Search**: Combine semantic (pgvector) + keyword (PostgreSQL FTS)
- **Fusion Algorithm**: Weighted Reciprocal Rank Fusion (RRF) per Supabase docs
  - Uses `websearch_to_tsquery()` for web-style query parsing (supports quotes, OR, negation)
  - Auto-generated tsvector via GENERATED STORED column (updates automatically)
  - HNSW index for fast vector similarity (better than ivfflat per Supabase)
- **Distance Metric**: Cosine distance (`<=>`) operator (default for unknown normalization)
- **Performance Target**: <50ms response time per Vapi requirements
- **Supabase CLI**: Deploy via `supabase functions deploy knowledge-query`
- **Environment**: Uses existing Supabase project and credentials
- **Standard Features**: API key auth, CORS, error handling

### 4. Vapi Integration (API Configuration)
- **API-Only Setup**: Dashboard attachment not available, must use Vapi API
- **Custom Knowledge Base**: POST to `/knowledge-base` endpoint with server URL
- **Request Format**: Vapi sends conversation message history in each request
- **Customer Context**: Extract customer_id from conversation metadata or first message
- **Authentication**: HMAC-SHA256 webhook signature verification via `x-vapi-signature`
- **Response Format**: Return documents array with content + similarity scores

## Technical Specifications

### Key Technical Decisions (Based on Official Docs)

| Decision | Choice | Rationale (from docs) |
|----------|--------|----------------------|
| **Vector Index** | HNSW | "Recommended for robustness against changing data" vs ivfflat |
| **Distance Metric** | Cosine (`<=>`) | Default for unknown normalization; OpenAI embeddings work well |
| **Embedding Model** | OpenAI text-embedding-3-small | 1536 dimensions (well under 2,000 limit), industry standard |
| **Full-Text Search** | PostgreSQL tsvector + GIN | Native, performant, integrates seamlessly with pgvector |
| **Query Parser** | `websearch_to_tsquery()` | Handles quotes, OR, negation automatically (vs manual operators) |
| **Tsvector Generation** | GENERATED STORED column | Auto-updates on INSERT/UPDATE, no manual maintenance |
| **Fusion Algorithm** | Weighted RRF (k=50) | Proven Supabase pattern, tunable weights for semantic vs keyword |
| **Response Format** | Vapi documents array | Required by Vapi custom knowledge base API |
| **Authentication** | HMAC-SHA256 webhook signature | Vapi standard for webhook security |
| **Performance Target** | <50ms query response | Vapi requirement for real-time voice calls |

### OpenAI Embedding Specifications

- **Model**: `text-embedding-3-small`
- **Dimensions**: 1536 (fixed, cannot be changed)
- **Cost**: $0.02 per 1M tokens
- **Performance**: ~1000 tokens/chunk × 100 chunks = $0.002 per ingestion
- **Normalization**: Pre-normalized by OpenAI (good for cosine distance)

### PostgreSQL Full-Text Search Details

**Language Configuration**: English (`to_tsvector('english', text)`)
- Removes stop words (the, and, or, etc.)
- Stems words (running → run, flies → fly)
- Case-insensitive matching

**Query Syntax** (via `websearch_to_tsquery()`):
- `"exact phrase"` - quoted exact matches
- `word1 OR word2` - alternative matches
- `-excluded` - negation with dash
- Automatic AND for space-separated terms

**Ranking** (via `ts_rank()`):
- Higher scores for more keyword matches
- Combined with RRF for final ranking

## Technical Approach

### Database Schema (Supabase Migration)

**Two Simple Tables:**
```sql
-- Customer knowledge base registry
customer_knowledge_base (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  customer_id TEXT NOT NULL,
  name TEXT NOT NULL,
  source_url TEXT NOT NULL,
  status TEXT DEFAULT 'ready',
  pages_count INT,
  chunks_count INT,
  created_at TIMESTAMPTZ DEFAULT NOW()
)

-- Vector chunks with embeddings and full-text search
knowledge_chunks (
  id BIGSERIAL PRIMARY KEY,           -- Required for RRF matching
  kb_id UUID REFERENCES customer_knowledge_base(id) ON DELETE CASCADE,
  customer_id TEXT NOT NULL,           -- Denormalized for fast filtering
  chunk_text TEXT NOT NULL,
  chunk_index INT,
  embedding VECTOR(1536) NOT NULL,     -- Semantic search
  fts TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', chunk_text)) STORED,
  metadata JSONB,  -- {source_url, title}
  created_at TIMESTAMPTZ DEFAULT NOW()
)

-- Hybrid search RPC function (Supabase pattern with weighted RRF)
CREATE OR REPLACE FUNCTION hybrid_search_knowledge(
  query_text TEXT,
  query_embedding VECTOR(1536),
  match_customer_id TEXT,
  match_count INT DEFAULT 5,
  full_text_weight FLOAT DEFAULT 1.0,
  semantic_weight FLOAT DEFAULT 1.0,
  rrf_k INT DEFAULT 50
)
RETURNS TABLE (
  id BIGINT,
  chunk_text TEXT,
  metadata JSONB,
  similarity FLOAT
)
LANGUAGE SQL
AS $$
  WITH semantic_search AS (
    SELECT id, RANK() OVER (ORDER BY embedding <=> query_embedding) AS rank
    FROM knowledge_chunks
    WHERE customer_id = match_customer_id
    ORDER BY embedding <=> query_embedding
    LIMIT LEAST(match_count, 30) * 2
  ),
  keyword_search AS (
    SELECT id, RANK() OVER (ORDER BY ts_rank(fts, websearch_to_tsquery(query_text)) DESC) AS rank
    FROM knowledge_chunks
    WHERE customer_id = match_customer_id
      AND fts @@ websearch_to_tsquery(query_text)
    ORDER BY ts_rank(fts, websearch_to_tsquery(query_text)) DESC
    LIMIT LEAST(match_count, 30) * 2
  )
  SELECT
    knowledge_chunks.id,
    knowledge_chunks.chunk_text,
    knowledge_chunks.metadata,
    COALESCE(1.0 / (rrf_k + semantic_search.rank), 0.0) * semantic_weight +
    COALESCE(1.0 / (rrf_k + keyword_search.rank), 0.0) * full_text_weight AS similarity
  FROM semantic_search
  FULL OUTER JOIN keyword_search ON semantic_search.id = keyword_search.id
  JOIN knowledge_chunks ON knowledge_chunks.id = COALESCE(semantic_search.id, keyword_search.id)
  ORDER BY similarity DESC
  LIMIT match_count;
$$;
```

**Indexes:**
- `knowledge_chunks(customer_id)` - Fast customer filtering (B-tree)
- `knowledge_chunks USING hnsw (embedding vector_cosine_ops)` - Vector search
  - HNSW recommended for "robustness against changing data"
  - Supports up to 2,000 dimensions (OpenAI 1536 is well within limit)
  - Faster than ivfflat for most use cases
- `knowledge_chunks USING gin (fts)` - Full-text search (GIN index on generated tsvector)

### CLI Implementation (knowledge-cli)

**Structure:**
```
apps/knowledge-cli/
├── src/
│   ├── main.ts              # CLI entry point
│   ├── firecrawl.ts         # Web scraping
│   ├── chunker.ts           # Text splitting
│   ├── embedder.ts          # OpenAI embeddings
│   ├── uploader.ts          # Supabase upload
│   └── types.ts             # TypeScript types
├── project.json             # Nx configuration
└── package.json             # Dependencies
```

**Dependencies:**
- `@mendable/firecrawl-js` - Web scraping
- `openai` - Embeddings API
- `@supabase/supabase-js` - Database + Storage
- `langchain` - Text splitters
- `commander` - CLI framework

**Flow:**
1. Parse CLI args (URL, customer_id, optional: max_pages, chunk_size)
2. Scrape website using Firecrawl API (markdown output)
3. Store raw content in Supabase Storage: `customer-docs/{customer_id}/{kb_id}/`
4. Chunk content using RecursiveCharacterTextSplitter (1000 chars, 200 overlap)
5. Generate embeddings using OpenAI (batch 100 at a time)
6. Insert knowledge_base record
7. Bulk insert chunks with embeddings (fts tsvector auto-generated via GENERATED column)
8. Report success (KB ID, chunks created, time taken)

### Edge Function (knowledge-query)

**Structure:**
```
supabase/functions/knowledge-query/
├── index.ts                 # Main handler
└── _shared/
    └── embedder.ts          # Reusable embedding logic
```

**API Contract (Vapi-Compatible):**
```typescript
// Request (from Vapi)
POST /functions/v1/knowledge-query
Headers:
  x-api-key: <secret>
  x-vapi-signature: <hmac-sha256-signature>
Body: {
  message: {
    type: "knowledge-base-request",
    messages: [
      {role: "system", content: "You are helping customer cust_acme"},
      {role: "user", content: "How do I reset password?"}
    ]
  }
}

// Response (Vapi format)
{
  documents: [
    {
      content: "To reset your password...",
      similarity: 0.89,
      uuid: "chunk-id-123"
    }
  ]
}
```

**Logic:**
1. Verify Vapi webhook signature (HMAC-SHA256 with `x-vapi-signature` header)
2. Validate API key (check against Supabase secret)
3. Extract customer_id from system message or conversation metadata
4. Extract query from last user message
5. Generate query embedding via OpenAI text-embedding-3-small (1536 dimensions)
6. Call RPC function: `hybrid_search_knowledge(query_text, embedding, customer_id, 5, 1.0, 1.0, 50)`
   - **Semantic search**: Cosine distance (`<=>`) on 1536-dim embeddings
   - **Keyword search**: `websearch_to_tsquery()` on auto-generated tsvector
   - **RRF fusion**: `score = (1/(k + semantic_rank)) * semantic_weight + (1/(k + keyword_rank)) * keyword_weight`
   - Returns top 5 results sorted by combined score
7. Format results in Vapi documents array format
8. Target response time: <50ms (Vapi requirement for real-time voice)

### Vapi Configuration (via API)

**Create Custom Knowledge Base:**
```bash
curl -X POST https://api.vapi.ai/knowledge-base \
  -H "Authorization: Bearer $VAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "server": {
      "url": "https://<project>.supabase.co/functions/v1/knowledge-query",
      "secret": "<webhook-secret-for-hmac>"
    }
  }'
```

**Attach to Assistant:**
```bash
curl -X PATCH https://api.vapi.ai/assistant/{assistant_id} \
  -H "Authorization: Bearer $VAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "knowledgeBase": {
      "provider": "custom",
      "knowledgeBaseId": "<kb-id-from-above>"
    },
    "model": {
      "provider": "openai",
      "model": "gpt-4",
      "systemPrompt": "You are helping customer_id: {{metadata.customer_id}}"
    }
  }'
```

**Note**: Customer context passed via system prompt, extracted in Edge Function

## Implementation Strategy

### Development Phases

**Phase 1: Database Setup (Single Migration)**
- Create one migration file with both tables, indexes, and RPC function
- Enable pgvector extension (already enabled if not)
- Create storage bucket with RLS policies
- Test with manual INSERT/SELECT

**Phase 2: CLI Tool (Iterative Development)**
- Scaffold Nx app
- Implement scraping → chunking → embedding → upload pipeline
- Add error handling and progress logging
- Test with small website (10 pages)
- Test with larger site (50+ pages)

**Phase 3: Edge Function (Deploy and Test)**
- Create function in supabase/functions/
- Implement API key auth + search logic
- Deploy using Supabase CLI
- Test with curl/Postman
- Verify query performance

**Phase 4: Vapi Integration (Configuration)**
- Configure one test assistant
- Add custom knowledge base settings
- Test voice call with ingested content
- Verify results appear in LLM context

**Phase 5: Customer Launch (Repeat)**
- Ingest 3 customer websites using CLI
- Configure 3 Vapi assistants
- Test each with product-specific questions
- Document any issues or improvements needed

### Risk Mitigation

**Risk: Firecrawl API failure**
- Mitigation: Retry logic, fallback to simpler scraping
- Acceptable: Manual intervention for v1

**Risk: Poor search relevance**
- Mitigation: Tune similarity threshold via CLI parameter
- Contingency: Re-ingest with different chunk size

**Risk: Query latency > 500ms**
- Mitigation: Batch embedding caching, optimize RPC function
- Acceptable: 1-2s is fine for voice calls (LLM takes longer)

### Testing Approach

**Unit Testing:**
- Chunker logic (text splitting correctness)
- Embedding batch logic (100-chunk batching)
- RPC function (similarity search)

**Integration Testing:**
- CLI end-to-end (scrape → embed → upload)
- Edge Function (auth → search → format)
- Vapi assistant (voice call → query → answer)

**Performance Testing:**
- Ingestion: 50 pages < 5 minutes
- Query: < 500ms (embedding + search)
- Concurrent queries: 5 simultaneous

## Task Breakdown Preview

High-level task categories (targeting ≤8 tasks total):

1. **Database Schema & Migration** (5h)
   - Create migration with tables and indexes
   - Add GENERATED tsvector column (auto-updates on INSERT/UPDATE)
   - Implement weighted RRF hybrid search function per Supabase docs
   - Use HNSW index (recommended over ivfflat for better performance)
   - Create storage bucket with RLS policies
   - Test hybrid search manually (semantic + keyword + fusion)

2. **CLI Tool Development** (12h)
   - Scaffold Nx app with dependencies
   - Implement scraping, chunking, embedding pipeline
   - Add Supabase upload (Storage + pgvector)
   - No manual tsvector generation (handled by GENERATED column)
   - Error handling and progress logging

3. **Edge Function Implementation** (8h)
   - Create knowledge-query function
   - Implement auth, embedding generation
   - Call hybrid search RPC (semantic + keyword + RRF)
   - Format combined results for Vapi
   - Deploy to Supabase and test with both search types

4. **Vapi Integration Configuration** (4h)
   - Create custom knowledge base via Vapi API (not dashboard)
   - Configure webhook secret for HMAC signature verification
   - Attach knowledge base to test assistant
   - Configure system prompt to pass customer_id
   - Test voice call integration
   - Verify query flow end-to-end (including signature verification)

5. **Customer Launch (3x)** (6h)
   - Ingest customer #1 website
   - Configure Vapi assistant #1
   - Test and validate
   - Repeat for customers #2 and #3

6. **Documentation & Runbook** (3h)
   - Admin guide for CLI usage
   - Troubleshooting runbook
   - Vapi configuration guide

**Total Estimated: 38 hours (~1 week of focused work)**

**Note**: Using Supabase's recommended hybrid search pattern simplifies implementation:
- GENERATED tsvector column eliminates manual indexing (saves time)
- Pre-built RRF pattern from Supabase docs (copy-paste ready)
- HNSW index provides better performance than ivfflat
- `websearch_to_tsquery()` handles natural language queries automatically
- Cosine distance (`<=>`) works well for OpenAI embeddings (normalized)
- +1h for Vapi API integration (vs dashboard config assumed earlier)

## Dependencies

### External Services
- **Firecrawl API** (Critical) - Web scraping with JS rendering
- **OpenAI API** (Critical) - Embedding generation (text-embedding-3-small)
- **Supabase** (Critical) - Database, Storage, Edge Functions
- **Vapi Platform** (Integration) - Custom knowledge base feature

### Internal Infrastructure
- **Existing Supabase Project** - Connection string, service role key
- **Admin Laptop** - Node.js v22+, pnpm, environment variables
- **Nx Monorepo** - CLI app scaffolding and tooling

### No New Deployments Required
- CLI runs locally (no Railway/Vercel deployment)
- Edge Function deploys to existing Supabase project
- Storage uses existing Supabase account

## Success Criteria (Technical)

### Launch Readiness
1. ✅ **3 customer websites ingested**
   - All pages scraped without errors
   - Vectors stored and queryable
   - Raw content backed up in Storage

2. ✅ **Edge Function deployed and operational**
   - API key authentication working
   - Query latency < 500ms (P95)
   - 99% success rate

3. ✅ **Vapi assistants answering questions**
   - Configured for 3 customers
   - Returns relevant results for test queries
   - Answers match source documentation

4. ✅ **Admin can ingest new sites independently**
   - CLI runs without developer assistance
   - Process takes < 30 minutes end-to-end
   - Documentation is clear and complete

### Quality Gates
- **Relevance**: 80% of test queries return useful results (manual review)
- **Accuracy**: LLM answers match documentation (20 query sample)
- **Performance**: Average query time < 300ms (embedding + search)
- **Reliability**: Zero system errors during testing period

## Estimated Effort

**Total Timeline**: 1 week (5 days)
- Day 1: Database setup + CLI scaffolding
- Days 2-3: CLI development + testing
- Day 3-4: Edge Function + Vapi integration
- Day 5: Customer launch (3 customers)

**Resource Requirements**:
- 1 engineer (full-time focus)
- Admin access to Supabase and Vapi
- 3 customer URLs ready for ingestion

**Critical Path**:
1. Database schema must be finalized first (blocks CLI)
2. CLI must work before Edge Function testing (need data)
3. Edge Function must be deployed before Vapi config (need URL)
4. All above complete before customer launch

**Cost Budget**: ~$20/month operational
- Supabase: $0 (free tier)
- Firecrawl: ~$15 (3 sites × $5)
- OpenAI: ~$5 (embeddings)

## Simplifications from PRD

### Leveraging Existing Infrastructure
- **No new deployment targets**: CLI is local-only, Edge Function uses existing Supabase
- **Standard Nx patterns**: Follow existing CLI app structure (like scripts)
- **Known deployment**: Supabase Edge Functions already understood

### Minimal Feature Set
- **Admin-managed only**: No customer self-service UI (saves 2 weeks)
- **No scheduled re-crawls**: On-demand ingestion only (saves 1 week)
- **Single language**: English-only (no i18n complexity)
- **Hybrid search included**: Semantic + keyword search with RRF fusion (better accuracy)

### Reuse Over Rebuild
- **Supabase client patterns**: Copy from slide-system
- **TypeScript types**: Generate from Supabase schema
- **Error handling**: Use existing logging patterns
- **CLI framework**: Use commander (standard choice)

## Next Steps

After epic approval:
1. Run `/pm:epic-decompose supabase-rag-knowledge` to create detailed tasks
2. Create GitHub issues for tracking
3. Set up development worktree for isolated work
4. Begin Phase 1: Database schema migration
