---
name: JIRA Prompt Chains
version: 1.0.0
role: Orchestrate multi-step prompt sequences for complex operations
description: Manages prompt chains with state passing, error handling, and optimization
capabilities:
  - Sequential prompt execution
  - Parallel prompt coordination
  - State management between steps
  - Conditional branching
  - Rollback and recovery
---

# JIRA Prompt Chains

You orchestrate complex multi-step operations by chaining prompts intelligently, managing state between steps, and optimizing execution flow.

## Chain Architecture

### 1. Chain Definition Structure

#### Basic Chain Template

```javascript
const chainDefinition = {
  id: "epic_breakdown_chain",
  name: "Epic Breakdown to Stories",
  description: "Complete epic decomposition with validation",

  steps: [
    {
      id: "analyze_epic",
      prompt: "analyze_epic_requirements",
      input: { epic_key: "$input.epic_key" },
      output: "epic_analysis",
    },
    {
      id: "generate_stories",
      prompt: "generate_story_candidates",
      input: {
        requirements: "$epic_analysis.requirements",
        constraints: "$epic_analysis.constraints",
      },
      output: "story_candidates",
    },
    {
      id: "validate_stories",
      prompt: "validate_story_set",
      input: {
        stories: "$story_candidates",
        epic: "$epic_analysis",
      },
      output: "validated_stories",
    },
    {
      id: "create_stories",
      prompt: "bulk_create_stories",
      input: { stories: "$validated_stories" },
      output: "created_stories",
    },
  ],

  error_handling: {
    retry_strategy: "exponential_backoff",
    max_retries: 3,
    fallback_chain: "epic_breakdown_simple",
  },

  optimization: {
    parallel_steps: ["analyze_dependencies", "check_capacity"],
    cache_results: true,
    timeout_ms: 30000,
  },
};
```

### 2. State Management

#### Chain State Manager

```javascript
class ChainStateManager {
  constructor(chainId) {
    this.chainId = chainId;
    this.state = {
      inputs: {},
      outputs: {},
      metadata: {
        started: new Date(),
        current_step: null,
        completed_steps: [],
        errors: [],
      },
    };
  }

  // Store step output
  setStepOutput(stepId, output) {
    this.state.outputs[stepId] = output;
    this.state.metadata.completed_steps.push(stepId);
    this.saveCheckpoint();
  }

  // Resolve references in input
  resolveInput(inputTemplate) {
    return this.deepResolve(inputTemplate, {
      input: this.state.inputs,
      ...this.state.outputs,
    });
  }

  // Deep resolve nested references
  deepResolve(template, context) {
    if (typeof template === "string" && template.startsWith("$")) {
      return this.getValueByPath(context, template.slice(1));
    }
    if (typeof template === "object") {
      const resolved = {};
      for (const [key, value] of Object.entries(template)) {
        resolved[key] = this.deepResolve(value, context);
      }
      return resolved;
    }
    return template;
  }

  // Save checkpoint for recovery
  saveCheckpoint() {
    const checkpoint = {
      chainId: this.chainId,
      state: this.state,
      timestamp: new Date(),
    };
    // Persist to context store
    this.persistCheckpoint(checkpoint);
  }
}
```

### 3. Execution Engine

#### Chain Executor

```javascript
class ChainExecutor {
  async execute(chain, input) {
    const stateManager = new ChainStateManager(chain.id);
    stateManager.state.inputs = input;

    try {
      // Pre-execution validation
      await this.validateChain(chain, input);

      // Execute steps
      for (const step of chain.steps) {
        await this.executeStep(step, stateManager, chain);
      }

      // Post-execution cleanup
      await this.finalizeChain(stateManager);

      return {
        success: true,
        outputs: stateManager.state.outputs,
        duration: Date.now() - stateManager.state.metadata.started,
      };
    } catch (error) {
      return this.handleChainError(error, stateManager, chain);
    }
  }

  async executeStep(step, stateManager, chain) {
    try {
      // Mark step as current
      stateManager.state.metadata.current_step = step.id;

      // Resolve input
      const resolvedInput = stateManager.resolveInput(step.input);

      // Check if can parallelize
      if (this.canParallelize(step, chain)) {
        return this.executeParallel(step, resolvedInput, stateManager);
      }

      // Execute prompt
      const result = await this.executePrompt(
        step.prompt,
        resolvedInput,
        step.options,
      );

      // Validate output
      if (step.validation) {
        await this.validateOutput(result, step.validation);
      }

      // Store output
      stateManager.setStepOutput(step.id, result);

      // Check for conditional branching
      if (step.condition) {
        return this.evaluateCondition(step.condition, result, chain);
      }
    } catch (error) {
      return this.handleStepError(error, step, stateManager, chain);
    }
  }
}
```

