# create-gitlab-workflow-plan

## Task: GitLab CI/CD Workflow Plan Creation

**Purpose**: Create structured workflow plans for GitLab CI/CD operations that integrate seamlessly with BMAD workflow planning system and other expansion packs.

**When to Use**:

- Planning complex CI/CD implementation projects
- Coordinating CI/CD improvements with development workflows
- Establishing CI/CD best practices and processes
- Integrating CI/CD operations with JIRA and parallel development

---

## Task Configuration

### Input Parameters

- `workflow_type` (optional): setup, optimization, debugging, integration (default: setup)
- `integration_packs` (optional): Comma-separated list of expansion packs to integrate (default: auto-detect)
- `project_context` (optional): Project type context for plan customization (default: detect)
- `complexity_level` (optional): simple, standard, complex (default: standard)
- `output_format` (optional): yaml, markdown, interactive (default: yaml)

### Expected Outputs

- Structured GitLab CI/CD workflow plan in BMAD format
- Integration checkpoints with other expansion packs
- Phase-based implementation approach
- Success criteria and validation steps

---

## Task Execution

### Phase 1: Context Analysis and Requirements Gathering

```bash
echo "📋 GitLab CI/CD Workflow Plan Creation"
echo "======================================"

WORKFLOW_TYPE=${workflow_type:-"setup"}
COMPLEXITY_LEVEL=${complexity_level:-"standard"}
OUTPUT_FORMAT=${output_format:-"yaml"}

echo "🎯 Workflow Type: $WORKFLOW_TYPE"
echo "📊 Complexity Level: $COMPLEXITY_LEVEL"
echo "📄 Output Format: $OUTPUT_FORMAT"

# Detect integration context
source .bmad-core/utils/gitlab-integration-bridge.md
detect_expansion_packs
auto_detect_integration_context

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

# Analyze current project context
if [ -f ".gitlab-ci.yml" ] || [ -f "gitlab-ci.yml" ]; then
  echo "✅ GitLab CI configuration exists"
  HAS_CI_CONFIG=true

  # Analyze existing configuration
  CI_CONFIG_FILE=$([ -f ".gitlab-ci.yml" ] && echo ".gitlab-ci.yml" || echo "gitlab-ci.yml")
  STAGES_COUNT=$(grep -A 10 "^stages:" "$CI_CONFIG_FILE" | grep "^  -" | wc -l 2>/dev/null || echo "0")
  JOBS_COUNT=$(grep -c "^[a-zA-Z0-9_-]*:" "$CI_CONFIG_FILE" | grep -v "stages\|variables\|before_script\|after_script" || echo "0")

  echo "   📊 Existing stages: $STAGES_COUNT"
  echo "   📋 Existing jobs: $JOBS_COUNT"
else
  echo "⚪ No GitLab CI configuration detected"
  HAS_CI_CONFIG=false
fi

# Detect project type
if [ -f "package.json" ]; then
  PROJECT_TYPE="nodejs"
  echo "📦 Project Type: Node.js/JavaScript"
elif [ -f "requirements.txt" ] || [ -f "setup.py" ]; then
  PROJECT_TYPE="python"
  echo "🐍 Project Type: Python"
elif [ -f "pom.xml" ] || [ -f "build.gradle" ]; then
  PROJECT_TYPE="java"
  echo "☕ Project Type: Java"
elif [ -f "Cargo.toml" ]; then
  PROJECT_TYPE="rust"
  echo "🦀 Project Type: Rust"
elif [ -f "go.mod" ]; then
  PROJECT_TYPE="go"
  echo "🐹 Project Type: Go"
else
  PROJECT_TYPE="generic"
  echo "📁 Project Type: Generic"
fi

# Integration pack detection
echo ""
echo "🔗 Integration Opportunities:"
echo "=========================="

INTEGRATION_PACKS_LIST=""
if [ "$JIRA_INTEGRATION" = "true" ]; then
  echo "✅ JIRA Integration: Available"
  INTEGRATION_PACKS_LIST="$INTEGRATION_PACKS_LIST,jira"
fi

if [ "$PARALLEL_DEV_INTEGRATION" = "true" ]; then
  echo "✅ Parallel Development: Available"
  INTEGRATION_PACKS_LIST="$INTEGRATION_PACKS_LIST,parallel-dev"
fi

if [ "$AI_AGENT_DEV_INTEGRATION" = "true" ]; then
  echo "✅ AI Agent Development: Available"
  INTEGRATION_PACKS_LIST="$INTEGRATION_PACKS_LIST,ai-agent-dev"
fi

# Clean up integration packs list
INTEGRATION_PACKS_LIST=$(echo "$INTEGRATION_PACKS_LIST" | sed 's/^,//')

if [ -z "$INTEGRATION_PACKS_LIST" ]; then
  echo "⚪ No integration packs detected"
  INTEGRATION_PACKS_LIST="none"
fi
```

