# Workflow Orchestrator

## ⚠️ CRITICAL EXECUTION NOTICE ⚠️

**THIS IS AN EXECUTABLE WORKFLOW - NOT REFERENCE MATERIAL**

When this task is invoked:
1. **AUTOMATIC AGENT COORDINATION** - Seamlessly coordinate all specialized agents
2. **WORKFLOW ORCHESTRATION** - Manage complete end-to-end workflow execution
3. **STATE MANAGEMENT** - Maintain workflow state across all phases and agent transitions
4. **ERROR RECOVERY** - Handle failures and provide workflow resumption capabilities

## Overview

This workflow serves as the central orchestration engine for complete engineering workflows, managing automatic agent handoffs, maintaining state consistency, and ensuring seamless execution from task import through implementation completion.

## Input Parameters

### Required Parameters
- **workflow_type**: "full-implementation" | "import-only" | "coordination-only"
- **task_groups**: Array of task group objects with coordination requirements

### Optional Parameters
- **execution_mode**: "automatic" | "step-by-step" | "manual-approval" (default: "automatic")
- **parallel_execution**: boolean (default: true) - Enable parallel group execution
- **error_handling**: "stop-on-error" | "continue-on-error" | "retry-on-error" (default: "retry-on-error")

## Execution Steps

### Phase 1: Orchestration Setup

```yaml
step: orchestration_initialization
description: Initialize complete workflow orchestration
actions:
  - validate_workflow_prerequisites: Ensure all required data and agents available
  - create_orchestration_state: Initialize comprehensive workflow state tracking
  - setup_agent_coordination: Prepare agent communication and handoff protocols
  - establish_execution_plan: Create detailed execution plan with dependencies
  - initialize_error_recovery: Setup error handling and recovery mechanisms
orchestration_components:
  workflow_state:
    - current_phase: "Active workflow phase"
    - execution_queue: "Queue of pending agent executions"
    - completed_phases: "List of successfully completed phases"
    - active_agents: "Currently executing agents"
    - pending_handoffs: "Agents waiting for handoff data"
  coordination_protocol:
    - handoff_format: "Standardized data format for agent handoffs"
    - state_synchronization: "Mechanism for maintaining consistent state"
    - error_propagation: "How errors are communicated and handled"
    - recovery_checkpoints: "Points where workflow can be resumed"
```

### Phase 2: Agent Execution Coordination

```yaml
step: agent_execution_management
description: Coordinate execution of all specialized agents
actions:
  - manage_execution_queue: Process agent execution queue with dependency handling
  - coordinate_parallel_execution: Enable parallel execution where dependencies allow
  - monitor_agent_progress: Continuously monitor progress of all active agents
  - handle_agent_handoffs: Facilitate seamless data handoffs between agents
  - maintain_coordination_state: Keep coordination state consistent across all agents
execution_patterns:
  sequential_execution:
    - dependency_driven: "Execute agents in dependency order"
    - data_flow_driven: "Execute based on data availability"
    - critical_path_driven: "Prioritize critical path agents"
  parallel_execution:
    - independent_groups: "Execute independent task groups in parallel"
    - different_stacks: "Run frontend and backend groups simultaneously"
    - separate_components: "Parallelize work on different system components"
coordination_mechanisms:
  - agent_communication: "Direct communication between coordinated agents"
  - shared_state: "Common state accessible to all agents"
  - event_driven_handoffs: "Automatic handoffs triggered by completion events"
  - data_validation: "Validation of handoff data before agent transitions"
```

### Phase 3: Implementation Workflow Execution

