# BuzzTrail Backup Workflows

A Motia-powered workflow system for automated customer data backup and cleanup operations supporting **Tavus** and **Langfuse** integrations.

## Overview

This application provides enterprise-grade backup and cleanup workflows using the Motia workflow framework. It features a comprehensive database schema supporting:

- **Tavus Integration**: Conversation transcripts, persona configurations, replica training data
- **Langfuse Integration**: Traces, observations, sessions, evaluation datasets  
- **Advanced Backup Management**: Automated scheduling, job tracking, retention policies
- **Visual Workflow Monitoring**: Real-time execution tracking via Motia workbench

## Architecture

### Motia Workflow Framework

The application uses Motia's step-based workflow system with visual flow diagrams. All workflows are defined as discrete steps that emit events to trigger subsequent steps.

### Key Components

1. **Backup Workflow** (`customer-backup-flow`)
   - `BackupInit`: Discovers customers and initializes backup configuration
   - `BackupExecution`: Executes backup operations for all customers with Tavus/Langfuse data
   - `BackupFinish`: Finalizes workflow and generates comprehensive reports

2. **Cleanup Workflow** (`cleanup-flow`)
   - `CleanupExpiredBackups`: Removes expired backups and frees storage space across all services

3. **API Triggers**
   - `TriggerBackup`: REST API endpoint to manually trigger backup workflows
   - `TriggerCleanup`: REST API endpoint to manually trigger cleanup workflows

4. **Extended Database Schema** (16 new tables)
   - **Tavus Tables**: 5 tables for conversations, personas, replicas, events, media
   - **Langfuse Tables**: 6 tables for traces, observations, sessions, scores, datasets
   - **Management Tables**: 5 tables for schedules, jobs, policies, API usage tracking

## Getting Started

### Prerequisites

- Node.js 18+ 
- pnpm package manager
- Built `@buzztrail/accounts-backup` and `@buzztrail/shared-database` libraries

### Installation

```bash
# Install dependencies
pnpm install

# Build the application
pnpm nx build backup-workflows
```

### Running the Application

```bash
# Start Motia development server with workbench
npx motia dev --port 3002
```

The Motia workbench will be available at http://localhost:3002/ where you can:
- View visual workflow diagrams
- Monitor workflow execution
- Debug step-by-step flow
- Access trace logs and state

## API Endpoints

### Trigger Backup Workflow

```bash
POST /backup/trigger
Content-Type: application/json

{
  "backupType": "full|incremental",     // Default: "full"
  "retentionDays": 30                   // Default: 30
}
```

**Response:**
```json
{
  "success": true,
  "message": "Backup workflow triggered successfully",
  "backupType": "full",
  "retentionDays": 30,
  "timestamp": "2025-09-02T08:00:00.000Z"
}
```

### Trigger Cleanup Workflow

```bash
POST /cleanup/trigger
Content-Type: application/json

{
  "retentionDays": 30,                  // Default: 30
  "forceCleanup": false                 // Default: false
}
```

**Response:**
```json
{
  "success": true,
  "message": "Cleanup workflow triggered successfully",
  "retentionDays": 30,
  "forceCleanup": false,
  "timestamp": "2025-09-02T08:00:00.000Z"
}
```

## Workflow Details

### Backup Workflow

The backup workflow executes in three main phases:

1. **Initialization** (`BackupInit`)
   - Connects to database and storage systems
   - Discovers all active customers
   - Stores customer list and configuration in workflow state

2. **Execution** (`BackupExecution`)
   - Iterates through each customer
   - Retrieves customer's Tavus accounts and personas
   - Creates compressed backup archives
   - Records backup metadata in database
   - Tracks success/failure for each customer

3. **Finalization** (`BackupFinish`)
   - Calculates summary statistics
   - Logs detailed results
   - Emits completion event

**Key Features:**
- Individual customer error isolation
- Compressed backup archives with checksums
- Automatic retention policy application
- Detailed execution logging

### Cleanup Workflow

The cleanup workflow (`CleanupExpiredBackups`) performs:

1. **Customer Discovery**
   - Identifies all customers with backups
   - Gets backup statistics before cleanup

2. **Cleanup Operations**
   - Removes expired backup directories from filesystem
   - Deletes expired backup records from database
   - Calculates storage freed per customer

