---
name: Tavus Development Environment & Testing Infrastructure
status: open
priority: high
effort: L
estimated_hours: 6-8 weeks
dependencies: []
created: 2025-10-02
updated: 2025-10-02
source: Archived planning document (tavus-dev-environment-plan.md)
---

# PRD: Tavus Development Environment & Testing Infrastructure

## Overview

Comprehensive development environment testing and routing infrastructure for Tavus API integration that prevents credit consumption during development, ensures proper environment separation (dev/staging/prod), and provides full observability through OpenTelemetry and Grafana Cloud.

**Key Objectives**:
1. **Prevent real Tavus credits from being burned during development and builds** (~$0.15/minute conversation costs)
2. **Ensure logging of all calls to real Tavus server** for insights and debugging
3. **Set up fake-tavus-server to run locally by default** with intelligent routing
4. **Make system adjustable** to switch between fake and real Tavus servers
5. **Implement comprehensive observability** with Grafana Cloud
6. **Provide dual server testing** for API contract validation

## Business Value

### Problem Statement

Current development environment has:
- **Credit Risk**: No safeguards preventing accidental real API calls during development (~$0.15/min × 100 dev calls/day = $15/day wasted)
- **Limited Observability**: No centralized logging or monitoring of Tavus API usage
- **Environment Confusion**: No clear separation between dev/staging/prod routing strategies
- **Testing Gaps**: No automated validation that fake server responses match real API
- **No Fallback Strategy**: Single point of failure if fake or real server unavailable

### Expected Outcomes

- **Zero credit consumption** in development and staging environments
- **100% API call logging** to Grafana Cloud for debugging and cost analysis
- **Seamless environment switching** via configuration (no code changes)
- **Automated testing** comparing fake vs real API responses for contract validation
- **Comprehensive observability** across all environments with dashboards and alerts

## Current State

### Existing Implementation (~40%)

**Implemented**:
- ✅ `fake-tavus-server` with 11 core conversation endpoints (apps/fake-tavus-server/)
- ✅ `proxy-server` with basic routing (apps/proxy-server/)
- ✅ Grafana Cloud account with API token configured
- ✅ Basic environment detection (NODE_ENV)
- ✅ TavusClient with configurable base URL

**Missing (~60%)**:
- ❌ OpenTelemetry integration (packages not installed)
- ❌ Comprehensive endpoint classification (free/safe/destructive flags)
- ❌ Environment-aware routing logic (dev/staging/prod strategies)
- ❌ Dual server testing for validation
- ❌ Fallback strategies when servers unavailable
- ❌ Mock data sync with real API
- ❌ Grafana Cloud dashboards and alerts
- ❌ API key management system (hard-coded keys in multiple files)

### Technical Debt

**Hard-coded API Keys** (security risk):
```typescript
// Files requiring cleanup:
// - libs/shared/config/src/tavus.ts: DEFAULT_TAVUS_API_KEY
// - libs/tavus/client/src/tavus.ts: DEFAULT_TAVUS_API_KEY
// - apps/tavus-zoom-bridge/src/tavus-bridge-manager.ts: hard-coded key
```

## Requirements

### Functional Requirements

#### FR1: OpenTelemetry Integration

**FR1.1**: Install OpenTelemetry packages
- Install `@opentelemetry/api`
- Install `@opentelemetry/auto-instrumentations-node`
- Configure OTLP exporter for Grafana Cloud

**FR1.2**: Environment-specific OpenTelemetry configuration
- **Development**: `deployment.environment=development`
- **Staging**: `deployment.environment=staging`
- **Production**: `deployment.environment=production`
- Service name: `buzztrail-tavus-api`
- Service namespace: `buzztrail-video-integration`

**FR1.3**: Automatic instrumentation
- Use `NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"`
- Auto-instrument HTTP requests, database queries, errors
- Resource detection: environment, host, OS

