# Motia + Supabase Architecture Guide

**Last Updated:** October 12, 2025
**App:** slide-system
**Purpose:** Comprehensive guide to the event-driven, stateless architecture for bot management

---

## Table of Contents

1. [Overview](#overview)
2. [Motia Framework Fundamentals](#motia-framework-fundamentals)
3. [Why Event-Driven + Supabase](#why-event-driven--supabase)
4. [Architecture Patterns](#architecture-patterns)
5. [Bot Management Implementation](#bot-management-implementation)
6. [Database Schema](#database-schema)
7. [Development Guidelines](#development-guidelines)
8. [Deployment Considerations](#deployment-considerations)

---

## Overview

The slide-system app uses **Motia** (event-driven backend framework) + **Supabase** (PostgreSQL database) for stateless, scalable bot management. This architecture enables:

- **Zero state loss** across server restarts
- **Horizontal scalability** (multiple Motia instances can share database)
- **Process independence** (bots survive parent termination)
- **Real-time health monitoring** via OS-level process checks

### Key Principle

> **Motia Steps are stateless functions, dynamically reloaded on each request.**
> Any in-memory state (singletons, Maps, arrays) will be lost between requests.
> **All persistent state must live in external systems (Supabase, Redis, file system).**

---

## Motia Framework Fundamentals

### What is Motia?

Motia is an event-driven backend framework where **Steps** are the core primitive.

**Step Definition:**
```typescript
export const config = {
  name: 'MyStep',
  type: 'api',           // or 'event'
  path: '/api/foo',      // for API steps
  method: 'POST',        // for API steps
  on: 'some.event',      // for event steps
  emits: ['other.event'] // events this step emits
};

export const handler = async (req: any, { emit }: any) => {
  // Your logic here
  await emit({ topic: 'other.event', data: {...} });
  return { status: 200, body: {...} };
};
```

### Key Characteristics

1. **Auto-Discovery**: Steps in `steps/*.step.ts` are automatically loaded
2. **Dynamic Reloading**: Module cache cleared on each request (development mode)
3. **Stateless Handlers**: Each request gets a fresh module instance
4. **Event-Driven**: Steps communicate via `emit()`, not direct calls
5. **No Shared State**: Singletons, static variables, and module-level state DO NOT persist

### Why Singletons Don't Work

**Anti-Pattern (BROKEN):**
```typescript
// ❌ screenshare-bot-manager.ts
class BotManager {
  private activeBots: Map<string, Bot> = new Map();
}
export const screenshareBotManager = new BotManager();

// ❌ bot-spawn.step.ts
import { screenshareBotManager } from './screenshare-bot-manager';
screenshareBotManager.spawnBot(botId);  // Works!

// ❌ bot-status.step.ts (different request)
import { screenshareBotManager } from './screenshare-bot-manager';
const bots = screenshareBotManager.getAllBots();  // Returns [] (NEW instance!)
```

**Root Cause**: Motia clears module cache → imports return fresh instances → state lost.

---

## Why Event-Driven + Supabase

### The Problem We Solved

**Original Architecture (Singleton-Based):**
```
Request 1: POST /api/bots/spawn
  → Import bot-manager (new instance)
  → Spawn bot, store in Map
  → Map has 1 bot ✓

Request 2: GET /api/bots/status
  → Import bot-manager (NEW instance! Module reloaded)
  → Query Map → Empty [] ✗
```

### The Solution (Event-Driven + Supabase)

**New Architecture:**
```
Request 1: POST /api/bots/spawn
  → Spawn detached bot process
  → Store metadata in Supabase
  → Database has 1 bot ✓

Request 2: GET /api/bots/status
  → Query Supabase for bots
  → Returns all bots from database ✓
```

### Benefits

| Feature | Singleton | Event-Driven + Supabase |
|---------|-----------|------------------------|
| Survives Motia restart | ❌ | ✅ |
| Horizontal scaling | ❌ | ✅ |
| State persistence | ❌ | ✅ |
| Process independence | ❌ | ✅ |
| Real-time health checks | ❌ | ✅ |
| Alignment with Motia | ❌ | ✅ |

---

## Architecture Patterns

### Pattern 1: Stateless Steps

**Every Step should be a pure function:**
```typescript
export const handler = async (req: any, { emit }: any) => {
  // 1. Extract input from request
  const { param } = req.body;

  // 2. Query external state (Supabase)
  const supabase = createSupabaseClient();
  const { data } = await supabase.from('table').select();

  // 3. Perform computation
  const result = processData(data);

  // 4. Update external state
  await supabase.from('table').insert(result);

  // 5. Emit events for other steps
  await emit({ topic: 'data.processed', data: result });

  // 6. Return response
  return { status: 200, body: result };
};
```

### Pattern 2: Process Management

**Spawn detached, orphaned processes:**
```typescript
import { spawn } from 'child_process';

const botProcess = spawn(pythonCmd, args, {
  detached: true,  // Process becomes orphan when parent dies
  stdio: ['ignore', 'pipe', 'pipe'],
  cwd: botDirectory,
});

botProcess.unref();  // Detach from parent's event loop

// Store PID in database
await supabase.from('active_bots').insert({
  bot_id: botId,
  pid: botProcess.pid
});
```

### Pattern 3: Database as Source of Truth

**Query database for all state:**
```typescript
// Check if bot exists
const { data: bot } = await supabase
  .from('active_bots')
  .select('*')
  .eq('bot_id', botId)
  .single();

// Validate process is still alive (OS-level check)
const isAlive = isProcessAlive(bot.pid);

// Update database if state changed
if (!isAlive && bot.status === 'running') {
  await supabase
    .from('active_bots')
    .update({ status: 'error', stopped_at: new Date() })
    .eq('bot_id', botId);
}
```

### Pattern 4: OS-Level Process Control

**Use OS signals, not process handles:**
```typescript
// Check if process exists (signal 0 doesn't kill)
export function isProcessAlive(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

// Graceful kill: SIGTERM → SIGKILL
export function killProcess(pid: number, timeoutMs = 10000) {
  process.kill(pid, 'SIGTERM');  // Graceful shutdown

  setTimeout(() => {
    if (isProcessAlive(pid)) {
      process.kill(pid, 'SIGKILL');  // Force kill
    }
  }, timeoutMs);
}
```

---

## Bot Management Implementation

### File Structure

```
apps/slide-system/
├── steps/
│   ├── bot-spawn.step.ts      # POST /api/bots/screenshare/spawn
│   ├── bot-status.step.ts     # GET /api/bots/screenshare/status
│   └── bot-kill.step.ts       # POST /api/bots/screenshare/kill/:bot_id
├── src/
│   └── lib/
│       └── supabase.ts        # Shared Supabase client + helpers
├── supabase/
│   └── migrations/
│       └── 20251012_create_active_bots.sql
└── bots/
    └── screenshare-bot/
        └── bot.py             # Python bot (Pipecat-based)
```

### Step Responsibilities

#### bot-spawn.step.ts

**Responsibilities:**
- Validate request parameters (room_url, deck_url, session_id)
- Check for duplicate bots (same session_id)
- Spawn detached Python bot process
- Store bot metadata in Supabase
- Return bot_id and PID to client

**Key Code:**
```typescript
// Spawn detached process
const botProcess = spawn(pythonCmd, [
  botScriptPath,
  room_url,
  deck_url,
  session_id,
  bot_id  // Pass bot_id as 4th arg
], {
  detached: true,
  stdio: ['ignore', 'pipe', 'pipe'],
  cwd: botDirectory,
});

botProcess.unref();

// Store in database
await supabase.from('active_bots').insert({
  bot_id,
  pid: botProcess.pid,
  session_id,
  room_url,
  deck_url,
  status: 'spawning',
  log_file_path: logFilePath,
});
```

#### bot-status.step.ts

**Responsibilities:**
- Query active_bots table from Supabase
- Validate process health via `isProcessAlive(pid)`
- Auto-update database if process died unexpectedly
- Return bot status with `is_process_alive` flag

**Key Code:**
```typescript
// Query database
const { data: bot } = await supabase
  .from('active_bots')
  .select('*')
  .eq('bot_id', botId)
  .single();

// Check OS-level process health
const isAlive = isProcessAlive(bot.pid);

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

return {
  status: 200,
  body: { ...bot, is_process_alive: isAlive }
};
```

#### bot-kill.step.ts

**Responsibilities:**
- Query bot from Supabase
- Validate process exists before kill attempt
- Send SIGTERM → SIGKILL (graceful → force)
- Update database status to 'stopping'
- Emit event for monitoring

**Key Code:**
```typescript
// Query database for PID
const { data: bot } = await supabase
  .from('active_bots')
  .select('*')
  .eq('bot_id', botId)
  .single();

// Check if process is alive
if (!isProcessAlive(bot.pid)) {
  await supabase
    .from('active_bots')
    .update({ status: 'stopped' })
    .eq('bot_id', botId);
  return { status: 409, body: { error: 'Already stopped' } };
}

// Kill process (graceful → force)
killProcess(bot.pid);

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

---

## Database Schema

### Table: `active_bots`

```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,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes for performance
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);
CREATE INDEX idx_active_bots_spawned_at ON active_bots(spawned_at DESC);
```

### Status State Machine

```
spawning → running → stopping → stopped
           ↓
         error
```

- **spawning**: Bot process just started, joining Daily.co room
- **running**: Bot successfully joined room, streaming frames
- **stopping**: SIGTERM sent, waiting for graceful shutdown
- **stopped**: Process exited cleanly (exit code 0)
- **error**: Process crashed or killed forcefully

### Queries

**Get all active bots:**
```typescript
const { data: bots } = await supabase
  .from('active_bots')
  .select('*')
  .in('status', ['spawning', 'running'])
  .order('spawned_at', { ascending: false });
```

**Check for duplicate session:**
```typescript
const { data: existingBots } = await supabase
  .from('active_bots')
  .select('*')
  .eq('session_id', session_id)
  .in('status', ['spawning', 'running']);
```

---

## Development Guidelines

### 1. Never Use Singletons

**❌ WRONG:**
```typescript
class MyService {
  private cache = new Map();
}
export const myService = new MyService();
```

**✅ CORRECT:**
```typescript
export function getDataFromDatabase(id: string) {
  const supabase = createSupabaseClient();
  return supabase.from('table').select().eq('id', id);
}
```

### 2. Always Query External State

**❌ WRONG:**
```typescript
let activeBots = [];  // Module-level state

export const handler = async () => {
  activeBots.push(newBot);  // Lost on next request!
};
```

**✅ CORRECT:**
```typescript
export const handler = async () => {
  const supabase = createSupabaseClient();
  await supabase.from('active_bots').insert(newBot);
};
```

### 3. Use Detached Processes

**❌ WRONG:**
```typescript
const botProcess = spawn(cmd, args);  // Dies with parent
```

**✅ CORRECT:**
```typescript
const botProcess = spawn(cmd, args, {
  detached: true,
  stdio: ['ignore', 'pipe', 'pipe']
});
botProcess.unref();  // Orphan the process
```

### 4. Emit Events for Side Effects

**❌ WRONG:**
```typescript
import { otherStep } from './other.step';
await otherStep.handler(data);  // Direct call, tight coupling
```

**✅ CORRECT:**
```typescript
await emit({
  topic: 'bot.spawned',
  data: { bot_id, session_id }
});
// Other steps subscribe to 'bot.spawned' via config.on
```

### 5. Environment Variables

**Required for all bot steps:**
```bash
DAILY_PIPECAT_API_KEY=<daily.co_api_key>
SUPABASE_URL=https://<project>.supabase.co
SUPABASE_SERVICE_KEY=<service_role_key>
```

**Set in development:**
```bash
# .env.motia (auto-loaded by Motia)
DAILY_PIPECAT_API_KEY=xxx
SUPABASE_URL=https://dwdytxxqcvlrmyemonxz.supabase.co
SUPABASE_SERVICE_KEY=yyy
```

**Set in production (Railway):**
```bash
railway variables set DAILY_PIPECAT_API_KEY=xxx
railway variables set SUPABASE_URL=https://...
railway variables set SUPABASE_SERVICE_KEY=yyy
```

---

## Deployment Considerations

### Supabase Project Setup

1. **Create Supabase project** at https://supabase.com/dashboard
2. **Run migrations** via CLI:
   ```bash
   cd apps/slide-system
   supabase link --project-ref <your-project-ref>
   supabase db push
   ```
3. **Get credentials**:
   - Project URL: Settings → API → Project URL
   - Service Role Key: Settings → API → service_role key (secret)

### Motia Server Deployment

**Start development server:**
```bash
cd apps/slide-system
export DAILY_PIPECAT_API_KEY=xxx
export SUPABASE_URL=https://...
export SUPABASE_SERVICE_KEY=yyy
pnpx motia dev --port 3002
```

**Production deployment (Railway):**
```bash
# Set environment variables
railway variables set DAILY_PIPECAT_API_KEY=xxx
railway variables set SUPABASE_URL=https://...
railway variables set SUPABASE_SERVICE_KEY=yyy

# Deploy
railway up
```

### Python Bot Requirements

**Virtual environment:**
```bash
cd bots/screenshare-bot
uv venv
source .venv/bin/activate  # or .venv\Scripts\activate on Windows
uv pip install -r requirements.txt
.venv/bin/playwright install chromium
```

**Dockerfile (for containerized deployment):**
```dockerfile
FROM python:3.11
RUN apt-get update && apt-get install -y chromium
COPY bots/screenshare-bot/ /app/
WORKDIR /app
RUN pip install -r requirements.txt
RUN playwright install chromium
CMD ["python", "bot.py"]
```

### Monitoring & Health Checks

**Railway health check endpoint:**
```typescript
// steps/health.step.ts
export const config = {
  name: 'Health',
  type: 'api',
  path: '/health',
  method: 'GET',
};

export const handler = async () => {
  const supabase = createSupabaseClient();
  const { error } = await supabase.from('active_bots').select('bot_id').limit(1);

  return {
    status: error ? 503 : 200,
    body: {
      status: error ? 'unhealthy' : 'healthy',
      database: error ? 'down' : 'up',
    },
  };
};
```

---

## Troubleshooting

### Issue: "Bot spawned but not in database"

**Cause**: Database insert failed after process spawn
**Solution**: Check Supabase credentials and RLS policies

```typescript
// Add error handling
const { data, error } = await supabase
  .from('active_bots')
  .insert(botData)
  .select()
  .single();

if (error) {
  // Kill bot if DB insert failed
  process.kill(botProcess.pid, 'SIGKILL');
  throw new Error(`DB insert failed: ${error.message}`);
}
```

### Issue: "Status shows active_count: 0 but bot is running"

**Cause**: Motia reloaded module, lost singleton state
**Solution**: This is expected! Use Supabase queries, not in-memory state.

### Issue: "Bot process dies immediately"

**Cause**: Missing Python dependencies or Playwright browsers
**Solution**:
```bash
cd bots/screenshare-bot
source .venv/bin/activate
uv pip install -r requirements.txt
playwright install chromium
```

### Issue: "Module 'supabase-py' not found in bot.py"

**Cause**: Bot needs Supabase client for status updates
**Solution**: Add to requirements.txt:
```
supabase==2.10.0
```

---

## Future Enhancements

### 1. Bot Status Updates from Python

**Goal**: Bot reports its own status to Supabase

```python
# bot.py
from supabase import create_client

supabase = create_client(os.getenv('SUPABASE_URL'), os.getenv('SUPABASE_SERVICE_KEY'))

# When bot joins room
supabase.table('active_bots').update({
  'status': 'running'
}).eq('bot_id', bot_id).execute()

# When streaming starts
supabase.table('active_bots').update({
  'frame_count': frame_count
}).eq('bot_id', bot_id).execute()
```

### 2. Supabase Realtime for Live Updates

**Goal**: UI gets real-time bot status via WebSockets

```typescript
const supabase = createSupabaseClient();

supabase
  .channel('active_bots')
  .on('postgres_changes',
    { event: '*', schema: 'public', table: 'active_bots' },
    (payload) => {
      console.log('Bot status changed:', payload);
      updateUI(payload.new);
    }
  )
  .subscribe();
```

### 3. Bot Auto-Cleanup

**Goal**: Automatically clean up dead bots

```typescript
// steps/bot-cleanup.step.ts
export const config = {
  name: 'BotCleanup',
  type: 'cron',
  schedule: '*/5 * * * *',  // Every 5 minutes
};

export const handler = async () => {
  const supabase = createSupabaseClient();

  const { data: bots } = await supabase
    .from('active_bots')
    .select('*')
    .in('status', ['spawning', 'running']);

  for (const bot of bots || []) {
    if (!isProcessAlive(bot.pid)) {
      await supabase
        .from('active_bots')
        .update({ status: 'error', stopped_at: new Date() })
        .eq('bot_id', bot.bot_id);
    }
  }
};
```

---

## References

- **Motia Documentation**: https://www.motia.dev/docs
- **Motia Manifesto**: https://www.motia.dev/manifesto
- **Supabase Docs**: https://supabase.com/docs
- **Original Refactor Doc**: `docs/ARCHITECTURE_REFACTOR.md`
- **Database Migrations**: `supabase/migrations/`

---

## Conclusion

The Motia + Supabase architecture provides a **stateless, event-driven, scalable** foundation for bot management. By embracing Motia's dynamic module reloading and storing all state in Supabase, we achieve:

- ✅ Zero state loss across restarts
- ✅ Horizontal scalability
- ✅ Process independence
- ✅ Real-time health monitoring
- ✅ Clean separation of concerns

**Key Takeaway**: Treat Motia Steps as pure functions. Query external state on every request. Never rely on in-memory state.
