# validate-infrastructure-ci

## Task: Comprehensive Infrastructure CI/CD Validation

**Purpose**: Bridge GitLab CI/CD automation with infrastructure DevOps validation, providing comprehensive assessment of infrastructure deployment pipelines, checklist validation with live CI data, and cross-pack coordination for infrastructure reliability.

**When to Use**:

- After infrastructure deployments to validate CI/CD integration
- Before production infrastructure releases
- During infrastructure checklist validation
- When coordinating infrastructure changes with development teams

---

## Task Configuration

### Input Parameters

- `validation_mode` (optional): full, checklist-only, ci-only, integration (default: full)
- `infrastructure_scope` (optional): all, networking, security, deployment, containers (default: all)
- `ci_health_threshold` (optional): Minimum CI health percentage for validation (default: 80)
- `include_recommendations` (optional): Include improvement recommendations (default: true)
- `generate_report` (optional): Generate comprehensive validation report (default: true)

### Expected Outputs

- Infrastructure CI/CD validation status
- Enhanced checklist validation with live CI data
- Cross-pack integration assessment
- Infrastructure deployment health analysis
- Recommendations for improvements

---

## Task Execution

### Phase 1: Integration Detection and Setup

```bash
echo "🏗️ Infrastructure CI/CD Validation"
echo "=================================="

# Load integration bridge utilities
source .bmad-core/utils/gitlab-integration-bridge.md

# Detect available integrations
detect_expansion_packs

VALIDATION_MODE=${validation_mode:-"full"}
INFRASTRUCTURE_SCOPE=${infrastructure_scope:-"all"}
CI_HEALTH_THRESHOLD=${ci_health_threshold:-80}

echo "🎯 Validation Mode: $VALIDATION_MODE"
echo "🏗️ Infrastructure Scope: $INFRASTRUCTURE_SCOPE"
echo "📊 CI Health Threshold: $CI_HEALTH_THRESHOLD%"

# Verify required integrations
if [ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" != "true" ]; then
  echo "⚠️ Infrastructure DevOps integration not detected"
  echo "   💡 Install bmad-infrastructure-devops expansion pack for full validation"
  echo "   📦 Run: bmad-enhanced install --expansion-packs bmad-infrastructure-devops"
  echo ""
  echo "   Proceeding with GitLab CI/CD validation only..."
  VALIDATION_MODE="ci-only"
fi

# Auto-detect infrastructure context
auto_detect_integration_context

echo ""
echo "🔍 Infrastructure Context Analysis:"
echo "=================================="

if [ "$INFRASTRUCTURE_CONTEXT" = "true" ]; then
  echo "✅ Infrastructure-as-code patterns detected"
  echo "   📂 IaC files found in repository"
  echo "   🔧 Infrastructure CI validation applicable"
else
  echo "ℹ️ No infrastructure-as-code patterns detected"
  echo "   💡 This validation focuses on CI/CD pipeline health"
fi
```

### Phase 2: GitLab CI/CD Pipeline Analysis

