# Workflow Sequence Diagrams

Detailed sequence diagrams for all Yemaya platform workflows.

## Table of Contents

1. [Authentication Workflows](#authentication-workflows)
2. [Project Management Workflows](#project-management-workflows)
3. [Asset Management Workflows](#asset-management-workflows)
4. [3D Generation Workflows](#3d-generation-workflows)
5. [Real-Time Collaboration Workflows](#real-time-collaboration-workflows)
6. [Agent Task Workflows](#agent-task-workflows)
7. [Quality Gate Workflows](#quality-gate-workflows)
8. [Pipeline Execution Workflows](#pipeline-execution-workflows)

---

## Authentication Workflows

### User Registration

```mermaid
sequenceDiagram
    participant C as Client
    participant RL as Rate Limiter
    participant API as API Server
    participant Auth as Auth Service
    participant DB as Database
    participant Email as Email Service

    C->>API: POST /auth/register
    API->>RL: Check rate limit
    RL-->>API: OK

    API->>Auth: Validate registration data
    Auth->>Auth: Validate password strength
    Auth->>DB: Check email uniqueness

    alt Email exists
        DB-->>Auth: Email taken
        Auth-->>API: Error: Email in use
        API-->>C: 409 Conflict
    else Email available
        DB-->>Auth: OK
        Auth->>Auth: Hash password
        Auth->>DB: Create user record
        DB-->>Auth: User created
        Auth->>Auth: Generate JWT tokens
        Auth->>Email: Send verification email
        Email-->>Auth: Queued
        Auth-->>API: Success + tokens
        API-->>C: 201 Created { user, tokens }
    end
```

### Login with Email/Password

```mermaid
sequenceDiagram
    participant C as Client
    participant RL as Rate Limiter
    participant API as API Server
    participant Auth as Auth Service
    participant DB as Database
    participant Session as Session Store

    C->>API: POST /auth/login
    API->>RL: Check rate limit (by IP)
    RL-->>API: OK

    API->>Auth: Authenticate user
    Auth->>DB: Find user by email
    DB-->>Auth: User record

    alt User not found
        Auth-->>API: Invalid credentials
        API-->>C: 401 Unauthorized
    else User found
        Auth->>Auth: Verify password hash
        alt Invalid password
            Auth->>RL: Record failed attempt
            Auth-->>API: Invalid credentials
            API-->>C: 401 Unauthorized
        else Password valid
            Auth->>Session: Create session
            Session-->>Auth: Session ID
            Auth->>Auth: Generate access token (15min)
            Auth->>Auth: Generate refresh token (7d)
            Auth->>DB: Update last login
            Auth-->>API: Success + tokens
            API-->>C: 200 OK { user, tokens }
        end
    end
```

### OAuth Authentication

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant OAuth as OAuth Provider
    participant Auth as Auth Service
    participant DB as Database

    C->>API: GET /auth/oauth/{provider}
    API->>API: Generate state token
    API-->>C: 302 Redirect to OAuth provider

    C->>OAuth: Authorize with provider
    OAuth-->>C: Redirect with code

    C->>API: GET /auth/oauth/{provider}/callback?code=...
    API->>OAuth: Exchange code for tokens
    OAuth-->>API: Access token + user info

    API->>Auth: Process OAuth response
    Auth->>DB: Find user by OAuth ID

    alt Existing user
        DB-->>Auth: User record
        Auth->>Auth: Update OAuth tokens
    else New user
        Auth->>DB: Create user from OAuth data
        DB-->>Auth: User created
    end

    Auth->>Auth: Generate JWT tokens
    Auth-->>API: Success + tokens
    API-->>C: Redirect to app with tokens
```

### Token Refresh

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Auth as Auth Service
    participant DB as Database

    C->>API: POST /auth/refresh
    Note over C,API: { refreshToken: "..." }

    API->>Auth: Validate refresh token
    Auth->>Auth: Decode & verify JWT

    alt Token invalid/expired
        Auth-->>API: Invalid token
        API-->>C: 401 Unauthorized
    else Token valid
        Auth->>DB: Check token not revoked
        alt Token revoked
            DB-->>Auth: Token revoked
            Auth-->>API: Token revoked
            API-->>C: 401 Unauthorized
        else Token valid
            Auth->>Auth: Generate new access token
            Auth->>Auth: Optionally rotate refresh token
            Auth-->>API: New tokens
            API-->>C: 200 OK { tokens }
        end
    end
```

### Password Reset

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Auth as Auth Service
    participant DB as Database
    participant Email as Email Service

    Note over C,Email: Request Reset
    C->>API: POST /auth/password/reset
    API->>Auth: Request password reset
    Auth->>DB: Find user by email

    alt User exists
        Auth->>Auth: Generate reset token (1h expiry)
        Auth->>DB: Store reset token
        Auth->>Email: Send reset email
    end

    Auth-->>API: Success (always, for security)
    API-->>C: 200 OK { message: "If email exists..." }

    Note over C,Email: Confirm Reset
    C->>API: POST /auth/password/reset/confirm
    Note over C,API: { token, newPassword }

    API->>Auth: Confirm password reset
    Auth->>DB: Validate reset token

    alt Token invalid/expired
        Auth-->>API: Invalid token
        API-->>C: 400 Bad Request
    else Token valid
        Auth->>Auth: Hash new password
        Auth->>DB: Update password
        Auth->>DB: Invalidate all sessions
        Auth->>DB: Delete reset token
        Auth-->>API: Success
        API-->>C: 200 OK
    end
```

---

## Project Management Workflows

### Create Project

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Proj as Project Service
    participant DB as Database
    participant Activity as Activity Logger

    C->>API: POST /projects
    Note over C,API: { name, type, settings, ... }

    API->>API: Authenticate & authorize
    API->>Proj: Create project

    Proj->>Proj: Validate input data
    Proj->>Proj: Generate unique slug
    Proj->>DB: Create project record
    DB-->>Proj: Project ID

    Proj->>DB: Add creator as owner
    Proj->>DB: Initialize default settings
    Proj->>Activity: Log project creation

    Proj-->>API: Project details
    API-->>C: 201 Created { project }
```

### Duplicate Project

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Proj as Project Service
    participant Asset as Asset Service
    participant DB as Database
    participant Storage as MinIO Storage

    C->>API: POST /projects/{id}/duplicate
    Note over C,API: { name, includeAssets }

    API->>API: Authenticate & authorize
    API->>Proj: Duplicate project

    Proj->>DB: Load source project
    DB-->>Proj: Project data

    Proj->>Proj: Generate new slug
    Proj->>DB: Create new project record
    DB-->>Proj: New project ID

    alt includeAssets = true
        Proj->>Asset: Get project assets
        Asset->>DB: List assets
        DB-->>Asset: Asset list

        loop For each asset
            Asset->>Storage: Copy asset file
            Storage-->>Asset: New file URL
            Asset->>DB: Create asset record
        end
    end

    Proj->>DB: Copy project settings
    Proj->>DB: Add user as owner

    Proj-->>API: New project details
    API-->>C: 201 Created { project }
```

### Add Project Member

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Proj as Project Service
    participant Notify as Notification Service
    participant DB as Database
    participant Email as Email Service

    C->>API: POST /projects/{id}/members
    Note over C,API: { userId/email, role }

    API->>API: Authenticate & authorize (admin+)
    API->>Proj: Add member

    Proj->>DB: Check project exists
    Proj->>DB: Check user not already member

    alt Invite by email (user doesn't exist)
        Proj->>DB: Create pending invitation
        Proj->>Email: Send invitation email
        Email-->>Proj: Sent
        Proj-->>API: Invitation sent
        API-->>C: 200 OK { status: "invited" }
    else Add existing user
        Proj->>DB: Add member with role
        DB-->>Proj: Member added
        Proj->>Notify: Send in-app notification
        Proj->>Email: Send welcome email
        Proj-->>API: Member details
        API-->>C: 201 Created { member }
    end
```

---

## Asset Management Workflows

### Chunked File Upload

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Upload as Upload Service
    participant Storage as MinIO Storage
    participant DB as Database

    Note over C,DB: Initiate Upload
    C->>API: POST /projects/{id}/assets/upload
    Note over C,API: { filename, size, contentType }

    API->>Upload: Initialize chunked upload
    Upload->>Upload: Validate file type & size
    Upload->>Storage: Create multipart upload
    Storage-->>Upload: Upload ID
    Upload->>DB: Store upload session
    Upload-->>API: { uploadId, chunkSize }
    API-->>C: 200 OK { uploadId, chunkSize }

    Note over C,DB: Upload Chunks
    loop For each chunk
        C->>API: PUT /assets/upload/{uploadId}/chunks/{n}
        Note over C,API: Binary chunk data
        API->>Upload: Process chunk
        Upload->>Upload: Verify chunk size & hash
        Upload->>Storage: Upload part
        Storage-->>Upload: Part ETag
        Upload->>DB: Update chunk status
        Upload-->>API: Chunk received
        API-->>C: 200 OK { chunksReceived }
    end

    Note over C,DB: Complete Upload
    C->>API: POST /assets/upload/{uploadId}/complete
    API->>Upload: Finalize upload

    Upload->>DB: Verify all chunks received
    Upload->>Storage: Complete multipart upload
    Storage-->>Upload: Final file URL

    Upload->>DB: Create asset record
    Upload->>Upload: Extract metadata
    Upload->>DB: Update asset metadata

    Upload-->>API: Asset details
    API-->>C: 201 Created { asset }
```

### Asset Processing Pipeline

```mermaid
sequenceDiagram
    participant Upload as Upload Service
    participant Queue as BullMQ Queue
    participant Worker as Asset Worker
    participant Storage as MinIO Storage
    participant DB as Database
    participant WS as WebSocket

    Upload->>Queue: Enqueue processing job
    Note over Queue: { assetId, type, processing }

    Queue->>Worker: Process asset job
    Worker->>DB: Load asset record
    DB-->>Worker: Asset details
    Worker->>Storage: Download asset
    Storage-->>Worker: File data

    Worker->>WS: Emit progress (0%)

    alt Image asset
        Worker->>Worker: Generate thumbnails
        Worker->>Worker: Extract EXIF metadata
        Worker->>Worker: Optimize for web
    else Video asset
        Worker->>Worker: Extract frames
        Worker->>Worker: Transcode to HLS
        Worker->>Worker: Generate preview
    else 3D model
        Worker->>Worker: Validate geometry
        Worker->>Worker: Generate preview render
        Worker->>Worker: Extract mesh stats
    else Audio
        Worker->>Worker: Normalize audio
        Worker->>Worker: Generate waveform
        Worker->>Worker: Transcode to web formats
    end

    Worker->>WS: Emit progress (50%)

    Worker->>Storage: Upload processed files
    Storage-->>Worker: URLs

    Worker->>DB: Update asset with metadata
    Worker->>WS: Emit complete (100%)

    Worker-->>Queue: Job complete
```

### Asset Version Control

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Asset as Asset Service
    participant DB as Database
    participant Storage as MinIO Storage

    Note over C,Storage: Create New Version
    C->>API: POST /assets/{id}/versions
    Note over C,API: { file, changelog }

    API->>Asset: Create version
    Asset->>DB: Load current asset
    DB-->>Asset: Asset record

    Asset->>Asset: Increment version number
    Asset->>Storage: Upload new file
    Storage-->>Asset: New file URL

    Asset->>DB: Create version record
    Asset->>DB: Update current version pointer

    Asset-->>API: Version details
    API-->>C: 201 Created { version }

    Note over C,Storage: Restore Previous Version
    C->>API: POST /assets/{id}/versions/{vId}/restore

    API->>Asset: Restore version
    Asset->>DB: Load version record
    DB-->>Asset: Version data

    Asset->>DB: Create new version (copy of old)
    Asset->>DB: Update current pointer

    Asset-->>API: Restored version
    API-->>C: 200 OK { version }
```

---

## 3D Generation Workflows

### Text-to-3D Generation

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Gen as Generation Service
    participant Queue as Job Queue
    participant Worker as 3D Worker
    participant Provider as 3D Provider
    participant Mesh as Mesh Processor
    participant Texture as Texture Processor
    participant Storage as MinIO
    participant DB as Database
    participant WS as WebSocket

    C->>API: POST /3d/generate
    Note over C,API: { prompt, provider, quality }

    API->>Gen: Create generation job
    Gen->>Gen: Validate provider availability
    Gen->>Gen: Optimize prompt for provider
    Gen->>DB: Create job record
    DB-->>Gen: Job ID
    Gen->>Queue: Enqueue generation job
    Gen-->>API: Job ID + status
    API-->>C: 202 Accepted { jobId }

    Queue->>Worker: Process generation job
    Worker->>DB: Update status: processing
    Worker->>WS: Emit status update

    Worker->>Provider: Submit generation request
    Note over Provider: Rodin/Meshy/Tripo/etc.

    loop Until complete
        Worker->>Provider: Poll status
        Provider-->>Worker: Progress update
        Worker->>WS: Emit progress %
    end

    Provider-->>Worker: Raw 3D model

    Worker->>Mesh: Process mesh
    Mesh->>Mesh: Optimize geometry
    Mesh->>Mesh: Clean topology
    Mesh->>Mesh: Generate LODs
    Mesh->>Mesh: UV unwrap
    Mesh-->>Worker: Processed mesh

    Worker->>WS: Emit progress (mesh done)

    Worker->>Texture: Process textures
    Texture->>Texture: Generate PBR maps
    Texture->>Texture: Upscale textures
    Texture->>Texture: Bake maps
    Texture-->>Worker: Textured model

    Worker->>WS: Emit progress (textures done)

    Worker->>Storage: Upload final model
    Storage-->>Worker: Asset URLs

    Worker->>DB: Update job: completed
    Worker->>WS: Emit completion event

    C->>API: GET /3d/jobs/{jobId}
    API-->>C: 200 OK { status: completed, assets }
```

### Image-to-3D with Auto-Rigging

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Gen as Generation Service
    participant Worker as 3D Worker
    participant Provider as 3D Provider
    participant Rig as Rigging Engine
    participant Storage as MinIO
    participant WS as WebSocket

    C->>API: POST /3d/image-to-3d
    Note over C,API: { image, autoRig: true, rigType }

    API->>Gen: Create generation job
    Gen-->>API: Job ID
    API-->>C: 202 Accepted { jobId }

    Note over Worker: ... 3D Generation Process ...
    Worker->>Provider: Generate from image
    Provider-->>Worker: Raw mesh

    Worker->>WS: Emit: mesh generated

    alt autoRig enabled
        Worker->>Rig: Auto-rig character
        Rig->>Rig: Detect skeleton type

        alt Humanoid
            Rig->>Rig: Create humanoid skeleton
            Rig->>Rig: Auto-weight painting
            Rig->>Rig: Generate IK constraints
        else Quadruped
            Rig->>Rig: Create quadruped skeleton
            Rig->>Rig: Setup leg IK
        else Custom
            Rig->>Rig: Infer bone structure
        end

        Rig->>Rig: Validate rig quality
        Rig->>Rig: Test deformations
        Rig-->>Worker: Rigged model + metadata
        Worker->>WS: Emit: rigging complete
    end

    Worker->>Storage: Upload rigged model
    Storage-->>Worker: URLs (FBX, GLTF, etc.)

    Worker->>WS: Emit: job complete
    C->>API: GET /3d/jobs/{id}/download
    API-->>C: { urls: { fbx, gltf, usd } }
```

### Batch 3D Generation

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Gen as Generation Service
    participant Queue as Job Queue
    participant Worker as 3D Worker
    participant WS as WebSocket

    C->>API: POST /3d/batch
    Note over C,API: { prompts: [...], provider, quality }

    API->>Gen: Create batch job
    Gen->>Gen: Validate batch size limit

    loop For each prompt
        Gen->>Queue: Enqueue individual job
    end

    Gen-->>API: Batch ID + job IDs
    API-->>C: 202 Accepted { batchId, jobs: [...] }

    par Parallel Processing
        Worker->>Queue: Process job 1
        Worker->>WS: Emit progress (job 1)
    and
        Worker->>Queue: Process job 2
        Worker->>WS: Emit progress (job 2)
    and
        Worker->>Queue: Process job 3
        Worker->>WS: Emit progress (job 3)
    end

    loop Until all complete
        C->>API: GET /3d/batch/{batchId}
        API-->>C: { status, completed: n/total }
    end

    API-->>C: { status: completed, results: [...] }
```

---

## Real-Time Collaboration Workflows

### Join Collaboration Session

```mermaid
sequenceDiagram
    participant C as Client
    participant WS as WebSocket Server
    participant Collab as Collaboration Service
    participant Yjs as Yjs Document
    participant DB as Database

    C->>WS: Connect WebSocket
    WS->>WS: Authenticate token
    WS-->>C: Connected

    C->>WS: join_session { projectId, resourceId }
    WS->>Collab: Join session

    Collab->>DB: Get/create room
    DB-->>Collab: Room ID

    Collab->>Yjs: Initialize/connect to document
    Yjs-->>Collab: Document state

    Collab->>Collab: Add participant
    Collab->>WS: Broadcast participant_joined

    WS-->>C: session_joined { roomId, participants }
    WS-->>C: document_sync { state }

    loop Real-time updates
        C->>WS: cursor_move { position }
        WS->>Collab: Update cursor
        Collab->>WS: Broadcast to others
        WS-->>C: cursors_updated { cursors }
    end
```

### Real-Time Document Editing

```mermaid
sequenceDiagram
    participant C1 as Client 1
    participant C2 as Client 2
    participant WS as WebSocket Server
    participant Yjs as Yjs CRDT
    participant DB as Database

    Note over C1,DB: Client 1 makes edit
    C1->>WS: document_update { ops }
    WS->>Yjs: Apply operations
    Yjs->>Yjs: CRDT merge
    Yjs-->>WS: Merged state

    WS->>DB: Persist state (debounced)
    WS-->>C2: document_update { ops }

    Note over C1,DB: Concurrent edit from Client 2
    C2->>WS: document_update { ops }
    WS->>Yjs: Apply operations
    Yjs->>Yjs: CRDT merge (auto-resolve)
    Yjs-->>WS: Merged state

    WS-->>C1: document_update { ops }
    WS-->>C2: ack

    Note over C1,DB: Both clients now in sync
```

### Comment Thread Workflow

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Collab as Collaboration Service
    participant Notify as Notification Service
    participant DB as Database
    participant WS as WebSocket

    Note over C,WS: Create Thread
    C->>API: POST /projects/{id}/comments
    Note over C,API: { content, resourceId, position, mentions }

    API->>Collab: Create comment thread
    Collab->>DB: Create thread record
    DB-->>Collab: Thread ID
    Collab->>DB: Create initial comment

    Collab->>Notify: Notify mentioned users
    Notify->>WS: Push notification

    Collab->>WS: Broadcast thread_created
    Collab-->>API: Thread details
    API-->>C: 201 Created { thread }

    Note over C,WS: Reply to Thread
    C->>API: POST /comments/{threadId}/reply
    API->>Collab: Add reply
    Collab->>DB: Create comment
    Collab->>Notify: Notify thread participants
    Collab->>WS: Broadcast comment_added
    API-->>C: 201 Created { comment }

    Note over C,WS: Resolve Thread
    C->>API: POST /comments/{threadId}/resolve
    API->>Collab: Resolve thread
    Collab->>DB: Update thread status
    Collab->>WS: Broadcast thread_resolved
    API-->>C: 200 OK
```

### Review Workflow

```mermaid
sequenceDiagram
    participant Req as Requester
    participant API as API Server
    participant Collab as Collaboration Service
    participant Rev as Reviewer
    participant Notify as Notification
    participant DB as Database

    Note over Req,DB: Create Review
    Req->>API: POST /projects/{id}/reviews
    Note over API: { entityId, reviewers, deadline }

    API->>Collab: Create review
    Collab->>DB: Create review record
    Collab->>DB: Create reviewer assignments

    loop For each reviewer
        Collab->>Notify: Send review request
    end

    Collab-->>API: Review details
    API-->>Req: 201 Created { review }

    Note over Req,DB: Reviewer Submits Decision
    Rev->>API: POST /reviews/{id}/decision
    Note over API: { decision: "approve", comment }

    API->>Collab: Record decision
    Collab->>DB: Update reviewer record
    Collab->>Notify: Notify requester

    Collab->>DB: Check if all reviewed

    alt All reviewers decided
        Collab->>DB: Update review status
        Collab->>Notify: Notify requester of completion

        alt All approved
            Collab-->>API: { status: "approved" }
        else Has rejections
            Collab-->>API: { status: "changes_requested" }
        end
    else Pending reviewers
        Collab-->>API: { status: "pending", remaining: n }
    end

    API-->>Rev: 200 OK { review }
```

### Resource Locking

```mermaid
sequenceDiagram
    participant C1 as Client 1
    participant C2 as Client 2
    participant API as API Server
    participant Lock as Lock Service
    participant DB as Database
    participant WS as WebSocket

    Note over C1,WS: Acquire Lock
    C1->>API: POST /locks
    Note over API: { resourceId, lockType: "exclusive" }

    API->>Lock: Acquire lock
    Lock->>DB: Check existing locks

    alt Resource unlocked
        Lock->>DB: Create lock record
        DB-->>Lock: Lock ID
        Lock->>WS: Broadcast lock_acquired
        Lock-->>API: Lock details
        API-->>C1: 200 OK { lock, expiresAt }
    else Resource locked
        Lock-->>API: Lock conflict
        API-->>C1: 409 Conflict { holder, expiresAt }
    end

    Note over C1,WS: Client 2 Tries to Lock
    C2->>API: POST /locks
    API->>Lock: Acquire lock
    Lock->>DB: Check existing locks
    Lock-->>API: Lock conflict
    API-->>C2: 409 Conflict { holder: "Client 1" }

    Note over C1,WS: Release Lock
    C1->>API: DELETE /locks/{lockId}
    API->>Lock: Release lock
    Lock->>DB: Delete lock record
    Lock->>WS: Broadcast lock_released
    Lock-->>API: OK
    API-->>C1: 200 OK
```

---

## Agent Task Workflows

### Single Agent Task Execution

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Queue as Job Queue
    participant Worker as Agent Worker
    participant LLM as LLM Provider
    participant Tools as Tool Executor
    participant DB as Database
    participant WS as WebSocket

    C->>API: POST /agents/tasks
    Note over C,API: { taskType, context, model }

    API->>Queue: Enqueue agent task
    API->>DB: Create task record
    API-->>C: 202 Accepted { taskId }

    Queue->>Worker: Process task
    Worker->>DB: Update status: processing
    Worker->>WS: Emit task_started

    Worker->>Worker: Initialize agent
    Worker->>Worker: Load context & tools

    loop Agent execution
        Worker->>LLM: Send prompt
        LLM-->>Worker: Response

        alt Tool use required
            Worker->>Tools: Execute tool
            Tools-->>Worker: Tool result
            Worker->>WS: Emit tool_executed
        else Direct response
            Worker->>Worker: Process response
        end

        Worker->>WS: Emit progress
    end

    Worker->>DB: Store results
    Worker->>DB: Update status: completed
    Worker->>WS: Emit task_completed

    C->>API: GET /agents/tasks/{id}
    API-->>C: 200 OK { status, result }
```

### Multi-Agent Collaboration

```mermaid
sequenceDiagram
    participant C as Client
    participant Crew as Crew Orchestrator
    participant Bus as Message Bus
    participant A1 as Agent 1 (Writer)
    participant A2 as Agent 2 (Editor)
    participant A3 as Agent 3 (Reviewer)
    participant LLM as LLM Provider

    C->>Crew: Execute crew task
    Crew->>Crew: Parse task dependencies
    Crew->>Bus: Initialize message bus

    Note over Crew,LLM: Sequential execution mode

    Crew->>A1: Assign task: Write draft
    A1->>LLM: Generate content
    LLM-->>A1: Draft content
    A1->>Bus: Publish result
    Bus->>Crew: Task complete

    Crew->>A2: Assign task: Edit draft
    Bus->>A2: Provide draft from A1
    A2->>LLM: Edit content
    LLM-->>A2: Edited content
    A2->>Bus: Publish result
    Bus->>Crew: Task complete

    Crew->>A3: Assign task: Review
    Bus->>A3: Provide edited content
    A3->>LLM: Review content
    LLM-->>A3: Review feedback

    alt Approved
        A3->>Bus: Publish: approved
        Bus->>Crew: Task complete
        Crew-->>C: Final result
    else Changes needed
        A3->>Bus: Publish: revisions needed
        Bus->>A2: Handoff with feedback
        Note over A2,LLM: Revision loop
    end
```

### Batch Agent Processing

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Queue as Job Queue
    participant W1 as Worker 1
    participant W2 as Worker 2
    participant W3 as Worker 3
    participant DB as Database

    C->>API: POST /agents/batch
    Note over C,API: { tasks: [...], maxConcurrent: 3 }

    API->>DB: Create batch record

    loop For each task
        API->>Queue: Enqueue task
    end

    API-->>C: 202 Accepted { batchId, tasks }

    par Parallel execution (up to maxConcurrent)
        Queue->>W1: Process task 1
        W1-->>Queue: Complete
    and
        Queue->>W2: Process task 2
        W2-->>Queue: Complete
    and
        Queue->>W3: Process task 3
        W3-->>Queue: Complete
    end

    W1->>DB: Update task status
    W2->>DB: Update task status
    W3->>DB: Update task status

    DB->>DB: Check batch completion

    alt All tasks complete
        DB->>DB: Update batch: completed
    else Some failed
        DB->>DB: Update batch: partial_failure
    end

    C->>API: GET /agents/batch/{batchId}
    API-->>C: { status, results: [...] }
```

---

## Quality Gate Workflows

### Quality Gate Assessment

```mermaid
sequenceDiagram
    participant Pipeline as Pipeline Executor
    participant QG as Quality Gate System
    participant Checks as Quality Checkers
    participant LLM as LLM Analyzer
    participant DB as Database
    participant Notify as Notification

    Pipeline->>QG: Submit for quality check
    Note over Pipeline,QG: { phaseOutput, gateType }

    QG->>QG: Determine applicable checks

    par Run checks in parallel
        QG->>Checks: Narrative check
        Checks->>LLM: Analyze script quality
        LLM-->>Checks: Quality scores
        Checks-->>QG: Narrative report
    and
        QG->>Checks: Visual check
        Checks->>Checks: Style consistency
        Checks->>Checks: Technical specs
        Checks-->>QG: Visual report
    and
        QG->>Checks: Technical check
        Checks->>Checks: Performance metrics
        Checks->>Checks: Memory usage
        Checks-->>QG: Technical report
    end

    QG->>QG: Aggregate scores
    QG->>QG: Identify issues

    alt Score >= threshold
        QG->>DB: Log: PASSED
        QG-->>Pipeline: { decision: "pass" }
    else Score < threshold (minor issues)
        QG->>DB: Log: WARNING
        QG->>Notify: Alert stakeholders
        QG-->>Pipeline: { decision: "warning", issues }
    else Critical issues found
        QG->>DB: Log: BLOCKED
        QG->>Notify: Alert stakeholders (urgent)
        QG-->>Pipeline: { decision: "block", issues }
    end
```

### Issue Auto-Remediation

```mermaid
sequenceDiagram
    participant QG as Quality Gate
    participant Auto as Auto-Fixer
    participant LLM as LLM
    participant Tools as Remediation Tools
    participant DB as Database

    QG->>Auto: Attempt auto-fix
    Note over QG,Auto: { issues: [...] }

    loop For each issue
        Auto->>Auto: Check if auto-fixable

        alt Auto-fixable
            Auto->>Tools: Apply fix
            Tools-->>Auto: Fixed

            alt Fix successful
                Auto->>Auto: Mark issue resolved
            else Fix failed
                Auto->>Auto: Mark for manual review
            end
        else Requires human
            Auto->>Auto: Mark for manual review
        end
    end

    Auto->>DB: Update issue statuses

    alt All issues resolved
        Auto-->>QG: { success: true }
    else Some issues remain
        Auto-->>QG: { success: false, remaining: [...] }
    end
```

### Human Review Override

```mermaid
sequenceDiagram
    participant QG as Quality Gate
    participant Notify as Notification
    participant Human as Human Reviewer
    participant API as API Server
    participant Pipeline as Pipeline Executor
    participant DB as Database

    QG->>Notify: Request human review
    Note over Notify: { issues, context, severity }

    Notify->>Human: Send review request
    Note over Human: Email + in-app notification

    Human->>API: GET /quality-gates/{id}/review
    API-->>Human: Issue details + context

    Human->>API: POST /quality-gates/{id}/decision
    Note over API: { decision, justification }

    API->>DB: Record decision + justification

    alt Approved (override)
        API->>QG: Override: approved
        QG->>Pipeline: Continue execution
        QG->>DB: Log override with reason
    else Rejected
        API->>QG: Decision: rejected
        QG->>Pipeline: Block execution
        QG->>Notify: Notify stakeholders
    else Request fixes
        API->>QG: Decision: request_fixes
        QG->>Pipeline: Return for remediation
        QG->>Notify: Notify responsible parties
    end

    API-->>Human: 200 OK
```

---

## Pipeline Execution Workflows

### Full Pipeline Execution

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Exec as Pipeline Executor
    participant Sched as Resource Scheduler
    participant Phase as Phase Handler
    participant QG as Quality Gate
    participant CP as Checkpoint Manager
    participant DB as Database
    participant WS as WebSocket

    C->>API: POST /pipelines/execute
    Note over C,API: { templateId, parameters }

    API->>Exec: Initialize pipeline
    Exec->>DB: Create pipeline run record
    Exec->>Sched: Allocate resources
    Sched-->>Exec: Resources allocated

    Exec->>CP: Create initial checkpoint
    Exec-->>API: Pipeline started
    API-->>C: 202 Accepted { runId }

    loop For each phase
        Exec->>Sched: Request phase resources
        Sched-->>Exec: Resources ready

        Exec->>Phase: Execute phase
        Phase->>WS: Emit phase_started
        Phase->>Phase: Process phase logic
        Phase->>WS: Emit progress updates
        Phase-->>Exec: Phase output

        Exec->>CP: Create checkpoint
        Exec->>QG: Quality gate check

        alt Passed
            QG-->>Exec: Continue
            Exec->>WS: Emit phase_completed
        else Failed
            QG-->>Exec: Block
            Exec->>WS: Emit quality_gate_failed
            Exec->>Exec: Await resolution
        end
    end

    Exec->>DB: Update run: completed
    Exec->>WS: Emit pipeline_completed
    Exec->>Sched: Release resources

    C->>API: GET /pipelines/runs/{runId}
    API-->>C: { status: completed, outputs }
```

### Pipeline Recovery from Checkpoint

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Exec as Pipeline Executor
    participant CP as Checkpoint Manager
    participant DB as Database
    participant WS as WebSocket

    Note over C,WS: Pipeline failure occurred

    C->>API: POST /pipelines/runs/{runId}/resume
    API->>Exec: Resume pipeline

    Exec->>CP: Load latest checkpoint
    CP->>DB: Fetch checkpoint data
    DB-->>CP: Checkpoint state
    CP-->>Exec: Restored state

    Exec->>Exec: Validate checkpoint integrity
    Exec->>Exec: Identify failed phase
    Exec->>WS: Emit pipeline_resuming

    Exec->>Exec: Resume from failed phase

    loop Continue remaining phases
        Exec->>Exec: Execute phase
        Exec->>CP: Create checkpoint
        Exec->>WS: Emit progress
    end

    Exec->>DB: Update run: completed
    Exec->>WS: Emit pipeline_completed

    API-->>C: 200 OK { status: resumed }
```

### Pipeline Rollback

```mermaid
sequenceDiagram
    participant C as Client
    participant API as API Server
    participant Exec as Pipeline Executor
    participant Rollback as Rollback Manager
    participant CP as Checkpoint Manager
    participant DB as Database
    participant WS as WebSocket

    C->>API: POST /pipelines/runs/{runId}/rollback
    Note over C,API: { targetPhase }

    API->>Exec: Initiate rollback
    Exec->>CP: Get checkpoint for target phase
    CP-->>Exec: Checkpoint state

    Exec->>Rollback: Begin rollback

    loop For each phase to rollback (reverse order)
        Rollback->>WS: Emit phase_rolling_back
        Rollback->>Rollback: Execute rollback logic
        Rollback->>Rollback: Cleanup artifacts
        Rollback->>DB: Update phase status
        Rollback->>WS: Emit phase_rolled_back
    end

    Rollback->>DB: Restore checkpoint state
    Rollback-->>Exec: Rollback complete

    Exec->>DB: Update run status
    Exec->>WS: Emit rollback_complete

    API-->>C: 200 OK { status: rolled_back, currentPhase }
```

---

## Summary

These sequence diagrams document the core workflows of the Yemaya platform:

| Category       | Workflows                                                 |
| -------------- | --------------------------------------------------------- |
| Authentication | Registration, Login, OAuth, Token Refresh, Password Reset |
| Projects       | Creation, Duplication, Member Management                  |
| Assets         | Chunked Upload, Processing, Version Control               |
| 3D Generation  | Text-to-3D, Image-to-3D, Batch Generation                 |
| Collaboration  | Sessions, Real-time Editing, Comments, Reviews, Locking   |
| Agents         | Single Task, Multi-Agent, Batch Processing                |
| Quality Gates  | Assessment, Auto-Remediation, Human Override              |
| Pipelines      | Full Execution, Checkpoint Recovery, Rollback             |

---

## See Also

- [Pipeline Architecture](./pipelines.md)
- [API Endpoints Reference](../api/endpoints/README.md)
- [WebSocket Events](../api/endpoints/websocket.md)
