# PRD: Bot Debugging and Immediate Fixes

## Document Control
- **Status**: Draft
- **Priority**: P0 (Critical - Blocks production usage)
- **Estimated Effort**: 1-2 days
- **Owner**: TBD
- **Created**: 2025-10-17
- **Last Updated**: 2025-10-17
- **Related PRDs**:
  - `screenshare-bot-service-separation.md` (Follow-up architectural refactoring)

## Executive Summary

Fix critical issues preventing screenshare bots from running in production:
1. **Bot crash on spawn** - Bots spawn (PID assigned) but crash immediately without logs
2. **Broken logs endpoint** - `/api/bots/logs/:bot_id` returns Motia workbench HTML instead of logs
3. **Confusing naming** - `tavus-tool-forwarder` is too specific (also needed for LiveKit)
4. **Direct API calls** - Voice agent should call slide-system API directly (no forwarder needed)

**Current State**: All 21 bots in "error" state are zombie bots from before deck URL fix. New bots spawn but crash immediately.

**Success Criteria**:
- ✅ New bots successfully join LiveKit rooms and stream slides
- ✅ Bot logs accessible via API endpoint
- ✅ Clear bot naming and architecture
- ✅ Voice agent can control slides via direct API calls

## Problem Statement

### Issue 1: Bot Crash on Spawn
**Observed Behavior**:
```bash
[ScreenshareBotSpawnLiveKit] ✅ Bot spawned successfully (PID: 363)
# But bot never appears in database - crashed immediately
```

**Root Cause**: Unknown - cannot access logs to diagnose

**Impact**: Screenshare bots cannot run, blocking voice demo feature

### Issue 2: Broken Logs Endpoint
**Current**:
```typescript
// GET /api/bots/logs/:bot_id
// Returns: Motia workbench HTML (wrong!)
```

**Expected**:
```json
{
  "bot_id": "0137dc0a-...",
  "logs": "...",
  "last_lines": 100
}
```

**Root Cause**: Likely routing conflict or missing implementation

### Issue 3: Naming Confusion
**Current**: `tavus-tool-forwarder` bot
- Too specific - also needed for LiveKit voice conversations
- Naming implies Tavus-only usage

**Proposed**: `tool-forwarder` or `conversation-tool-forwarder`
- Generic enough for any conversation platform
- Clear purpose: forwards tool calls to slide-system API

### Issue 4: Unnecessary Indirection
**Current**: Voice agent → ??? → Slide system API
**Proposed**: Voice agent → Slide system API (direct HTTP)

Voice agent already has `httpx` installed and can make authenticated API calls directly.

## Architecture Context

### Current Bot Architecture (In Motia)
```
apps/slide-system/ (Motia app)
├── steps/
│   ├── bot-spawn-livekit.step.ts  ← Spawns Python child process
│   ├── bot-status.step.ts         ← Queries Supabase
│   └── bot-logs-get.step.ts       ← BROKEN
└── bots/
    ├── screenshare-bot/            ← Python bot
    │   ├── bot.py
    │   ├── lifecycle_manager.py
    │   └── logs/bot-*.log
    └── tavus-tool-forwarder/       ← Needs rename
```

**Issues**:
- Bot stdout/stderr not captured in Railway logs
- Log files written to `/app/bots/screenshare-bot/logs/` but not accessible
- Child process management complex

### Bot Lifecycle Flow
```
1. POST /api/bots/screenshare/spawn-livekit
   ↓
2. bot-spawn-livekit.step.ts spawns Python process
   ↓
3. bot.py starts with BotLifecycleManager
   ↓
4. BotLifecycleManager registers in Supabase (active_bots table)
   ↓
5. Bot joins LiveKit room and starts streaming
   ↓
6. Logs written to /app/bots/screenshare-bot/logs/bot-{id}.log
```

**Current Problem**: Step 4 never happens (bot crashes before registration)

## Technical Requirements

### 1. Fix Bot Crash

