---
created: 2025-10-10T11:28:08Z
last_updated: 2025-10-15T16:15:01Z
version: 1.2
author: Claude Code PM System
---

# System Patterns

## Architectural Style

### Monorepo Architecture
- **Pattern**: Nx-powered monorepo with shared libraries
- **Purpose**: Code reuse, consistent tooling, atomic commits
- **Implementation**: Apps and libs separated with clear dependency boundaries

### Microservices
- **Pattern**: Multiple independent services with specific responsibilities
- **Services**:
  - `slide-system` (Railway) - Deck generation and control
  - `proxy-server` (Vercel) - API gateway and webhooks
  - `backup-workflows` (Motia) - Background job processing

### Serverless Functions
- **Pattern**: Function-as-a-Service on Vercel
- **Usage**: API endpoints, webhook handlers
- **Benefits**: Auto-scaling, pay-per-use, zero maintenance

## Design Patterns

### API Layer Patterns

**RESTful API Design**
```
POST /api/slidev/generate    - Create resource
POST /api/slidev/control     - Command endpoint
POST /demo-sessions          - Session creation
GET  /health                 - Health check
```

**Command Pattern**
- Control commands sent to presentations
- Decoupled sender and receiver
- Commands: `next`, `prev`, `goto`, `sync`, `reload`

**Repository Pattern**
- Data access abstraction
- Supabase client wrapped in repository interfaces
- Clear separation of data and business logic

### Frontend Patterns

**Component Composition**
- Small, reusable React components
- Props-based configuration
- Composition over inheritance

**Atomic Design**
- Component hierarchy: atoms → molecules → organisms
- Shared component library in `libs/shared/components`
- Design system with Radix UI primitives

**Render Props & Hooks**
- Custom hooks for shared logic
- React hooks for state and effects
- Composition through hooks

**State Management**
- Jotai for atomic state
- Local state for component-specific data
- Server state via Supabase real-time

### Backend Patterns

**Middleware Pipeline**
- Express middleware chain
- Security (Helmet, CORS)
- Logging (Morgan, Winston)
- Rate limiting
- Error handling

**Event-Driven Architecture (Motia Framework)** - **NEW PATTERN (Oct 2025)**
- **Stateless Steps**: Functions dynamically reloaded on each request
- **No Singletons**: All state stored in external systems (Supabase, files)
- **Event Communication**: Steps communicate via `emit()`, not direct calls
- **Database as Source of Truth**: All persistent state in Supabase
- **Detached Processes**: Long-running tasks spawned as independent OS processes
- **Documentation**: `apps/slide-system/docs/MOTIA_SUPABASE_ARCHITECTURE.md`

**Event-Driven Architecture (Supabase Realtime)**
- Supabase real-time subscriptions
- Pub/sub for command broadcasting
- Event listeners in presentation viewers

**Worker Pattern**
- Motia workflows for background jobs
- Async task processing
- Job queuing and scheduling

## Data Flow Patterns

### Request-Response Flow
```
Client Request
    ↓
API Gateway (proxy-server)
    ↓
Business Logic (slide-system)
    ↓
Database (Supabase)
    ↓
Response to Client
```

### Real-time Data Flow
```
Control Command
    ↓
API Endpoint
    ↓
Database Insert (slide_control_commands)
    ↓
Supabase Realtime Broadcast
    ↓
Subscribed Clients Receive Update
    ↓
Presentation State Updates
```

### Generation Flow
```
Generate Request
    ↓
Session Creation
    ↓
Template Processing
    ↓
Slidev Build
    ↓
GitHub Pages Deploy
    ↓
Database Record Update
    ↓
Return Presentation URL
```

## Error Handling Patterns

### Try-Catch with Logging
```typescript
try {
  await operation();
} catch (error) {
  logger.error('Operation failed', { error, context });
  throw new ApplicationError('User-friendly message', error);
}
```

### Error Boundaries (React)
- Top-level error boundaries
- Fallback UI for errors
- Error reporting and recovery

### HTTP Error Responses
```typescript
{
  error: {
    code: 'ERROR_CODE',
    message: 'User-friendly message',
    details: {}
  }
}
```

## Security Patterns

### API Authentication
- API key validation via headers
- Environment-based key management
- Rate limiting per key

### Input Validation
- Zod/Joi schema validation
- Request sanitization
- Type-safe validation

### CORS Configuration
- Whitelist allowed origins
- Credential handling
- Method restrictions