```bash
echo ""
echo "📊 GitLab CI/CD Pipeline Analysis:"
echo "================================="

# Get current pipeline status
PIPELINE_DATA=$(glab ci get --output json 2>/dev/null)

if [ $? -eq 0 ] && [ "$PIPELINE_DATA" != "" ]; then
  # Extract pipeline metrics
  PIPELINE_STATUS=$(echo "$PIPELINE_DATA" | jq -r '.status // "unknown"')
  PIPELINE_ID=$(echo "$PIPELINE_DATA" | jq -r '.id // "unknown"')
  PIPELINE_URL=$(echo "$PIPELINE_DATA" | jq -r '.web_url // ""')
  TOTAL_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs | length')
  FAILED_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.status == "failed") | .name' | wc -l)

  if [ "$TOTAL_JOBS" -gt 0 ]; then
    SUCCESS_RATE=$(( (TOTAL_JOBS - FAILED_JOBS) * 100 / TOTAL_JOBS ))
  else
    SUCCESS_RATE=0
  fi

  echo "🔄 Current Pipeline Status:"
  echo "   ID: $PIPELINE_ID"
  echo "   Status: $PIPELINE_STATUS"
  echo "   Success Rate: $SUCCESS_RATE% ($((TOTAL_JOBS - FAILED_JOBS))/$TOTAL_JOBS jobs)"
  echo "   URL: $PIPELINE_URL"

  # Infrastructure-specific job analysis
  if [ "$INFRASTRUCTURE_CONTEXT" = "true" ]; then
    echo ""
    echo "🏗️ Infrastructure Job Analysis:"

    INFRA_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.name | test("terraform|deploy|infra|provision|infrastructure|docker|k8s|helm")) | .name' || echo "")

    if [ -n "$INFRA_JOBS" ]; then
      echo "   Infrastructure jobs detected:"
      echo "$INFRA_JOBS" | while read job; do
        JOB_STATUS=$(echo "$PIPELINE_DATA" | jq -r ".jobs[] | select(.name == \"$job\") | .status")
        JOB_STAGE=$(echo "$PIPELINE_DATA" | jq -r ".jobs[] | select(.name == \"$job\") | .stage")
        STATUS_EMOJI=$(case "$JOB_STATUS" in
          "success") echo "✅" ;;
          "failed") echo "❌" ;;
          "running") echo "🔄" ;;
          *) echo "⚪" ;;
        esac)
        echo "     $STATUS_EMOJI $job [$JOB_STAGE]: $JOB_STATUS"
      done
    else
      echo "   ⚪ No infrastructure-specific jobs detected"
      echo "   💡 Consider adding infrastructure validation jobs"
    fi
  fi

  # CI Health Assessment
  echo ""
  echo "📈 CI Health Assessment:"
  if [ "$SUCCESS_RATE" -ge "$CI_HEALTH_THRESHOLD" ]; then
    echo "   ✅ CI Health: EXCELLENT ($SUCCESS_RATE%)"
    CI_HEALTH_STATUS="EXCELLENT"
  elif [ "$SUCCESS_RATE" -ge 60 ]; then
    echo "   ⚠️ CI Health: NEEDS ATTENTION ($SUCCESS_RATE%)"
    CI_HEALTH_STATUS="NEEDS_ATTENTION"
  else
    echo "   🚨 CI Health: CRITICAL ($SUCCESS_RATE%)"
    CI_HEALTH_STATUS="CRITICAL"
  fi

else
  echo "❌ No pipeline data available"
  echo "   ⚠️ Cannot perform CI validation without pipeline data"
  PIPELINE_STATUS="no-pipeline"
  CI_HEALTH_STATUS="UNKNOWN"
fi
```

### Phase 3: Infrastructure Checklist Integration

