# generate-ci-health-report

## Task: Comprehensive GitLab CI/CD Health Assessment and Reporting

**Purpose**: Generate detailed health reports for GitLab CI/CD pipelines with metrics, trends, and actionable insights for continuous improvement.

**When to Use**:

- Regular CI/CD health monitoring and reporting
- Team performance assessments
- Process improvement initiatives
- Stakeholder reporting and documentation

---

## Task Configuration

### Input Parameters

- `branches` (optional): Comma-separated list of branches to analyze (default: main,develop)
- `report_format` (optional): markdown, html, json, csv (default: markdown)
- `time_period` (optional): Days to analyze (default: 7)
- `include_trends` (optional): Include historical trend analysis (default: true)
- `integration_status` (optional): Include cross-pack integration health (default: true)
- `output_file` (optional): Custom output file name (default: auto-generated)

### Expected Outputs

- Comprehensive CI/CD health report
- Pipeline performance metrics and trends
- Integration status with other expansion packs
- Actionable recommendations for improvement
- Executive summary for stakeholders

---

## Task Execution

### Phase 1: Data Collection and Context Setup

```bash
echo "📊 GitLab CI/CD Health Report Generation"
echo "======================================="

# Initialize report parameters
REPORT_DATE=$(date '+%Y-%m-%d %H:%M:%S')
REPORT_TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
BRANCHES_TO_ANALYZE=${branches:-"main,develop"}
ANALYSIS_DAYS=${time_period:-7}
REPORT_FORMAT=${report_format:-"markdown"}

echo "📅 Report Date: $REPORT_DATE"
echo "🎯 Branches: $BRANCHES_TO_ANALYZE"
echo "📆 Analysis Period: $ANALYSIS_DAYS days"
echo "📄 Format: $REPORT_FORMAT"

# Verify GitLab CLI authentication
glab auth status || {
  echo "❌ GitLab CLI not authenticated"
  exit 1
}

# Get project information
PROJECT_INFO=$(glab repo view --output json 2>/dev/null)
PROJECT_NAME=$(echo "$PROJECT_INFO" | jq -r '.path_with_namespace // "Unknown Project"')
PROJECT_URL=$(echo "$PROJECT_INFO" | jq -r '.web_url // ""')

echo "📁 Project: $PROJECT_NAME"
```

### Phase 2: Pipeline Health Analysis by Branch

```bash
echo ""
echo "🔍 Analyzing Pipeline Health by Branch:"
echo "======================================"

# Initialize metrics storage
declare -A BRANCH_METRICS

IFS=',' read -ra BRANCH_ARRAY <<< "$BRANCHES_TO_ANALYZE"
for branch in "${BRANCH_ARRAY[@]}"; do
  branch=$(echo "$branch" | xargs)  # Trim whitespace
  echo ""
  echo "📍 Analyzing branch: $branch"
  echo "----------------------------"

  # Get pipeline data for branch
  PIPELINE_DATA=$(glab ci get --output json --branch "$branch" 2>/dev/null)

  if [ $? -eq 0 ] && [ "$PIPELINE_DATA" != "" ]; then
    # Extract metrics using utilities
    source .bmad-core/utils/ci-status-parser.md
    source .bmad-core/utils/pipeline-analyzer.md

    # Basic metrics
    STATUS=$(echo "$PIPELINE_DATA" | jq -r '.status // "unknown"')
    DURATION=$(echo "$PIPELINE_DATA" | jq -r '.duration // 0')
    TOTAL_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs | length')
    FAILED_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.status == "failed") | .name' | wc -l)
    SUCCESS_RATE=$(( (TOTAL_JOBS - FAILED_JOBS) * 100 / TOTAL_JOBS ))

    # Store metrics
    BRANCH_METRICS["$branch,status"]="$STATUS"
    BRANCH_METRICS["$branch,duration"]="$DURATION"
    BRANCH_METRICS["$branch,total_jobs"]="$TOTAL_JOBS"
    BRANCH_METRICS["$branch,failed_jobs"]="$FAILED_JOBS"
    BRANCH_METRICS["$branch,success_rate"]="$SUCCESS_RATE"

    echo "   Status: $(status_to_emoji "$STATUS") $STATUS"
    echo "   Duration: $(format_duration "$DURATION")"
    echo "   Jobs: $TOTAL_JOBS total, $FAILED_JOBS failed"
    echo "   Success Rate: $SUCCESS_RATE%"

    # Health assessment
    if [ "$STATUS" = "success" ] && [ "$SUCCESS_RATE" -gt 90 ]; then
      HEALTH_SCORE="EXCELLENT"
      HEALTH_EMOJI="✅"
    elif [ "$STATUS" = "success" ] && [ "$SUCCESS_RATE" -gt 70 ]; then
      HEALTH_SCORE="GOOD"
      HEALTH_EMOJI="👍"
    elif [ "$SUCCESS_RATE" -gt 50 ]; then
      HEALTH_SCORE="NEEDS_ATTENTION"
      HEALTH_EMOJI="⚠️"
    else
      HEALTH_SCORE="CRITICAL"
      HEALTH_EMOJI="❌"
    fi

    BRANCH_METRICS["$branch,health_score"]="$HEALTH_SCORE"
    BRANCH_METRICS["$branch,health_emoji"]="$HEALTH_EMOJI"

    echo "   Health: $HEALTH_EMOJI $HEALTH_SCORE"

  else
    echo "   ⚪ No pipeline data available"
    BRANCH_METRICS["$branch,status"]="no-pipeline"
    BRANCH_METRICS["$branch,health_score"]="NO_DATA"
    BRANCH_METRICS["$branch,health_emoji"]="⚪"
  fi
done
```

