workflow:
  id: spec-pipeline
  name: Spec Pipeline - Requirements to Specification
  version: "1.0"
  description: >-
    Pipeline completo que transforma requisitos informais em especificações
    executáveis. Orquestra 5 fases: Gather → Assess → Research → Write → Critique.
    Adapta as fases baseado na complexidade do requisito.

    Part of the Auto-Claude ADE (Autonomous Development Engine) infrastructure.

  type: pipeline
  project_types:
    - aiox-development
    - autonomous-development
    - spec-generation

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              TRIGGER CONFIGURATION
  # ═══════════════════════════════════════════════════════════════════════════════════

  triggers:
    # Primary trigger: Explicit command
    - event: command
      command: "*create-spec"
      action: run_pipeline

    # Secondary trigger: New story created
    - event: story_created
      condition: projectConfig.autoSpec.enabled === true
      action: run_pipeline

    # Agent-specific triggers
    - event: command
      command: "*gather-requirements"
      action: run_phase
      phase: gather

    - event: command
      command: "*assess-complexity"
      action: run_phase
      phase: assess

    - event: command
      command: "*research-deps"
      action: run_phase
      phase: research

    - event: command
      command: "*write-spec"
      action: run_phase
      phase: spec

    - event: command
      command: "*critique-spec"
      action: run_phase
      phase: critique

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              CONFIGURATION
  # ═══════════════════════════════════════════════════════════════════════════════════

  config:
    # Auto-spec when story is created
    autoSpec:
      enabled: false
      trigger: story_created

    # Progress tracking
    showProgress: true
    verbose: true

    # Retry configuration
    maxRetries: 2
    retryDelay: 1000

    # Gate behavior
    strictGate: true  # BLOCKED verdict halts pipeline

    # Output directory pattern
    outputDir: docs/stories/{storyId}/spec/

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              COMPLEXITY-BASED PHASES
  # ═══════════════════════════════════════════════════════════════════════════════════

  phases:
    # SIMPLE: Minimal pipeline for straightforward tasks
    SIMPLE:
      description: "Tarefa direta, padrões existentes"
      steps:
        - gather
        - spec
        - critique
      estimated_time: "30-60 min"

    # STANDARD: Full pipeline for moderate complexity
    STANDARD:
      description: "Complexidade moderada, alguma pesquisa necessária"
      steps:
        - gather
        - assess
        - research
        - spec
        - critique
        - plan
      estimated_time: "2-4 hours"

    # COMPLEX: Extended pipeline with revision loop
    COMPLEX:
      description: "Alta complexidade, múltiplas iterações"
      steps:
        - gather
        - assess
        - research
        - spec
        - critique_1
        - revise
        - critique_2
        - plan
      estimated_time: "4-8 hours"
      flags:
        - "Architectural review recommended"
        - "Consider breaking into smaller stories"

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              PRE-FLIGHT CHECKS
  # ═══════════════════════════════════════════════════════════════════════════════════

  pre_flight:
    enabled: true

    checks:
      - id: story_exists
        description: "Verify story directory exists or can be created"
        script: |
          const fs = require('fs');
          const path = `docs/stories/${storyId}`;
          if (!fs.existsSync(path)) {
            fs.mkdirSync(path, { recursive: true });
          }
          return true;
        blocking: true
        error: "Cannot create story directory"

      - id: no_existing_spec
        description: "Check for existing spec (avoid overwrite)"
        script: |
          const fs = require('fs');
          const specPath = `docs/stories/${storyId}/spec/spec.md`;
          return !fs.existsSync(specPath);
        blocking: false
        warning: "Existing spec found - will iterate"

      - id: agents_available
        description: "Verify required agents are configured"
        check: "All spec pipeline agents have autoClaude.specPipeline defined"
        blocking: true

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              WORKFLOW SEQUENCE
  # ═══════════════════════════════════════════════════════════════════════════════════

  sequence:

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 1: GATHER REQUIREMENTS
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: gather
      phase: 1
      phase_name: "Gather Requirements"
      agent: pm

      description: >-
        Collect and structure requirements from user input, PRD, or existing spec.
        Creates requirements.json with functional, non-functional, constraints.

      task: spec-gather-requirements.md

      inputs:
        storyId: "{storyId}"
        source: "{source|user}"
        prdPath: "{prdPath|null}"

      outputs:
        - requirements.json

      elicit: true  # Requires user interaction

      on_success:
        log: "✅ Requirements gathered: {requirements.functional.length} FR, {requirements.nonFunctional.length} NFR"
        next: assess

      on_failure:
        action: halt
        error: "Failed to gather requirements"

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 2: ASSESS COMPLEXITY
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: assess
      phase: 2
      phase_name: "Assess Complexity"
      agent: architect

      description: >-
        Evaluate complexity across 5 dimensions: scope, integration, infrastructure,
        knowledge, risk. Determines which pipeline phases are needed.

      task: spec-assess-complexity.md

      inputs:
        storyId: "{storyId}"
        requirements: "docs/stories/{storyId}/spec/requirements.json"
        overrideComplexity: "{complexity|null}"

      outputs:
        - complexity.json

      skip_if: "source === 'simple' OR overrideComplexity === 'SIMPLE'"

      on_success:
        log: "📊 Complexity assessed: {complexity.result} (score: {complexity.totalScore})"
        dynamic_phases: true  # Use complexity.result to determine phases
        next: research

      on_failure:
        action: continue
        fallback: "Assume STANDARD complexity"

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 3: RESEARCH DEPENDENCIES
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: research
      phase: 3
      phase_name: "Research Dependencies"
      agent: analyst

      description: >-
        Research external dependencies using Context7 (library docs) and EXA (web search).
        Validates technologies and gathers implementation patterns.

      task: spec-research-dependencies.md

      inputs:
        storyId: "{storyId}"
        requirements: "docs/stories/{storyId}/spec/requirements.json"
        complexity: "docs/stories/{storyId}/spec/complexity.json"

      outputs:
        - research.json

      skip_if: "complexity.result === 'SIMPLE'"

      tools:
        - context7
        - exa

      on_success:
        log: "🔍 Research complete: {research.dependencies.length} dependencies, {research.unverifiedClaims.length} unverified"
        next: spec

      on_failure:
        action: continue
        fallback: "Proceed with minimal research output"

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 4: WRITE SPECIFICATION
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: spec
      phase: 4
      phase_name: "Write Specification"
      agent: pm

      description: >-
        Generate complete spec.md from all previous artifacts.
        No invention - only derive content from inputs.

      task: spec-write-spec.md

      inputs:
        storyId: "{storyId}"
        requirements: "docs/stories/{storyId}/spec/requirements.json"
        complexity: "docs/stories/{storyId}/spec/complexity.json"
        research: "docs/stories/{storyId}/spec/research.json"

      outputs:
        - spec.md

      on_success:
        log: "📝 Specification written: docs/stories/{storyId}/spec/spec.md"
        next: critique

      on_failure:
        action: halt
        error: "Failed to write specification"

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 5: CRITIQUE SPECIFICATION
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: critique
      phase: 5
      phase_name: "Critique Specification"
      agent: qa

      description: >-
        Quality gate that validates spec against requirements.
        Evaluates accuracy, completeness, consistency, feasibility, alignment.

      task: spec-critique.md

      inputs:
        storyId: "{storyId}"
        spec: "docs/stories/{storyId}/spec/spec.md"
        requirements: "docs/stories/{storyId}/spec/requirements.json"
        complexity: "docs/stories/{storyId}/spec/complexity.json"
        research: "docs/stories/{storyId}/spec/research.json"

      outputs:
        - critique.json

      gate: true  # Blocking gate

      on_verdict:
        APPROVED:
          log: "✅ Spec APPROVED (score: {critique.scores.average})"
          next: plan
          action: continue

        NEEDS_REVISION:
          log: "⚠️ Spec NEEDS_REVISION: {critique.verdictReason}"
          action: return_to_spec
          pass: [critique.json, critique.autoFixes]
          max_iterations: 2

        BLOCKED:
          log: "🛑 Spec BLOCKED: {critique.verdictReason}"
          action: halt
          escalate_to: "@architect"

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 5b: REVISE SPECIFICATION (COMPLEX only)
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: revise
      phase: "5b"
      phase_name: "Revise Specification"
      agent: pm

      description: >-
        Apply critique feedback and auto-fixes to improve specification.
        Only runs for COMPLEX pipeline or when NEEDS_REVISION.

      condition: "complexity.result === 'COMPLEX' OR critique.verdict === 'NEEDS_REVISION'"

      inputs:
        storyId: "{storyId}"
        spec: "docs/stories/{storyId}/spec/spec.md"
        critique: "docs/stories/{storyId}/spec/critique.json"

      outputs:
        - spec.md (updated)

      on_success:
        log: "🔄 Specification revised based on critique"
        next: critique_2

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 5c: SECOND CRITIQUE (COMPLEX only)
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: critique_2
      phase: "5c"
      phase_name: "Second Critique"
      agent: qa

      description: >-
        Second quality gate for revised specification.
        More lenient on MEDIUM issues if improvements shown.

      condition: "complexity.result === 'COMPLEX'"

      task: spec-critique.md

      inputs:
        storyId: "{storyId}"
        spec: "docs/stories/{storyId}/spec/spec.md"
        requirements: "docs/stories/{storyId}/spec/requirements.json"
        iteration: 2

      outputs:
        - critique.json (updated)

      gate: true

      on_verdict:
        APPROVED:
          next: plan
        NEEDS_REVISION:
          action: halt
          error: "Spec failed second critique - manual intervention needed"
        BLOCKED:
          action: halt
          escalate_to: "@architect"

    # ═════════════════════════════════════════════════════════════════════════════════
    # PHASE 6: CREATE IMPLEMENTATION PLAN
    # ═════════════════════════════════════════════════════════════════════════════════

    - step: plan
      phase: 6
      phase_name: "Create Implementation Plan"
      agent: architect

      description: >-
        Generate implementation plan from approved specification.
        Breaks spec into tasks, identifies dependencies, estimates effort.

      condition: "critique.verdict === 'APPROVED'"

      task: plan-create-implementation.md  # Future task

      inputs:
        storyId: "{storyId}"
        spec: "docs/stories/{storyId}/spec/spec.md"
        complexity: "docs/stories/{storyId}/spec/complexity.json"

      outputs:
        - plan.json

      on_success:
        log: "📋 Implementation plan created"
        complete: true

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              WORKFLOW COMPLETION
  # ═══════════════════════════════════════════════════════════════════════════════════

  completion:
    success_message: |
      ╔══════════════════════════════════════════════════════════════╗
      ║  ✅ Spec Pipeline Complete                                   ║
      ╚══════════════════════════════════════════════════════════════╝

      Story:       {storyId}
      Complexity:  {complexity.result}
      Verdict:     {critique.verdict}
      Score:       {critique.scores.average}/5

      📁 Artifacts:
         • docs/stories/{storyId}/spec/requirements.json
         • docs/stories/{storyId}/spec/complexity.json
         • docs/stories/{storyId}/spec/research.json
         • docs/stories/{storyId}/spec/spec.md
         • docs/stories/{storyId}/spec/critique.json

      📌 Next Steps:
         • Review spec.md
         • Run @dev *develop {storyId}

    outputs:
      - storyId
      - requirements.json
      - complexity.json
      - research.json
      - spec.md
      - critique.json

    next_steps:
      - "Review specification: docs/stories/{storyId}/spec/spec.md"
      - "Start development: @dev *develop {storyId}"
      - "View critique: docs/stories/{storyId}/spec/critique.json"

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

  error_handling:
    missing_story_id:
      message: "Story ID is required"
      suggestion: "Usage: *create-spec STORY-42"
      action: prompt

    phase_failed:
      message: "Phase {phase} failed"
      suggestion: "Check logs and retry: *create-spec {storyId} --resume"
      action: halt

    max_iterations_reached:
      message: "Max revision iterations reached"
      suggestion: "Manual intervention needed - escalating to @architect"
      action: escalate

    critique_blocked:
      message: "Specification blocked by QA gate"
      suggestion: "Review critique.json and address HIGH severity issues"
      action: halt

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              RESUME SUPPORT
  # ═══════════════════════════════════════════════════════════════════════════════════

  resume:
    enabled: true

    state_file: docs/stories/{storyId}/spec/.pipeline-state.json

    checkpoints:
      - after: gather
        state: requirements_gathered
      - after: assess
        state: complexity_assessed
      - after: research
        state: research_complete
      - after: spec
        state: spec_written
      - after: critique
        state: critique_complete

    resume_from:
      requirements_gathered: assess
      complexity_assessed: research
      research_complete: spec
      spec_written: critique
      critique_complete: plan

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              INTEGRATION
  # ═══════════════════════════════════════════════════════════════════════════════════

  integration:
    # Integration with status.json
    status_json:
      track_pipeline: true
      field: specPipeline
      update_on_each_phase: true

    # Integration with project status
    project_status:
      update_story_status: true
      status_field: specStatus

    # Notification hooks
    notifications:
      on_complete:
        message: "Spec ready for {storyId}"
        channels: [log]
      on_blocked:
        message: "Spec blocked for {storyId} - needs attention"
        channels: [log]

  # ═══════════════════════════════════════════════════════════════════════════════════
  #                              METADATA
  # ═══════════════════════════════════════════════════════════════════════════════════

  metadata:
    story: "3.6"
    epic: "Epic 3 - Spec Pipeline"
    created: "2026-01-28"
    author: "@architect (Aria)"
    dependencies:
      - spec-gather-requirements.md
      - spec-assess-complexity.md
      - spec-research-dependencies.md
      - spec-write-spec.md
      - spec-critique.md
    tags:
      - spec-pipeline
      - workflow
      - orchestration
      - ade