```yaml
step: implementation_coordination
description: Orchestrate complete implementation workflow across all agents
actions:
  - coordinate_backend_implementation: Manage backend development agent execution
  - coordinate_frontend_implementation: Manage frontend development agent execution
  - coordinate_integration_work: Manage integration coordination agent
  - coordinate_testing_validation: Manage testing and validation agent
  - synchronize_cross_cutting_concerns: Handle concerns spanning multiple agents
implementation_phases:
  backend_phase:
    agent: "hubtel-backend-dev"
    coordination_requirements:
      - "API contract definition and validation"
      - "Database schema coordination"
      - "Performance benchmark establishment"
    handoff_data_to:
      - target: "hubtel-integration-coordinator"
        data: "API contracts, database schema, configuration"
      - target: "hubtel-frontend-dev"
        data: "API documentation, endpoint specifications"
  frontend_phase:
    agent: "hubtel-frontend-dev"
    coordination_requirements:
      - "API contract consumption validation"
      - "UI/UX consistency verification"
      - "Cross-browser compatibility confirmation"
    handoff_data_to:
      - target: "hubtel-integration-coordinator"
        data: "Frontend build artifacts, integration points"
      - target: "hubtel-test-engineer"
        data: "UI components for testing, user journeys"
  integration_phase:
    agent: "hubtel-integration-coordinator"
    coordination_requirements:
      - "Frontend-backend integration validation"
      - "Environment configuration management"
      - "Deployment coordination"
    handoff_data_to:
      - target: "hubtel-test-engineer"
        data: "Integration test environments, test data"
  testing_phase:
    agent: "hubtel-test-engineer"
    coordination_requirements:
      - "Comprehensive test suite execution"
      - "Coverage validation and reporting"
      - "Quality gate validation"
    handoff_data_to:
      - target: "workflow-completion"
        data: "Test results, coverage reports, quality metrics"
```

### Phase 4: State Management & Synchronization

```yaml
step: state_synchronization
description: Maintain consistent workflow state across all agents and phases
actions:
  - synchronize_agent_states: Ensure all agents have consistent view of workflow state
  - update_progress_tracking: Continuously update progress tracking and visibility
  - validate_state_consistency: Validate state consistency across all components
  - checkpoint_workflow_state: Create recovery checkpoints at key transitions
  - handle_state_conflicts: Resolve any state inconsistencies or conflicts
state_management_components:
  workflow_state:
    - phase_status: "Current status of each workflow phase"
    - agent_progress: "Detailed progress for each active agent"
    - dependency_status: "Status of all inter-agent dependencies"
    - data_flow_status: "Status of data flow between agents"
  synchronization_mechanisms:
    - state_broadcasting: "Broadcast state changes to all interested agents"
    - state_validation: "Validate state changes for consistency"
    - conflict_resolution: "Resolve conflicts in state updates"
    - atomic_updates: "Ensure state updates are atomic and consistent"
  recovery_mechanisms:
    - checkpoint_creation: "Create checkpoints at key workflow milestones"
    - state_reconstruction: "Reconstruct state from checkpoints and logs"
    - partial_recovery: "Resume workflow from partial completion states"
    - rollback_capability: "Rollback to previous stable state if necessary"
```

### Phase 5: Completion & Validation

```yaml
step: workflow_completion
description: Validate workflow completion and finalize all coordination
actions:
  - validate_all_phases_complete: Ensure all workflow phases completed successfully
  - validate_quality_gates: Verify all quality gates and validation criteria met
  - finalize_agent_coordination: Complete all pending agent handoffs and coordination
  - generate_completion_report: Create comprehensive workflow completion report
  - archive_workflow_artifacts: Archive all workflow state and artifacts for future reference
completion_validation:
  phase_completion:
    - all_tasks_implemented: "Every task in workflow fully implemented"
    - all_agents_completed: "All assigned agents completed their work"
    - all_handoffs_successful: "All agent handoffs completed successfully"
    - all_coordination_resolved: "All coordination requirements satisfied"
  quality_validation:
    - acceptance_criteria_met: "All UAC acceptance criteria satisfied"
    - test_coverage_achieved: "Minimum test coverage thresholds met"
    - code_quality_standards: "All code quality standards satisfied"
    - integration_validation: "All system integrations working correctly"
  final_validation:
    - workflow_objectives_achieved: "All original workflow objectives met"
    - no_outstanding_issues: "No unresolved issues or blockers"
    - deployment_readiness: "Implementation ready for deployment"
    - documentation_complete: "All documentation updated and complete"
```

## Output Format

### Orchestration Status
```yaml
orchestration_status:
  workflow:
    id: "batch-20241214-143022"
    type: "full-implementation"
    status: "in_progress"
    current_phase: "implementation_coordination"
    overall_progress: "75%"
    estimated_completion: "45 minutes"
  
  execution_plan:
    phases:
      - phase: "backend_implementation"
        status: "completed"
        agent: "hubtel-backend-dev"
        completion_time: "1.5 hours"
        handoffs_completed: true
      
      - phase: "frontend_implementation"
        status: "in_progress"
        agent: "hubtel-frontend-dev"
        progress: "80%"
        estimated_remaining: "20 minutes"
      
      - phase: "integration_coordination"
        status: "pending"
        agent: "hubtel-integration-coordinator"
        dependencies_met: false
        waiting_for: ["frontend_implementation"]
      
      - phase: "testing_validation"
        status: "pending"
        agent: "hubtel-test-engineer"
        dependencies_met: false
        waiting_for: ["frontend_implementation", "integration_coordination"]
  
  coordination_health:
    active_handoffs: 1
    completed_handoffs: 3
    pending_handoffs: 2
    coordination_efficiency: "95%"
    state_consistency: "validated"
```