### Security Headers (Helmet)
- Content Security Policy
- XSS Protection
- Frame options
- HSTS

## Testing Patterns

### Test Pyramid
```
       E2E (Playwright)
      ↗
    Integration (Jest)
   ↗
 Unit Tests (Jest)
```

### Test Organization
- `*.spec.ts` for unit tests
- `tests/e2e/` for E2E tests
- Co-located tests with source code

### Mock Patterns
- Mock external APIs for testing
- Fake Tavus server for local development
- Test fixtures and factories

### Test Data Builders
- Factory functions for test data
- Consistent test setup
- Reusable test utilities

## Logging Patterns

### Structured Logging
```typescript
logger.info('Event occurred', {
  userId: 'user-123',
  action: 'generate_deck',
  deckId: 'deck-456',
  timestamp: new Date().toISOString()
});
```

### Log Levels
- `error` - Failures and exceptions
- `warn` - Warning conditions
- `info` - Informational messages
- `debug` - Debug information
- `trace` - Detailed trace logs

### Context Propagation
- Request ID tracking
- User context in logs
- Correlation IDs for distributed tracing

## Configuration Patterns

### Environment-Based Config
- `.env` files for configuration
- Environment variable validation
- Defaults with overrides

### Feature Flags
- Environment-based feature toggles
- Testing mode flags
- Gradual feature rollout

### Configuration Objects
```typescript
const config = {
  api: {
    baseUrl: process.env.API_URL,
    timeout: 30000
  },
  database: {
    url: process.env.DATABASE_URL
  }
};
```

## Build & Deployment Patterns

### Continuous Deployment
- **Railway**: Auto-deploy from `main` branch
- **Vercel**: Auto-deploy on git push
- **GitHub Pages**: Deploy via GitHub Actions

### Build Caching
- Nx computation caching
- Nx Cloud remote caching
- Docker layer caching

### Incremental Builds
- Only rebuild changed projects
- Dependency graph analysis
- Parallel build execution

## Code Organization Patterns

### Feature-Based Structure
```
libs/
  feature-name/
    src/
      lib/
        components/
        hooks/
        utils/
        index.ts
```

### Barrel Exports
```typescript
// index.ts
export * from './component-a';
export * from './component-b';
export { default as FeatureModule } from './feature';
```

### Path Aliases
```typescript
import { Button } from '@buzztrail/shared/components';
import { logger } from '@buzztrail/shared/utils';
```

## Performance Patterns

### Code Splitting
- Dynamic imports for routes
- Lazy loading components
- Bundle size optimization

### Caching Strategies
- API response caching
- Build artifact caching
- Browser caching headers

### Database Optimization
- Indexed queries
- Connection pooling
- Query result caching

## Real-time Communication Patterns

### WebSocket Connections
- Supabase real-time channels
- Automatic reconnection
- Subscription management

### Polling Fallback
- Graceful degradation
- Poll interval configuration
- Bandwidth optimization

### Server-Sent Events (SSE)
- One-way server-to-client communication
- Long-lived connections
- Event streaming

## Dependency Injection

### Service Locator Pattern
- Centralized service registry
- Lazy initialization
- Testability through mocking

### Constructor Injection
```typescript
class Service {
  constructor(
    private readonly logger: Logger,
    private readonly db: Database
  ) {}
}
```

## Validation Patterns

### Schema-Based Validation
```typescript
const schema = z.object({
  name: z.string().min(1),
  email: z.string().email()
});

const validated = schema.parse(input);
```

### Guard Clauses
```typescript
function process(data: unknown) {
  if (!data) return;
  if (!isValid(data)) throw new Error('Invalid data');

  // Process valid data
}
```

## API Versioning

### URL Versioning
```
/api/v1/endpoint
/api/v2/endpoint
```

Currently using unversioned endpoints with backward compatibility commitment.

## Observability Patterns

### OpenTelemetry Integration
- Distributed tracing
- Metrics collection
- Context propagation across services

### Health Checks
- `/health` endpoints
- Database connectivity checks
- External service status

### Metrics Collection
- Request count and latency
- Error rates
- Resource utilization

## Module Patterns

### CommonJS & ES Modules
- `type: "commonjs"` in package.json
- ES module support in TypeScript
- Interop between module systems

### Singleton Pattern (DEPRECATED in Motia)

