# Bot Manager Architecture Refactor

**Date:** 2025-10-12
**Status:** Planned
**Goal:** Align bot management with Motia's event-driven, stateless architecture

---

## Current Architecture Problems ❌

### 1. Fighting Motia's Design
- **Using singleton pattern** with `screenshareBotManager` instance
- **Maintaining in-memory state** via `Map<string, ActiveBot>`
- **Expecting module persistence** across API requests

### 2. Motia's Actual Behavior
- Steps are **dynamically imported** on each request
- Modules are **reloaded**, breaking singleton pattern
- Each API call creates a **new class instance**
- Result: State lost between spawn/status requests

### 3. Evidence from Logs
```
[ScreenshareBotManager] Initialized      # bot-spawn.step.ts
[ScreenshareBotManager] Active bots: 1   # Added to instance A's Map

[ScreenshareBotManager] Initialized      # bot-status.step.ts (NEW instance!)
[ScreenshareBotStatus] Status request    # Checking instance B's empty Map
Response: {"active_count": 0}            # State lost!
```

### 4. Root Cause Analysis
**Motia is event-driven and stateless by design:**
- Steps communicate via **events**, not shared state
- State should be **external** (database, context.state API)
- Long-running processes should be **orphaned** and tracked externally

---

## New Architecture: Event-Driven + Supabase ✅

### Core Principles

1. **Stateless Steps** - No shared in-memory state
2. **External State** - Store bot metadata in Supabase
3. **Event-Driven** - Steps emit events for monitoring/workflows
4. **OS-Level Control** - Use PIDs and signals for process management

### Architecture Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                    Motia Steps (Stateless)                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  bot-spawn.step.ts          bot-status.step.ts             │
│  ┌──────────────┐           ┌──────────────┐              │
│  │ 1. spawn()   │           │ 1. Query DB  │              │
│  │ 2. Insert DB │           │ 2. Check PID │              │
│  │ 3. Emit event│           │ 3. Return    │              │
│  └──────┬───────┘           └──────────────┘              │
│         │                                                   │
│         │                   bot-kill.step.ts               │
│         │                   ┌──────────────┐              │
│         │                   │ 1. Query DB  │              │
│         │                   │ 2. kill(PID) │              │
│         │                   │ 3. Update DB │              │
│         │                   └──────────────┘              │
└─────────┼───────────────────────────────────────────────────┘
          │
          │ Spawns & orphans
          ▼
┌─────────────────────────────────────────────────────────────┐
│              Orphaned Bot Processes                         │
│  ┌──────────────────┐  ┌──────────────────┐               │
│  │ Bot PID 12345    │  │ Bot PID 67890    │               │
│  │ (Pipecat)        │  │ (Pipecat)        │               │
│  └──────────────────┘  └──────────────────┘               │
└─────────────────────────────────────────────────────────────┘
          │                         │
          │ Writes logs             │
          ▼                         ▼
