# sync-ci-status-to-jira

## Task: Intelligent CI Status Synchronization with JIRA

**Purpose**: Automatic synchronization of GitLab CI/CD pipeline status to JIRA issues with intelligent context awareness and seamless integration with the JIRA expansion pack.

**When to Use**:

- Automatic CI status updates to JIRA issues
- Pipeline failure notifications to stakeholders
- Development progress tracking in JIRA
- Deployment status synchronization

---

## Task Configuration

### Input Parameters

- `branch` (optional): Target branch to sync (default: current branch)
- `jira_issues` (optional): Specific JIRA issues to update (default: auto-detect from commits)
- `sync_mode` (optional): automatic, manual, notification-only (default: automatic)
- `update_transitions` (optional): Enable JIRA status transitions based on CI (default: true)
- `create_comments` (optional): Add CI status comments to JIRA (default: true)
- `failure_handling` (optional): create-bugs, comment-only, notify-only (default: comment-only)

### Expected Outputs

- JIRA issues updated with current CI status
- Automatic status transitions based on CI results
- Detailed CI failure information in JIRA comments
- Cross-reference links between GitLab pipelines and JIRA issues

---

## Task Execution

### Phase 1: Integration Detection and Authentication

```bash
echo "🎯 GitLab CI/CD to JIRA Synchronization"
echo "======================================"

# Check for JIRA integration availability
source .bmad-core/utils/gitlab-integration-bridge.md
detect_expansion_packs

if [ "$JIRA_INTEGRATION" != "true" ]; then
  echo "❌ JIRA integration not available"
  echo "   💡 Install ck-jira-integration expansion pack for JIRA connectivity"
  echo "   📦 Command: bmad-enhanced install --expansion-packs ck-jira-integration"
  exit 1
fi

echo "✅ JIRA integration detected"

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

# Get current context
SYNC_BRANCH=${branch:-$(git branch --show-current)}
echo "📍 Syncing branch: $SYNC_BRANCH"

# Auto-detect integration context
auto_detect_integration_context
```

### Phase 2: JIRA Issue Discovery and Validation

```bash
echo ""
echo "🔍 JIRA Issue Discovery:"
echo "======================"

# Determine which JIRA issues to update
if [ -n "$jira_issues" ]; then
  # Use explicitly provided issues
  TARGET_ISSUES="$jira_issues"
  echo "📝 Using provided JIRA issues: $TARGET_ISSUES"
else
  # Auto-detect from commits
  if [ -n "$DETECTED_JIRA_ISSUES" ]; then
    TARGET_ISSUES="$DETECTED_JIRA_ISSUES"
    echo "🎯 Auto-detected JIRA issues from commits: $TARGET_ISSUES"
  else
    # Try to extract from recent commits on this branch
    echo "🔍 Scanning recent commits for JIRA issue references..."
    TARGET_ISSUES=$(git log --oneline -10 2>/dev/null | grep -oE '[A-Z]+-[0-9]+' | sort -u | tr '\n' ' ' | xargs)

    if [ -n "$TARGET_ISSUES" ]; then
      echo "🎯 Found JIRA issues in recent commits: $TARGET_ISSUES"
    else
      echo "⚪ No JIRA issues detected in recent commits"
      echo "   💡 JIRA issues should be referenced in commit messages (e.g., PROJ-123)"

      if [ "$sync_mode" = "automatic" ]; then
        echo "   ⏩ Skipping sync in automatic mode"
        exit 0
      else
        echo "   ⚠️ Continuing with manual mode"
      fi
    fi
  fi
fi

# Validate JIRA issues if found
if [ -n "$TARGET_ISSUES" ]; then
  echo ""
  echo "✅ JIRA Issues to Sync:"
  for issue in $TARGET_ISSUES; do
    echo "   - $issue"
  done
fi
```

### Phase 3: Pipeline Status Analysis