### Phase 2: Workflow Plan Template Selection

```bash
echo ""
echo "📋 Workflow Plan Template Selection:"
echo "=================================="

# Select appropriate workflow plan template based on context
case "$WORKFLOW_TYPE" in
  "setup")
    if [ "$HAS_CI_CONFIG" = true ]; then
      PLAN_TEMPLATE="gitlab-ci-enhancement"
      echo "🔧 Selected: GitLab CI Enhancement Plan"
      echo "   (Improving existing CI configuration)"
    else
      PLAN_TEMPLATE="gitlab-ci-setup"
      echo "🚀 Selected: GitLab CI Setup Plan"
      echo "   (Initial CI/CD implementation)"
    fi
    ;;
  "optimization")
    PLAN_TEMPLATE="gitlab-ci-optimization"
    echo "⚡ Selected: GitLab CI Optimization Plan"
    echo "   (Performance and efficiency improvements)"
    ;;
  "debugging")
    PLAN_TEMPLATE="gitlab-ci-debugging"
    echo "🔍 Selected: GitLab CI Debugging Plan"
    echo "   (Issue resolution and troubleshooting)"
    ;;
  "integration")
    PLAN_TEMPLATE="gitlab-ci-integration"
    echo "🔗 Selected: GitLab CI Integration Plan"
    echo "   (Cross-pack integration and coordination)"
    ;;
  *)
    PLAN_TEMPLATE="gitlab-ci-generic"
    echo "📋 Selected: Generic GitLab CI Plan"
    ;;
esac

echo "   📊 Complexity: $COMPLEXITY_LEVEL"
echo "   🔗 Integrations: $INTEGRATION_PACKS_LIST"
echo "   📦 Project Type: $PROJECT_TYPE"
```

### Phase 3: Plan Structure Generation

```bash
echo ""
echo "🏗️ Generating Workflow Plan Structure:"
echo "====================================="

# Create plan metadata
PLAN_ID="gitlab-ci-workflow-$(date +%Y%m%d-%H%M%S)"
PLAN_TITLE="GitLab CI/CD $(echo $WORKFLOW_TYPE | sed 's/.*/\u&/') Workflow"
CURRENT_DATE=$(date +%Y-%m-%d)

echo "📝 Plan ID: $PLAN_ID"
echo "📄 Title: $PLAN_TITLE"

# Generate plan content based on template and context
case "$PLAN_TEMPLATE" in
  "gitlab-ci-setup")
    generate_setup_plan
    ;;
  "gitlab-ci-enhancement")
    generate_enhancement_plan
    ;;
  "gitlab-ci-optimization")
    generate_optimization_plan
    ;;
  "gitlab-ci-debugging")
    generate_debugging_plan
    ;;
  "gitlab-ci-integration")
    generate_integration_plan
    ;;
  *)
    generate_generic_plan
    ;;
esac
```

### Phase 4: Plan Generation Functions