┌─────────────────────────────────────────────────────────────┐
│                      Supabase                               │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  active_bots table          bot_logs table                 │
│  ┌─────────────────┐        ┌─────────────────┐           │
│  │ bot_id (PK)     │        │ log_id (PK)     │           │
│  │ pid             │        │ bot_id (FK)     │           │
│  │ session_id      │        │ timestamp       │           │
│  │ room_url        │        │ level           │           │
│  │ deck_url        │        │ message         │           │
│  │ status          │        └─────────────────┘           │
│  │ spawned_at      │                                       │
│  │ stopped_at      │                                       │
│  │ error_message   │                                       │
│  └─────────────────┘                                       │
└─────────────────────────────────────────────────────────────┘
```

---

## Implementation Plan

### Phase 1: Database Schema

**Create `active_bots` table:**

```sql
CREATE TABLE active_bots (
  bot_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  pid INTEGER NOT NULL,
  session_id UUID NOT NULL,
  room_url TEXT NOT NULL,
  deck_url TEXT NOT NULL,
  status TEXT NOT NULL CHECK (status IN ('spawning', 'running', 'stopping', 'stopped', 'error')),
  spawned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  stopped_at TIMESTAMPTZ,
  error_message TEXT,
  log_file_path TEXT,

  -- Metadata
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes for common queries
CREATE INDEX idx_active_bots_session_id ON active_bots(session_id);
CREATE INDEX idx_active_bots_status ON active_bots(status);
CREATE INDEX idx_active_bots_pid ON active_bots(pid);

-- Auto-update updated_at
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_active_bots_updated_at
  BEFORE UPDATE ON active_bots
  FOR EACH ROW
  EXECUTE FUNCTION update_updated_at_column();
```

**Optional: Create `bot_logs` table for structured logging:**

```sql
CREATE TABLE bot_logs (
  log_id BIGSERIAL PRIMARY KEY,
  bot_id UUID NOT NULL REFERENCES active_bots(bot_id) ON DELETE CASCADE,
  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  level TEXT NOT NULL CHECK (level IN ('DEBUG', 'INFO', 'WARNING', 'ERROR')),
  message TEXT NOT NULL,
  metadata JSONB
);

CREATE INDEX idx_bot_logs_bot_id ON bot_logs(bot_id);
CREATE INDEX idx_bot_logs_timestamp ON bot_logs(timestamp DESC);
```

---

### Phase 2: Refactor Steps

#### 2.1 Remove `screenshare-bot-manager.ts` Singleton

**Current:** `src/services/screenshare-bot-manager.ts` (300+ lines)
**New:** Delete entire file - move logic into steps directly

#### 2.2 Refactor `bot-spawn.step.ts`

**Before:**
```typescript
import { screenshareBotManager } from '../src/services/screenshare-bot-manager';

export const handler = async (req: any) => {
  const result = await screenshareBotManager.spawnBot({
    roomUrl: req.body.room_url,
    // ...
  });
  return { status: 200, body: result };
};
```

**After:**
```typescript
import { spawn } from 'child_process';
import { createClient } from '@supabase/supabase-js';
import { v4 as uuidv4 } from 'uuid';

export const handler = async (req: any, { emit }: any) => {
  const { room_url, deck_url, session_id, meeting_token } = req.body;

  // 1. Spawn bot process (orphaned)
  const botId = uuidv4();
  const botProcess = spawn(pythonCmd, args, {
    env: { ...process.env, PYTHONUNBUFFERED: '1' },
    cwd: botDir,
    stdio: ['ignore', 'pipe', 'pipe'],
    detached: true,  // Important: detach so it survives parent
  });

  // Detach from parent (bot becomes independent)
  botProcess.unref();

  // 2. Store in Supabase
  const supabase = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_KEY!
  );

  const { data, error } = await supabase
    .from('active_bots')
    .insert({
      bot_id: botId,
      pid: botProcess.pid,
      session_id,
      room_url,
      deck_url,
      status: 'spawning',
      log_file_path: `/logs/bot-${botId}.log`,
    })
    .select()
    .single();

  if (error) {
    // Kill the bot if DB insert failed
    process.kill(botProcess.pid!, 'SIGKILL');
    throw error;
  }

  // 3. Emit event for monitoring
  emit('screenshare.bot.spawned', {
    bot_id: botId,
    session_id,
    pid: botProcess.pid,
  });

  return {
    status: 200,
    body: {
      bot_id: botId,
      pid: botProcess.pid,
      status: 'spawning',
      estimated_join_time: '5s',
    },
  };
};
```

**Key Changes:**
- ✅ No shared state
- ✅ Bot process detached (`detached: true`, `unref()`)
- ✅ State stored in Supabase
- ✅ Events emitted for workflows

#### 2.3 Refactor `bot-status.step.ts`

**Before:**
```typescript
import { screenshareBotManager } from '../src/services/screenshare-bot-manager';

export const handler = async (req: any) => {
  const botId = req.params?.bot_id;
  const botStatus = screenshareBotManager.getBotStatus(botId);
  // ...
};
```

**After:**
```typescript
import { createClient } from '@supabase/supabase-js';

