# Slidev Database Schema Documentation

**Created:** 2025-10-08
**Migration:** `002_slidev_schema.sql`
**Status:** Ready for deployment

---

## Overview

The Slidev schema consists of two tables for managing presentation deck metadata and remote control commands:

1. **`slidev_decks`** - Stores deck metadata (NOT presentation content)
2. **`slide_control_commands`** - Remote control commands broadcast via Realtime

### Key Architecture Decisions

- **Separation of Concerns**: Database stores metadata only; presentation content (markdown/HTML) is served via slide-server at `https://slides.buzztrail.ai/d/{deckId}`
- **Security Model**: Deck metadata is service-role-only; control commands are readable by anonymous/authenticated users for Realtime subscriptions
- **Realtime Integration**: Control commands are broadcast via Supabase Realtime for synchronized slide navigation

---

## Tables

### 1. `slidev_decks`

Stores metadata about generated presentation decks.

#### Schema

| Column             | Type         | Constraints        | Description                                      |
| ------------------ | ------------ | ------------------ | ------------------------------------------------ |
| `id`               | UUID         | PRIMARY KEY        | Auto-generated UUID                              |
| `deck_id`          | TEXT         | UNIQUE NOT NULL    | Unique identifier used in URLs                   |
| `session_id`       | UUID         | FK (nullable)      | References `conversation_sessions(id)`           |
| `template_id`      | TEXT         | NOT NULL           | Template/theme used (default: 'starter')         |
| `generation_data`  | JSONB        | -                  | Generation metadata (insights, customization)    |
| `created_at`       | TIMESTAMPTZ  | DEFAULT NOW()      | Creation timestamp                               |
| `updated_at`       | TIMESTAMPTZ  | DEFAULT NOW()      | Last update timestamp (auto-updated)             |

#### Indexes

- `idx_slidev_decks_deck_id` - Fast lookups by deck_id (most common query)
- `idx_slidev_decks_session_id` - Lookup decks by session (partial index)
- `idx_slidev_decks_template_id` - Template analytics

#### Example `generation_data` Structure

```json
{
  "company_name": "Acme Corporation",
  "industry": "SaaS",
  "template": "starter",
  "slides_generated": 12,
  "customization": {
    "pain_points_slide": true,
    "roi_calculator": true,
    "case_studies": ["tech_startup", "enterprise_saas"]
  },
  "generation_timestamp": "2025-10-08T18:00:00Z",
  "llm_model": "claude-3-5-sonnet-20241022"
}
```

#### RLS Policies

**Service Role Only:**
```sql
CREATE POLICY "Service role only for deck metadata"
  ON slidev_decks FOR ALL TO service_role
  USING (true) WITH CHECK (true);
```

**Rationale:** Deck metadata contains customer discovery insights and should not be publicly accessible. Presentations themselves are served via slide-server URLs.

---

### 2. `slide_control_commands`

Stores remote control commands for Realtime slide navigation.

#### Schema

| Column      | Type         | Constraints                          | Description                                |
| ----------- | ------------ | ------------------------------------ | ------------------------------------------ |
| `id`        | UUID         | PRIMARY KEY                          | Auto-generated UUID                        |
| `deck_id`   | TEXT         | NOT NULL                             | Deck being controlled                      |
| `command`   | TEXT         | NOT NULL, CHECK (IN next/prev/goto)  | Command type                               |
| `slide_id`  | TEXT         | nullable                             | Target slide (required for 'goto')         |
| `timestamp` | TIMESTAMPTZ  | DEFAULT NOW()                        | Command timestamp                          |

#### Constraints

- **`goto_requires_slide_id`**: Ensures 'goto' commands have a `slide_id`

#### Indexes

- `idx_slide_control_commands_deck_id` - **CRITICAL** for Realtime filtering performance
- `idx_slide_control_commands_timestamp` - Command history queries
- `idx_slide_control_commands_deck_timestamp` - Composite index for deck command history

#### Command Types

| Command | `slide_id` | Description               | Example Usage                     |
| ------- | ---------- | ------------------------- | --------------------------------- |
| `next`  | NULL       | Advance to next slide     | `{command: 'next'}`               |
| `prev`  | NULL       | Go back to previous slide | `{command: 'prev'}`               |
| `goto`  | Required   | Jump to specific slide    | `{command: 'goto', slide_id: '5'}`|

#### RLS Policies

**Insert (Service Role):**
```sql
CREATE POLICY "Service role inserts control commands"
  ON slide_control_commands FOR INSERT TO service_role
  WITH CHECK (true);
```

**Select (Anonymous/Authenticated):**
```sql
CREATE POLICY "Allow reading control commands for Realtime"
  ON slide_control_commands FOR SELECT TO anon, authenticated
  USING (true);
```

**Rationale:**
- API/Pipecat (service role) writes commands
- Browser-based Slidev clients (anon/authenticated) subscribe via Realtime
- Only navigation data is exposed (deck_id, command, slide_id, timestamp) - no sensitive customer data

