# PRD Template: Motia Architecture Guidelines

> **Purpose:** Template for PRDs that involve Motia backend development.
> **Copy this section into new PRDs that touch slide-system or other Motia apps.**

---

## Motia Architecture Constraints

### What is Motia?

**Motia** is an event-driven backend framework where:
- **Steps** are the core primitive (auto-discovered from `steps/*.step.ts`)
- Steps are **stateless functions**, dynamically reloaded on each request
- Steps communicate via **events** (`emit()`), not direct function calls
- **No shared in-memory state** (singletons, Maps, static variables)

📖 **Full Documentation**: See `apps/slide-system/docs/MOTIA_SUPABASE_ARCHITECTURE.md`

### Critical Rule: No Singletons

```typescript
// ❌ WRONG - State lost on module reload
class MyService {
  private cache = new Map();
}
export const myService = new MyService();

// ✅ CORRECT - Query external state
export async function getData(id: string) {
  const supabase = createSupabaseClient();
  return supabase.from('table').select().eq('id', id);
}
```

### Architecture Pattern: External State

**All persistent state must live in external systems:**

| State Type | Storage | Example |
|------------|---------|---------|
| Database records | Supabase | Bot metadata, user data |
| File data | File system | Logs, uploads |
| Cache | Redis | Session data, rate limits |
| Configuration | Environment vars | API keys, feature flags |

**Example Step:**
```typescript
export const config = {
  name: 'MyStep',
  type: 'api',
  path: '/api/my-endpoint',
  method: 'POST',
};

export const handler = async (req: any, { emit }: any) => {
  // 1. Query external state (Supabase, Redis, etc.)
  const supabase = createSupabaseClient();
  const { data } = await supabase.from('items').select();

  // 2. Process request
  const result = processData(req.body, data);

  // 3. Update external state
  await supabase.from('items').insert(result);

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

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

---

## Process Management Pattern

For spawning long-running processes (bots, workers):

### Detached Processes

```typescript
import { spawn } from 'child_process';

const process = spawn(cmd, args, {
  detached: true,      // Survive parent termination
  stdio: ['ignore', 'pipe', 'pipe'],
  cwd: workingDir,
});

process.unref();  // Detach from event loop

// Store PID in database
await supabase.from('processes').insert({
  process_id: id,
  pid: process.pid,
  status: 'running',
});
```

### OS-Level Process Control

```typescript
// Check if process is alive (signal 0 doesn't kill)
function isProcessAlive(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

// Graceful kill: SIGTERM → SIGKILL
function killProcess(pid: number) {
  process.kill(pid, 'SIGTERM');
  setTimeout(() => {
    if (isProcessAlive(pid)) {
      process.kill(pid, 'SIGKILL');
    }
  }, 10000);
}
```

---

## Supabase Integration

### Setup

1. **Install client:**
   ```bash
   pnpm add @supabase/supabase-js
   ```

2. **Create helper:**
   ```typescript
   // src/lib/supabase.ts
   import { createClient } from '@supabase/supabase-js';

   export function createSupabaseClient() {
     return createClient(
       process.env.SUPABASE_URL!,
       process.env.SUPABASE_SERVICE_KEY!
     );
   }
   ```

3. **Environment variables:**
   ```bash
   SUPABASE_URL=https://xxx.supabase.co
   SUPABASE_SERVICE_KEY=eyJhbGc...
   ```

### Migration Pattern

Create app-specific migrations:
```
apps/your-app/
└── supabase/
    └── migrations/
        └── YYYYMMDD_description.sql
```

Apply via Supabase CLI:
```bash
cd apps/your-app
supabase link --project-ref <your-project>
supabase db push
```

---

## Event-Driven Communication

### Publishing Events

```typescript
await emit({
  topic: 'resource.created',
  data: { id, timestamp, payload }
});
```

### Subscribing to Events

```typescript
export const config = {
  name: 'ResourceProcessor',
  type: 'event',
  on: 'resource.created',  // Subscribe to topic
};

export const handler = async (event: any) => {
  console.log('Received event:', event.data);
  // Process event...
};
```

---

## Development Guidelines

### ✅ DO

- Query external state on every request
- Use detached processes for long-running tasks
- Store process metadata (PID) in database
- Use OS-level signals for process control
- Emit events for cross-step communication
- Use environment variables for configuration

### ❌ DON'T

- Use singleton classes or static variables
- Store state in module-level variables
- Cache data in memory (use Redis instead)
- Keep process handles across requests
- Call other steps directly (use events)
- Hardcode configuration values

---

## Testing Locally

Start Motia with environment variables:
```bash
cd apps/your-app
export SUPABASE_URL=https://...
export SUPABASE_SERVICE_KEY=...
export OTHER_API_KEY=...
pnpx motia dev --port 3000
```

Test API endpoints:
```bash
curl -X POST http://localhost:3000/api/endpoint \
  -H "Content-Type: application/json" \
  -d '{"param": "value"}'
```

---

## Deployment

### Railway

```bash
railway variables set SUPABASE_URL=https://...
railway variables set SUPABASE_SERVICE_KEY=...
railway up
```

### Docker

```dockerfile
FROM node:20
WORKDIR /app
COPY . .
RUN pnpm install
CMD ["pnpx", "motia", "start"]
```

---

## Common Pitfalls

### 1. Using Singletons

**Problem:** State lost on module reload
**Solution:** Query Supabase on every request

### 2. Missing Process Detachment

**Problem:** Bot dies when Motia restarts
**Solution:** Use `detached: true` and `unref()`

### 3. Hardcoded Values

**Problem:** Can't change config without redeployment
**Solution:** Use environment variables

### 4. Direct Step Calls

**Problem:** Tight coupling, breaks modularity
**Solution:** Use event-driven communication

---

## Resources

- **Motia Docs**: https://www.motia.dev/docs
- **Architecture Guide**: `apps/slide-system/docs/MOTIA_SUPABASE_ARCHITECTURE.md`
- **Supabase Docs**: https://supabase.com/docs
- **Example Implementation**: `apps/slide-system/steps/bot-*.step.ts`

---

## Checklist for Motia PRDs

- [ ] No singletons or module-level state
- [ ] External state storage defined (Supabase, Redis, files)
- [ ] Process management strategy (detached + PID storage)
- [ ] Event topics defined for inter-step communication
- [ ] Environment variables documented
- [ ] Database migrations planned
- [ ] Health check endpoint included
- [ ] Error handling for external dependencies