```bash
if [ "$VALIDATION_MODE" = "full" ] || [ "$VALIDATION_MODE" = "checklist-only" ]; then
  if [ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" = "true" ]; then
    echo ""
    echo "📋 Infrastructure Checklist Integration:"
    echo "======================================="

    # Enhance infrastructure checklist with CI data
    enhance_infrastructure_checklist

    echo ""
    echo "🔍 Focused Checklist Validation:"
    echo "--------------------------------"

    case "$INFRASTRUCTURE_SCOPE" in
      "all")
        echo "📋 Validating all infrastructure checklist sections..."
        CHECKLIST_SECTIONS="security networking deployment containers cicd monitoring"
        ;;
      "security")
        echo "🔒 Validating security-focused checklist sections..."
        CHECKLIST_SECTIONS="security"
        ;;
      "networking")
        echo "🌐 Validating networking-focused checklist sections..."
        CHECKLIST_SECTIONS="networking"
        ;;
      "deployment")
        echo "🚀 Validating deployment-focused checklist sections..."
        CHECKLIST_SECTIONS="deployment cicd"
        ;;
      "containers")
        echo "📦 Validating container platform sections..."
        CHECKLIST_SECTIONS="containers"
        ;;
    esac

    # Validate specific checklist sections with CI context
    for section in $CHECKLIST_SECTIONS; do
      echo ""
      case "$section" in
        "cicd")
          echo "🔄 Section 8: CI/CD & Deployment (Enhanced with Live Data)"
          echo "   Current Pipeline Status: $PIPELINE_STATUS"
          echo "   CI Health: $CI_HEALTH_STATUS"
          if [ "$PIPELINE_STATUS" = "success" ]; then
            echo "   ✅ Pipeline passing - checklist validation recommended"
          elif [ "$PIPELINE_STATUS" = "failed" ]; then
            echo "   ❌ Pipeline failing - resolve CI issues before validation"
          else
            echo "   ⚪ Pipeline status unclear - manual validation required"
          fi
          ;;
        "security")
          echo "🔒 Section 1: Security & Compliance (CI-Enhanced)"
          SECURITY_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.name | test("security|scan|lint|audit")) | .name' 2>/dev/null | wc -l || echo "0")
          if [ "$SECURITY_JOBS" -gt 0 ]; then
            echo "   ✅ Security scanning jobs detected: $SECURITY_JOBS"
            echo "   💡 Review job results for security validation"
          else
            echo "   ⚠️ No security scanning jobs detected"
            echo "   💡 Consider adding security validation to CI"
          fi
          ;;
        "deployment")
          echo "🚀 Section 8: Deployment Strategy (Live Validation)"
          DEPLOY_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.name | test("deploy|provision|release")) | .name' 2>/dev/null | wc -l || echo "0")
          if [ "$DEPLOY_JOBS" -gt 0 ]; then
            echo "   ✅ Deployment jobs configured: $DEPLOY_JOBS"
            DEPLOY_STATUS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.name | test("deploy")) | .status' 2>/dev/null | head -1 || echo "unknown")
            echo "   📊 Latest deployment status: $DEPLOY_STATUS"
          else
            echo "   ℹ️ No deployment jobs detected"
            echo "   💡 Manual deployment validation required"
          fi
          ;;
        *)
          echo "📋 Section: $section (Standard Validation)"
          echo "   ℹ️ Use standard infrastructure checklist validation"
          ;;
      esac
    done

  else
    echo ""
    echo "⚠️ Infrastructure DevOps integration not available"
    echo "   📦 Install bmad-infrastructure-devops for checklist integration"
    echo "   💡 Continuing with CI-only validation..."
  fi
fi
```

### Phase 4: Cross-Pack Integration Assessment