```bash
generate_setup_plan() {
  WORKFLOW_PLAN=$(cat << 'EOF'
name: gitlab-ci-setup-workflow
title: GitLab CI/CD Initial Setup
description: Comprehensive workflow for implementing GitLab CI/CD from scratch with best practices and integration capabilities

metadata:
  estimated_duration: "2-5 days"
  complexity: "COMPLEXITY_PLACEHOLDER"
  prerequisites:
    - GitLab repository access
    - GitLab CLI authentication
    - Basic understanding of CI/CD concepts
  integrations: "INTEGRATIONS_PLACEHOLDER"

phases:
  preparation:
    title: "Preparation and Planning"
    description: "Initial setup and requirement analysis"
    estimated_duration: "0.5-1 day"
    tasks:
      - analyze_project_requirements
      - define_ci_cd_strategy
      - setup_development_environment
      - validate_gitlab_access
    success_criteria:
      - Project requirements documented
      - CI/CD strategy defined
      - Development environment configured
      - GitLab access validated

  configuration:
    title: "CI Configuration Implementation"
    description: "Create and configure GitLab CI/CD pipeline"
    estimated_duration: "1-2 days"
    dependencies: ["preparation"]
    tasks:
      - create_gitlab_ci_config
      - define_pipeline_stages
      - configure_job_definitions
      - setup_environment_variables
      - implement_caching_strategy
    decision_points:
      - pipeline_strategy_review:
          question: "Does the pipeline strategy align with project needs?"
          if_no: "Revise pipeline design based on requirements"
    success_criteria:
      - GitLab CI configuration created
      - Pipeline stages properly defined
      - Jobs configured with appropriate scripts
      - Environment variables secured
      - Caching implemented for performance

  testing:
    title: "Pipeline Testing and Validation"
    description: "Test and validate the CI/CD pipeline functionality"
    estimated_duration: "0.5-1 day"
    dependencies: ["configuration"]
    tasks:
      - test_pipeline_execution
      - validate_job_outputs
      - verify_caching_behavior
      - test_failure_scenarios
    success_criteria:
      - Pipeline executes successfully
      - All jobs produce expected outputs
      - Caching works as designed
      - Failure scenarios handled gracefully

  integration:
    title: "INTEGRATION_PHASE_PLACEHOLDER"
    description: "INTEGRATION_DESC_PLACEHOLDER"
    estimated_duration: "0.5-1 day"
    dependencies: ["testing"]
    tasks: "INTEGRATION_TASKS_PLACEHOLDER"
    success_criteria: "INTEGRATION_SUCCESS_PLACEHOLDER"

  deployment:
    title: "Production Deployment"
    description: "Deploy CI/CD pipeline to production environment"
    estimated_duration: "0.5 day"
    dependencies: ["integration"]
    tasks:
      - finalize_configuration
      - setup_production_variables
      - enable_pipeline_triggers
      - configure_notifications
      - document_pipeline_usage
    success_criteria:
      - Production configuration deployed
      - Pipeline triggers functional
      - Notifications configured
      - Documentation complete

checkpoints:
  - phase: preparation
    checkpoint: requirements_analysis
    validation: "Project requirements and CI/CD strategy documented"
  - phase: configuration
    checkpoint: pipeline_created
    validation: "GitLab CI configuration file created and syntactically valid"
  - phase: testing
    checkpoint: pipeline_validated
    validation: "Pipeline successfully executes and produces expected results"
  - phase: integration
    checkpoint: integrations_working
    validation: "CHECKPOINT_INTEGRATION_PLACEHOLDER"
  - phase: deployment
    checkpoint: production_ready
    validation: "CI/CD pipeline fully operational in production"

tools_and_resources:
  required_tools:
    - GitLab CLI (glab)
    - Git
    - Project-specific build tools
  recommended_tools:
    - IDE with GitLab integration
    - Local CI testing tools
  documentation:
    - GitLab CI/CD documentation
    - Project-specific CI/CD guidelines
    - Best practices guide

risk_mitigation:
  - risk: "Pipeline configuration errors"
    mitigation: "Use CI lint validation and staged testing"
  - risk: "Security vulnerabilities in CI"
    mitigation: "Follow security best practices and use secret management"
  - risk: "Performance issues"
    mitigation: "Implement caching and optimize job execution"

quality_gates:
  - gate: configuration_review
    criteria: "CI configuration follows best practices"
    phase: configuration
  - gate: security_review
    criteria: "No secrets in configuration, proper access controls"
    phase: configuration
  - gate: performance_review
    criteria: "Pipeline execution time within acceptable limits"
    phase: testing
  - gate: integration_review
    criteria: "QUALITY_GATE_INTEGRATION_PLACEHOLDER"
    phase: integration
EOF
)
}

generate_enhancement_plan() {
  WORKFLOW_PLAN=$(cat << 'EOF'
name: gitlab-ci-enhancement-workflow
title: GitLab CI/CD Enhancement and Improvement
description: Systematic improvement of existing GitLab CI/CD pipeline with optimization and integration enhancements

metadata:
  estimated_duration: "1-3 days"
  complexity: "COMPLEXITY_PLACEHOLDER"
  prerequisites:
    - Existing GitLab CI configuration
    - Pipeline execution history
    - Performance baseline metrics
  integrations: "INTEGRATIONS_PLACEHOLDER"

phases:
  assessment:
    title: "Current State Assessment"
    description: "Analyze existing CI/CD pipeline performance and identify improvement opportunities"
    estimated_duration: "0.5 day"
    tasks:
      - analyze_current_configuration
      - review_pipeline_performance
      - identify_bottlenecks
      - assess_integration_opportunities
    success_criteria:
      - Current state documented
      - Performance baseline established
      - Improvement opportunities identified
      - Integration gaps assessed

  optimization:
    title: "Pipeline Optimization"
    description: "Implement performance and efficiency improvements"
    estimated_duration: "1-1.5 days"
    dependencies: ["assessment"]
    tasks:
      - optimize_caching_strategy
      - improve_job_parallelization
      - enhance_configuration_structure
      - implement_security_improvements
    decision_points:
      - optimization_impact_review:
          question: "Do optimizations provide measurable improvements?"
          if_no: "Revise optimization approach"
    success_criteria:
      - Caching optimized for better hit rates
      - Job execution time reduced
      - Configuration structure improved
      - Security enhancements implemented

  integration_enhancement:
    title: "INTEGRATION_ENHANCEMENT_PLACEHOLDER"
    description: "INTEGRATION_ENHANCEMENT_DESC_PLACEHOLDER"
    estimated_duration: "0.5-1 day"
    dependencies: ["optimization"]
    tasks: "INTEGRATION_ENHANCEMENT_TASKS_PLACEHOLDER"
    success_criteria: "INTEGRATION_ENHANCEMENT_SUCCESS_PLACEHOLDER"

  validation:
    title: "Enhancement Validation"
    description: "Validate improvements and measure performance gains"
    estimated_duration: "0.5 day"
    dependencies: ["integration_enhancement"]
    tasks:
      - measure_performance_improvements
      - validate_enhanced_functionality
      - test_integration_features
      - document_changes
    success_criteria:
      - Performance improvements measured
      - Enhanced functionality validated
      - Integration features tested
      - Changes documented

checkpoints:
  - phase: assessment
    checkpoint: baseline_established
    validation: "Current state and improvement opportunities documented"
  - phase: optimization
    checkpoint: optimizations_implemented
    validation: "Performance and efficiency improvements deployed"
  - phase: integration_enhancement
    checkpoint: integrations_enhanced
    validation: "CHECKPOINT_INTEGRATION_ENHANCEMENT_PLACEHOLDER"
  - phase: validation
    checkpoint: improvements_validated
    validation: "All enhancements tested and performance gains confirmed"
EOF
)
}

generate_optimization_plan() {
  WORKFLOW_PLAN=$(cat << 'EOF'
name: gitlab-ci-optimization-workflow
title: GitLab CI/CD Performance Optimization
description: Focused workflow for optimizing GitLab CI/CD pipeline performance and resource utilization

metadata:
  estimated_duration: "1-2 days"
  complexity: "COMPLEXITY_PLACEHOLDER"
  prerequisites:
    - Existing CI/CD pipeline
    - Performance metrics baseline
    - Access to pipeline logs and metrics
  integrations: "INTEGRATIONS_PLACEHOLDER"

phases:
  performance_analysis:
    title: "Performance Analysis"
    description: "Deep analysis of current pipeline performance and resource usage"
    estimated_duration: "0.5 day"
    tasks:
      - analyze_pipeline_duration_trends
      - identify_slowest_jobs
      - review_resource_utilization
      - analyze_caching_effectiveness
    success_criteria:
      - Performance bottlenecks identified
      - Resource usage patterns analyzed
      - Optimization targets prioritized

  optimization_implementation:
    title: "Optimization Implementation"
    description: "Implement targeted performance optimizations"
    estimated_duration: "1 day"
    dependencies: ["performance_analysis"]
    tasks:
      - optimize_job_parallelization
      - enhance_caching_strategies
      - implement_resource_constraints
      - optimize_image_usage
    success_criteria:
      - Job parallelization optimized
      - Cache hit rates improved
      - Resource usage optimized
      - Image sizes reduced

  performance_validation:
    title: "Performance Validation"
    description: "Validate optimization results and measure improvements"
    estimated_duration: "0.5 day"
    dependencies: ["optimization_implementation"]
    tasks:
      - measure_performance_gains
      - validate_resource_efficiency
      - test_optimization_stability
      - document_optimization_results
    success_criteria:
      - Performance gains measured and validated
      - Resource efficiency improved
      - Optimizations proven stable
      - Results documented for future reference
EOF
)
}

generate_debugging_plan() {
  WORKFLOW_PLAN=$(cat << 'EOF'
name: gitlab-ci-debugging-workflow
title: GitLab CI/CD Issue Resolution and Debugging
description: Systematic approach to diagnosing and resolving GitLab CI/CD pipeline issues

metadata:
  estimated_duration: "1-3 days"
  complexity: "COMPLEXITY_PLACEHOLDER"
  prerequisites:
    - Access to failing pipeline
    - Pipeline logs and error messages
    - Development environment access
  integrations: "INTEGRATIONS_PLACEHOLDER"

phases:
  issue_diagnosis:
    title: "Issue Diagnosis"
    description: "Comprehensive analysis of pipeline failures and issues"
    estimated_duration: "0.5-1 day"
    tasks:
      - analyze_failure_patterns
      - review_error_logs
      - identify_root_causes
      - assess_issue_impact
    success_criteria:
      - Failure patterns documented
      - Root causes identified
      - Issue impact assessed
      - Resolution strategy defined

  resolution_implementation:
    title: "Resolution Implementation"
    description: "Implement fixes and improvements to resolve identified issues"
    estimated_duration: "0.5-1.5 days"
    dependencies: ["issue_diagnosis"]
    tasks:
      - implement_configuration_fixes
      - resolve_dependency_issues
      - fix_script_errors
      - update_environment_settings
    decision_points:
      - fix_validation:
          question: "Do the implemented fixes resolve the identified issues?"
          if_no: "Review diagnosis and implement alternative solutions"
    success_criteria:
      - Configuration issues resolved
      - Dependencies fixed
      - Script errors corrected
      - Environment properly configured

  validation_and_monitoring:
    title: "Validation and Monitoring"
    description: "Validate fixes and establish monitoring to prevent future issues"
    estimated_duration: "0.5 day"
    dependencies: ["resolution_implementation"]
    tasks:
      - validate_pipeline_functionality
      - test_edge_cases
      - setup_monitoring_alerts
      - document_resolution_process
    success_criteria:
      - Pipeline functionality validated
      - Edge cases tested
      - Monitoring established
      - Resolution documented
EOF
)
}

generate_integration_plan() {
  WORKFLOW_PLAN=$(cat << 'EOF'
name: gitlab-ci-integration-workflow
title: GitLab CI/CD Cross-Pack Integration
description: Comprehensive workflow for integrating GitLab CI/CD with other BMAD expansion packs

metadata:
  estimated_duration: "2-4 days"
  complexity: "COMPLEXITY_PLACEHOLDER"
  prerequisites:
    - Functional GitLab CI/CD pipeline
    - Target expansion packs installed
    - Integration requirements defined
  integrations: "INTEGRATIONS_PLACEHOLDER"

phases:
  integration_planning:
    title: "Integration Planning"
    description: "Plan and design cross-pack integrations"
    estimated_duration: "0.5-1 day"
    tasks:
      - assess_integration_requirements
      - design_integration_architecture
      - plan_data_flow_patterns
      - define_integration_checkpoints
    success_criteria:
      - Integration requirements documented
      - Architecture designed
      - Data flows planned
      - Success criteria defined

  integration_implementation:
    title: "Integration Implementation"
    description: "Implement cross-pack integration features"
    estimated_duration: "1-2 days"
    dependencies: ["integration_planning"]
    tasks:
      - implement_jira_integration
      - setup_parallel_dev_coordination
      - configure_cross_pack_communication
      - establish_data_synchronization
    success_criteria:
      - JIRA integration functional
      - Parallel development coordinated
      - Cross-pack communication established
      - Data synchronization working

  integration_testing:
    title: "Integration Testing"
    description: "Test and validate all integration features"
    estimated_duration: "0.5-1 day"
    dependencies: ["integration_implementation"]
    tasks:
      - test_jira_status_sync
      - validate_parallel_ci_coordination
      - verify_cross_pack_workflows
      - test_integration_scenarios
    success_criteria:
      - JIRA sync validated
      - Parallel coordination tested
      - Cross-pack workflows verified
      - Integration scenarios successful

  integration_optimization:
    title: "Integration Optimization"
    description: "Optimize integration performance and reliability"
    estimated_duration: "0.5 day"
    dependencies: ["integration_testing"]
    tasks:
      - optimize_integration_performance
      - enhance_error_handling
      - implement_monitoring
      - document_integration_patterns
    success_criteria:
      - Performance optimized
      - Error handling robust
      - Monitoring implemented
      - Documentation complete
EOF
)
}

generate_generic_plan() {
  WORKFLOW_PLAN=$(cat << 'EOF'
name: gitlab-ci-generic-workflow
title: GitLab CI/CD Generic Workflow
description: Flexible workflow plan adaptable to various GitLab CI/CD scenarios

metadata:
  estimated_duration: "1-3 days"
  complexity: "COMPLEXITY_PLACEHOLDER"
  prerequisites:
    - GitLab repository access
    - Basic CI/CD knowledge
    - Project requirements defined
  integrations: "INTEGRATIONS_PLACEHOLDER"

phases:
  analysis:
    title: "Analysis and Planning"
    description: "Analyze requirements and plan implementation approach"
    estimated_duration: "0.5 day"
    tasks:
      - analyze_project_context
      - define_objectives
      - plan_implementation_approach
      - identify_success_metrics
    success_criteria:
      - Project context understood
      - Objectives clearly defined
      - Implementation plan created
      - Success metrics identified

  implementation:
    title: "Implementation"
    description: "Execute the planned GitLab CI/CD implementation"
    estimated_duration: "1-2 days"
    dependencies: ["analysis"]
    tasks:
      - implement_core_functionality
      - configure_integration_points
      - setup_monitoring_and_alerts
      - implement_quality_gates
    success_criteria:
      - Core functionality implemented
      - Integration points configured
      - Monitoring established
      - Quality gates functional

  validation:
    title: "Validation and Finalization"
    description: "Validate implementation and finalize deployment"
    estimated_duration: "0.5 day"
    dependencies: ["implementation"]
    tasks:
      - validate_functionality
      - test_integration_scenarios
      - finalize_documentation
      - plan_maintenance_approach
    success_criteria:
      - Functionality validated
      - Integration tested
      - Documentation complete
      - Maintenance plan established
EOF
)
}
```

