# jira

Universal JIRA operations hub that handles all JIRA interactions through natural language understanding - from story sync to bug analysis, work tracking to maintenance.

## TODO TOOL INTEGRATION - MANDATORY FOR COMPLEX OPERATIONS

[[LLM: CRITICAL - This is a complex multi-step task requiring todo tool usage:

MANDATORY TODO TOOL ACTIVATION:
Before starting JIRA operations, MUST use todo_tool to break down the complex workflow:

1. ALWAYS say "use todo_tool" or "break down this task step by step" first
2. Create specific, actionable subtasks for:
   - Project mapping validation and configuration loading
   - JIRA MCP connectivity verification and tool availability check
   - Operation type detection and workflow routing
   - Data collection and analysis (story sync, bug analysis, work tracking)
   - Validation and error handling
   - Results reporting and follow-up actions
3. Execute tasks one by one, updating status as you progress
4. Only mark tasks complete when fully accomplished with all validation steps done

Keywords that trigger planning mode:

- "use todo_tool"
- "break down this task step by step"
- "create a step-by-step plan"
- "use planning tool"
- "decompose this complex task"

This ensures systematic execution and prevents operation failures or incomplete processing.
]]

## MCP Tool Requirements

[[LLM: MANDATORY - At the start of ANY JIRA operation:

1. PROJECT MAPPING CHECK:
   - Check if `.bmad-workspace/ck-jira-integration/config/jira-expansion-config.yaml` exists
   - If NOT exists, check legacy location `.bmad-workspace/config/jira-expansion-config.yaml`
   - If found in legacy location, migrate to new location
   - If NOT exists in either:
     - ERROR: "❌ No JIRA expansion config found. Please run 'setup' first to configure JIRA-Git mapping."
     - DO NOT proceed with operations
   - If exists:
     - Load project key, git repositories, and other mappings
     - Use this configuration for ALL operations

2. TIME ACCURACY CHECK:
   - Check if `mcp__MCP_DOCKER__get_current_time` is available
   - If available: Use with timezone "America/Los_Angeles" for all timestamps
   - If NOT available: Add warning to outputs: "⚠️ Time accuracy warning: Real-time data unavailable"

3. JIRA MCP CHECK:
   - Check for Atlassian MCP tools by listing tools with prefix 'mcp**mcp-atlassian**'
   - If tools are found, verify basic connectivity with a simple test query
   - If tools are NOT available:
     - Immediately inform the user: "JIRA MCP tools are not configured. To use JIRA integration features, you need to set up the Atlassian MCP."
     - Provide setup instructions from utils/jira-mcp.md
     - Ask if they want to proceed with limited functionality (analysis of existing BMAD docs only)
4. Store the MCP availability status for the session to avoid repeated checks
   ]]

## Core Philosophy

Single entry point for all JIRA operations, using intelligence to understand intent and execute the appropriate workflow. The LLM should:

1. **Interpret any JIRA request** through natural language
2. **Auto-select the right operation** (sync, analyze, track, clean)
3. **Maintain three-way sync** (git-BMAD-JIRA) awareness
4. **Scale complexity** based on request
5. **Provide clear feedback** on actions taken
6. **Handle errors gracefully** with helpful guidance

## Natural Language Triggers

### Universal JIRA Requests

- "work with jira"
- "jira help"
- "update jira"
- "jira operations"
- "jira" (alone)

### Story Synchronization

- "sync this story to jira"
- "update jira with changes"
- "create jira tickets"
- "sync epic to jira"
- "push stories to jira"
- "pull jira updates"

### Bug Operations

- "analyze bug PROJ-123"
- "document this bug"
- "root cause analysis"
- "bug investigation"
- "create bug report"

### Work Tracking

- "update work in jira"
- "track this in jira"
- "log work to jira"
- "document in jira"
- "jira work items"

### Maintenance & Cleanup

- "cleanup jira"
- "fix jira data"
- "jira hygiene"
- "remove duplicates"
- "archive old tickets"

### Test Generation

- "generate tests from jira"
- "test this ticket"
- "create test cases"
- "regression tests for bug"