```bash
echo ""
echo "📊 Pipeline Status Analysis:"
echo "=========================="

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

if [ $? -ne 0 ] || [ "$PIPELINE_DATA" = "" ]; then
  echo "❌ No pipeline data available for branch: $SYNC_BRANCH"

  if [ -n "$TARGET_ISSUES" ]; then
    echo "💡 Updating JIRA with 'no pipeline' status"
    NO_PIPELINE_COMMENT="h3. 🔄 CI/CD Status Update

*Branch:* $SYNC_BRANCH
*Status:* ⚪ No pipeline configured or triggered
*Updated:* $(date)

No CI/CD pipeline found for this branch. Consider:
* Triggering a new pipeline
* Checking GitLab CI configuration
* Verifying branch exists on remote

"

    # Prepare JIRA update for no-pipeline status
    echo "JIRA_UPDATE_DATA={\"issues\":\"$TARGET_ISSUES\",\"status\":\"no-pipeline\",\"comment\":\"$NO_PIPELINE_COMMENT\"}"
  fi

  exit 1
fi

# Extract pipeline metrics
source .bmad-core/utils/ci-status-parser.md

PIPELINE_ID=$(echo "$PIPELINE_DATA" | jq -r '.id')
PIPELINE_STATUS=$(echo "$PIPELINE_DATA" | jq -r '.status')
PIPELINE_URL=$(echo "$PIPELINE_DATA" | jq -r '.web_url')
PIPELINE_DURATION=$(echo "$PIPELINE_DATA" | jq -r '.duration // 0')
PIPELINE_CREATED=$(echo "$PIPELINE_DATA" | jq -r '.created_at')
PIPELINE_UPDATED=$(echo "$PIPELINE_DATA" | jq -r '.updated_at')

# Job analysis
TOTAL_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs | length')
FAILED_JOBS=$(echo "$PIPELINE_DATA" | jq -r '.jobs[] | select(.status == "failed") | .name')
FAILED_COUNT=$(echo "$FAILED_JOBS" | grep -c . || echo "0")
SUCCESS_RATE=$(( (TOTAL_JOBS - FAILED_COUNT) * 100 / TOTAL_JOBS ))

echo "📋 Pipeline Overview:"
echo "   ID: $PIPELINE_ID"
echo "   Status: $(status_to_emoji "$PIPELINE_STATUS") $PIPELINE_STATUS"
echo "   Duration: $(format_duration "$PIPELINE_DURATION")"
echo "   Jobs: $TOTAL_JOBS total, $FAILED_COUNT failed"
echo "   Success Rate: $SUCCESS_RATE%"
echo "   URL: $PIPELINE_URL"
```

### Phase 4: JIRA Status Update Generation

```bash
echo ""
echo "📝 Generating JIRA Updates:"
echo "=========================="

# Generate appropriate JIRA comment based on pipeline status
case "$PIPELINE_STATUS" in
  "success")
    STATUS_EMOJI="✅"
    STATUS_DESCRIPTION="Pipeline completed successfully"
    JIRA_PRIORITY="Normal"
    SUGGESTED_TRANSITION="Ready for Review"
    ;;
  "failed")
    STATUS_EMOJI="❌"
    STATUS_DESCRIPTION="Pipeline failed - attention required"
    JIRA_PRIORITY="High"
    SUGGESTED_TRANSITION="In Development"
    ;;
  "running")
    STATUS_EMOJI="🔄"
    STATUS_DESCRIPTION="Pipeline currently running"
    JIRA_PRIORITY="Normal"
    SUGGESTED_TRANSITION=""
    ;;
  "canceled"|"cancelled")
    STATUS_EMOJI="⏹️"
    STATUS_DESCRIPTION="Pipeline was canceled"
    JIRA_PRIORITY="Normal"
    SUGGESTED_TRANSITION=""
    ;;
  *)
    STATUS_EMOJI="❓"
    STATUS_DESCRIPTION="Pipeline status: $PIPELINE_STATUS"
    JIRA_PRIORITY="Normal"
    SUGGESTED_TRANSITION=""
    ;;
esac

# Create comprehensive JIRA comment
JIRA_COMMENT="h3. $STATUS_EMOJI CI/CD Pipeline Update

*Branch:* $SYNC_BRANCH
*Status:* $STATUS_EMOJI $PIPELINE_STATUS
*Description:* $STATUS_DESCRIPTION
*Duration:* $(format_duration "$PIPELINE_DURATION")
*Success Rate:* $SUCCESS_RATE% ($((TOTAL_JOBS - FAILED_COUNT))/$TOTAL_JOBS jobs)
*Pipeline:* [#$PIPELINE_ID|$PIPELINE_URL]
*Updated:* $(date)

"

# Add job details for failed pipelines
if [ "$PIPELINE_STATUS" = "failed" ] && [ "$FAILED_COUNT" -gt 0 ]; then
  JIRA_COMMENT="${JIRA_COMMENT}h4. ❌ Failed Jobs:
"
  echo "$FAILED_JOBS" | while read job_name; do
    if [ -n "$job_name" ]; then
      JIRA_COMMENT="${JIRA_COMMENT}* $job_name
"
    fi
  done

  JIRA_COMMENT="${JIRA_COMMENT}
*Recommended Actions:*
* Review failed job logs in GitLab pipeline
* Address identified issues and push fixes
* Monitor new pipeline execution

"
fi

# Add success details for successful pipelines
if [ "$PIPELINE_STATUS" = "success" ]; then
  JIRA_COMMENT="${JIRA_COMMENT}h4. ✅ Ready for Next Steps:
* All CI checks passed successfully
* Code quality validated
* Ready for code review and merge
* Consider deployment to staging/production

"
fi

echo "📄 JIRA Comment Generated:"
echo "========================="
echo "$JIRA_COMMENT"
```