```bash
echo ""
echo "🔗 Cross-Pack Integration Assessment:"
echo "===================================="

# Generate comprehensive integration status
generate_integration_status

echo ""
echo "🎯 Integration Health Summary:"

INTEGRATION_SCORE=0
TOTAL_INTEGRATIONS=0

# JIRA Integration Assessment
if [ "$JIRA_INTEGRATION" = "true" ]; then
  TOTAL_INTEGRATIONS=$((TOTAL_INTEGRATIONS + 1))
  if [ -n "$DETECTED_JIRA_ISSUES" ]; then
    echo "   ✅ JIRA Integration: ACTIVE (Issues: $DETECTED_JIRA_ISSUES)"
    INTEGRATION_SCORE=$((INTEGRATION_SCORE + 1))
  else
    echo "   ⚪ JIRA Integration: AVAILABLE (No issues detected)"
  fi
else
  echo "   ⚪ JIRA Integration: NOT AVAILABLE"
fi

# Parallel Development Assessment
if [ "$PARALLEL_DEV_INTEGRATION" = "true" ]; then
  TOTAL_INTEGRATIONS=$((TOTAL_INTEGRATIONS + 1))
  if [ "$PARALLEL_DEV_ACTIVE" = "true" ]; then
    echo "   ✅ Parallel Development: ACTIVE (Multiple worktrees detected)"
    INTEGRATION_SCORE=$((INTEGRATION_SCORE + 1))
  else
    echo "   ⚪ Parallel Development: AVAILABLE (Single worktree)"
  fi
else
  echo "   ⚪ Parallel Development: NOT AVAILABLE"
fi

# Infrastructure DevOps Assessment
if [ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" = "true" ]; then
  TOTAL_INTEGRATIONS=$((TOTAL_INTEGRATIONS + 1))
  if [ "$INFRASTRUCTURE_CONTEXT" = "true" ]; then
    echo "   ✅ Infrastructure DevOps: ACTIVE (IaC patterns detected)"
    INTEGRATION_SCORE=$((INTEGRATION_SCORE + 1))
  else
    echo "   ⚪ Infrastructure DevOps: AVAILABLE (No IaC patterns)"
  fi
else
  echo "   ❌ Infrastructure DevOps: NOT AVAILABLE"
  echo "      💡 Install bmad-infrastructure-devops for full validation"
fi

# Calculate integration health
if [ "$TOTAL_INTEGRATIONS" -gt 0 ]; then
  INTEGRATION_HEALTH=$((INTEGRATION_SCORE * 100 / TOTAL_INTEGRATIONS))
  echo ""
  echo "📊 Integration Health: $INTEGRATION_HEALTH% ($INTEGRATION_SCORE/$TOTAL_INTEGRATIONS integrations active)"
else
  INTEGRATION_HEALTH=0
  echo ""
  echo "📊 Integration Health: 0% (No integrations available)"
fi
```

### Phase 5: Validation Summary and Recommendations