### Agent Coordination Status
```yaml
agent_coordination:
  active_agents:
    - agent: "hubtel-frontend-dev"
      status: "executing"
      current_task: "AZ-124"
      progress: "80%"
      coordination_data:
        received_from: "hubtel-integration-coordinator"
        data_package: "API contracts and integration guidelines"
        handoff_quality: "validated"
  
  completed_agents:
    - agent: "hubtel-backend-dev"
      status: "completed"
      completion_time: "2024-12-14T16:30:00Z"
      work_delivered: ["AZ-123", "AZ-125"]
      handoff_data:
        delivered_to: ["hubtel-integration-coordinator", "hubtel-frontend-dev"]
        data_quality: "validated"
        coordination_success: true
  
  pending_agents:
    - agent: "hubtel-test-engineer"
      status: "waiting"
      dependencies: ["frontend_implementation"]
      readiness_status: "prepared"
      estimated_start: "2024-12-14T17:00:00Z"
  
  coordination_metrics:
    handoff_success_rate: "100%"
    average_handoff_time: "3 minutes"
    coordination_overhead: "5%"
    data_integrity_score: "100%"
```

### Workflow State
```yaml
workflow_state:
  current_state:
    phase: "implementation_coordination"
    subphase: "frontend_implementation"
    active_operations: ["AZ-124_component_implementation"]
    blocked_operations: []
    next_operations: ["integration_validation", "testing_setup"]
  
  state_history:
    - timestamp: "2024-12-14T14:30:00Z"
      phase: "workflow_initialization"
      action: "Workflow started with 4 tasks"
    
    - timestamp: "2024-12-14T14:45:00Z"
      phase: "task_enhancement"
      action: "All tasks enhanced to implementation readiness"
    
    - timestamp: "2024-12-14T15:00:00Z"
      phase: "uac_generation"
      action: "UAC generated and confirmed by user"
    
    - timestamp: "2024-12-14T15:15:00Z"
      phase: "implementation_coordination"
      action: "Backend implementation started"
    
    - timestamp: "2024-12-14T16:30:00Z"
      phase: "implementation_coordination"
      action: "Backend implementation completed, frontend started"
  
  checkpoints:
    - checkpoint_id: "workflow_initialized"
      timestamp: "2024-12-14T14:30:00Z"
      state_snapshot: "Initial workflow state with task groups"
    
    - checkpoint_id: "uac_confirmed"
      timestamp: "2024-12-14T15:00:00Z"
      state_snapshot: "UAC confirmed, ready for implementation"
    
    - checkpoint_id: "backend_completed"
      timestamp: "2024-12-14T16:30:00Z"
      state_snapshot: "Backend implementation completed with handoff data"
```

### Error Recovery Information
```yaml
error_recovery:
  recovery_capabilities:
    - checkpoint_recovery: "Resume from any saved checkpoint"
    - partial_recovery: "Resume from partial completion states"
    - agent_recovery: "Restart specific agents with preserved context"
    - state_reconstruction: "Rebuild state from logs and artifacts"
  
  current_status:
    errors_encountered: 0
    recovery_attempts: 0
    state_integrity: "validated"
    recovery_readiness: "prepared"
  
  recovery_plan:
    immediate_recovery: "Resume from current state"
    checkpoint_recovery: "Resume from 'backend_completed' checkpoint"
    full_restart: "Restart workflow from 'uac_confirmed' checkpoint"
    manual_intervention: "Escalate to manual coordination if automated recovery fails"
```

## Integration Points

### Agent Integration
- **Seamless handoffs**: Automatic data handoffs between all specialized agents
- **State synchronization**: Shared workflow state across all agents
- **Error propagation**: Coordinated error handling across agent boundaries

### Workflow Integration
- **Progress tracking**: Real-time progress updates fed to progress tracker
- **State persistence**: Workflow state maintained for resumption capabilities
- **Quality validation**: Continuous quality gate monitoring and validation

### User Experience
- **Visibility**: Complete visibility into workflow execution and coordination
- **Control**: User control over workflow execution mode and error handling
- **Transparency**: Clear understanding of workflow status and next steps