### Phase 5: JIRA Integration Execution

```bash
echo ""
echo "🔄 Executing JIRA Integration:"
echo "============================="

if [ "$create_comments" = "true" ] && [ -n "$TARGET_ISSUES" ]; then
  echo "💬 Adding CI status comments to JIRA issues..."

  for issue in $TARGET_ISSUES; do
    echo "   📝 Updating $issue with CI status"

    # Prepare JIRA comment data for the JIRA agent
    echo "JIRA_COMMENT_DATA={
      \"issue\": \"$issue\",
      \"comment\": \"$JIRA_COMMENT\",
      \"pipeline_status\": \"$PIPELINE_STATUS\",
      \"pipeline_url\": \"$PIPELINE_URL\",
      \"branch\": \"$SYNC_BRANCH\"
    }"

    # In a real implementation, this would call the JIRA agent
    echo "   💡 Use jira agent to execute: jira add-comment $issue"
  done
fi

# Handle status transitions
if [ "$update_transitions" = "true" ] && [ -n "$SUGGESTED_TRANSITION" ] && [ -n "$TARGET_ISSUES" ]; then
  echo ""
  echo "🔄 JIRA Status Transition Recommendations:"

  for issue in $TARGET_ISSUES; do
    echo "   🎯 $issue: Suggest transition to '$SUGGESTED_TRANSITION'"
    echo "      Reason: $STATUS_DESCRIPTION"

    # Prepare transition data for JIRA agent
    echo "JIRA_TRANSITION_DATA={
      \"issue\": \"$issue\",
      \"status\": \"$SUGGESTED_TRANSITION\",
      \"comment\": \"Automated transition based on CI status: $PIPELINE_STATUS\",
      \"pipeline_url\": \"$PIPELINE_URL\"
    }"

    echo "   💡 Use jira agent to execute transition if appropriate"
  done
fi
```

### Phase 6: Failure Handling and Bug Creation

```bash
if [ "$PIPELINE_STATUS" = "failed" ] && [ "$failure_handling" = "create-bugs" ] && [ -n "$TARGET_ISSUES" ]; then
  echo ""
  echo "🐛 Pipeline Failure - Bug Creation Mode:"
  echo "======================================="

  # Analyze failures for bug creation
  source .bmad-core/utils/pipeline-analyzer.md

  echo "🔍 Analyzing failures for bug report creation..."

  # Generate bug report summary
  BUG_SUMMARY="CI Pipeline Failure - $SYNC_BRANCH ($(date '+%Y-%m-%d'))"
  BUG_DESCRIPTION="h2. Pipeline Failure Summary

*Branch:* $SYNC_BRANCH
*Pipeline ID:* $PIPELINE_ID
*Failure Time:* $(date)
*Failed Jobs:* $FAILED_COUNT of $TOTAL_JOBS

h3. Failed Jobs:
$(echo "$FAILED_JOBS" | while read job; do echo "* $job"; done)

h3. Investigation Steps:
1. Review pipeline logs: [View Pipeline|$PIPELINE_URL]
2. Analyze failed job details
3. Identify root cause
4. Implement fixes
5. Verify with new pipeline run

h3. Related Issues:
$(for issue in $TARGET_ISSUES; do echo "* $issue"; done)

*This bug was automatically created due to CI pipeline failure.*
"

  echo "📝 Bug Report Prepared:"
  echo "   Summary: $BUG_SUMMARY"
  echo "   💡 Use jira agent to create bug with this information"

  # Prepare bug creation data
  echo "JIRA_BUG_DATA={
    \"summary\": \"$BUG_SUMMARY\",
    \"description\": \"$BUG_DESCRIPTION\",
    \"issue_type\": \"Bug\",
    \"priority\": \"$JIRA_PRIORITY\",
    \"related_issues\": \"$TARGET_ISSUES\",
    \"pipeline_url\": \"$PIPELINE_URL\"
  }"
fi
```

### Phase 7: Cross-Reference and Linking

```bash
echo ""
echo "🔗 Cross-Reference Management:"
echo "============================="

# Create cross-references between GitLab and JIRA
if [ -n "$TARGET_ISSUES" ]; then
  echo "📎 Establishing cross-references..."

  for issue in $TARGET_ISSUES; do
    echo "   🔗 $issue ↔ Pipeline #$PIPELINE_ID"

    # Prepare cross-reference data
    echo "CROSS_REFERENCE_DATA={
      \"jira_issue\": \"$issue\",
      \"gitlab_pipeline\": \"$PIPELINE_ID\",
      \"gitlab_url\": \"$PIPELINE_URL\",
      \"branch\": \"$SYNC_BRANCH\",
      \"status\": \"$PIPELINE_STATUS\",
      \"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"
    }"
  done

  echo "   ✅ Cross-reference data prepared for JIRA agent integration"
fi

# Update GitLab with JIRA context if possible
echo ""
echo "📋 GitLab Context Update:"
echo "   💡 Consider adding JIRA issue links to pipeline descriptions"
echo "   🔗 JIRA Issues: $TARGET_ISSUES"
echo "   📍 Pipeline: $PIPELINE_URL"
```