export const handler = async (req: any) => {
  const botId = req.params?.bot_id;

  const supabase = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_KEY!
  );

  if (botId) {
    // Get specific bot
    const { data: bot, error } = await supabase
      .from('active_bots')
      .select('*')
      .eq('bot_id', botId)
      .single();

    if (error || !bot) {
      return { status: 404, body: { error: 'Bot not found' } };
    }

    // Check if process is still alive
    const isAlive = checkPidAlive(bot.pid);

    // Update status if process died
    if (!isAlive && bot.status !== 'stopped') {
      await supabase
        .from('active_bots')
        .update({ status: 'error', stopped_at: new Date(), error_message: 'Process died unexpectedly' })
        .eq('bot_id', botId);

      bot.status = 'error';
      bot.error_message = 'Process died unexpectedly';
    }

    return {
      status: 200,
      body: {
        bot_id: bot.bot_id,
        session_id: bot.session_id,
        room_url: bot.room_url,
        deck_url: bot.deck_url,
        status: bot.status,
        pid: bot.pid,
        spawned_at: bot.spawned_at,
        stopped_at: bot.stopped_at,
        error: bot.error_message,
      },
    };
  } else {
    // Get all bots
    const { data: bots, error } = await supabase
      .from('active_bots')
      .select('*')
      .order('spawned_at', { ascending: false });

    return {
      status: 200,
      body: {
        active_count: bots?.length || 0,
        bots: bots || [],
      },
    };
  }
};

function checkPidAlive(pid: number): boolean {
  try {
    // Send signal 0 to check if process exists
    process.kill(pid, 0);
    return true;
  } catch (e) {
    return false;
  }
}
```

**Key Changes:**
- ✅ Query Supabase instead of in-memory Map
- ✅ Verify PID is alive via OS signal
- ✅ Auto-update status if process died

#### 2.4 Refactor `bot-kill.step.ts`

**Before:**
```typescript
import { screenshareBotManager } from '../src/services/screenshare-bot-manager';

export const handler = async (req: any) => {
  const botId = req.params?.bot_id;
  screenshareBotManager.killBot(botId);
  // ...
};
```

**After:**
```typescript
import { createClient } from '@supabase/supabase-js';

export const handler = async (req: any, { emit }: any) => {
  const botId = req.params?.bot_id;

  const supabase = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_KEY!
  );

  // Get bot from DB
  const { data: bot, error } = await supabase
    .from('active_bots')
    .select('*')
    .eq('bot_id', botId)
    .single();

  if (error || !bot) {
    return { status: 404, body: { error: 'Bot not found' } };
  }

  if (bot.status === 'stopped' || bot.status === 'error') {
    return { status: 400, body: { error: 'Bot already stopped' } };
  }

  try {
    // Send SIGTERM for graceful shutdown
    process.kill(bot.pid, 'SIGTERM');

    // Update status
    await supabase
      .from('active_bots')
      .update({ status: 'stopping' })
      .eq('bot_id', botId);

    // Force kill after timeout (in a separate process)
    setTimeout(async () => {
      // Check if still alive
      try {
        process.kill(bot.pid, 0);
        // Still alive, force kill
        process.kill(bot.pid, 'SIGKILL');
        await supabase
          .from('active_bots')
          .update({
            status: 'stopped',
            stopped_at: new Date(),
            error_message: 'Force killed after timeout'
          })
          .eq('bot_id', botId);
      } catch {
        // Already dead, update status
        await supabase
          .from('active_bots')
          .update({ status: 'stopped', stopped_at: new Date() })
          .eq('bot_id', botId);
      }
    }, 10000);

    // Emit event
    emit('screenshare.bot.killed', {
      bot_id: botId,
      session_id: bot.session_id,
      pid: bot.pid,
    });

    return {
      status: 200,
      body: {
        message: `SIGTERM sent to bot ${botId}`,
        bot_id: botId,
        pid: bot.pid,
      },
    };

  } catch (killError: any) {
    return {
      status: 500,
      body: {
        error: 'Failed to kill bot',
        details: killError.message,
      },
    };
  }
};
```

**Key Changes:**
- ✅ Query Supabase for bot metadata
- ✅ Use OS signals (`SIGTERM`, `SIGKILL`)
- ✅ Update status in database
- ✅ No need for process handle reference

---

### Phase 3: Bot Process Changes

#### 3.1 Make Bot Self-Report Status

**Add Supabase status updates to `bot.py`:**

```python
import os
from supabase import create_client, Client