**Configuration Template**:
```bash
# Development
OTEL_TRACES_EXPORTER="otlp"
OTEL_EXPORTER_OTLP_ENDPOINT="https://otlp-gateway-prod-gb-south-1.grafana.net/otlp"
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic <token>"
OTEL_RESOURCE_ATTRIBUTES="service.name=buzztrail-tavus-api,service.namespace=buzztrail-video-integration,deployment.environment=development"
OTEL_NODE_RESOURCE_DETECTORS="env,host,os"
NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
```

#### FR2: API Endpoint Classification System

**FR2.1**: Boolean-based endpoint flags
```typescript
interface EndpointFlags {
  free: boolean;        // Does not consume credits
  safe: boolean;        // No side effects, idempotent, non-destructive
  destructive: boolean; // Permanently deletes or changes data
}

// Logic rules:
// - If safe=true: automatically idempotent=true and destructive=false
// - If safe=false: either destructive=true OR creates new resources
```

**FR2.2**: Endpoint classification database
- **Free Endpoints**: Health checks (`GET /v2/health`, `GET /v2/status`), read-only operations (`GET /v2/personas`, `GET /v2/conversations`)
- **Safe Endpoints**: Analytics (`GET /v2/analytics`), usage (`GET /v2/usage`), config (`GET /v2/config`)
- **Destructive Endpoints**: All PATCH/DELETE operations, resource creation (POST)

**FR2.3**: Testing strategy per endpoint
- **Free + Safe**: Test against real server in all environments
- **Free but not Safe**: Test against fake server only (dev/staging)
- **Paid + Safe**: Test against real server with monitoring
- **Paid + Destructive**: Fake server only (dev/staging), real server only for authenticated customers (prod)

**Example Classification**:
```typescript
const endpointConfig = {
  'GET /v2/personas': {
    flags: { free: true, safe: true, destructive: false },
    testing: 'Test against real server for data validation'
  },
  'DELETE /v2/personas/{id}': {
    flags: { free: false, safe: false, destructive: true },
    testing: 'Fake server only in development/staging'
  }
};
```

#### FR3: Environment-Aware Routing

**FR3.1**: Development environment strategy
- **Default**: `full-testing-with-safe-real` mode
- **Fake Server**: All endpoints (primary)
- **Real Server**: Only free + safe endpoints (for validation)
- **Testing Mode**: Dual server testing for comparison

**FR3.2**: Staging environment strategy
- **Default**: `full-testing-with-safe-real` mode (same as dev)
- **Allowed Endpoints**: Only free + safe endpoints to real server
- **Blocked Endpoints**: POST/PATCH/DELETE operations (credit consumption risk)
- **Purpose**: Validate integration without credit costs

**FR3.3**: Production environment strategy
- **Default**: `production` mode
- **Real Server**: All endpoints enabled
- **Authentication**: Customer-only access (no internal testing)
- **Fake Server**: Emergency fallback for critical operations only

**FR3.4**: Testing mode configuration
```typescript
type TestingMode =
  | 'full-testing-with-safe-real' // Fake all + real safe/free (default dev/staging)
  | 'fake-only'                    // Pure development without real API
  | 'real-only'                    // Test real API behavior (safe endpoints)
  | 'safe-only'                    // Real server safe endpoints, block others
  | 'production';                  // All endpoints for authenticated customers
```

**Environment Variables**:
```bash
# Development
TESTING_MODE=full-testing-with-safe-real
FAKE_SERVER_URL=http://localhost:3001
REAL_SERVER_URL=https://tavusapi.com

# Staging
TESTING_MODE=full-testing-with-safe-real
FAKE_SERVER_URL=https://fake-server.staging.buzztrail.ai
REAL_SERVER_URL=https://tavusapi.com

# Production
TESTING_MODE=production
REAL_SERVER_URL=https://tavusapi.com
```

#### FR4: Dual Server Testing

**FR4.1**: Automated comparison testing
- Test same request against both fake and real servers
- Compare response structure, status codes, data types
- Log differences for contract validation
- Alert on significant deviations

**FR4.2**: Response validation
```typescript
interface ResponseValidation {
  schema: 'Match real API response schema',
  timing: 'Fake server should respond faster than real API',
  data: 'Mock data should be realistic and consistent',
  errors: 'Fake server should simulate real error conditions'
}
```