```bash
echo ""
echo "📋 Validation Summary:"
echo "====================="

echo "🎯 Overall Validation Results:"
echo "   CI Health: $CI_HEALTH_STATUS ($SUCCESS_RATE%)"
echo "   Integration Health: $INTEGRATION_HEALTH%"
echo "   Infrastructure Context: $([ "$INFRASTRUCTURE_CONTEXT" = "true" ] && echo "DETECTED" || echo "NOT DETECTED")"
echo "   Infrastructure DevOps: $([ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" = "true" ] && echo "AVAILABLE" || echo "NOT AVAILABLE")"

# Overall validation status
OVERALL_STATUS="UNKNOWN"
if [ "$CI_HEALTH_STATUS" = "EXCELLENT" ] && [ "$INTEGRATION_HEALTH" -ge 75 ]; then
  OVERALL_STATUS="EXCELLENT"
  VALIDATION_EMOJI="✅"
elif [ "$CI_HEALTH_STATUS" = "EXCELLENT" ] || [ "$CI_HEALTH_STATUS" = "NEEDS_ATTENTION" ]; then
  OVERALL_STATUS="GOOD"
  VALIDATION_EMOJI="👍"
elif [ "$CI_HEALTH_STATUS" = "CRITICAL" ]; then
  OVERALL_STATUS="CRITICAL"
  VALIDATION_EMOJI="🚨"
else
  OVERALL_STATUS="NEEDS_ATTENTION"
  VALIDATION_EMOJI="⚠️"
fi

echo ""
echo "$VALIDATION_EMOJI OVERALL VALIDATION STATUS: $OVERALL_STATUS"

if [ "$include_recommendations" = "true" ]; then
  echo ""
  echo "💡 Recommendations:"
  echo "=================="

  case "$OVERALL_STATUS" in
    "EXCELLENT")
      echo "✅ Infrastructure CI/CD is in excellent condition"
      echo "   💡 Consider regular validation to maintain health"
      echo "   📊 Monitor trends for continuous improvement"
      ;;
    "GOOD")
      echo "👍 Infrastructure CI/CD is in good condition with minor areas for improvement"
      if [ "$CI_HEALTH_STATUS" = "NEEDS_ATTENTION" ]; then
        echo "   🔧 Focus on improving CI pipeline success rate"
        echo "   📋 Use 'analyze-pipeline-failures' for detailed diagnosis"
      fi
      if [ "$INTEGRATION_HEALTH" -lt 75 ]; then
        echo "   🔗 Consider installing additional expansion packs for better integration"
        echo "   📦 bmad-infrastructure-devops recommended for infrastructure projects"
      fi
      ;;
    "NEEDS_ATTENTION")
      echo "⚠️ Infrastructure CI/CD needs attention before production deployment"
      echo "   🔧 Address CI pipeline issues identified above"
      echo "   📋 Complete infrastructure checklist validation manually if needed"
      echo "   🔗 Ensure proper integration between CI/CD and infrastructure systems"
      ;;
    "CRITICAL")
      echo "🚨 CRITICAL: Infrastructure CI/CD validation failed"
      echo "   🛑 DO NOT PROCEED with infrastructure deployment"
      echo "   🚨 Resolve CI pipeline failures immediately"
      echo "   📞 Escalate to infrastructure team if needed"
      echo "   🔄 Re-run validation after fixes are implemented"
      ;;
  esac

  # Specific recommendations based on context
  echo ""
  echo "🎯 Specific Recommendations:"

  if [ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" != "true" ]; then
    echo "   📦 Install Infrastructure DevOps Pack:"
    echo "      bmad-enhanced install --expansion-packs bmad-infrastructure-devops"
    echo "      Benefits: Enhanced checklist validation, infrastructure workflows"
  fi

  if [ "$INFRASTRUCTURE_CONTEXT" = "true" ] && [ "$SUCCESS_RATE" -lt "$CI_HEALTH_THRESHOLD" ]; then
    echo "   🏗️ Infrastructure CI Improvements:"
    echo "      - Add infrastructure-specific validation jobs"
    echo "      - Implement security scanning for IaC files"
    echo "      - Add deployment smoke tests"
  fi

  if [ "$INTEGRATION_HEALTH" -lt 50 ]; then
    echo "   🔗 Integration Improvements:"
    echo "      - Install complementary expansion packs for better coordination"
    echo "      - Configure JIRA integration for issue tracking"
    echo "      - Set up parallel development if working with multiple features"
  fi
fi
```

### Phase 6: Report Generation