### Phase 5: Plan Customization and Integration

```bash
echo ""
echo "🔧 Customizing Plan for Project Context:"
echo "======================================="

# Replace placeholders with context-specific content
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/COMPLEXITY_PLACEHOLDER/$COMPLEXITY_LEVEL/g")
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATIONS_PLACEHOLDER/$INTEGRATION_PACKS_LIST/g")

# Customize integration sections based on available packs
if [ "$INTEGRATION_PACKS_LIST" != "none" ]; then
  # Generate integration-specific content
  INTEGRATION_PHASE="Cross-Pack Integration"
  INTEGRATION_DESC="Integrate GitLab CI/CD with available expansion packs"
  INTEGRATION_TASKS=""
  INTEGRATION_SUCCESS=""
  CHECKPOINT_INTEGRATION="Cross-pack integrations functional and tested"
  QUALITY_GATE_INTEGRATION="All integrations working as designed"

  if [[ "$INTEGRATION_PACKS_LIST" == *"jira"* ]]; then
    INTEGRATION_TASKS="$INTEGRATION_TASKS      - setup_jira_ci_sync\n"
    INTEGRATION_TASKS="$INTEGRATION_TASKS      - configure_jira_status_updates\n"
    INTEGRATION_SUCCESS="$INTEGRATION_SUCCESS      - JIRA CI status sync functional\n"
  fi

  if [[ "$INTEGRATION_PACKS_LIST" == *"parallel-dev"* ]]; then
    INTEGRATION_TASKS="$INTEGRATION_TASKS      - setup_parallel_ci_coordination\n"
    INTEGRATION_TASKS="$INTEGRATION_TASKS      - configure_multi_worktree_monitoring\n"
    INTEGRATION_SUCCESS="$INTEGRATION_SUCCESS      - Parallel development CI coordination working\n"
  fi

  if [[ "$INTEGRATION_PACKS_LIST" == *"ai-agent-dev"* ]]; then
    INTEGRATION_TASKS="$INTEGRATION_TASKS      - integrate_ai_development_workflows\n"
    INTEGRATION_TASKS="$INTEGRATION_TASKS      - setup_agent_testing_pipeline\n"
    INTEGRATION_SUCCESS="$INTEGRATION_SUCCESS      - AI agent development CI integration functional\n"
  fi
else
  INTEGRATION_PHASE="Additional Configuration"
  INTEGRATION_DESC="Final configuration and optimization"
  INTEGRATION_TASKS="      - optimize_pipeline_configuration\n      - setup_basic_monitoring\n"
  INTEGRATION_SUCCESS="      - Pipeline configuration optimized\n      - Basic monitoring functional\n"
  CHECKPOINT_INTEGRATION="Pipeline fully configured and optimized"
  QUALITY_GATE_INTEGRATION="Pipeline meets performance and quality standards"
fi

# Apply integration customizations
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_PHASE_PLACEHOLDER/$INTEGRATION_PHASE/g")
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_DESC_PLACEHOLDER/$INTEGRATION_DESC/g")
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_TASKS_PLACEHOLDER/$INTEGRATION_TASKS/g")
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_SUCCESS_PLACEHOLDER/$INTEGRATION_SUCCESS/g")
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/CHECKPOINT_INTEGRATION_PLACEHOLDER/$CHECKPOINT_INTEGRATION/g")
WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/QUALITY_GATE_INTEGRATION_PLACEHOLDER/$QUALITY_GATE_INTEGRATION/g")

# Apply enhancement-specific customizations if needed
if [ "$PLAN_TEMPLATE" = "gitlab-ci-enhancement" ]; then
  INTEGRATION_ENHANCEMENT="Integration Enhancement"
  INTEGRATION_ENHANCEMENT_DESC="Enhance cross-pack integration capabilities"
  INTEGRATION_ENHANCEMENT_TASKS="      - enhance_existing_integrations\n      - add_new_integration_features\n"
  INTEGRATION_ENHANCEMENT_SUCCESS="      - Integration enhancements deployed\n      - New features functional\n"
  CHECKPOINT_INTEGRATION_ENHANCEMENT="Integration enhancements validated and operational"

  WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_ENHANCEMENT_PLACEHOLDER/$INTEGRATION_ENHANCEMENT/g")
  WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_ENHANCEMENT_DESC_PLACEHOLDER/$INTEGRATION_ENHANCEMENT_DESC/g")
  WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_ENHANCEMENT_TASKS_PLACEHOLDER/$INTEGRATION_ENHANCEMENT_TASKS/g")
  WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/INTEGRATION_ENHANCEMENT_SUCCESS_PLACEHOLDER/$INTEGRATION_ENHANCEMENT_SUCCESS/g")
  WORKFLOW_PLAN=$(echo "$WORKFLOW_PLAN" | sed "s/CHECKPOINT_INTEGRATION_ENHANCEMENT_PLACEHOLDER/$CHECKPOINT_INTEGRATION_ENHANCEMENT/g")
fi

echo "✅ Plan customized for project context"
echo "   🔗 Integrations: $INTEGRATION_PACKS_LIST"
echo "   📦 Project Type: $PROJECT_TYPE"
echo "   🎯 Workflow Type: $WORKFLOW_TYPE"
```

