# ============================================
# Epic Orchestration Workflow Template
#
# Generic, reusable template for executing epics
# with wave-based parallel execution and quality gates.
#
# Each story within a wave runs the full development-cycle
# (PO validates → Executor develops → Self-healing → Quality Gate → DevOps push)
#
# Project-specific execution plans reference this template
# and live in docs/stories/epics/{epic-name}/
#
# @version 1.0.0
# @author @pm (Bob) + @architect (Aria)
# ============================================

workflow:
  id: epic-orchestration
  name: "Epic Wave Orchestration"
  version: "1.0.0"
  description: >-
    Reusable template for executing epics with wave-based parallel development.
    Stories within each wave run the full development-cycle workflow
    (PO → Executor → Self-Healing → Quality Gate → DevOps → Checkpoint).
    Wave gates validate integration before proceeding to next wave.
    Supports worktree isolation for conflict-free parallel development.

  type: epic-orchestration
  project_types:
    - greenfield
    - brownfield
    - aiox-development
    - epic-execution

  metadata:
    elicit: true
    confirmation_required: true

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              EXECUTION MODES
  # ═══════════════════════════════════════════════════════════════════════════════════

  execution_modes:
    - mode: yolo
      description: Autonomous - waves run with minimal interaction, checkpoints auto-GO
      prompts: 0-2
    - mode: interactive
      description: Human checkpoints between waves and at quality gates
      prompts: 5-10
      default: true
    - mode: preflight
      description: Full dependency analysis before execution begins
      prompts: 10-15

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              CONFIGURATION (overridden by project execution plan)
  # ═══════════════════════════════════════════════════════════════════════════════════

  config:
    # These values are OVERRIDDEN by the project-specific execution plan
    epicId: "${epicId}"
    epicIndex: "${epicIndex}"
    storyBasePath: "${storyBasePath}"

    # Parallel execution defaults
    maxConcurrency: 4
    worktreeIsolation: true

    # Timeouts
    storyTimeout: 7200000       # 2 hours per story (development-cycle total)
    gateTimeout: 1800000        # 30 min per wave gate
    totalTimeout: 43200000      # 12 hours total

    # Quality gates
    gatePolicy: strict          # strict | lenient | skip
    requireIntegrationReview: true

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              INNER WORKFLOW
  # ═══════════════════════════════════════════════════════════════════════════════════
  #
  # Each story within a wave executes the full development-cycle:
  #
  #   Phase 1: @po validates story (validate-story-draft)
  #   Phase 2: ${story.executor} develops (dynamic executor)
  #   Phase 3: @dev self-healing (CodeRabbit, conditional)
  #   Phase 4: ${story.quality_gate} reviews (agent != executor)
  #   Phase 5: @devops push & PR
  #   Phase 6: @po checkpoint (AUTO-GO in wave mode, human in interactive)
  #
  # Reference: .aiox-core/development/workflows/development-cycle.yaml

  inner_workflow:
    ref: development-cycle
    per_story: true
    checkpoint_mode:
      in_wave: auto_go           # Don't pause between parallel stories
      between_waves: interactive  # Pause for human decision between waves

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              WAVE EXECUTION PATTERN
  # ═══════════════════════════════════════════════════════════════════════════════════
  #
  # Waves are defined in the project-specific execution plan.
  # This template defines the PATTERN each wave follows:
  #
  #   ┌─────────────────────────────────────────────────────┐
  #   │  WAVE N                                              │
  #   │                                                      │
  #   │  Story A ──→ development-cycle ──→ branch pushed     │
  #   │  Story B ──→ development-cycle ──→ branch pushed     │ PARALLEL
  #   │  Story C ──→ development-cycle ──→ branch pushed     │
  #   │                                                      │
  #   │  ──→ WAVE GATE (integration review) ──→ merge        │
  #   └─────────────────────────────────────────────────────┘

  wave_pattern:

    # Step 1: Per-story development (parallel within wave)
    story_execution:
      parallel: true
      max_concurrency: "${config.maxConcurrency}"
      worktree_isolation: "${config.worktreeIsolation}"
      workflow: development-cycle
      inputs:
        story_file: "${story.file}"
        epic_context:
          epicId: "${config.epicId}"
          waveNumber: "${wave.number}"
          totalWaves: "${wave.total}"

    # Step 2: Wave gate (sequential, after all stories in wave complete)
    wave_gate:
      description: "Integration review after wave completes"
      steps:

        - id: integration-review
          agent: "${wave.gate_agent}"
          action: review_wave_integration
          notes: |
            Review focus (per-story QA already done in development-cycle):
            - Cross-story integration compatibility
            - Shared file conflict detection
            - Combined test suite passes
            - No regressions from parallel changes
            - Architecture consistency across stories

        - id: merge-wave
          agent: devops
          action: merge_wave_branches
          condition: gate_approved
          notes: |
            Merge all wave branches to main:
            - Follow merge order from execution plan
            - Resolve conflicts if any
            - Run full test suite on merged result
            - Tag: wave-{N}-complete
            - Clean up worktrees

    # Step 3: Human checkpoint (between waves)
    checkpoint:
      agent: po
      elicit: true
      options:
        GO: "Continue to next wave"
        PAUSE: "Save state, stop execution"
        REVIEW: "Show wave summary before deciding"
        ABORT: "Stop the epic"
      on_go: next_wave
      on_pause: save_state
      on_abort: abort_epic

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              STATE MANAGEMENT
  # ═══════════════════════════════════════════════════════════════════════════════════

  state:
    persistence:
      enabled: true
      location: ".aiox/workflow-state/"
      format: json
      file: "${config.epicId}-pipeline.json"

    tracked_fields:
      - current_wave
      - wave_status
      - story_statuses
      - gate_verdicts
      - started_at
      - last_updated

    recovery:
      enabled: true
      auto_resume: true
      resume_from: last_completed_wave

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              ERROR HANDLING
  # ═══════════════════════════════════════════════════════════════════════════════════

  error_handling:
    story_failed:
      description: "A story's development-cycle failed"
      action: |
        - development-cycle handles retries internally (max 3 attempts)
        - If still failing, mark story as blocked
        - Continue other parallel stories in wave
        - Report blocked story at wave gate
      escalation: wave_gate

    gate_failed:
      description: "Wave integration gate failed"
      action: |
        - Identify failing stories/integrations
        - Create fix tasks for specific issues
        - Re-run development-cycle for affected stories
        - Re-submit for gate review
      max_retries: 2
      escalation: human

    merge_conflict:
      description: "Conflict during wave branch merge"
      action: |
        - Follow merge order from execution plan
        - Resolve conflicts in recommended order
        - Re-run tests after resolution
      escalation: human

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              FLOW DIAGRAM
  # ═══════════════════════════════════════════════════════════════════════════════════

  flow_diagram: |
    ```
    ┌─────────────────────────────────────────────────────────────┐
    │                 EPIC WAVE ORCHESTRATION                      │
    └─────────────────────────────────────────────────────────────┘

    For each WAVE defined in project execution plan:

    ┌─────────────────────────────────────────────────────────────┐
    │  WAVE N (stories run in PARALLEL)                           │
    │                                                             │
    │  Story A ──→ development-cycle ──→ branch pushed            │
    │    (PO validate → Executor dev → Self-heal → QA → Push)    │
    │                                                             │
    │  Story B ──→ development-cycle ──→ branch pushed            │
    │    (PO validate → Executor dev → Self-heal → QA → Push)    │
    │                                                             │
    │  Story C ──→ development-cycle ──→ branch pushed            │
    │    (PO validate → Executor dev → Self-heal → QA → Push)    │
    └───────────────────────┬─────────────────────────────────────┘
                            │
                            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  WAVE GATE (integration review only - per-story QA done)    │
    │                                                             │
    │  gate_agent: Review cross-story integration                 │
    │  @devops:    Merge branches → main                          │
    └───────────────────────┬─────────────────────────────────────┘
                            │
                            ▼
    ┌─────────────────────────────────────────────────────────────┐
    │  CHECKPOINT (between waves)                                  │
    │                                                             │
    │  @po asks: [ GO ] [ PAUSE ] [ REVIEW ] [ ABORT ]            │
    └───────────────────────┬─────────────────────────────────────┘
                            │
                            ▼
                      Next Wave...
    ```

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              DECISION GUIDANCE
  # ═══════════════════════════════════════════════════════════════════════════════════

  decision_guidance:
    when_to_use:
      - Epic with 4+ stories that can be grouped into parallel waves
      - Stories have clear dependency graph (some parallel, some sequential)
      - Need quality gates between groups of related stories
      - Team has capacity for parallel development streams

    when_not_to_use:
      - Epic with 1-3 stories (use story-development-cycle directly)
      - All stories are strictly sequential (use story-development-cycle in loop)
      - Simple bug fixes without integration concerns

    how_to_use:
      - Create project execution plan in docs/stories/epics/{epic}/
      - Define waves, story assignments, branches, gates
      - Reference this template as the orchestration pattern
      - Execute via WorkflowOrchestrator with execution plan config

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              RELATED WORKFLOWS
  # ═══════════════════════════════════════════════════════════════════════════════════

  related:
    - id: development-cycle
      role: "Inner loop - runs per story within each wave"
      file: development-cycle.yaml

    - id: qa-loop
      role: "QA review cycle - used within development-cycle Phase 4"
      file: qa-loop.yaml

    - id: auto-worktree
      role: "Worktree creation - used for parallel story isolation"
      file: auto-worktree.yaml

    - id: story-development-cycle
      role: "Simplified story cycle (legacy) - use development-cycle instead"
      file: story-development-cycle.yaml

metadata:
  author: "@pm (Bob) + @architect (Aria)"
  created: "2026-02-06"
  version: 1.0.0
  tags:
    - epic-orchestration
    - parallel-execution
    - wave-executor
    - quality-gates
    - worktree-isolation
    - reusable-template