**FR4.3**: Validation reporting
- Daily validation report: % of endpoints matching real API
- Drift detection: Highlight when fake server diverges from real API
- Contract updates: Automated alerts when real API changes

#### FR5: Fallback Strategies

**FR5.1**: Fake server unavailable (development)
- If endpoint is free OR safe: Route to real server
- Otherwise: Throw error (prevent accidental credit consumption)

**FR5.2**: Real server unavailable (staging)
- If endpoint is free OR safe: Route to fake server
- Otherwise: Throw error (endpoint not allowed in staging)

**FR5.3**: Real server unavailable (production)
- If critical operation: Emergency fallback to fake server
- Otherwise: Return service degradation error

**FR5.4**: Network error handling
- Retry logic for transient failures (3 retries with exponential backoff)
- Circuit breaker pattern to prevent cascading failures
- Comprehensive error logging with context

#### FR6: API Key Management

**FR6.1**: Remove all hard-coded API keys
- Audit and remove from libs/shared/config/src/tavus.ts
- Audit and remove from libs/tavus/client/src/tavus.ts
- Audit and remove from apps/tavus-zoom-bridge/src/tavus-bridge-manager.ts

**FR6.2**: Secure key storage
- Environment variables for all API keys
- Support multiple customer API keys (multi-tenant)
- Secure key management system (encrypted at rest)

**FR6.3**: Environment-specific key configuration
- Development: Testing API key (limited credits)
- Staging: Staging API key (different Tavus account)
- Production: Customer API keys (managed per customer)

#### FR7: Mock Data Synchronization

**FR7.1**: Periodic sync from real API
- Sync personas (free endpoint): Update fake server personas weekly
- Sync conversations (read-only): Mirror real conversation structures
- Sync configuration: Match real API settings

**FR7.2**: Realistic mock data generation
- Generate personas matching real API structure
- Generate conversations with realistic patterns
- Maintain data consistency and relationships

**FR7.3**: Manual sync trigger
- CLI command to force immediate sync
- Validation that fake data matches real API schema
- Report sync status and drift metrics

#### FR8: Monitoring & Alerting

**FR8.1**: Grafana Cloud dashboards
- **Real-time Operations**: Live API call rates, response times, errors
- **Business Intelligence**: Customer usage patterns, cost analysis
- **Development Insights**: Fake vs real API usage, mock data patterns
- **Performance Optimization**: Response time distributions, bottlenecks

**FR8.2**: Alerting rules
- **Credit consumption**: Alert if any credits consumed in dev/staging
- **Error rate thresholds**: Alert on >5% API failure rate
- **Performance degradation**: Alert on >2s response times
- **Environment switching**: Notify when production falls back to fake server

**FR8.3**: Cost tracking
- Track credit consumption per environment
- Track credit consumption per customer (production)
- Monthly cost reports and projections
- Budget alerts and anomaly detection

### Non-Functional Requirements

#### NFR1: Security
- API keys encrypted at rest
- API keys never logged or exposed in errors
- Secure transmission of API keys to services
- Role-based access control for different API keys

#### NFR2: Performance
- Fake server response time <100ms (vs real API ~300-500ms)
- Dual server testing overhead <500ms additional latency
- OpenTelemetry overhead <5% performance impact
- Circuit breaker activates within 3 failed requests

#### NFR3: Reliability
- Fake server uptime >99% in development
- Graceful degradation when servers unavailable
- No silent failures (all errors logged)
- Automatic recovery from transient failures

#### NFR4: Maintainability
- Endpoint classification defined in single configuration file
- Testing modes configurable via environment variables only
- OpenTelemetry configuration externalized
- Clear documentation for adding new endpoints

## Implementation Plan

### Phase 1: Foundation (Week 1-2)

**Day 1-3: OpenTelemetry Setup**
- Install OpenTelemetry packages
- Create environment-specific configuration files (.env.development, .env.staging, .env.production)
- Implement OpenTelemetry client initialization
- Test basic tracing to Grafana Cloud