3. **Reporting**
   - Generates cleanup summary
   - Reports total backups deleted and storage freed

## Data Storage

### Database Tables

The system uses an extensive SQLite schema managed by `@buzztrail/accounts-backup`:

#### **Core Tables**
- `customers`: Customer information and metadata
- `backups`: Backup records with paths, sizes, and checksums
- `customer_tavus_accounts`: Tavus account configurations

#### **Tavus Extended Tables** (NEW)
- `tavus_conversation_transcripts`: Complete conversation dialogue content
- `tavus_persona_configurations`: LLM settings, TTS/STT engines, behavior configs
- `tavus_replica_training`: Training progress, status, source materials
- `tavus_conversation_events`: Callback events and system notifications
- `tavus_media_assets`: Avatar images, training videos, audio files

#### **Langfuse Tables** (NEW)
- `langfuse_traces`: Core observability data with input/output
- `langfuse_observations`: Individual LLM calls with usage metrics
- `langfuse_sessions`: User session groupings and metadata
- `langfuse_scores`: Evaluation metrics and human feedback
- `langfuse_datasets`: Training and evaluation datasets
- `langfuse_dataset_items`: Individual dataset entries

#### **Backup Management Tables** (NEW)
- `backup_schedules`: Automated backup timing configuration
- `export_jobs`: Long-running export operation tracking
- `data_retention_policies`: Per-customer, per-service retention rules
- `service_api_usage`: API rate limiting and quota management
- `backup_job_dependencies`: Complex workflow orchestration

### File Structure

```
./backup-data/
├── customers/
│   ├── customer-1/
│   │   ├── 2025-09-02T08-00-00-000Z/
│   │   │   └── customer-data/
│   │   │       └── customer-1.json
│   │   └── 2025-09-01T08-00-00-000Z/
│   └── customer-2/
└── temp/
    ├── customer-1-full-2025-09-02T08-00-00-000Z.zip
    └── customer-2-full-2025-09-02T08-00-00-000Z.zip
```

## Monitoring and Debugging

### Motia Workbench

Access the visual workflow interface at http://localhost:3002/:

- **Flow Diagrams**: Visual representation of workflow steps and connections
- **Trace Timeline**: Step-by-step execution history
- **State Inspection**: View workflow state data between steps
- **Logs**: Centralized logging from all workflow steps

### Logging

All steps use structured logging with emojis for easy identification:

- 🔧 Initialization operations
- 💾 Backup execution
- 🧹 Cleanup operations
- ✅ Success indicators
- ❌ Error indicators
- 📊 Statistical information

### Error Handling

- Customer-level error isolation prevents single failures from stopping workflows
- Detailed error logging with context
- Graceful degradation for non-critical failures
- State preservation for debugging

## Development

### Project Structure

```
backup-workflows/
├── steps/                          # Motia workflow steps
│   ├── simple-backup-init.step.ts
│   ├── simple-backup-run.step.ts
│   ├── simple-backup-finish.step.ts
│   ├── emit-cleanup-event.step.ts
│   ├── trigger-backup-api.step.ts
│   └── trigger-cleanup-api.step.ts
├── motia-workbench.json            # Workflow visual layout
├── types.d.ts                      # Motia handler type definitions
└── src/
    └── main.ts                     # Application entry point
```

### Adding New Steps

1. Create a new step file in `steps/` directory
2. Export `config` (EventConfig/ApiRouteConfig) and `handler`
3. Update `motia-workbench.json` for visual positioning
4. Add to `types.d.ts` for TypeScript support

### Testing

```bash
# Build and run tests
pnpm nx build backup-workflows

# Test API endpoints
curl -X POST http://localhost:3002/backup/trigger \
  -H "Content-Type: application/json" \
  -d '{"backupType": "full"}'
```

## Integration

This application integrates with:

- **@buzztrail/accounts-backup**: Database and storage operations
- **@buzztrail/shared-database**: Common database schemas
- **Motia Framework**: Workflow orchestration and UI
- **Better-SQLite3**: Local database storage
- **FS-Extra**: File system operations

## Security

- No sensitive data logging
- Secure file path handling
- Database connection management
- Error message sanitization

## License

Private - BuzzTrail Internal Use Only