### Phase 8: Sync Summary and Recommendations

```bash
echo ""
echo "📊 Synchronization Summary:"
echo "=========================="

echo "✅ Sync Status: COMPLETED"
echo "📍 Branch: $SYNC_BRANCH"
echo "🎯 JIRA Issues: $(echo "$TARGET_ISSUES" | wc -w) issues targeted"
echo "🔄 Pipeline Status: $STATUS_EMOJI $PIPELINE_STATUS"

if [ "$create_comments" = "true" ]; then
  echo "💬 Comments: Prepared for JIRA agent"
fi

if [ "$update_transitions" = "true" ] && [ -n "$SUGGESTED_TRANSITION" ]; then
  echo "🔄 Transitions: Recommended '$SUGGESTED_TRANSITION'"
fi

if [ "$failure_handling" = "create-bugs" ] && [ "$PIPELINE_STATUS" = "failed" ]; then
  echo "🐛 Bug Reports: Prepared for critical failures"
fi

echo ""
echo "🎯 Next Steps:"
echo "============="

case "$PIPELINE_STATUS" in
  "success")
    echo "✅ SUCCESS ACTIONS:"
    echo "   1. 👀 JIRA issues updated with success status"
    echo "   2. 🔄 Consider transitioning issues to 'Ready for Review'"
    echo "   3. 🚀 Proceed with deployment or merge process"
    echo "   4. 📋 Update stakeholders on completion"
    ;;
  "failed")
    echo "🚨 FAILURE ACTIONS:"
    echo "   1. 🔍 Review failed jobs in GitLab pipeline"
    echo "   2. 🐛 Check if bug reports were created"
    echo "   3. 🔧 Address root causes identified"
    echo "   4. 📝 Update JIRA with progress/findings"
    echo "   5. 🔄 Re-run pipeline after fixes"
    ;;
  "running")
    echo "🔄 MONITORING ACTIONS:"
    echo "   1. ⏱️ Continue monitoring pipeline progress"
    echo "   2. 👀 JIRA updated with running status"
    echo "   3. 🔔 Wait for completion before next actions"
    ;;
esac

echo ""
echo "🔗 Integration Commands:"
echo "   - JIRA agent: Use for manual JIRA operations"
echo "   - Monitor pipeline: monitor-pipeline-status --branch $SYNC_BRANCH"
echo "   - Failure analysis: analyze-pipeline-failures --branch $SYNC_BRANCH"

echo ""
echo "📈 SYNCHRONIZATION COMPLETE"
echo "🎯 JIRA and GitLab CI/CD are now synchronized"
```

---

## Integration Data Formats

### JIRA Comment Data Structure

```json
{
  "issue": "PROJ-123",
  "comment": "Formatted JIRA comment with CI status",
  "pipeline_status": "success|failed|running",
  "pipeline_url": "https://gitlab.com/project/-/pipelines/123",
  "branch": "feature-branch"
}
```

### JIRA Transition Data Structure

```json
{
  "issue": "PROJ-123",
  "status": "Ready for Review",
  "comment": "Automated transition based on CI status",
  "pipeline_url": "https://gitlab.com/project/-/pipelines/123"
}
```

### Bug Creation Data Structure

```json
{
  "summary": "CI Pipeline Failure - branch-name",
  "description": "Detailed failure description with context",
  "issue_type": "Bug",
  "priority": "High",
  "related_issues": "PROJ-123 PROJ-124",
  "pipeline_url": "https://gitlab.com/project/-/pipelines/123"
}
```

---

## Success Criteria

- ✅ Successfully detects and validates JIRA integration availability
- ✅ Accurately identifies relevant JIRA issues from commits
- ✅ Generates appropriate JIRA comments based on CI status
- ✅ Provides intelligent transition recommendations
- ✅ Handles pipeline failures with configurable response options
- ✅ Maintains cross-references between GitLab and JIRA
- ✅ Operates autonomously with intelligent context awareness

## Dependencies

- **JIRA Integration Pack** (ck-jira-integration) for JIRA connectivity
- **GitLab CLI** (`glab`) with authentication
- **Utilities**: ci-status-parser, pipeline-analyzer, gitlab-integration-bridge
- **Git repository** with commit history and JIRA issue references