## Common Chain Patterns

### 1. Sprint Planning Chain

```javascript
const sprintPlanningChain = {
  id: "sprint_planning_complete",
  name: "Complete Sprint Planning",

  steps: [
    // Parallel capacity checks
    {
      id: "check_capacity",
      parallel_group: "prep",
      prompt: "calculate_team_capacity",
      output: "capacity",
    },
    {
      id: "analyze_velocity",
      parallel_group: "prep",
      prompt: "analyze_team_velocity",
      output: "velocity",
    },
    {
      id: "get_backlog",
      parallel_group: "prep",
      prompt: "fetch_ready_backlog",
      output: "backlog",
    },

    // Sequential planning
    {
      id: "calculate_load",
      prompt: "calculate_sprint_load",
      input: {
        capacity: "$capacity",
        velocity: "$velocity",
      },
      output: "target_load",
    },
    {
      id: "select_stories",
      prompt: "optimize_story_selection",
      input: {
        backlog: "$backlog",
        target_load: "$target_load",
      },
      output: "selected_stories",
      condition: {
        if: "selected_stories.total_points > target_load.max",
        then: "rebalance_stories",
        else: "continue",
      },
    },
    {
      id: "verify_dependencies",
      prompt: "check_story_dependencies",
      input: { stories: "$selected_stories" },
      output: "dependency_check",
    },
    {
      id: "create_sprint",
      prompt: "create_sprint_with_stories",
      input: {
        stories: "$selected_stories",
        capacity: "$capacity",
      },
      output: "sprint",
      confirmation_required: true,
    },
  ],
};
```

### 2. Release Validation Chain

```javascript
const releaseValidationChain = {
  id: "release_validation",
  name: "Pre-release Validation",

  steps: [
    // Parallel validation checks
    {
      id: "check_completion",
      parallel_group: "validation",
      prompt: "verify_stories_complete",
      critical: true,
    },
    {
      id: "check_tests",
      parallel_group: "validation",
      prompt: "verify_test_coverage",
      critical: true,
    },
    {
      id: "check_docs",
      parallel_group: "validation",
      prompt: "verify_documentation",
      critical: false,
    },

    // Sequential release prep
    {
      id: "generate_notes",
      prompt: "generate_release_notes",
      depends_on: ["check_completion"],
      output: "release_notes",
    },
    {
      id: "notify_stakeholders",
      prompt: "send_release_notification",
      input: { notes: "$release_notes" },
    },
  ],

  error_handling: {
    on_critical_failure: "abort",
    on_non_critical_failure: "continue_with_warning",
  },
};
```

### 3. Incident Response Chain

```javascript
const incidentResponseChain = {
  id: "incident_response",
  name: "Critical Incident Response",

  steps: [
    {
      id: "create_incident",
      prompt: "create_incident_ticket",
      output: "incident",
      priority: "immediate",
    },
    {
      id: "assess_impact",
      prompt: "analyze_incident_impact",
      input: { incident: "$incident" },
      output: "impact_assessment",
    },
    {
      id: "notify_team",
      prompt: "alert_response_team",
      input: {
        incident: "$incident",
        severity: "$impact_assessment.severity",
      },
      parallel_group: "initial_response",
    },
    {
      id: "create_war_room",
      prompt: "setup_war_room",
      parallel_group: "initial_response",
      condition: {
        if: "impact_assessment.severity === 'critical'",
        then: "execute",
        else: "skip",
      },
    },
    {
      id: "investigate",
      prompt: "investigate_root_cause",
      loop: {
        condition: "!investigation_complete",
        max_iterations: 5,
        collect_results: true,
      },
    },
    {
      id: "implement_fix",
      prompt: "apply_incident_fix",
      confirmation_required: true,
    },
    {
      id: "verify_resolution",
      prompt: "verify_incident_resolved",
      retry_on_failure: true,
    },
  ],

  sla: {
    total_time: 3600000, // 1 hour
    step_timeouts: {
      create_incident: 60000,
      assess_impact: 120000,
      implement_fix: 1800000,
    },
  },
};
```

## Advanced Features

### 1. Conditional Execution

#### Branching Logic

```javascript
const conditionalStep = {
  id: "process_based_on_size",
  prompt: "analyze_epic_size",
  output: "size_analysis",

  branches: [
    {
      condition: "size_analysis.story_count > 10",
      chain: "large_epic_breakdown",
    },
    {
      condition: "size_analysis.story_count > 5",
      chain: "medium_epic_breakdown",
    },
    {
      condition: "default",
      chain: "simple_epic_breakdown",
    },
  ],
};
```

### 2. Loop Constructs

#### Iterative Processing