**Investigation Steps**:
- [ ] Check if SUPABASE_URL/SUPABASE_SERVICE_KEY are set in Railway
- [ ] Check if LIVEKIT_API_KEY/LIVEKIT_API_SECRET are set
- [ ] Verify Playwright browsers installed (`playwright install --with-deps chromium`)
- [ ] Check Python dependencies (`uv sync` successful in Dockerfile)
- [ ] Add startup logging BEFORE any imports that might fail

**Fixes**:
```python
# At top of bot.py - before any imports
import sys
print(f"[STARTUP] Python: {sys.version}", flush=True)
print(f"[STARTUP] Args: {sys.argv}", flush=True)

try:
    import asyncio
    print("[STARTUP] asyncio imported", flush=True)
    import playwright
    print("[STARTUP] playwright imported", flush=True)
    from supabase import create_client
    print("[STARTUP] supabase imported", flush=True)
except Exception as e:
    print(f"[STARTUP ERROR] {e}", flush=True)
    sys.exit(1)
```

**Environment Check**:
```python
# In bot.py main()
required_env = [
    'SUPABASE_URL',
    'SUPABASE_SERVICE_KEY',
    'LIVEKIT_API_KEY',
    'LIVEKIT_API_SECRET'
]
missing = [k for k in required_env if not os.getenv(k)]
if missing:
    logger.error(f"Missing environment variables: {missing}")
    sys.exit(1)
```

### 2. Fix Logs Endpoint

**Current Implementation** (apps/slide-system/steps/bot-logs-get.step.ts):
```typescript
export const config = {
  name: 'ScreenshareBotLogsGet',
  type: 'api',
  path: '/api/bots/logs/:bot_id',
  method: 'GET',
};

export const handler = async (req: any) => {
  const { bot_id } = req.params;
  const logFile = `/app/bots/screenshare-bot/logs/bot-${bot_id}.log`;

  // Read log file
  const logs = await fs.readFile(logFile, 'utf-8');

  return {
    status: 200,
    body: { bot_id, logs }
  };
};
```

**Issue**: Likely missing or routing conflict with Motia workbench

**Fix Options**:

**Option A**: Use different route (avoid conflict)
```typescript
path: '/api/bots/screenshare/logs/:bot_id',  // More specific
```

**Option B**: Return plain text (not JSON)
```typescript
return {
  status: 200,
  headers: { 'Content-Type': 'text/plain' },
  body: logs  // Raw string, not JSON
};
```

**Option C**: Stream logs via Railway logs
```typescript
// Redirect logs to stdout instead of file
const process = spawn('python', args, {
  stdio: ['ignore', 'inherit', 'inherit'],  // stdout/stderr → Railway
});
```

**Recommended**: Option C + Keep file logging for backup

### 3. Rename Tool Forwarder

**Files to Update**:
```bash
# Rename directory
mv apps/slide-system/bots/tavus-tool-forwarder \
   apps/slide-system/bots/tool-forwarder

# Update imports in:
apps/slide-system/steps/spawn-tool-forwarder.step.ts
apps/slide-system/steps/kill-tool-forwarder.step.ts
apps/slide-system/steps/tool-forwarder-status.step.ts

# Update environment variables
TOOL_FORWARDER_BOT_PATH=./bots/tool-forwarder/bot.py
```

**Code Changes**:
```typescript
// spawn-tool-forwarder.step.ts
const botPath = path.join(__dirname, '../bots/tool-forwarder/bot.py');

// Update logs
logger.info('[ToolForwarder] Spawning tool forwarder bot...');
```

**Database Changes**:
```sql
-- Update active_bots table constraint
ALTER TABLE active_bots DROP CONSTRAINT IF EXISTS active_bots_bot_type_check;
ALTER TABLE active_bots ADD CONSTRAINT active_bots_bot_type_check
  CHECK (bot_type IN ('screenshare', 'screenshare_livekit', 'tool-forwarder', 'voice-agent'));
```