#### Realtime Configuration

```sql
ALTER PUBLICATION supabase_realtime ADD TABLE slide_control_commands;
```

**Client Subscription Example:**
```typescript
const channel = supabase
  .channel('slidev')
  .on('postgres_changes', {
    event: 'INSERT',
    schema: 'public',
    table: 'slide_control_commands',
    filter: `deck_id=eq.${deckId}`
  }, (payload) => {
    const { command, slide_id } = payload.new;
    // Navigate slides based on command
  })
  .subscribe();
```

---

## Security Model

### Overview

The Slidev schema implements a **tiered security model**:

1. **Deck Metadata** (`slidev_decks`) - **Service Role ONLY**
   - Contains customer discovery insights (company, pain points, budget, etc.)
   - Should never be publicly accessible
   - Only backend services can read/write

2. **Presentation Content** - **Publicly Served via slide-server**
   - Generated markdown/HTML served at `https://slides.buzztrail.ai/d/{deckId}`
   - No authentication required (presentations are meant to be viewed)
   - Content is derived from metadata but sanitized for public viewing

3. **Control Commands** (`slide_control_commands`) - **Mixed Access**
   - **Write**: Service role only (API/Pipecat)
   - **Read**: Anonymous/authenticated (for Realtime subscriptions)
   - No sensitive data exposed (just navigation events)

### Why Allow Anonymous Access to Control Commands?

**Problem:** Browser-based Slidev clients need to subscribe to Realtime updates to receive slide navigation commands.

**Solution:** Allow `anon`/`authenticated` SELECT access, but:
- Only navigation data is exposed (deck_id, command, slide_id, timestamp)
- No customer PII or business insights in this table
- Deck metadata remains protected (service role only)

**Data Flow:**
```
1. Avatar/API writes command -> service_role INSERT
2. Supabase Realtime broadcasts -> postgres_changes event
3. Browser subscribes with anon key -> receives command
4. Browser updates slide position
```

### What Data is Protected?

**Protected (Service Role Only):**
- `slidev_decks.generation_data` - Discovery insights, customization metadata
- `conversation_sessions.*` - Full session data

**Public (via slide-server URLs):**
- Generated presentation content (markdown/HTML)
- Company name, industry (visible in slides)

**Readable by Anon/Authenticated:**
- `slide_control_commands.*` - Navigation commands only

---

## Dependencies

### Required Tables

- **`conversation_sessions`** (from `001_initial_schema.sql`)
  - Tracks discovery phase and session lifecycle
  - Referenced by `slidev_decks.session_id` (nullable FK)

### Required Functions

- **`update_updated_at_column()`** (from `001_initial_schema.sql`)
  - Auto-updates `updated_at` timestamp on row updates
  - Reused for `slidev_decks` trigger

---

## Usage Examples

### 1. Create a New Deck

```sql
-- Insert deck metadata (service role)
INSERT INTO slidev_decks (deck_id, session_id, template_id, generation_data)
VALUES (
  'acme-2025-10-08-abc123',
  'f47ac10b-58cc-4372-a567-0e02b2c3d479'::uuid,
  'professional',
  '{
    "company_name": "Acme Corp",
    "industry": "SaaS",
    "slides_generated": 10
  }'::jsonb
);
```

### 2. Send Control Command

```sql
-- Insert navigation command (service role)
INSERT INTO slide_control_commands (deck_id, command, slide_id)
VALUES ('acme-2025-10-08-abc123', 'goto', '5');
```

### 3. Query Deck History

```sql
-- Get deck with session info
SELECT
  d.deck_id,
  d.template_id,
  d.generation_data->>'company_name' AS company_name,
  s.status AS session_status,
  s.discovery_ended_at
FROM slidev_decks d
LEFT JOIN conversation_sessions s ON d.session_id = s.id
WHERE d.deck_id = 'acme-2025-10-08-abc123';
```

### 4. Command History

```sql
-- Get recent commands for a deck
SELECT
  command,
  slide_id,
  timestamp
FROM slide_control_commands
WHERE deck_id = 'acme-2025-10-08-abc123'
ORDER BY timestamp DESC
LIMIT 10;
```

---

## Performance Considerations

### Critical Indexes

1. **`idx_slide_control_commands_deck_id`** (B-tree)
   - **Why Critical**: Realtime subscriptions filter by `deck_id`
   - Without this index, Realtime queries would scan entire table
   - Expected QPS: High during active presentations

2. **`idx_slidev_decks_deck_id`** (B-tree)
   - Fast lookups when serving presentation metadata
   - Used by slide-server to validate deck existence

### Query Optimization

- Use `deck_id` in WHERE clauses (indexed)
- Avoid full table scans on `slide_control_commands` (can grow large)
- Consider TTL/cleanup policy for old commands (future enhancement)

---

## Future Enhancements

### 1. Command Cleanup Policy