### Phase 6: Plan Output and Finalization

```bash
echo ""
echo "📄 Generating Workflow Plan Output:"
echo "=================================="

# Determine output file name
case "$OUTPUT_FORMAT" in
  "yaml"|"yml")
    OUTPUT_FILE="$PLAN_ID.yml"
    ;;
  "markdown"|"md")
    OUTPUT_FILE="$PLAN_ID.md"
    ;;
  *)
    OUTPUT_FILE="$PLAN_ID.yml"
    OUTPUT_FORMAT="yaml"
    ;;
esac

echo "📁 Output file: $OUTPUT_FILE"
echo "📄 Format: $OUTPUT_FORMAT"

# Generate output based on format
case "$OUTPUT_FORMAT" in
  "markdown"|"md")
    # Convert YAML to Markdown format
    echo "# $PLAN_TITLE" > "$OUTPUT_FILE"
    echo "" >> "$OUTPUT_FILE"
    echo "**Generated:** $(date)" >> "$OUTPUT_FILE"
    echo "**Plan ID:** $PLAN_ID" >> "$OUTPUT_FILE"
    echo "**Complexity:** $COMPLEXITY_LEVEL" >> "$OUTPUT_FILE"
    echo "**Integrations:** $INTEGRATION_PACKS_LIST" >> "$OUTPUT_FILE"
    echo "" >> "$OUTPUT_FILE"
    echo "\`\`\`yaml" >> "$OUTPUT_FILE"
    echo "$WORKFLOW_PLAN" >> "$OUTPUT_FILE"
    echo "\`\`\`" >> "$OUTPUT_FILE"
    ;;
  *)
    # Output as YAML
    echo "$WORKFLOW_PLAN" > "$OUTPUT_FILE"
    ;;
esac

echo "✅ Workflow plan generated successfully"

# Display plan summary
echo ""
echo "📋 Plan Summary:"
echo "==============="

PHASE_COUNT=$(echo "$WORKFLOW_PLAN" | grep -c "^  [a-zA-Z_]*:$" || echo "0")
TASK_COUNT=$(echo "$WORKFLOW_PLAN" | grep -c "^      - " || echo "0")
CHECKPOINT_COUNT=$(echo "$WORKFLOW_PLAN" | grep -c "^  - phase:" || echo "0")

echo "   📊 Phases: $PHASE_COUNT"
echo "   📋 Tasks: $TASK_COUNT"
echo "   🎯 Checkpoints: $CHECKPOINT_COUNT"
echo "   📄 File: $OUTPUT_FILE"
```