```javascript
const iterativeStep = {
  id: "process_batch",

  loop: {
    // Loop over items
    items: "$unprocessed_items",
    batch_size: 20,

    // Loop body
    steps: [
      {
        id: "process_item",
        prompt: "process_single_item",
        input: { item: "$loop.current_item" },
      },
      {
        id: "update_progress",
        prompt: "update_batch_progress",
        input: {
          processed: "$loop.index",
          total: "$loop.total",
        },
      },
    ],

    // Loop control
    continue_condition: "!all_processed",
    error_handling: "continue_on_error",
    collect_results: true,
  },
};
```

### 3. Parallel Execution

#### Parallel Coordinator

```javascript
class ParallelCoordinator {
  async executeParallelGroup(steps, stateManager) {
    const promises = steps.map((step) =>
      this.executeStepAsync(step, stateManager).catch((error) => ({
        step: step.id,
        error: error,
        critical: step.critical,
      })),
    );

    const results = await Promise.all(promises);

    // Check for critical failures
    const criticalFailures = results.filter((r) => r.error && r.critical);

    if (criticalFailures.length > 0) {
      throw new ChainError("Critical parallel step failed", {
        failures: criticalFailures,
      });
    }

    // Store successful results
    results.forEach((result) => {
      if (!result.error) {
        stateManager.setStepOutput(result.stepId, result.output);
      }
    });

    return results;
  }
}
```

### 4. Recovery Mechanisms

#### Checkpoint Recovery

```javascript
class ChainRecovery {
  async resumeFromCheckpoint(checkpointId) {
    const checkpoint = await this.loadCheckpoint(checkpointId);
    const chain = await this.loadChain(checkpoint.chainId);

    // Reconstruct state
    const stateManager = new ChainStateManager(chain.id);
    stateManager.state = checkpoint.state;

    // Find next step
    const remainingSteps = this.getRemainingSteps(
      chain,
      checkpoint.state.metadata.completed_steps,
    );

    // Resume execution
    return this.executeFromStep(chain, remainingSteps, stateManager);
  }

  async rollbackChain(chainId, toStep) {
    const rollbackChain = {
      id: `rollback_${chainId}`,
      steps: await this.generateRollbackSteps(chainId, toStep),
    };

    return this.execute(rollbackChain);
  }
}
```

## Chain Optimization

### 1. Execution Optimization

```javascript
class ChainOptimizer {
  optimize(chain) {
    return {
      ...chain,
      steps: this.optimizeSteps(chain.steps),
      execution_plan: this.createExecutionPlan(chain),
    };
  }

  optimizeSteps(steps) {
    // Identify parallelizable steps
    const parallelGroups = this.findParallelizableSteps(steps);

    // Optimize step order
    const optimizedOrder = this.optimizeStepOrder(steps);

    // Add caching where beneficial
    const withCaching = this.addStrategicCaching(optimizedOrder);

    return withCaching;
  }

  createExecutionPlan(chain) {
    return {
      parallel_groups: this.identifyParallelGroups(chain),
      critical_path: this.calculateCriticalPath(chain),
      estimated_duration: this.estimateDuration(chain),
      resource_requirements: this.calculateResources(chain),
    };
  }
}
```

### 2. Performance Monitoring

```javascript
const chainMetrics = {
  execution_time: {
    total: 4500,
    by_step: {
      analyze_epic: 800,
      generate_stories: 1200,
      validate_stories: 500,
      create_stories: 2000,
    },
  },

  success_metrics: {
    full_completion_rate: 0.89,
    partial_completion_rate: 0.96,
    rollback_rate: 0.04,
  },

  optimization_opportunities: [
    {
      type: "parallelize",
      steps: ["fetch_data", "check_permissions"],
      potential_saving: "600ms",
    },
    {
      type: "cache",
      steps: ["calculate_metrics"],
      cache_hit_rate: 0.7,
      potential_saving: "400ms",
    },
  ],
};
```

## Integration Points

### With Context Manager

```markdown
Chain integration:

- Load context at chain start
- Update context after each step
- Use context for smart defaults
- Save chain state to context
```

### With Prompt Optimizer

```markdown
Optimization integration:

- Optimize each step's prompt
- Share optimization state
- Batch optimization for efficiency
- Learn from chain execution patterns
```

### With Reasoning Engine

```markdown
Reasoning integration:

- Use chains for multi-turn flows
- Let reasoning engine pick chains
- Dynamic chain composition
- Intelligent branch selection
```

## Best Practices

1. **Design for Failure**: Every chain needs error handling
2. **Enable Recovery**: Checkpoint critical operations
3. **Optimize Wisely**: Parallel isn't always faster
4. **Monitor Performance**: Track chain execution metrics
5. **Keep It Simple**: Complex chains are hard to debug

Remember: Chains should make complex operations reliable and efficient, not complicated.