```bash
if [ "$generate_report" = "true" ]; then
  echo ""
  echo "📄 Generating Validation Report:"
  echo "==============================="

  REPORT_FILE="infrastructure_ci_validation_$(date +%Y%m%d_%H%M%S).md"

  cat > "$REPORT_FILE" << EOF
# Infrastructure CI/CD Validation Report

**Generated:** $(date)
**Validation Mode:** $VALIDATION_MODE
**Infrastructure Scope:** $INFRASTRUCTURE_SCOPE
**CI Health Threshold:** $CI_HEALTH_THRESHOLD%

## Executive Summary

**Overall Status:** $VALIDATION_EMOJI $OVERALL_STATUS
**CI Health:** $CI_HEALTH_STATUS ($SUCCESS_RATE%)
**Integration Health:** $INTEGRATION_HEALTH%
**Infrastructure Context:** $([ "$INFRASTRUCTURE_CONTEXT" = "true" ] && echo "DETECTED" || echo "NOT DETECTED")

## Pipeline Analysis

**Pipeline ID:** $PIPELINE_ID
**Status:** $PIPELINE_STATUS
**Success Rate:** $SUCCESS_RATE% ($((TOTAL_JOBS - FAILED_JOBS))/$TOTAL_JOBS jobs)
**URL:** $PIPELINE_URL

### Infrastructure Jobs
$(if [ -n "$INFRA_JOBS" ]; then
  echo "$INFRA_JOBS" | while read job; do
    JOB_STATUS=$(echo "$PIPELINE_DATA" | jq -r ".jobs[] | select(.name == \"$job\") | .status")
    echo "- $job: $JOB_STATUS"
  done
else
  echo "- No infrastructure-specific jobs detected"
fi)

## Integration Status

$(if [ "$JIRA_INTEGRATION" = "true" ]; then
  echo "- **JIRA Integration:** Available $([ -n "$DETECTED_JIRA_ISSUES" ] && echo "(Issues: $DETECTED_JIRA_ISSUES)" || echo "")"
else
  echo "- **JIRA Integration:** Not Available"
fi)

$(if [ "$PARALLEL_DEV_INTEGRATION" = "true" ]; then
  echo "- **Parallel Development:** Available $([ "$PARALLEL_DEV_ACTIVE" = "true" ] && echo "(Active)" || echo "")"
else
  echo "- **Parallel Development:** Not Available"
fi)

$(if [ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" = "true" ]; then
  echo "- **Infrastructure DevOps:** Available $([ "$INFRASTRUCTURE_CONTEXT" = "true" ] && echo "(IaC Detected)" || echo "")"
else
  echo "- **Infrastructure DevOps:** Not Available"
fi)

## Recommendations

$(case "$OVERALL_STATUS" in
  "EXCELLENT")
    echo "✅ Infrastructure CI/CD is in excellent condition. Continue monitoring."
    ;;
  "GOOD")
    echo "👍 Minor improvements recommended. Focus on CI success rate and integrations."
    ;;
  "NEEDS_ATTENTION")
    echo "⚠️ Address CI issues and complete infrastructure validation before deployment."
    ;;
  "CRITICAL")
    echo "🚨 CRITICAL: Do not proceed with deployment. Resolve CI failures immediately."
    ;;
esac)

## Next Steps

1. **Address CI Issues:** $([ "$SUCCESS_RATE" -lt "$CI_HEALTH_THRESHOLD" ] && echo "Fix failing pipeline jobs" || echo "Monitor for regressions")
2. **Infrastructure Validation:** $([ "$INFRASTRUCTURE_DEVOPS_INTEGRATION" = "true" ] && echo "Complete checklist validation" || echo "Install Infrastructure DevOps pack")
3. **Integration Optimization:** $([ "$INTEGRATION_HEALTH" -lt 75 ] && echo "Install additional expansion packs" || echo "Maintain current integrations")

---
*Report generated by GitLab CI/CD Automation - validate-infrastructure-ci task*
EOF

  echo "📁 Report saved: $REPORT_FILE"
fi

echo ""
echo "🎯 Validation Complete!"
echo "======================"
echo "Status: $VALIDATION_EMOJI $OVERALL_STATUS"
echo "Report: $([ "$generate_report" = "true" ] && echo "$REPORT_FILE" || echo "Not generated")"

# Return appropriate exit code
case "$OVERALL_STATUS" in
  "EXCELLENT"|"GOOD") exit 0 ;;
  "NEEDS_ATTENTION") exit 1 ;;
  "CRITICAL") exit 2 ;;
  *) exit 3 ;;
esac
```

---

## Success Criteria

- ✅ Successfully validates GitLab CI/CD pipeline health
- ✅ Integrates with infrastructure DevOps checklist when available
- ✅ Provides comprehensive cross-pack integration assessment
- ✅ Generates actionable recommendations based on validation results
- ✅ Supports multiple validation modes and scopes
- ✅ Creates detailed validation reports for stakeholders
- ✅ Handles graceful degradation when integrations are unavailable

## Dependencies

- **GitLab CLI** (`glab`) with authentication
- **GitLab CI/CD pipeline** with job data
- **Integration bridge utilities** for cross-pack coordination
- **Optional**: Infrastructure DevOps pack for enhanced checklist validation
- **Optional**: JIRA integration for issue tracking coordination
- **Optional**: Parallel development pack for multi-worktree scenarios
