# Phase 0 Debugging Guide

## Overview

This guide provides troubleshooting procedures and debugging techniques for Phase 0 infrastructure components.

## Table of Contents

1. [Motia Step Debugging](#motia-step-debugging)
2. [Supabase Edge Function Debugging](#supabase-edge-function-debugging)
3. [Daily.co Integration Debugging](#dailyco-integration-debugging)
4. [Database Debugging](#database-debugging)
5. [Common Issues and Fixes](#common-issues-and-fixes)
6. [Useful CLI Commands](#useful-cli-commands)

---

## Slide System Debugging (Railway Deployment)

### Viewing Production Logs

The slide system is deployed on Railway at: `https://slide-system-production-5813.up.railway.app`

**Via Railway Dashboard:**
1. Go to https://railway.app
2. Select your project: `slide-system-production`
3. View real-time logs in the **Deployments** tab

**Via Railway CLI:**
```bash
# Follow logs in real-time
railway logs --follow

# View recent logs
railway logs --tail 100
```

**Log Output Example:**
```
[INFO] Motia.dev step registered: slidev-generate
[INFO] Motia.dev step registered: slidev-control
[DEBUG] POST /api/slidev/generate
[INFO] Generating deck for session: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[INFO] Deck generated successfully: deck-1234567890
```

### Testing Slide System API
**Generate Deck:**
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d '{
    "sessionId": "test-session-id",
    "templateId": "starter",
    "data": {"company": "Test Corp"}
  }'
```

**Expected Success Response (HTTP 200):**
```json
{
  "deckId": "deck-1234567890-xxxxx",
  "deckUrl": "https://buzztrail.github.io/buzztrail-presentations/deck-1234567890-xxxxx",
  "message": "Deck generated successfully"
}
```
**Control Deck (next/prev/goto):**
```bash
curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_SLIDEV_API_KEY" \
  -d '{
    "deckId": "deck-1234567890-xxxxx",
    "command": "next"
  }'
```

**Expected Success Response (HTTP 200):**
```json
{
  "success": true,
  "message": "Command 'next' sent successfully"
}
```

### Testing Locally

**Start Local Development Server:**
```bash
cd apps/slide-system
pnpx motia dev --port 3002
```

**Test Generation Endpoint:**
```bash
curl -X POST http://localhost:3002/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d '{"sessionId": "test", "templateId": "starter", "data": {}}'
```

### Common Issues

#### Issue: "Session not found"

**Symptom**: HTTP 404 when generating deck

**Cause**: Session ID doesn't exist in Supabase `conversation_sessions` table

**Fix**:
1. Create session first via `/demo-sessions` endpoint
2. Or use the test utilities that auto-create sessions:
   ```bash
   npm run test:performance
   ```

#### Issue: "Invalid API key"

**Symptom**: HTTP 401 when calling `/api/slidev/control`

**Cause**: Missing or incorrect `SLIDEV_API_KEY` in Railway environment

**Fix**:
```bash
# Set via Railway CLI
railway variables set SLIDEV_API_KEY=your-api-key-here

# Or via Railway dashboard: Settings → Variables
```

#### Issue: "GitHub Pages publish failed"

**Symptom**: Deck generated but URL returns 404

**Cause**: GitHub Pages deployment may be pending (can take 30-60 seconds)

**Fix**: Wait for GitHub Pages to publish, then verify:
```bash
curl -I https://buzztrail.github.io/buzztrail-presentations/deck-1234567890-xxxxx
# Should return HTTP 200 after publishing completes
```

---

## Supabase Edge Function Debugging

### Viewing Edge Function Logs

**Via Supabase Dashboard:**
1. Go to https://supabase.com/dashboard
2. Select your project
3. Navigate to **Edge Functions** → `create-demo-session`
4. Click **Logs** tab
5. View real-time invocation logs

**Via Supabase CLI:**
```bash
# Follow logs in real-time
supabase functions logs create-demo-session --follow

# View recent logs
supabase functions logs create-demo-session --limit 50
```

### Testing Edge Function Locally

**Start Supabase Local Development:**
```bash
supabase start
supabase functions serve create-demo-session
```

**Test Function:**
```bash
curl -X POST http://localhost:54321/functions/v1/create-demo-session \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "Content-Type: application/json" \
  -d '{"session_type": "test"}'
```

### Testing Edge Function (Production)

```bash
curl -X POST https://dwdytxxqcvlrmyemonxz.supabase.co/functions/v1/create-demo-session \
  -H "Authorization: Bearer YOUR_ANON_KEY" \
  -H "Content-Type: application/json" \
  -d '{"session_type": "test"}'
```

### Common Edge Function Issues

#### Issue: "Missing Authorization header"

**Symptom**: HTTP 401 Unauthorized

**Fix**: Include Supabase anon key in Authorization header:
```bash
-H "Authorization: Bearer YOUR_SUPABASE_ANON_KEY"
```

#### Issue: "Cannot reach Slide System endpoint"

**Symptom**: `Error: connect ECONNREFUSED` or timeout

**Cause**: Railway deployment not accessible or incorrect URL

**Fix**:
```bash
# Verify Railway deployment is running
railway status

# Check environment variable in Edge Function
supabase secrets list

# Update if needed
supabase secrets set MOTIA_API_URL=https://slide-system-production-5813.up.railway.app
```

#### Issue: "Function deployment failed"

**Symptom**: Error during `supabase functions deploy`

**Debug Steps:**
1. Check function syntax:
   ```bash
   deno check supabase/functions/create-demo-session/index.ts
   ```

2. Test locally first:
   ```bash
   supabase functions serve create-demo-session
   ```

3. Check secrets are set:
   ```bash
   supabase secrets list
   ```

---

## Daily.co Integration Debugging

### Testing Daily.co API Directly

**Create Room:**
```bash
curl -X POST https://api.daily.co/v1/rooms \
  -H "Authorization: Bearer YOUR_DAILY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "test-room-'$(date +%s)'",
    "properties": {
      "exp": '$(( $(date +%s) + 3600 ))',
      "enable_recording": "cloud"
    }
  }'
```

**Expected Response:**
```json
{
  "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "name": "test-room-1234567890",
  "url": "https://buzztrail.daily.co/test-room-1234567890",
  "created_at": "2025-10-08T08:00:00.000Z",
  "config": {
    "exp": 1234570890,
    "enable_recording": "cloud"
  }
}
```

### Verifying Room Accessibility

**Open room URL in browser:**
```bash
# macOS
open "https://buzztrail.daily.co/demo-1234567890-xxxxx"

# Linux
xdg-open "https://buzztrail.daily.co/demo-1234567890-xxxxx"
```

**Test room via API:**
```bash
curl -I "https://buzztrail.daily.co/demo-1234567890-xxxxx"
# Should return HTTP 200
```

### Common Daily.co Issues

#### Issue: "Invalid API key"

**Symptom**: HTTP 401 from Daily.co API

**Fix**: Verify `DAILY_API_KEY` in `.env`:
```bash
# Check key is set
grep DAILY_API_KEY .env

# Test key directly
curl -H "Authorization: Bearer $DAILY_API_KEY" \
  https://api.daily.co/v1/rooms
```

#### Issue: "Room already exists"

**Symptom**: Error "room name already in use"

**Cause**: Duplicate room name (room names must be unique)

**Fix**: Motia Step uses timestamp-based names (automatic uniqueness):
```typescript
const roomName = `demo-${Date.now()}-${generateRandomId()}`;
```

If testing manually, ensure unique names:
```bash
curl -X POST https://api.daily.co/v1/rooms \
  -H "Authorization: Bearer $DAILY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "test-'$(date +%s)'-'$RANDOM'"}'
```

---

## Database Debugging

### Connecting to Supabase Database

**Via Supabase Dashboard:**
1. Go to https://supabase.com/dashboard
2. Select project
3. Navigate to **SQL Editor**
4. Run queries

**Via psql CLI:**
```bash
# Get connection string from Supabase dashboard (Settings → Database → Connection string)
psql "postgresql://postgres:your_password@db.your_project_ref.supabase.co:5432/postgres"
```

### Useful Database Queries

**View Recent Sessions:**
```sql
SELECT
  session_id,
  session_type,
  status,
  daily_room_url,
  created_at,
  updated_at
FROM conversation_sessions
ORDER BY created_at DESC
LIMIT 10;
```

**Check Session Statuses:**
```sql
SELECT
  status,
  COUNT(*) as count
FROM conversation_sessions
GROUP BY status
ORDER BY count DESC;
```

**Find Sessions by Daily Room:**
```sql
SELECT *
FROM conversation_sessions
WHERE daily_room_url LIKE '%demo-1234567890%';
```

**View Session Transcript Data:**
```sql
SELECT
  session_id,
  status,
  discovery_transcript->0 as first_discovery_message,
  presentation_transcript->0 as first_presentation_message
FROM conversation_sessions
WHERE discovery_transcript IS NOT NULL
LIMIT 5;
```

**Calculate Average Session Durations:**
```sql
SELECT
  AVG(discovery_duration_seconds) as avg_discovery_duration,
  AVG(presentation_duration_seconds) as avg_presentation_duration
FROM conversation_sessions
WHERE status = 'completed';
```

### Common Database Issues

#### Issue: "Table does not exist"

**Symptom**: `relation "conversation_sessions" does not exist`

**Fix**: Run database migration:
```bash
cd supabase
supabase migration up
```

Or apply SQL manually via Supabase dashboard SQL Editor.

#### Issue: "Duplicate session_id"

**Symptom**: `duplicate key value violates unique constraint`

**Cause**: Attempting to insert session with existing UUID (should never happen with UUID v4)

**Debug**:
```sql
SELECT session_id, COUNT(*)
FROM conversation_sessions
GROUP BY session_id
HAVING COUNT(*) > 1;
```

#### Issue: "JSONB field not updating"

**Symptom**: `discovery_insights` or transcript fields not saving

**Debug**: Check JSONB format:
```sql
-- Valid JSONB
INSERT INTO conversation_sessions (session_id, discovery_insights)
VALUES ('...', '{"objective1": "value1", "objective2": "value2"}'::jsonb);

-- Test JSONB validity
SELECT '{"test": "valid"}'::jsonb; -- Should succeed
SELECT '{"test": invalid}'::jsonb; -- Should fail
```

---

## Common Issues and Fixes

### Issue: "Port already in use" (Motia Dev Server)

**Symptom**: `Error: listen EADDRINUSE: address already in use :::3005`

**Cause**: Another process using port 3005

**Fix**:
```bash
# Find process on port 3005
lsof -i :3005

# Kill the process
kill -9 <PID>

# Or use a different port
pnpx motia dev --port 3006
```

### Issue: Tunnel Disconnected

**Symptom**: Edge Function returns `ECONNREFUSED` to Motia endpoint

**Cause**: Cloudflare tunnel terminated

**Check**:
```bash
# Test tunnel URL
curl https://your-tunnel-url.trycloudflare.com/health

# If 404 or timeout, tunnel is down
```

**Fix**:
```bash
# Restart tunnel
cloudflared tunnel --url http://localhost:3005

# Update Edge Function environment variable with new URL
supabase secrets set MOTIA_API_URL=https://new-tunnel-url.trycloudflare.com
```

**Long-term Fix**: Use Motia Cloud deployment (when 429 rate limiting resolves)

### Issue: Environment Variables Not Loaded

**Symptom**: `undefined` errors for environment variables

**Debug**:
```bash
# Check .env file exists
ls -la .env

# Verify variables are set
grep DAILY_API_KEY .env
grep SUPABASE_URL .env
grep MOTIA_API_KEY .env

# Source manually (bash)
source .env
echo $DAILY_API_KEY

# For Motia (uses .env.motia)
cat apps/backup-workflows/.env.motia
```

**Fix**:
```bash
# Create missing .env files
cp .env.example .env
cp .env.example apps/backup-workflows/.env.motia

# Edit and add actual values
nano .env
```

---

## Useful CLI Commands

### Slide System Commands

```bash
# Start local development server
cd apps/slide-system
pnpx motia dev --port 3002

# Deploy to Railway
railway up

# View Railway deployment status
railway status

# View Railway logs
railway logs --follow

# Test generation API locally
curl -X POST http://localhost:3002/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d '{"sessionId": "test", "templateId": "starter", "data": {}}'

# Test control API locally
curl -X POST http://localhost:3002/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_SLIDEV_API_KEY" \
  -d '{"deckId": "test-deck", "command": "next"}'
```

### Supabase Commands

```bash
# Start local Supabase
supabase start

# Stop local Supabase
supabase stop

# View database migrations
supabase migration list

# Apply migrations
supabase migration up

# Create new migration
supabase migration new migration_name

# Deploy Edge Function
supabase functions deploy create-demo-session

# View Edge Function logs
supabase functions logs create-demo-session --follow

# List environment secrets
supabase secrets list

# Set environment secret
supabase secrets set SECRET_NAME=value

# Test Edge Function locally
supabase functions serve create-demo-session
```

### Daily.co Commands

```bash
# List all rooms
curl -H "Authorization: Bearer $DAILY_API_KEY" \
  https://api.daily.co/v1/rooms

# Get room details
curl -H "Authorization: Bearer $DAILY_API_KEY" \
  https://api.daily.co/v1/rooms/room-name

# Delete room
curl -X DELETE \
  -H "Authorization: Bearer $DAILY_API_KEY" \
  https://api.daily.co/v1/rooms/room-name
```

### Database Commands (psql)

```bash
# Connect to database
psql "postgresql://postgres:PASSWORD@db.PROJECT_REF.supabase.co:5432/postgres"

# Common queries inside psql
\dt                    # List tables
\d conversation_sessions  # Describe table
\q                     # Quit
```

### Performance Testing Commands

```bash
# Run performance tests (requires Railway deployment)
npm run test:performance

# Run with custom iterations
npm run test:performance -- --iterations 20

# Run concurrent load tests
npm run test:concurrent

# Run E2E tests (Playwright)
npm run test:e2e
```

---

## Performance Monitoring

### Check Slide System Response Time
```bash
# Measure deck generation time
time curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/generate \
  -H "Content-Type: application/json" \
  -d '{"sessionId": "test", "templateId": "starter", "data": {"company": "Test"}}'

# Expected: < 15 seconds (build time)
# Measure control command latency
time curl -X POST https://slide-system-production-5813.up.railway.app/api/slidev/control \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_SLIDEV_API_KEY" \
  -d '{"deckId": "test-deck", "command": "next"}'

# Expected: < 500ms
```

### Monitor Database Query Performance

```sql
-- Enable query timing in psql
\timing on

-- Run query and see execution time
SELECT * FROM conversation_sessions LIMIT 100;
```

### Check Daily.co API Latency

```bash
time curl -X POST https://api.daily.co/v1/rooms \
  -H "Authorization: Bearer $DAILY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "perf-test-'$(date +%s)'"}'

# Expected: <5 seconds
```

---

## Getting Help

### Documentation Resources

- **Motia.dev Docs**: https://docs.motia.dev
- **Railway Docs**: https://docs.railway.app
- **Supabase Docs**: https://supabase.com/docs
- **Daily.co Docs**: https://docs.daily.co
- **Slidev Docs**: https://sli.dev

### Project-Specific Documentation

- **Phase 0 Setup Guide**: `.claude/docs/phase0-setup-guide.md`
- **Slidev API PRDs**: `.claude/prds/core-presentation-engine/`
- **Epic Documentation**: `.claude/epics/slidev-control-mvp/`

### Logging Issues

When reporting issues, include:
1. **Error Message**: Full error output
2. **Environment**: Local dev / Supabase staging / production
3. **Reproduction Steps**: How to trigger the error
4. **Logs**: Relevant Motia/Edge Function/database logs
5. **Environment Variables**: Which variables are set (redact sensitive values)

---

**Created**: 2025-10-08
**Last Updated**: 2025-10-08
**Related**: Phase 0 Infrastructure Setup