### 4. Voice Agent Direct API Integration

**Add to voice-agent-livekit**:

```python
# apps/voice-agent-livekit/src/tools/slides.py
import httpx
import os

SLIDE_SYSTEM_URL = os.getenv('SLIDE_SYSTEM_URL', 'https://slide-system-production-5813.up.railway.app')
SLIDE_SYSTEM_API_KEY = os.getenv('SLIDE_SYSTEM_API_KEY')  # Optional auth

async def generate_slides(topic: str, session_id: str) -> dict:
    """Generate slides for a topic."""
    async with httpx.AsyncClient() as client:
        response = await client.post(
            f"{SLIDE_SYSTEM_URL}/api/slidev/generate",
            json={
                "topic": topic,
                "session_id": session_id,
                "template_id": "default"
            },
            headers={"X-API-Key": SLIDE_SYSTEM_API_KEY} if SLIDE_SYSTEM_API_KEY else {},
            timeout=30.0
        )
        response.raise_for_status()
        return response.json()

async def next_slide(session_id: str, deck_id: str) -> None:
    """Advance to next slide."""
    async with httpx.AsyncClient() as client:
        await client.post(
            f"{SLIDE_SYSTEM_URL}/api/slidev/control",
            json={
                "session_id": session_id,
                "deck_id": deck_id,
                "command": "next"
            },
            timeout=5.0
        )

async def previous_slide(session_id: str, deck_id: str) -> None:
    """Go to previous slide."""
    async with httpx.AsyncClient() as client:
        await client.post(
            f"{SLIDE_SYSTEM_URL}/api/slidev/control",
            json={
                "session_id": session_id,
                "deck_id": deck_id,
                "command": "prev"
            },
            timeout=5.0
        )

async def goto_slide(session_id: str, deck_id: str, slide_number: int) -> None:
    """Jump to specific slide."""
    async with httpx.AsyncClient() as client:
        await client.post(
            f"{SLIDE_SYSTEM_URL}/api/slidev/control",
            json={
                "session_id": session_id,
                "deck_id": deck_id,
                "command": "goto",
                "slide_number": slide_number
            },
            timeout=5.0
        )
```

**Environment Variables**:
```bash
# Railway voice-agent-livekit service
SLIDE_SYSTEM_URL=https://slide-system-production-5813.up.railway.app
SLIDE_SYSTEM_API_KEY=optional-secret-key
```

**No Forwarder Bot Needed!** Voice agent calls API directly.

## Implementation Plan

### Phase 1: Debug Bot Crash (Day 1, Morning)
1. [ ] Add startup logging to bot.py (before imports)
2. [ ] Add environment variable validation
3. [ ] Deploy to Railway
4. [ ] Spawn test bot and check Railway logs for startup errors
5. [ ] Fix identified issues (missing env vars, import errors, etc.)

### Phase 2: Fix Logs Endpoint (Day 1, Afternoon)
1. [ ] Update bot-logs-get.step.ts route to avoid conflicts
2. [ ] Add file existence check and error handling
3. [ ] Update bot spawn to log to stdout (Railway logs)
4. [ ] Test logs endpoint returns actual logs
5. [ ] Document usage: `curl https://.../api/bots/screenshare/logs/:bot_id`

### Phase 3: Rename Tool Forwarder (Day 1, Evening)
1. [ ] Rename directory: `tavus-tool-forwarder` → `tool-forwarder`
2. [ ] Update imports in 3 step files
3. [ ] Update database constraint for bot_type
4. [ ] Update environment variables in Railway
5. [ ] Test tool forwarder still works

### Phase 4: Voice Agent Integration (Day 2)
1. [ ] Create `apps/voice-agent-livekit/src/tools/slides.py`
2. [ ] Implement slide control functions (generate, next, prev, goto)
3. [ ] Add environment variables to Railway
4. [ ] Test voice agent can generate and control slides
5. [ ] Update voice agent tools registration