**Traditional Singleton** (No longer used in `slide-system`):
```typescript
// ❌ DEPRECATED - Do not use in Motia steps
class Logger {
  private static instance: Logger;

  static getInstance() {
    if (!Logger.instance) {
      Logger.instance = new Logger();
    }
    return Logger.instance;
  }
}
```

**Motia Pattern** (Correct approach):
```typescript
// ✅ CORRECT - Query external state
export async function getBots() {
  const supabase = createSupabaseClient();
  return supabase.from('active_bots').select();
}
```

## Anti-Patterns Avoided

✅ **No God Objects** - Small, focused modules
✅ **No Circular Dependencies** - Enforced by Nx
✅ **No Shared Mutable State** - Immutable data patterns (ESPECIALLY in Motia)
✅ **No Singletons in Motia** - All state in Supabase, not memory
✅ **No Callback Hell** - Async/await everywhere
✅ **No Magic Strings** - Constants and enums
✅ **No Deep Nesting** - Flat structures where possible

## New Patterns (October 2025)

### Pluggable Transport Pattern (Screenshare Bot)

**Factory Pattern for Multiple Transports**: Bot supports both Daily.co and LiveKit via pluggable architecture (October 2025).

**Key Components**:
1. **BaseTransport**: Abstract interface defining transport contract
2. **Transport Factory**: `create_transport(type, config)` → BaseTransport
3. **Adapters**: DailyTransport, LiveKitTransport implement BaseTransport
4. **Environment Switching**: `TRANSPORT_TYPE=daily|livekit` env var

**Benefits**:
- ✅ Zero code duplication (90% code reuse)
- ✅ Side-by-side testing (both transports work)
- ✅ Single maintenance point (fix bugs once)
- ✅ Easy migration (gradual Daily.co → LiveKit transition)

**Example**:
```python
# transports/base.py
class BaseTransport(ABC):
    @abstractmethod
    async def join_room(self, room_url: str): ...
    @abstractmethod
    async def send_image(self, frame: bytes): ...
    @abstractmethod
    async def cleanup(self): ...

# transports/__init__.py (Factory)
def create_transport(transport_type: str, config: dict) -> BaseTransport:
    if transport_type == 'daily':
        return DailyTransport(config)
    elif transport_type == 'livekit':
        return LiveKitTransport(config)
    raise ValueError(f"Unknown transport: {transport_type}")

# bot.py (Usage)
transport_type = os.getenv('TRANSPORT_TYPE', 'daily')
transport = create_transport(transport_type, config)
await transport.join_room(room_url)
```

**File Structure**:
```
bots/screenshare-bot/
├── transports/
│   ├── __init__.py         # Factory
│   ├── base.py             # Abstract interface
│   ├── daily_transport.py  # Daily.co adapter
│   └── livekit_transport.py # LiveKit adapter
└── bot.py                  # Main bot (transport-agnostic)
```

### Motia Event-Driven Architecture

**Architecture Refactor**: Migrated `slide-system` from singleton-based to event-driven + Supabase.

**Key Principles**:
1. **Stateless Steps**: Motia reloads modules → in-memory state lost
2. **External State**: All persistence in Supabase, not Maps/singletons
3. **Detached Processes**: Spawn with `detached: true` and `unref()`
4. **OS-Level Control**: Use `process.kill()` signals, not handles
5. **Event Communication**: Steps emit events, never direct calls

**Example Pattern**:
```typescript
// Motia step for bot management
export const config = {
  name: 'BotSpawn',
  type: 'api',
  path: '/api/bots/spawn',
  method: 'POST',
  emits: ['bot.spawned']
};

export const handler = async (req: any, { emit }: any) => {
  // 1. Spawn detached process
  const process = spawn(cmd, args, { detached: true });
  process.unref();

  // 2. Store state in Supabase
  const supabase = createSupabaseClient();
  await supabase.from('active_bots').insert({
    bot_id: id,
    pid: process.pid,
    status: 'running'
  });

  // 3. Emit event
  await emit({ topic: 'bot.spawned', data: { bot_id: id } });

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

**Documentation**:
- `apps/slide-system/docs/MOTIA_SUPABASE_ARCHITECTURE.md` - Full architecture guide
- `apps/slide-system/docs/PRODUCTION_DEPLOYMENT_RUNBOOK.md` - Deployment procedures
- `.claude/prds/_TEMPLATE_MOTIA_ARCHITECTURE.md` - PRD template