## Intelligent Operation Detection

[[LLM: Automatically determine operation type from request:

1. Parse natural language for intent
2. Identify JIRA ticket references (PROJ-123 format)
3. Detect operation keywords (sync, analyze, track, clean)
4. Consider context (current files, recent operations)
5. Select appropriate workflow

Learning:

- Log: operation_intent with detected type
- Track: confidence level in intent detection
- Monitor: if user corrects/clarifies, log: intent_clarification event
  ]]

## Story Synchronization Operations

### Single Story Sync

**Triggered by**: Specific story reference or current file context

**Workflow**:

1. Extract JIRA key from story metadata or generate new
2. Compare BMAD content with JIRA fields
3. [[LLM: CRITICAL - Convert Markdown to JIRA Wiki Markup:
   - Use utils/jira-wiki-converter.md conversion rules
   - Convert description field from Markdown to Wiki markup
   - Convert acceptance criteria to Wiki markup
   - Show format conversion in preview
   - Track: format_conversion_applied event]]
4. Show preview of changes (with converted formatting)
   [[LLM: Log: sync_preview_shown event
   - Track: preview acceptance rate
   - If cancelled after preview, log: preview_cancelled with reason if given]]
5. [[LLM: Use `mcp__mcp-atlassian__jira_update_issue` or `jira_create_issue` with Wiki-formatted content]]
6. Update metadata with sync timestamp
   [[LLM: Log: sync_success event with duration and story_count=1]]

### Bulk Sync Operations

**Triggered by**: Epic references, directory context, or "all" keywords

[[LLM: Log: bulk_sync_initiated event with estimated_count]]

**Workflow**:

1. Scan for all relevant stories
2. [[LLM: Use `mcp__mcp-atlassian__jira_search` to find existing tickets]]
3. Identify new, modified, and unchanged stories
4. [[LLM: CRITICAL - Convert all Markdown content to Wiki Markup:
   - Apply jira-wiki-converter.md rules to all descriptions
   - Convert acceptance criteria and technical notes
   - Show conversion summary: "Converting 12 stories from Markdown to Wiki Markup..."
   - Track: bulk_format_conversion with story_count]]
5. Preview bulk changes (with converted formatting)
   [[LLM: Track: bulk preview acceptance/cancellation rates]]
6. [[LLM: Use `mcp__mcp-atlassian__jira_batch_create_issues` with Wiki-formatted content]]
   [[LLM: Log: bulk_sync_completed with story_count, duration, success_rate]]
7. Generate sync report

### Sync Modes

- **Light Sync**: Title, status, and assignee only
- **Full Sync**: All fields including description and acceptance criteria
- **Smart Sync**: Auto-detect based on story completeness

## Bug Analysis Operations

### Bug Investigation

**Triggered by**: Bug ID, error messages, or investigation keywords

**Workflow**:

1. [[LLM: Use `mcp__mcp-atlassian__jira_get_issue` to fetch bug details]]
2. Analyze attachments and comments
3. Search git history for related commits
4. Correlate with BMAD stories
5. Generate investigation summary

### Root Cause Analysis

**Enhanced workflow**:

1. Timeline reconstruction from all sources
2. Pattern matching across similar bugs
3. Impact assessment on features
4. Generate RCA document
5. Suggest preventive measures

## Work Tracking Operations

### Document Upload

**Triggered by**: "document in jira", "attach to ticket"

**Workflow**:

1. Identify target ticket
2. Prepare content for JIRA format
   [[LLM: Apply jira-wiki-converter.md rules:
   - Convert Markdown to Wiki markup
   - Ensure professional formatting
   - Preserve code blocks and links]]
3. [[LLM: Use `mcp__mcp-atlassian__jira_update_issue` with Wiki-formatted content]]
4. Link related tickets
5. Update BMAD metadata

### Progress Updates

**Workflow**:

1. Aggregate work from git commits
2. Update ticket status and comments
3. Log time if requested
4. Update story progress in BMAD

## Maintenance Operations

### Data Cleanup

**Triggered by**: Cleanup keywords or scheduled maintenance