## Testing Strategy

### Test 1: Bot Spawn Success
```bash
# Spawn new bot
# that is the wrong URL it just goes to the Motia workbench
curl -X POST https://slide-system-production-5813.up.railway.app/api/bots/screenshare/spawn-livekit \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "test-session-123",
    "room_name": "test-room",
    "deck_url": "https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/",
    "token": "..."
  }'

# Expected: Bot ID returned, bot appears in database with status "running"
```

### Test 2: Bot Logs Access
```bash
# Get bot logs
curl https://slide-system-production-5813.up.railway.app/api/bots/screenshare/logs/BOT_ID

# Expected: JSON with bot logs (not HTML)
# Alternative: Plain text logs
```

### Test 3: Voice Agent Slide Control
```python
# In voice agent
from tools.slides import generate_slides, next_slide

# Test slide generation
result = await generate_slides("AI in Healthcare", session_id)
print(f"Deck URL: {result['deck_url']}")

# Test slide navigation
await next_slide(session_id, deck_id)
```

## Success Metrics

**Before (Broken)**:
- 0/21 bots running successfully
- Logs endpoint returns HTML
- Voice agent cannot control slides

**After (Fixed)**:
- ✅ New bots spawn and run successfully
- ✅ Logs accessible via API
- ✅ Voice agent controls slides directly
- ✅ Clear naming: "tool-forwarder" (not "tavus-tool-forwarder")

## Rollback Plan

**If bot crash not fixed**:
- Revert to logging more startup diagnostics
- Test bot locally with same environment variables
- Check Railway environment parity

**If logs endpoint still broken**:
- Use Railway native logs (`railway logs --service slide-system`)
- Add backup logs streaming endpoint

**If voice agent integration fails**:
- Fallback to tool-forwarder bot pattern temporarily
- Debug API authentication issues

## Future Work (Not in Scope)

These will be addressed in `screenshare-bot-service-separation.md`:
- [ ] Separate screenshare-bot into standalone Railway service
- [ ] HTTP API for bot spawn (not child process)
- [ ] Better bot health monitoring
- [ ] Auto-scaling bot instances

## Dependencies

**Environment Variables Required**:
```bash
# slide-system service
SUPABASE_URL=https://...
SUPABASE_SERVICE_KEY=...
LIVEKIT_API_KEY=...
LIVEKIT_API_SECRET=...

# voice-agent-livekit service (new)
SLIDE_SYSTEM_URL=https://slide-system-production-5813.up.railway.app
SLIDE_SYSTEM_API_KEY=optional-secret-key
```

**Railway Services**:
- `slide-system` (existing)
- `voice-agent-livekit` (existing)

## Questions & Decisions

**Q1**: Should logs endpoint return JSON or plain text?
**A1**: Plain text is simpler for debugging, JSON is better for programmatic access. Start with plain text, can add JSON format later.

**Q2**: Keep file-based logging or switch to stdout only?
**A2**: Both - stdout for Railway logs, files for backup/persistence.

**Q3**: Should voice agent auth with slide-system API?
**A3**: Optional - start without auth (internal service), add API key later if needed.

**Q4**: What if bot still crashes after fixes?
**A4**: Add Railway exec command to test bot manually: `railway run python apps/slide-system/bots/screenshare-bot/bot.py ...`

## Appendix

### Zombie Bots Analysis

All 21 "error" bots are using OLD broken deck URL:
```
https://buzztrail.github.io/buzztrail-presentations/decks/p10e-2f8z-h0fi/ (404)
```

Fix already deployed (commits 8908129, 6259af9):
```
https://buzztrail.github.io/buzztrail-presentations/p10e-2f8z-h0fi/ (200)
```

These are not a bug - they're leftover from before the fix. Can be safely cleaned up:
```sql
DELETE FROM active_bots WHERE status = 'error' AND spawned_at < '2025-10-17';
```