**Problem:** `slide_control_commands` table will grow indefinitely.

**Solution:**
```sql
-- Nightly cleanup job (cron or pg_cron)
DELETE FROM slide_control_commands
WHERE timestamp < NOW() - INTERVAL '7 days';
```

### 2. Deck Analytics

Track slide engagement:
- Time spent on each slide
- Slides skipped/revisited
- Viewer drop-off points

**Potential Schema Addition:**
```sql
CREATE TABLE slide_engagement (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  deck_id TEXT NOT NULL,
  slide_id TEXT NOT NULL,
  viewer_id UUID,
  entered_at TIMESTAMPTZ NOT NULL,
  exited_at TIMESTAMPTZ,
  duration_ms INTEGER GENERATED ALWAYS AS (
    EXTRACT(EPOCH FROM (exited_at - entered_at)) * 1000
  ) STORED
);
```

### 3. Multi-Viewer Support

Currently, control commands apply to all viewers of a deck. Future enhancement: per-viewer navigation.

**Potential Schema Change:**
```sql
ALTER TABLE slide_control_commands
  ADD COLUMN viewer_id UUID REFERENCES viewers(id);
```

---

## TypeScript Type Generation

**IMPORTANT:** After any database schema changes, you must regenerate TypeScript types.

### Generate Types from Supabase Schema

```bash
# Generate types for bot-spawner (or any service using Supabase)
npx supabase gen types typescript --project-id dwdytxxqcvlrmyemonxz --schema public > apps/bot-spawner/src/types/database.ts
```

### Why This Matters

- **Type Safety**: Ensures your TypeScript code matches the actual database schema
- **Catch Errors Early**: TypeScript will error if you try to insert/update with wrong field names or types
- **No Runtime Surprises**: Prevents "column doesn't exist" errors in production

### When to Regenerate Types

✅ **Always regenerate after:**
- Adding/removing columns
- Changing column types
- Adding new tables
- Modifying RLS policies (if they affect available fields)
- Running any database migration

### Example: Adding a Column

1. **Run migration** (adds `new_field` to `active_bots`)
2. **Regenerate types** (run command above)
3. **Update code** to use `new_field` with proper types
4. **Commit both** the migration AND the updated `database.ts` file

---

## Migration Instructions

### Step 1: Run Migration

**Using Supabase CLI:**
```bash
cd /path/to/epic-slidev-control-mvp
supabase db push
```

**Using SQL Editor (Supabase Dashboard):**
1. Go to SQL Editor
2. Paste contents of `.claude/supabase/migrations/002_slidev_schema.sql`
3. Execute

### Step 2: Enable Realtime Replication

1. Go to Supabase Dashboard → Database → Replication
2. Find `slide_control_commands` table
3. Enable replication (INSERT events)
4. Save changes

### Step 3: Seed Test Data (Optional)

```bash
# Using psql
psql $DATABASE_URL -f scripts/seed-slidev-test-data.sql

# Or via SQL Editor
# Paste contents of scripts/seed-slidev-test-data.sql
```

### Step 4: Verify

```sql
-- Check tables exist
SELECT table_name FROM information_schema.tables
WHERE table_name IN ('slidev_decks', 'slide_control_commands');

-- Check RLS is enabled
SELECT tablename, rowsecurity FROM pg_tables
WHERE tablename IN ('slidev_decks', 'slide_control_commands');

-- Check Realtime is enabled
SELECT schemaname, tablename FROM pg_publication_tables
WHERE pubname = 'supabase_realtime';
```

---

## Troubleshooting

### Issue: Realtime Not Working

**Symptoms:** Browser doesn't receive control commands

**Checklist:**
1. ✅ Realtime replication enabled in Dashboard?
2. ✅ RLS policy allows `anon` SELECT access?
3. ✅ Client using correct `deck_id` filter?
4. ✅ Client subscribed before commands inserted?

**Debug Query:**
```sql
-- Check recent commands
SELECT * FROM slide_control_commands
WHERE deck_id = 'your-deck-id'
ORDER BY timestamp DESC LIMIT 5;
```

### Issue: Permission Denied

**Symptoms:** Cannot insert deck metadata

**Cause:** Attempting to write as `anon`/`authenticated` instead of `service_role`

**Solution:** Use service role key for backend operations:
```typescript
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
```

---

## References

- **Migration File:** `.claude/supabase/migrations/002_slidev_schema.sql`
- **Seed Data:** `scripts/seed-slidev-test-data.sql`
- **Related Schema:** `001_initial_schema.sql` (conversation_sessions)
- **Supabase Realtime Docs:** https://supabase.com/docs/guides/realtime
- **RLS Policies Guide:** https://supabase.com/docs/guides/auth/row-level-security

---

## Change Log

| Date       | Version | Changes                                      |
| ---------- | ------- | -------------------------------------------- |
| 2025-10-08 | 1.0     | Initial schema creation (Issue #97)          |