**Day 4-7: API Key Cleanup**
- Audit all hard-coded API keys
- Create secure key management system
- Update all services to use environment variables
- Validate no keys in codebase (git-secrets scan)

**Day 8-10: Grafana Cloud Dashboards**
- Set up basic API monitoring dashboard
- Configure real-time operations view
- Add initial alerting rules (credit consumption, error rates)

### Phase 2: Endpoint Classification (Week 3)

**Day 11-13: Classification System**
- Create endpoint configuration database
- Define flags for all existing endpoints (11 endpoints in fake server)
- Implement classification validation logic
- Add unit tests for classification rules

**Day 14-17: Testing Strategy Implementation**
- Implement testing mode configuration
- Create environment-specific routing logic
- Add endpoint-level testing strategy override
- Validate classification with real API documentation

### Phase 3: Environment-Aware Router (Week 4-5)

**Day 18-21: Router Implementation**
- Create EnvironmentRouter class with mode detection
- Implement development routing strategy
- Implement staging routing strategy
- Implement production routing strategy

**Day 22-25: Testing Mode Support**
- Implement `full-testing-with-safe-real` mode
- Implement `fake-only` mode
- Implement `real-only` mode (safe endpoints)
- Implement `safe-only` mode (staging)

**Day 26-28: Integration Testing**
- Test all routing modes against fake server
- Test safe endpoints against real API (validation only)
- Validate credit consumption = 0 in dev/staging
- End-to-end testing all environment strategies

### Phase 4: Dual Server Testing (Week 6)

**Day 29-32: Comparison Testing**
- Implement DualServerTester class
- Add response comparison logic (schema, timing, data)
- Create validation reporting system
- Add drift detection alerts

**Day 33-35: Validation Automation**
- Automated daily validation runs
- Contract update detection
- Validation metrics dashboard in Grafana
- CI/CD integration for pre-deployment validation

### Phase 5: Fallback Strategies (Week 7)

**Day 36-39: Server Failure Handling**
- Implement FallbackStrategy class
- Add fake server failure handling (dev)
- Add real server failure handling (staging/prod)
- Implement circuit breaker pattern

**Day 40-42: Network Error Handling**
- Implement NetworkErrorHandler class
- Add retry logic with exponential backoff
- Add transient error detection
- Test all failure scenarios

### Phase 6: Mock Data Sync (Week 8)

**Day 43-46: Sync Implementation**
- Create DataSyncManager class
- Implement periodic sync from real API (free endpoints only)
- Add manual sync CLI command
- Validate sync accuracy

**Day 47-49: Mock Data Generation**
- Create MockDataGenerator class
- Generate realistic personas matching real API
- Generate realistic conversations
- Maintain data consistency and relationships

**Day 50-52: Final Testing & Documentation**
- End-to-end testing all environments
- Load testing dual server mode
- Complete documentation (setup guides, troubleshooting)
- Training session for development team

## Testing Strategy

### Unit Tests
- Endpoint classification logic
- Testing mode configuration
- Fallback strategy rules
- Mock data generation

### Integration Tests
- Environment-aware routing end-to-end
- Dual server testing comparison
- Fallback activation scenarios
- OpenTelemetry trace generation

### Contract Tests
- Fake server responses match real API schema
- All endpoints validated against real API documentation
- Automated regression detection

### Load Tests
- Dual server testing overhead measurement
- OpenTelemetry performance impact
- Circuit breaker activation under load

## Success Metrics

### Development Environment
- **Zero credits consumed**: 100% of API calls to fake server
- **Fast response times**: <100ms fake server responses
- **100% endpoint coverage**: All endpoints classified and routed correctly

### Staging Environment
- **Zero credits consumed**: Only free + safe endpoints to real server
- **Validation rate**: >95% of fake responses match real API
- **Error rate**: <1% routing errors

### Production Environment
- **Customer isolation**: 100% of customer requests to real server
- **Uptime**: >99.9% availability with fallback
- **Cost tracking**: Accurate credit consumption per customer

### Observability
- **100% trace coverage**: All API calls logged to Grafana Cloud
- **Alert response time**: <5 minutes to credit consumption alerts
- **Dashboard adoption**: Used daily by 100% of dev team