# Initialize Supabase client
supabase: Client = create_client(
    os.getenv("SUPABASE_URL"),
    os.getenv("SUPABASE_SERVICE_KEY")
)

# Update status when bot joins room
async def update_bot_status(bot_id: str, status: str):
    supabase.table('active_bots').update({
        'status': status,
        'updated_at': 'now()'
    }).eq('bot_id', bot_id).execute()

# In bot.py startup:
bot_id = sys.argv[4]  # Pass bot_id as argument
await update_bot_status(bot_id, 'running')

# On error:
await update_bot_status(bot_id, 'error')

# On graceful shutdown:
await update_bot_status(bot_id, 'stopped')
```

#### 3.2 Update Bot Spawn Args

Pass bot_id to Python bot:

```typescript
// In bot-spawn.step.ts
const args = [
  botScriptPath,
  room_url,
  deck_url,
  session_id,
  botId,  // NEW: pass bot_id
  meeting_token,
].filter(Boolean);
```

---

### Phase 4: Migration Strategy

#### 4.1 Create Migration File

`apps/slide-system/supabase/migrations/001_create_active_bots.sql`

#### 4.2 Apply Migration

```bash
supabase db push
```

#### 4.3 Update Dependencies

```bash
pnpm add @supabase/supabase-js
```

#### 4.4 Deployment Order

1. Apply Supabase migration
2. Deploy updated Motia code
3. Old bots will be orphaned (acceptable - they'll timeout)
4. New bots use new architecture

---

## Benefits of New Architecture

### 1. Fits Motia's Design ✅
- Stateless steps
- Event-driven communication
- No module reload issues

### 2. Persistence ✅
- State survives Motia restarts
- Can track bots even after deployment
- Historical data for analytics

### 3. Scalability ✅
- Multiple Motia instances can share state
- No single point of failure
- Horizontal scaling possible

### 4. Observability ✅
- All bot data queryable via SQL
- Can add monitoring/alerting
- Structured logging in database

### 5. Simplicity ✅
- No complex singleton patterns
- No global state hacks
- Clear separation of concerns

---

## Rollback Plan

If new architecture has issues:

1. **Database:** Keep old table, add new table
2. **Code:** Feature flag to switch between old/new
3. **Bots:** Independent of architecture changes
4. **Worst case:** Revert to global state (already implemented)

---

## Testing Plan

### 1. Unit Tests
- Bot spawn creates DB record
- Bot status queries DB correctly
- Bot kill sends signals and updates DB

### 2. Integration Tests
- Spawn → Status → Kill lifecycle
- Multiple concurrent bots
- Bot crash detection

### 3. Smoke Tests
- Deploy to staging
- Run full scenario
- Verify logs and DB state

---

## Timeline Estimate

- **Phase 1 (Database):** 30 minutes
- **Phase 2 (Refactor Steps):** 2-3 hours
- **Phase 3 (Bot Updates):** 1 hour
- **Phase 4 (Migration):** 1 hour
- **Testing:** 1-2 hours

**Total:** 5-7 hours

---

## Files to Change

### Delete
- ✅ `src/services/screenshare-bot-manager.ts` (no longer needed)

### Modify
- ✅ `steps/bot-spawn.step.ts` - Use Supabase
- ✅ `steps/bot-status.step.ts` - Query Supabase
- ✅ `steps/bot-kill.step.ts` - Use OS signals
- ✅ `bots/screenshare-bot/bot.py` - Add status updates

### Create
- ✅ `supabase/migrations/001_create_active_bots.sql`
- ✅ `src/lib/supabase.ts` - Shared client helper

---

## Risk Assessment

| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|------------|
| Orphaned bots | Low | Medium | Status check detects dead processes |
| DB connection failure | Low | High | Fallback to file-based tracking |
| Bot can't update status | Medium | Low | Parent process monitors |
| Migration issues | Low | High | Test on staging first |

---

## Success Criteria

✅ Bot spawn persists state in Supabase
✅ Status API returns correct data from DB
✅ Kill API successfully terminates bots
✅ No "Initialized" spam in logs
✅ State survives Motia restarts
✅ Multiple API calls see same data

---

**Ready to implement?** This architecture aligns with Motia's philosophy and solves all current issues.