### Phase 7: Integration with BMAD Workflow System

```bash
echo ""
echo "🔗 BMAD Workflow System Integration:"
echo "=================================="

# Check if plan management utility is available
if [ -f ".bmad-core/utils/plan-management.md" ]; then
  echo "✅ BMAD plan management utility detected"
  echo "   💡 Plan can be loaded into BMAD workflow system"
  echo "   🔄 Use plan-management utility to track progress"

  # Provide integration commands
  echo ""
  echo "📋 Integration Commands:"
  echo "   - Load plan: Use plan-management utility with $OUTPUT_FILE"
  echo "   - Track progress: Monitor workflow checkpoints"
  echo "   - Update status: Mark phases and tasks as completed"

else
  echo "ℹ️ BMAD plan management not detected"
  echo "   📋 Plan can be used manually for workflow guidance"
fi

# Integration with other expansion packs
if [ "$INTEGRATION_PACKS_LIST" != "none" ]; then
  echo ""
  echo "🔗 Expansion Pack Integration Points:"

  if [[ "$INTEGRATION_PACKS_LIST" == *"jira"* ]]; then
    echo "   🎯 JIRA: Use jira agent for issue tracking and status updates"
  fi

  if [[ "$INTEGRATION_PACKS_LIST" == *"parallel-dev"* ]]; then
    echo "   🔀 Parallel Dev: Use parallel-dev commands for multi-worktree coordination"
  fi

  if [[ "$INTEGRATION_PACKS_LIST" == *"ai-agent-dev"* ]]; then
    echo "   🤖 AI Agent Dev: Use llm-architect and llm-engineer for AI workflow integration"
  fi
fi
```