**Types**:

- **Duplicate Detection**: Find and merge duplicate tickets
- **Stale Data**: Archive old, irrelevant tickets
- **Field Cleanup**: Standardize fields across tickets
- **Link Repair**: Fix broken ticket relationships

### Health Checks

**Automated checks**:

1. Three-way sync status
2. Field consistency
3. Workflow violations
4. Orphaned tickets
5. Missing required data

## Test Generation

### Context-Aware Test Creation

**Workflow**:

1. Analyze ticket type (bug, story, task)
2. Extract requirements and acceptance criteria
3. Identify test scenarios
4. Generate test code in detected framework
5. Link tests to JIRA ticket

## Output Management

### Operation Results

[[LLM: For every operation:

1. Provide clear success/failure status
2. Show what was changed
3. Include JIRA ticket links
4. Mention any warnings or issues
5. Suggest next steps
   ]]

### File Management

[[LLM: When generating files use workspace-manager paths:

1. Bug reports: `.bmad-workspace/ck-jira-integration/reports/bugs/bug-{{ticket}}-{{date}}.md`
2. RCA documents: `.bmad-workspace/ck-jira-integration/reports/analysis/rca-{{ticket}}-{{date}}.md`
3. Test files: In appropriate test directory
4. Sync reports: `.bmad-workspace/ck-jira-integration/sync/reports/sync-report-{{date}}.md`
   ]]

## Error Handling

### Common Issues

- **No MCP**: Offer limited BMAD-only operations
- **Auth Failures**: Guide through setup
- **Field Mismatches**: Show field mapping options
- **Network Issues**: Suggest retry with backoff
- **JIRA Expansion Config Missing**: Direct to setup task
- **Corrupted Config**: Offer repair or reset options
- **Concurrent Operations**: Queue or warn about conflicts
- **Partial Sync Failure**: Save progress and offer resume

### Recovery Workflows

#### Operation State Persistence

[[LLM: For any operation that might fail:

1. Save current state to `.bmad-workspace/ck-jira-integration/recovery/operation-{{timestamp}}.yaml`
2. Include: operation type, progress, completed items, pending items
3. On failure, show: "Operation saved. Resume with 'jira resume'"
   ]]

#### Corrupted Configuration Recovery

[[LLM: If jira-expansion-config.yaml is corrupted:

1. Backup corrupted file to `.bmad-workspace/ck-jira-integration/backups/`
2. Attempt auto-repair using last known good config
3. If repair fails, offer guided reconfiguration
4. Log: config_corruption_recovered event
   ]]

#### MCP Timeout Handling

[[LLM: For MCP timeouts:

1. First timeout: Retry immediately
2. Second timeout: Wait 5 seconds, retry
3. Third timeout: Offer offline mode or manual instructions
4. Track: mcp_timeout_pattern for learning
   ]]

#### Concurrent Operation Protection

[[LLM: Before starting operations:

1. Check for `.bmad-workspace/ck-jira-integration/locks/jira-operation.lock`
2. If exists and <5min old: "Another operation in progress. Wait or force? (w/f)"
3. If exists and >5min old: Auto-clear stale lock
4. Create lock with operation ID and timestamp
5. Always remove lock on completion or error
   ]]

## Advanced Features

### Batch Intelligence

- Detect when multiple operations make sense
- Suggest bulk operations for efficiency
- Preview aggregate changes
- Optimize API calls

### Learning Mode

- Remember user preferences
- Adapt to team patterns
- Suggest workflow improvements
- Track operation success rates

### Integration Hooks

- Pre/post operation scripts
- Custom field handlers
- Workflow extensions
- Notification systems

## Examples

### Simple Request

User: "sync this story"
_Detects current file, syncs to JIRA_

### Complex Request

User: "analyze all bugs from last sprint and generate test cases"
_Searches sprint bugs, analyzes patterns, generates tests_

### Natural Conversation

User: "help me get this into jira"
_Asks clarifying questions, guides through process_

This unified task replaces analyze-jira-context, manage-work-items, and manage-cleanup, providing a single intuitive interface for all JIRA needs.