### Phase 3: Cross-Pack Integration Health Assessment

```bash
if [ "$integration_status" = "true" ]; then
  echo ""
  echo "🔗 Integration Health Assessment:"
  echo "==============================="

  # Use integration bridge utility
  source .bmad-core/utils/gitlab-integration-bridge.md

  # Detect available integrations
  detect_expansion_packs
  auto_detect_integration_context

  # Assess JIRA integration health
  if [ "$JIRA_INTEGRATION" = "true" ]; then
    echo ""
    echo "🎯 JIRA Integration Health:"
    echo "   Status: ✅ Available"

    if [ -n "$DETECTED_JIRA_ISSUES" ]; then
      echo "   Issues Detected: $DETECTED_JIRA_ISSUES"
      echo "   Sync Opportunity: ✅ CI status can be synced"
    else
      echo "   Issues Detected: None in recent commits"
      echo "   Sync Opportunity: ⚪ No immediate sync needed"
    fi
  else
    echo ""
    echo "🎯 JIRA Integration Health:"
    echo "   Status: ⚪ Not available"
  fi

  # Assess parallel development integration health
  if [ "$PARALLEL_DEV_INTEGRATION" = "true" ]; then
    echo ""
    echo "🔀 Parallel Development Health:"
    echo "   Status: ✅ Available"

    if [ "$PARALLEL_DEV_ACTIVE" = "true" ]; then
      echo "   Active Worktrees: Multiple detected"
      echo "   Coordination: ✅ CI coordination available"
    else
      echo "   Active Worktrees: Single worktree"
      echo "   Coordination: ⚪ Standard single-branch workflow"
    fi
  else
    echo ""
    echo "🔀 Parallel Development Health:"
    echo "   Status: ⚪ Not available"
  fi

  # Overall integration health
  INTEGRATION_HEALTH="HEALTHY"
  if [ "$JIRA_INTEGRATION" = "true" ] && [ "$PARALLEL_DEV_INTEGRATION" = "true" ]; then
    INTEGRATION_HEALTH="EXCELLENT"
  elif [ "$JIRA_INTEGRATION" = "true" ] || [ "$PARALLEL_DEV_INTEGRATION" = "true" ]; then
    INTEGRATION_HEALTH="GOOD"
  fi

  echo ""
  echo "📊 Overall Integration Health: $INTEGRATION_HEALTH"
fi
```

### Phase 4: Trend Analysis (if enabled)

