# Pipeline Analyzer Utility

## Intelligent Pipeline Analysis and Health Assessment

This utility provides comprehensive analysis of GitLab pipeline data to identify patterns, problems, and optimization opportunities. It builds on the verified GitLab commands to provide intelligent insights.

## Core Analysis Functions

### Pipeline Health Assessment

#### Overall Pipeline Health Score

```bash
# Calculate pipeline health score based on success rate, duration, and frequency
calculate_pipeline_health() {
  local branch=${1:-$(git branch --show-current)}

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

  if [ $? -eq 0 ] && [ "$RECENT_PIPELINES" != "" ]; then
    # Extract key metrics
    STATUS=$(echo "$RECENT_PIPELINES" | jq -r '.status // "unknown"')
    DURATION=$(echo "$RECENT_PIPELINES" | jq -r '.duration // 0')
    FAILED_JOBS=$(echo "$RECENT_PIPELINES" | jq -r '.jobs[] | select(.status == "failed") | .name' | wc -l)
    TOTAL_JOBS=$(echo "$RECENT_PIPELINES" | jq -r '.jobs[] | .name' | wc -l)

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

    echo "Pipeline Health Assessment for branch: $branch"
    echo "========================================"
    echo "Status: $STATUS"
    echo "Success Rate: $SUCCESS_RATE%"
    echo "Duration: ${DURATION}s"
    echo "Failed Jobs: $FAILED_JOBS/$TOTAL_JOBS"

    # Health score calculation
    if [ "$STATUS" = "success" ] && [ "$SUCCESS_RATE" -gt 90 ]; then
      echo "Health Score: EXCELLENT ✅"
    elif [ "$STATUS" = "success" ] && [ "$SUCCESS_RATE" -gt 70 ]; then
      echo "Health Score: GOOD 👍"
    elif [ "$SUCCESS_RATE" -gt 50 ]; then
      echo "Health Score: NEEDS ATTENTION ⚠️"
    else
      echo "Health Score: CRITICAL ❌"
    fi
  else
    echo "No pipeline data available for health assessment"
  fi
}
```

#### Failure Pattern Analysis

```bash
# Analyze failure patterns to identify recurring issues
analyze_failure_patterns() {
  local branch=${1:-$(git branch --show-current)}

  PIPELINE_INFO=$(glab ci get --output json --branch $branch 2>/dev/null)

  if [ $? -eq 0 ] && [ "$PIPELINE_INFO" != "" ]; then
    echo "Failure Pattern Analysis"
    echo "======================="

    # Get failed jobs
    FAILED_JOBS=$(echo "$PIPELINE_INFO" | jq -r '.jobs[] | select(.status == "failed") | .name')

    if [ -n "$FAILED_JOBS" ]; then
      echo "Failed Jobs:"
      echo "$FAILED_JOBS" | while read job_name; do
        echo "  - $job_name"

        # Get failure details from logs
        JOB_ID=$(echo "$PIPELINE_INFO" | jq -r ".jobs[] | select(.name == \"$job_name\") | .id")
        if [ "$JOB_ID" != "null" ]; then
          # Analyze last few lines of logs for common failure patterns
          LOGS=$(glab ci trace $JOB_ID 2>/dev/null | tail -10)

          # Check for common failure patterns
          if echo "$LOGS" | grep -q "permission denied"; then
            echo "    🔒 Pattern: Permission issue detected"
          elif echo "$LOGS" | grep -q "timeout"; then
            echo "    ⏱️ Pattern: Timeout issue detected"
          elif echo "$LOGS" | grep -q "dependency"; then
            echo "    📦 Pattern: Dependency issue detected"
          elif echo "$LOGS" | grep -q "test.*failed"; then
            echo "    🧪 Pattern: Test failure detected"
          elif echo "$LOGS" | grep -q "build.*failed"; then
            echo "    🔨 Pattern: Build failure detected"
          else
            echo "    ❓ Pattern: Unknown failure type"
          fi
        fi
      done
    else
      echo "No failed jobs in current pipeline"
    fi
  else
    echo "No pipeline data available for failure analysis"
  fi
}
```