## Dependencies

### External Dependencies
- **Grafana Cloud account**: Already configured with API token
- **Tavus API access**: For real server testing (free endpoints only)
- **fake-tavus-server**: Must be running locally (localhost:3001)

### Internal Dependencies
- **proxy-server**: Routing implementation
- **TavusClient**: Configurable base URL support
- **Environment configuration**: .env files for all environments

## Risks & Mitigation

### Risk 1: Accidental Credit Consumption
**Mitigation**:
- Dual layer protection (classification + routing)
- Real-time alerts on credit consumption
- Monthly cost budgets and limits

### Risk 2: Fake Server Drift from Real API
**Mitigation**:
- Daily automated validation
- Periodic sync from real API (free endpoints)
- Contract test alerts on drift

### Risk 3: OpenTelemetry Performance Impact
**Mitigation**:
- Asynchronous trace export
- Sampling in high-traffic scenarios
- Performance monitoring and tuning

### Risk 4: Complexity of Multi-Environment Routing
**Mitigation**:
- Clear configuration over code approach
- Comprehensive documentation
- Environment-specific validation tests

## Documentation Requirements

### Setup Guides
- OpenTelemetry installation and configuration
- Grafana Cloud dashboard setup
- Environment variable configuration
- API key management setup

### Developer Guides
- Adding new Tavus endpoints (classification checklist)
- Testing mode selection for different scenarios
- Interpreting Grafana dashboards
- Troubleshooting routing issues

### Operations Guides
- Monitoring credit consumption
- Responding to alerts
- Manual sync procedures
- Emergency fallback procedures

## Related PRDs

- **tavus-conversation-management-system.md**: Conversation features (distinct from environment infrastructure)
- **service-orchestration-coordination.md**: Dev service orchestration (distinct from Tavus-specific routing)
- **backend-event-driven-architecture.md**: Event coordination (may integrate with Tavus events)

## Appendix

### Endpoint Classification Reference

#### Free Endpoints (Test against real server)
```typescript
{
  'GET /v2/health': { free: true, safe: true, destructive: false },
  'GET /v2/status': { free: true, safe: true, destructive: false },
  'GET /v2/personas': { free: true, safe: true, destructive: false },
  'GET /v2/personas/{id}': { free: true, safe: true, destructive: false },
  'GET /v2/conversations': { free: true, safe: true, destructive: false },
  'GET /v2/conversations/{id}': { free: true, safe: true, destructive: false },
  'GET /v2/config': { free: true, safe: true, destructive: false }
}
```

#### Destructive Endpoints (Fake server only in dev/staging)
```typescript
{
  'PATCH /v2/personas/{id}': { free: false, safe: false, destructive: true },
  'PATCH /v2/conversations/{id}': { free: false, safe: false, destructive: true },
  'DELETE /v2/personas/{id}': { free: false, safe: false, destructive: true },
  'DELETE /v2/conversations/{id}': { free: false, safe: false, destructive: true }
}
```

### Grafana Cloud API Token
```bash
# API Token (already configured)
GRAFANA_OTLP_API_TOKEN=glc_eyJvIjoiMTUxNzc4OCIsIm4iOiJqYXZhc2NyaXB0LXRva2VuIiwiayI6Iks4NU43MTRueEMxWkQ1djFETEU0RjlXdyIsIm0iOnsiciI6InByb2QtZ2Itc291dGgtMSJ9fQ==

# OTLP Endpoint
GRAFANA_OTLP_ENDPOINT=https://otlp-gateway-prod-gb-south-1.grafana.net/otlp
```

### Testing Mode Decision Matrix

| Environment | Default Mode | Fake Server | Real Server | Purpose |
|-------------|-------------|-------------|-------------|---------|
| Development | full-testing-with-safe-real | All endpoints | Safe + Free only | Fast development, periodic validation |
| Staging | full-testing-with-safe-real | All endpoints | Safe + Free only | Integration testing, no credit costs |
| Production | production | Emergency only | All endpoints (authenticated) | Customer requests only |