```bash
if [ "$include_trends" = "true" ]; then
  echo ""
  echo "📈 Trend Analysis (Last $ANALYSIS_DAYS days):"
  echo "==========================================="

  # Note: In a real implementation, this would query historical pipeline data
  # For now, we'll provide trend analysis framework

  echo "📊 Pipeline Frequency Trends:"
  echo "   ℹ️ Trend analysis requires historical data collection"
  echo "   💡 Recommendation: Implement pipeline metrics collection"
  echo ""

  echo "🎯 Success Rate Trends:"
  for branch in "${BRANCH_ARRAY[@]}"; do
    branch=$(echo "$branch" | xargs)
    if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
      SUCCESS_RATE="${BRANCH_METRICS["$branch,success_rate"]}"
      echo "   $branch: $SUCCESS_RATE% (current)"
      echo "     💡 Track over time for trend analysis"
    fi
  done

  echo ""
  echo "⏱️ Performance Trends:"
  for branch in "${BRANCH_ARRAY[@]}"; do
    branch=$(echo "$branch" | xargs)
    if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
      DURATION="${BRANCH_METRICS["$branch,duration"]}"
      echo "   $branch: $(format_duration "$DURATION") (current)"
      echo "     💡 Monitor for performance regression"
    fi
  done
fi
```

### Phase 5: Report Generation

```bash
echo ""
echo "📄 Generating Health Report:"
echo "==========================="

# Determine output file name
if [ -n "$output_file" ]; then
  REPORT_FILE="$output_file"
else
  case "$REPORT_FORMAT" in
    "html") REPORT_FILE="ci_health_report_${REPORT_TIMESTAMP}.html" ;;
    "json") REPORT_FILE="ci_health_report_${REPORT_TIMESTAMP}.json" ;;
    "csv") REPORT_FILE="ci_health_report_${REPORT_TIMESTAMP}.csv" ;;
    *) REPORT_FILE="ci_health_report_${REPORT_TIMESTAMP}.md" ;;
  esac
fi

echo "📁 Report file: $REPORT_FILE"

# Generate report based on format
case "$REPORT_FORMAT" in
  "markdown")
    generate_markdown_report
    ;;
  "html")
    generate_html_report
    ;;
  "json")
    generate_json_report
    ;;
  "csv")
    generate_csv_report
    ;;
  *)
    echo "⚠️ Unknown format '$REPORT_FORMAT', generating markdown"
    generate_markdown_report
    ;;
esac
```

### Phase 6: Report Generation Functions