### Performance Analysis

#### Pipeline Duration Analysis

```bash
# Analyze pipeline and job durations for performance insights
analyze_pipeline_performance() {
  local branch=${1:-$(git branch --show-current)}

  PIPELINE_INFO=$(glab ci get --output json --branch $branch 2>/dev/null)

  if [ $? -eq 0 ] && [ "$PIPELINE_INFO" != "" ]; then
    echo "Pipeline Performance Analysis"
    echo "============================"

    TOTAL_DURATION=$(echo "$PIPELINE_INFO" | jq -r '.duration // 0')
    echo "Total Pipeline Duration: ${TOTAL_DURATION}s"

    # Job duration breakdown
    echo ""
    echo "Job Duration Breakdown:"
    echo "$PIPELINE_INFO" | jq -r '.jobs[] | "\(.name): \(.duration // 0)s (\(.status))"' | sort -k2 -nr

    # Identify longest running jobs
    echo ""
    echo "Performance Insights:"
    LONGEST_JOB=$(echo "$PIPELINE_INFO" | jq -r '.jobs[] | select(.duration != null) | "\(.duration) \(.name)"' | sort -nr | head -1)
    if [ -n "$LONGEST_JOB" ]; then
      echo "🐌 Slowest job: $LONGEST_JOB"
    fi

    # Duration assessment
    if [ "$TOTAL_DURATION" -lt 300 ]; then
      echo "⚡ Performance: FAST (under 5 minutes)"
    elif [ "$TOTAL_DURATION" -lt 900 ]; then
      echo "👍 Performance: ACCEPTABLE (5-15 minutes)"
    elif [ "$TOTAL_DURATION" -lt 1800 ]; then
      echo "⚠️ Performance: SLOW (15-30 minutes)"
    else
      echo "🚨 Performance: VERY SLOW (over 30 minutes)"
    fi
  else
    echo "No pipeline data available for performance analysis"
  fi
}
```

### Resource Usage Analysis

#### Job Resource Assessment

```bash
# Analyze job resource usage and efficiency
analyze_job_resources() {
  local branch=${1:-$(git branch --show-current)}

  PIPELINE_INFO=$(glab ci get --output json --branch $branch 2>/dev/null)

  if [ $? -eq 0 ] && [ "$PIPELINE_INFO" != "" ]; then
    echo "Job Resource Analysis"
    echo "===================="

    # Count jobs by stage
    echo "Jobs by Stage:"
    echo "$PIPELINE_INFO" | jq -r '.jobs[] | .stage' | sort | uniq -c | sort -nr

    echo ""
    echo "Jobs by Status:"
    echo "$PIPELINE_INFO" | jq -r '.jobs[] | .status' | sort | uniq -c | sort -nr

    # Parallel execution analysis
    echo ""
    echo "Parallel Execution Opportunities:"
    STAGES=$(echo "$PIPELINE_INFO" | jq -r '.jobs[] | .stage' | sort -u)
    echo "$STAGES" | while read stage; do
      JOB_COUNT=$(echo "$PIPELINE_INFO" | jq -r ".jobs[] | select(.stage == \"$stage\") | .name" | wc -l)
      echo "  $stage: $JOB_COUNT jobs"
    done
  else
    echo "No pipeline data available for resource analysis"
  fi
}
```

## Cross-Integration Analysis

### JIRA Integration Health