### Phase 8: Next Steps and Recommendations

```bash
echo ""
echo "🎯 Next Steps and Recommendations:"
echo "================================="

echo "✅ WORKFLOW PLAN CREATED SUCCESSFULLY"
echo ""
echo "📋 Immediate Actions:"
echo "   1. 📖 Review the generated workflow plan: $OUTPUT_FILE"
echo "   2. 🎯 Load plan into BMAD workflow system (if available)"
echo "   3. 👥 Share plan with team members for review"
echo "   4. 🚀 Begin execution with the first phase"

echo ""
echo "🔧 Implementation Guidance:"
case "$WORKFLOW_TYPE" in
  "setup")
    echo "   - Start with preparation phase to establish requirements"
    echo "   - Use GitLab CI lint validation during configuration"
    echo "   - Test incrementally with simple pipeline first"
    ;;
  "optimization")
    echo "   - Establish baseline metrics before optimization"
    echo "   - Implement optimizations incrementally"
    echo "   - Measure and validate each improvement"
    ;;
  "debugging")
    echo "   - Use analyze-pipeline-failures task for deep analysis"
    echo "   - Focus on highest impact issues first"
    echo "   - Document resolution process for future reference"
    ;;
  "integration")
    echo "   - Ensure all expansion packs are properly installed"
    echo "   - Test integrations in isolation before combining"
    echo "   - Use integration bridge utilities for coordination"
    ;;
esac

echo ""
echo "🔗 Related GitLab CI/CD Commands:"
echo "   - Monitor status: monitor-pipeline-status"
echo "   - Analyze failures: analyze-pipeline-failures"
echo "   - Debug config: debug-ci-configuration"
echo "   - Generate health report: generate-ci-health-report"

if [ "$INTEGRATION_PACKS_LIST" != "none" ]; then
  echo "   - Sync to JIRA: sync-ci-status-to-jira"
  echo "   - Coordinate parallel CI: coordinate-parallel-ci"
fi

echo ""
echo "📈 SUCCESS: WORKFLOW PLAN READY FOR EXECUTION"
echo "🎯 Use the structured plan to achieve your GitLab CI/CD objectives"
```

---

## Success Criteria

- ✅ Successfully generates structured workflow plans in BMAD format
- ✅ Customizes plans based on project context and available integrations
- ✅ Provides appropriate complexity levels and estimation
- ✅ Includes integration checkpoints with other expansion packs
- ✅ Supports multiple output formats (YAML, Markdown)
- ✅ Integrates with BMAD workflow planning system
- ✅ Delivers actionable implementation guidance

## Dependencies

- **BMAD Core** workflow planning utilities (recommended)
- **GitLab CLI** (`glab`) for context analysis
- **Git repository** for project context detection
- **Integration bridge** utilities for cross-pack coordination
- **Optional**: Other expansion packs for enhanced integration planning