```bash
generate_markdown_report() {
  cat > "$REPORT_FILE" << EOF
# GitLab CI/CD Health Report

**Generated:** $REPORT_DATE
**Project:** [$PROJECT_NAME]($PROJECT_URL)
**Analysis Period:** $ANALYSIS_DAYS days
**Branches Analyzed:** $BRANCHES_TO_ANALYZE

## Executive Summary

$(generate_executive_summary)

## Pipeline Health by Branch

$(for branch in "${BRANCH_ARRAY[@]}"; do
  branch=$(echo "$branch" | xargs)
  echo "### $branch"
  echo ""

  if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
    echo "- **Status:** ${BRANCH_METRICS["$branch,health_emoji"]} ${BRANCH_METRICS["$branch,status"]}"
    echo "- **Health Score:** ${BRANCH_METRICS["$branch,health_score"]}"
    echo "- **Success Rate:** ${BRANCH_METRICS["$branch,success_rate"]}%"
    echo "- **Duration:** $(format_duration "${BRANCH_METRICS["$branch,duration"]}")"
    echo "- **Total Jobs:** ${BRANCH_METRICS["$branch,total_jobs"]}"
    echo "- **Failed Jobs:** ${BRANCH_METRICS["$branch,failed_jobs"]}"
  else
    echo "- **Status:** ⚪ No pipeline data available"
  fi
  echo ""
done)

## Integration Status

$(if [ "$integration_status" = "true" ]; then
  echo "- **JIRA Integration:** $([ "$JIRA_INTEGRATION" = "true" ] && echo "✅ Available" || echo "⚪ Not configured")"
  echo "- **Parallel Development:** $([ "$PARALLEL_DEV_INTEGRATION" = "true" ] && echo "✅ Available" || echo "⚪ Not configured")"
  echo "- **Overall Integration Health:** $INTEGRATION_HEALTH"
else
  echo "Integration status not included in this report."
fi)

## Recommendations

$(generate_recommendations)

## Next Steps

1. 📊 **Monitor Key Metrics:** Track success rates and performance trends
2. 🔧 **Address Issues:** Focus on branches with health scores below "GOOD"
3. 🔄 **Regular Reviews:** Schedule weekly/monthly health report reviews
4. 📈 **Continuous Improvement:** Implement recommended optimizations

---

*Report generated by GitLab CI/CD Automation - generate-ci-health-report task*
*For interactive analysis, use the glab agent*
EOF
}

generate_executive_summary() {
  local TOTAL_BRANCHES=0
  local HEALTHY_BRANCHES=0
  local CRITICAL_BRANCHES=0

  for branch in "${BRANCH_ARRAY[@]}"; do
    branch=$(echo "$branch" | xargs)
    if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
      TOTAL_BRANCHES=$((TOTAL_BRANCHES + 1))

      case "${BRANCH_METRICS["$branch,health_score"]}" in
        "EXCELLENT"|"GOOD") HEALTHY_BRANCHES=$((HEALTHY_BRANCHES + 1)) ;;
        "CRITICAL") CRITICAL_BRANCHES=$((CRITICAL_BRANCHES + 1)) ;;
      esac
    fi
  done

  if [ $TOTAL_BRANCHES -eq 0 ]; then
    echo "⚠️ **No pipeline data available** for analysis across specified branches."
  elif [ $CRITICAL_BRANCHES -gt 0 ]; then
    echo "🚨 **Attention Required:** $CRITICAL_BRANCHES of $TOTAL_BRANCHES branches need immediate attention."
  elif [ $HEALTHY_BRANCHES -eq $TOTAL_BRANCHES ]; then
    echo "✅ **All Systems Healthy:** All $TOTAL_BRANCHES analyzed branches are performing well."
  else
    echo "👍 **Generally Healthy:** $HEALTHY_BRANCHES of $TOTAL_BRANCHES branches are healthy, with room for improvement on others."
  fi
}

generate_recommendations() {
  echo "### Performance Recommendations"
  echo "- 🚀 **Optimize slow pipelines:** Focus on branches with duration > 15 minutes"
  echo "- 📦 **Implement caching:** Reduce build times with dependency caching"
  echo "- ⚡ **Parallel execution:** Use parallel jobs for CPU-intensive tasks"
  echo ""
  echo "### Quality Recommendations"
  echo "- 🧪 **Improve test reliability:** Address flaky tests affecting success rates"
  echo "- 🔍 **Monitor failure patterns:** Use analyze-pipeline-failures task for deep insights"
  echo "- 📋 **Regular maintenance:** Schedule CI configuration reviews"
  echo ""
  echo "### Integration Recommendations"

  if [ "$JIRA_INTEGRATION" != "true" ]; then
    echo "- 🎯 **Enable JIRA Integration:** Connect CI status to issue tracking"
  fi

  if [ "$PARALLEL_DEV_INTEGRATION" != "true" ]; then
    echo "- 🔀 **Consider Parallel Development:** Enable multi-worktree CI coordination"
  fi

  echo "- 🔗 **Cross-team coordination:** Use integration features for better collaboration"
}

generate_json_report() {
  cat > "$REPORT_FILE" << EOF
{
  "report_metadata": {
    "generated_at": "$REPORT_DATE",
    "project_name": "$PROJECT_NAME",
    "project_url": "$PROJECT_URL",
    "analysis_period_days": $ANALYSIS_DAYS,
    "branches_analyzed": [$(IFS=,; echo "\"${BRANCH_ARRAY[*]}\"" | sed 's/,/","/g')]
  },
  "branch_health": {
$(for branch in "${BRANCH_ARRAY[@]}"; do
  branch=$(echo "$branch" | xargs)
  echo "    \"$branch\": {"
  if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
    echo "      \"status\": \"${BRANCH_METRICS["$branch,status"]}\","
    echo "      \"health_score\": \"${BRANCH_METRICS["$branch,health_score"]}\","
    echo "      \"success_rate\": ${BRANCH_METRICS["$branch,success_rate"]},"
    echo "      \"duration_seconds\": ${BRANCH_METRICS["$branch,duration"]},"
    echo "      \"total_jobs\": ${BRANCH_METRICS["$branch,total_jobs"]},"
    echo "      \"failed_jobs\": ${BRANCH_METRICS["$branch,failed_jobs"]}"
  else
    echo "      \"status\": \"no-pipeline\","
    echo "      \"health_score\": \"NO_DATA\""
  fi
  echo "    }$([ "$branch" != "${BRANCH_ARRAY[-1]// /}" ] && echo ",")"
done)
  },
  "integration_status": {
    "jira_integration": $([ "$JIRA_INTEGRATION" = "true" ] && echo "true" || echo "false"),
    "parallel_dev_integration": $([ "$PARALLEL_DEV_INTEGRATION" = "true" ] && echo "true" || echo "false"),
    "overall_health": "$INTEGRATION_HEALTH"
  }
}
EOF
}

generate_csv_report() {
  cat > "$REPORT_FILE" << EOF
branch,status,health_score,success_rate,duration_seconds,total_jobs,failed_jobs
$(for branch in "${BRANCH_ARRAY[@]}"; do
  branch=$(echo "$branch" | xargs)
  if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
    echo "$branch,${BRANCH_METRICS["$branch,status"]},${BRANCH_METRICS["$branch,health_score"]},${BRANCH_METRICS["$branch,success_rate"]},${BRANCH_METRICS["$branch,duration"]},${BRANCH_METRICS["$branch,total_jobs"]},${BRANCH_METRICS["$branch,failed_jobs"]}"
  else
    echo "$branch,no-pipeline,NO_DATA,0,0,0,0"
  fi
done)
EOF
}
```

