# ============================================
# Development Cycle Workflow
# Story 11.3: Projeto Bob - Orquestração de Agentes
#
# Ciclo completo: PO → Executor → Quality Gate → DevOps → Push
# com checkpoints humanos e self-healing integrado.
#
# @version 1.0.0
# @author @dev (Dex) for Story 11.3
# ============================================

workflow:
  id: development-cycle
  name: "Development Cycle (Projeto Bob)"
  version: "1.0.0"
  description: >-
    Workflow orquestrado para ciclo de desenvolvimento por story.
    Implementa o fluxo PO → Executor → Quality Gate → DevOps → Push
    com suporte a executor dinâmico, self-healing e checkpoints humanos.
  orchestrator: "@po"

  # ============================================
  # Triggers
  # ============================================
  triggers:
    - type: story_approved
      description: "Story aprovada pelo PO via validate-story-draft"
    - type: manual
      description: "Execução manual via *workflow development-cycle"

  # ============================================
  # Configuration
  # ============================================
  config:
    # Dynamic executor from Story 11.1
    use_dynamic_executor: true
    executor_assignment_module: ".aiox-core/core/orchestration/executor-assignment.js"

    # Terminal spawning from Story 11.2
    use_terminal_spawning: true
    terminal_spawner_module: ".aiox-core/core/orchestration/terminal-spawner.js"

    # Self-healing configuration
    self_healing:
      enabled: "${config.coderabbit_integration.enabled}"
      max_iterations: 3
      severity_filter: [CRITICAL, HIGH]

    # Checkpoint configuration
    checkpoint:
      enabled: true
      require_human_decision: true
      timeout_minutes: 30

    # Timeouts
    timeouts:
      validation: "10m"
      development: "2h"
      self_healing: "30m"
      quality_gate: "30m"
      push: "10m"

  # ============================================
  # Inputs
  # ============================================
  inputs:
    story_file:
      type: path
      required: true
      description: "Path to story file (.story.md)"
    epic_context:
      type: object
      required: false
      description: "Epic context with accumulated story info"

  # ============================================
  # Phases
  # ============================================
  phases:
    # ----------------------------------------
    # Phase 1: Story Validation
    # ----------------------------------------
    1_validation:
      id: validation
      name: "Story Validation"
      agent: "@po"
      task: "validate-story-draft"
      description: >-
        PO valida a story com Epic Context antes de iniciar desenvolvimento.
        Garante que a story tem executor e quality_gate atribuídos.

      inputs:
        - story_file
        - epic_context

      outputs:
        - validation_result:
            type: object
            properties:
              passed: boolean
              score: number
              issues: array

      validations:
        - check: "story.executor != null"
          error: "Story must have an executor assigned"
        - check: "story.quality_gate != null"
          error: "Story must have a quality_gate assigned"
        - check: "story.executor != story.quality_gate"
          error: "Executor and Quality Gate must be different agents"

      on_success: 2_development
      on_failure: reject_with_feedback

    # ----------------------------------------
    # Phase 2: Development (Dynamic Executor)
    # ----------------------------------------
    2_development:
      id: development
      name: "Development"
      agent: "${story.executor}"  # Dynamic from Story 11.1
      task: "develop"
      description: >-
        Executor dinâmico desenvolve a story baseado na atribuição.
        Usa terminal spawning para contexto limpo (Story 11.2).

      spawn_in_terminal: true  # Use TerminalSpawner

      inputs:
        - validated_story:
            from: 1_validation.validation_result
        - story_file

      outputs:
        - implementation:
            type: object
            properties:
              files_created: array
              files_modified: array
              tests_added: array
        - test_results:
            type: object
            properties:
              passed: number
              failed: number
              skipped: number

      timeout: "${config.timeouts.development}"

      on_success: 3_self_healing
      on_failure: return_to_po

    # ----------------------------------------
    # Phase 3: Self-Healing (Conditional)
    # ----------------------------------------
    3_self_healing:
      id: self_healing
      name: "Self-Healing"
      agent: "@dev"
      task: "self-heal"
      description: >-
        Self-healing com CodeRabbit para corrigir issues automaticamente.
        Só executa se coderabbit_integration.enabled == true.

      condition: "${config.coderabbit_integration.enabled} == true"

      inputs:
        - implementation:
            from: 2_development.implementation

      outputs:
        - healed_code:
            type: object
            properties:
              iterations: number
              issues_fixed: array
              issues_remaining: array

      config:
        max_iterations: 3
        severity_filter:
          - CRITICAL
          - HIGH
        auto_fix: true

      on_success: 4_quality_gate
      on_failure: 4_quality_gate  # Continue even if self-healing fails
      on_skip: 4_quality_gate     # Skip if condition not met

    # ----------------------------------------
    # Phase 4: Quality Gate
    # ----------------------------------------
    4_quality_gate:
      id: quality_gate
      name: "Quality Gate"
      agent: "${story.quality_gate}"  # Dynamic, different from executor
      task: "quality-review"
      description: >-
        Quality gate executado por agente DIFERENTE do executor.
        Valida código, testes, arquitetura e padrões.

      spawn_in_terminal: true  # Use TerminalSpawner

      inputs:
        - implementation:
            from: 2_development.implementation
        - healed_code:
            from: 3_self_healing.healed_code
            optional: true
        - quality_gate_tools:
            from: story.quality_gate_tools

      outputs:
        - review_result:
            type: object
            properties:
              verdict: enum[APPROVED, REJECTED, NEEDS_WORK]
              score: number
              findings: array
              recommendations: array

      validations:
        - check: "executor != quality_gate_agent"
          error: "Quality Gate agent must be different from executor"

      on_success: 5_push
      on_failure: return_to_development

    # ----------------------------------------
    # Phase 5: Push & PR
    # ----------------------------------------
    5_push:
      id: push
      name: "Push & PR"
      agent: "@devops"
      task: "push-and-pr"
      description: >-
        DevOps executa push ao final de cada story aprovada.
        Cria PR automaticamente com referência à story.

      spawn_in_terminal: true  # Use TerminalSpawner

      inputs:
        - reviewed_code:
            from: 4_quality_gate.review_result
        - story_file
        - implementation:
            from: 2_development.implementation

      outputs:
        - push_result:
            type: object
            properties:
              commit_hash: string
              branch: string
        - pr_url:
            type: string
            description: "URL of created PR"

      pre_checks:
        - name: "lint"
          command: "npm run lint"
        - name: "test"
          command: "npm test"
        - name: "typecheck"
          command: "npm run typecheck"

      on_success: 6_checkpoint
      on_failure: return_to_quality_gate

    # ----------------------------------------
    # Phase 6: Checkpoint (Human Decision)
    # ----------------------------------------
    6_checkpoint:
      id: checkpoint
      name: "Story Checkpoint"
      agent: "@po"
      task: "story-checkpoint"
      description: >-
        PO pausa entre stories para perguntar: GO / PAUSE / REVIEW / ABORT.
        Requer interação humana para decisão.

      elicit: true  # REQUIRES human interaction

      inputs:
        - story_file
        - pr_url:
            from: 5_push.pr_url
        - implementation:
            from: 2_development.implementation
        - review_result:
            from: 4_quality_gate.review_result

      outputs:
        - decision:
            type: enum
            values: [GO, PAUSE, REVIEW, ABORT]
        - next_story:
            type: path
            optional: true

      options:
        GO:
          description: "Continue to next story"
          action: suggest_next_story
        PAUSE:
          description: "Save state and stop"
          action: save_session_state
        REVIEW:
          description: "Show what was done"
          action: show_summary
        ABORT:
          description: "Stop the epic"
          action: abort_epic

      on_go: 1_validation  # Loop back with next story
      on_pause: workflow_paused
      on_review: show_summary_then_checkpoint
      on_abort: workflow_aborted

  # ============================================
  # Canonical Execution Contract
  # ============================================
  sequence:
    - step: validate_story
      id: validation
      phase: 1
      phase_name: "Story Validation"
      agent: "@po"
      task: "validate-story-draft"
      action: "Validate story and assignments"
      outputs:
        - validation_result
      next: development
      on_failure: reject_with_feedback

    - step: develop_story
      id: development
      phase: 2
      phase_name: "Development"
      agent: "${story.executor}"
      task: "develop"
      action: "Implement approved story"
      requires: validation
      outputs:
        - implementation
        - test_results
      next: self_healing
      on_failure: return_to_po

    - step: run_self_healing
      id: self_healing
      phase: 3
      phase_name: "Self-Healing"
      agent: "@dev"
      task: "self-heal"
      action: "Apply automated fixes when enabled"
      requires: development
      condition: "${config.coderabbit_integration.enabled} == true"
      outputs:
        - healed_code
      next: quality_gate
      on_failure: quality_gate

    - step: quality_review
      id: quality_gate
      phase: 4
      phase_name: "Quality Gate"
      agent: "${story.quality_gate}"
      task: "quality-review"
      action: "Review code quality and acceptance"
      requires:
        - development
        - self_healing
      outputs:
        - review_result
      next: push
      on_failure: return_to_development

    - step: push_and_pr
      id: push
      phase: 5
      phase_name: "Push & PR"
      agent: "@devops"
      task: "push-and-pr"
      action: "Run checks and publish PR"
      requires: quality_gate
      outputs:
        - push_result
        - pr_url
      next: checkpoint
      on_failure: return_to_quality_gate

    - step: story_checkpoint
      id: checkpoint
      phase: 6
      phase_name: "Story Checkpoint"
      agent: "@po"
      task: "story-checkpoint"
      action: "Collect human decision (GO/PAUSE/REVIEW/ABORT)"
      requires: push
      outputs:
        - decision
        - next_story
      on_complete:
        GO: validation
        PAUSE: workflow_paused
        REVIEW: show_summary_then_checkpoint
        ABORT: workflow_aborted

  # ============================================
  # Error Handlers
  # ============================================
  error_handlers:
    reject_with_feedback:
      description: "Story rejected with feedback to SM"
      actions:
        - log: "Story validation failed"
        - notify: "@sm"
        - save_feedback: true

    return_to_po:
      description: "Development failed, return to PO for decision"
      actions:
        - log: "Development phase failed"
        - save_state: true
        - await_decision: true

    return_to_development:
      description: "Quality gate failed, return to executor"
      actions:
        - log: "Quality gate failed"
        - increment_attempt: true
        - max_attempts: 3
        - on_max_attempts: escalate_to_human

    return_to_quality_gate:
      description: "Push failed, return to quality gate"
      actions:
        - log: "Push failed"
        - notify: "@devops"

  # ============================================
  # State Management
  # ============================================
  state:
    persistence:
      enabled: true
      location: ".aiox/workflow-state/"
      format: yaml

    tracked_fields:
      - current_phase
      - current_story
      - executor
      - quality_gate
      - attempt_count
      - started_at
      - last_updated
      - accumulated_context

    recovery:
      enabled: true
      auto_resume: true
      checkpoint_interval: "5m"

  # ============================================
  # Flow Diagram
  # ============================================
  flow_diagram: |
    ```
    ┌─────────────────────────────────────────────────────────────┐
    │                  DEVELOPMENT CYCLE WORKFLOW                  │
    │                     (Projeto Bob - 11.3)                     │
    └─────────────────────────────────────────────────────────────┘

    ┌──────────┐    ┌──────────────┐    ┌──────────────┐
    │   PO     │───▶│   Executor   │───▶│ Self-Healing │
    │ Validate │    │   (Dynamic)  │    │ (if enabled) │
    └──────────┘    └──────────────┘    └──────────────┘
         │                                      │
         │ ┌────────────────────────────────────┘
         │ │
         │ ▼
    ┌──────────────┐    ┌──────────┐    ┌──────────────┐
    │ Quality Gate │───▶│  DevOps  │───▶│  Checkpoint  │
    │  (≠ Executor)│    │   Push   │    │   (Human)    │
    └──────────────┘    └──────────┘    └──────────────┘
                                               │
                              ┌────────────────┼────────────────┐
                              │                │                │
                              ▼                ▼                ▼
                           [ GO ]          [ PAUSE ]       [ ABORT ]
                              │                │                │
                              ▼                ▼                ▼
                         Next Story      Save State         Stop Epic
    ```

# ============================================
# Metadata
# ============================================
metadata:
  author: "@dev (Dex)"
  story: "11.3"
  epic: "11 - Projeto Bob"
  created_date: "2026-02-05"
  version: "1.0.0"
  tags:
    - projeto-bob
    - orchestration
    - development-cycle
    - dynamic-executor
    - terminal-spawning
    - self-healing
    - checkpoint