```bash
# Analyze pipeline status for JIRA integration opportunities
analyze_jira_integration_opportunities() {
  local branch=${1:-$(git branch --show-current)}

  PIPELINE_INFO=$(glab ci get --output json --branch $branch 2>/dev/null)

  if [ $? -eq 0 ] && [ "$PIPELINE_INFO" != "" ]; then
    echo "JIRA Integration Analysis"
    echo "========================"

    STATUS=$(echo "$PIPELINE_INFO" | jq -r '.status')
    WEB_URL=$(echo "$PIPELINE_INFO" | jq -r '.web_url')

    # Check for JIRA-relevant events
    case "$STATUS" in
      "failed")
        echo "🚨 Recommended JIRA Action: Create bug report"
        echo "   Pipeline failed - may need investigation"
        echo "   URL: $WEB_URL"
        ;;
      "success")
        echo "✅ Recommended JIRA Action: Update deployment status"
        echo "   Pipeline successful - ready for deployment tracking"
        ;;
      "running")
        echo "🔄 Recommended JIRA Action: Update in-progress status"
        echo "   Pipeline running - update development status"
        ;;
      *)
        echo "ℹ️ Status: $STATUS - Monitor for updates"
        ;;
    esac

    # Extract commit messages for JIRA issue detection
    COMMIT_SHA=$(echo "$PIPELINE_INFO" | jq -r '.sha // ""')
    if [ -n "$COMMIT_SHA" ]; then
      COMMIT_MSG=$(git log --format=%s -n 1 $COMMIT_SHA 2>/dev/null || echo "")
      if echo "$COMMIT_MSG" | grep -qE '[A-Z]+-[0-9]+'; then
        JIRA_ISSUES=$(echo "$COMMIT_MSG" | grep -oE '[A-Z]+-[0-9]+')
        echo "🎯 Detected JIRA Issues: $JIRA_ISSUES"
      fi
    fi
  else
    echo "No pipeline data available for JIRA integration analysis"
  fi
}
```

### Parallel Development Coordination

```bash
# Analyze CI coordination for parallel development
analyze_parallel_dev_coordination() {
  echo "Parallel Development CI Analysis"
  echo "==============================="

  # Check for multiple worktrees
  WORKTREES=$(git worktree list 2>/dev/null | wc -l)

  if [ "$WORKTREES" -gt 1 ]; then
    echo "📍 Multiple worktrees detected: $WORKTREES"
    echo ""
    echo "Worktree CI Status:"

    git worktree list | while read worktree_info; do
      WORKTREE_PATH=$(echo "$worktree_info" | awk '{print $1}')
      BRANCH=$(echo "$worktree_info" | awk '{print $3}' | tr -d '[]')

      if [ -n "$BRANCH" ]; then
        # Check CI status for this branch
        STATUS=$(glab ci get --output json --branch "$BRANCH" 2>/dev/null | jq -r '.status // "no-pipeline"')
        echo "  $BRANCH: $STATUS"
      fi
    done

    echo ""
    echo "🔄 Parallel CI Coordination Opportunities:"
    echo "  - Monitor all worktree branches simultaneously"
    echo "  - Coordinate merge readiness across branches"
    echo "  - Aggregate CI health across parallel work"
  else
    echo "📍 Single worktree detected - standard CI monitoring"
  fi
}
```

## Comprehensive Analysis Report

### Generate Complete Pipeline Analysis

```bash
# Generate comprehensive pipeline analysis report
generate_comprehensive_analysis() {
  local branch=${1:-$(git branch --show-current)}

  echo "==========================================="
  echo "COMPREHENSIVE GITLAB CI/CD ANALYSIS REPORT"
  echo "==========================================="
  echo "Branch: $branch"
  echo "Timestamp: $(date)"
  echo ""

  # Run all analysis functions
  calculate_pipeline_health "$branch"
  echo ""

  analyze_failure_patterns "$branch"
  echo ""

  analyze_pipeline_performance "$branch"
  echo ""

  analyze_job_resources "$branch"
  echo ""

  analyze_jira_integration_opportunities "$branch"
  echo ""

  analyze_parallel_dev_coordination
  echo ""

  echo "==========================================="
  echo "END OF ANALYSIS REPORT"
  echo "==========================================="
}
```

## Usage Examples

```bash
# Basic health check
calculate_pipeline_health

# Analyze specific branch
analyze_failure_patterns develop

# Performance analysis
analyze_pipeline_performance main

# Full analysis report
generate_comprehensive_analysis main
```

## Integration Notes

- **JIRA Integration**: Use analyze_jira_integration_opportunities() to identify sync opportunities
- **Parallel Development**: Use analyze_parallel_dev_coordination() for multi-worktree CI monitoring
- **Core BMAD**: Integrate analysis results into development workflow decision points
- **Automation**: All functions designed for autonomous execution without user interaction