### Phase 7: Report Finalization and Summary

```bash
echo ""
echo "✅ Health Report Generated Successfully!"
echo "======================================="

echo "📄 Report Details:"
echo "   File: $REPORT_FILE"
echo "   Format: $REPORT_FORMAT"
echo "   Size: $(wc -l < "$REPORT_FILE") lines"

echo ""
echo "📊 Summary Statistics:"
TOTAL_ANALYZED=0
HEALTHY_COUNT=0
for branch in "${BRANCH_ARRAY[@]}"; do
  branch=$(echo "$branch" | xargs)
  if [ "${BRANCH_METRICS["$branch,status"]}" != "no-pipeline" ]; then
    TOTAL_ANALYZED=$((TOTAL_ANALYZED + 1))
    case "${BRANCH_METRICS["$branch,health_score"]}" in
      "EXCELLENT"|"GOOD") HEALTHY_COUNT=$((HEALTHY_COUNT + 1)) ;;
    esac
  fi
done

echo "   Branches Analyzed: $TOTAL_ANALYZED"
echo "   Healthy Branches: $HEALTHY_COUNT"
echo "   Overall Health: $([ $TOTAL_ANALYZED -eq $HEALTHY_COUNT ] && echo "✅ EXCELLENT" || echo "⚠️ NEEDS ATTENTION")"

echo ""
echo "🎯 Next Actions:"
echo "   1. 📖 Review the generated report: $REPORT_FILE"
echo "   2. 📊 Share with stakeholders as needed"
echo "   3. 🔧 Address any identified issues"
echo "   4. 📅 Schedule regular health report generation"

echo ""
echo "🔗 Related Commands:"
echo "   - Deep failure analysis: analyze-pipeline-failures"
echo "   - Real-time monitoring: monitor-pipeline-status"
echo "   - Configuration debugging: debug-ci-configuration"

echo ""
echo "📈 REPORT GENERATION COMPLETE"
```

---

## Success Criteria

- ✅ Successfully generates comprehensive CI/CD health reports
- ✅ Provides actionable insights and recommendations
- ✅ Supports multiple output formats (markdown, HTML, JSON, CSV)
- ✅ Includes integration status assessment
- ✅ Delivers executive summary suitable for stakeholders
- ✅ Operates autonomously with configurable parameters

## Dependencies

- **GitLab CLI** (`glab`) with authentication
- **Utilities**: ci-status-parser, pipeline-analyzer, gitlab-integration-bridge
- **Optional**: JIRA integration, parallel-dev integration for comprehensive health assessment
