---
name: version-validation
description: |
  Trigger this skill when validating API versions for discovered actions:

  **Triggers:**
  - "validate API versions"
  - "analyze versioning for [provider]"
  - "check for version conflicts"
  - After action discovery (automatic step)
  - When building new connectors

  **What it does:**
  1. Analyzes API version mapping for discovered endpoints
  2. Detects version conflicts and inconsistencies
  3. Identifies breaking changes between versions
  4. Provides migration recommendations
  5. Returns version-validated endpoints for config building

  **CRITICAL:** Run this AFTER discover_actions completes to ensure correct API versions.
---

# Version Validation Skill

## Overview

This skill validates API version mapping for discovered actions, detecting conflicts and ensuring connectors use the correct, stable API versions. It prevents breaking changes and API incompatibilities.

## When to Use

**Automatic triggers:**
- After `discover_actions` completes (Step 3 in workflow)
- Before config building (Step 4 in workflow)
- When provider has multiple API versions
- When API version changes detected

**Manual triggers:**
- User explicitly asks to validate versions
- Debugging API compatibility issues
- Migrating to new API version

## Why Version Validation Matters

### The Problem

Providers often have multiple API versions:
- **v1** (stable, widely supported, older features)
- **v2** (newer, more features, may have breaking changes)
- **v3** (latest, experimental, limited adoption)

**Issues without validation:**
- ❌ Mixing endpoints from different versions
- ❌ Using deprecated endpoints
- ❌ Missing breaking changes
- ❌ Incompatible request/response formats
- ❌ Authentication version mismatches

### The Solution

Version validation:
- ✅ Identifies recommended version per endpoint
- ✅ Detects version conflicts
- ✅ Highlights breaking changes
- ✅ Provides migration paths
- ✅ Ensures version consistency

## Prerequisites

- **Discovered actions** from `discover_actions` completed
- Extracted endpoints from discovered actions
- Provider name

## Execution Flow

### Step 1: Extract Endpoints from Discovered Actions

```typescript
// After discover_actions completes
const discoveredActions = discoverResult.result;

// Extract all endpoints
const endpoints = discoveredActions.categories
  .flatMap(cat => cat.actions)
  .map(action => action.endpoints[0]);

// Example endpoints:
[
  "/api/v2/users",
  "/api/v2/groups",
  "/api/v3/tickets",      // ⚠️ Version conflict!
  "/api/v2/organizations",
  "/api/v1/search"        // ⚠️ Older version!
]
```

### Step 2: Launch Version Analysis

```typescript
// Launch async version analysis (2-5 minutes)
const result = analyze_versioning({
  provider: "provider_name",
  endpoints: endpoints,        // Optional: specific endpoints to analyze
  maxIterations: 5             // Default: 5 (focused analysis)
});

// Extract taskId
const taskId = result.taskId;
```

**If no endpoints provided:**
- Tool analyzes ALL endpoints from provider docs
- Broader analysis, longer duration

**If endpoints provided:**
- Focused analysis on specified endpoints only
- Faster, more targeted results

### Step 3: Poll for Status

```typescript
// Check status every 30-60 seconds
const status = get_analyze_versioning_task_status(taskId, "provider_name");

// Status progression:
// "pending" → Task queued
// "running" → Active analysis
// "complete" → Finished successfully
// "error" → Failed
```

**Expected Timeline:**
- **Minute 0:** Launch task
- **Minutes 0-1:** Status = "pending"
- **Minutes 1-5:** Status = "running"
- **Minute 5:** Status = "complete"

### Step 4: Extract Results

```typescript
// When status = "complete"
const report = status.result;

// Report structure:
{
  "provider": "provider_name",
  "analysis_date": "2025-01-15T10:30:00Z",
  "recommended_version": "v2",
  "version_summary": {
    "v1": {
      "status": "deprecated",
      "endpoints_count": 15,
      "sunset_date": "2025-12-31"
    },
    "v2": {
      "status": "stable",
      "endpoints_count": 89,
      "adoption_rate": "high"
    },
    "v3": {
      "status": "beta",
      "endpoints_count": 23,
      "adoption_rate": "low"
    }
  },
  "conflicts": [
    {
      "endpoint_group": "Tickets",
      "issue": "Mixed versions",
      "details": {
        "v2_endpoints": ["/api/v2/tickets", "/api/v2/tickets/{id}"],
        "v3_endpoints": ["/api/v3/tickets/search"],
        "recommendation": "Standardize on v2 - v3 still in beta"
      }
    }
  ],
  "breaking_changes": [
    {
      "version_change": "v1 → v2",
      "endpoint": "/api/users",
      "changes": [
        "Field 'user_id' renamed to 'id'",
        "Field 'created' changed from timestamp to ISO 8601 string",
        "Pagination changed from offset to cursor-based"
      ],
      "migration_guide": "https://docs.provider.com/v1-to-v2"
    }
  ],
  "endpoint_recommendations": [
    {
      "endpoint": "/api/v1/search",
      "current_version": "v1",
      "recommended_version": "v2",
      "reason": "v1 deprecated, v2 has improved search performance",
      "alternative_endpoint": "/api/v2/search",
      "breaking_changes": ["Query syntax changed", "Response format updated"]
    }
  ]
}
```

### Step 5: Analyze Conflicts

**Review each conflict:**

```typescript
report.conflicts.forEach(conflict => {
  console.log(`⚠️ Conflict: ${conflict.issue}`);
  console.log(`   Group: ${conflict.endpoint_group}`);
  console.log(`   Recommendation: ${conflict.details.recommendation}`);
});
```

**Common conflict types:**

#### 1. Mixed Versions

**Issue:** Endpoints use different versions for same resource

```
Conflict: Mixed versions in User Management
- v2: /api/v2/users, /api/v2/users/{id}
- v3: /api/v3/users/search

Recommendation: Use v2 for all endpoints (v3 still experimental)
```

**Fix:** Standardize on stable version (v2)

#### 2. Deprecated Endpoints

**Issue:** Using endpoints marked for deprecation

```
Conflict: Deprecated endpoint in use
- Endpoint: /api/v1/reports
- Status: Deprecated (sunset: 2025-12-31)
- Alternative: /api/v2/analytics

Recommendation: Migrate to v2 before sunset date
```

**Fix:** Use alternative endpoint from recommended version

#### 3. Beta/Experimental Versions

**Issue:** Relying on unstable API versions

```
Conflict: Beta endpoint with low adoption
- Endpoint: /api/v3/webhooks/batch
- Status: Beta (adoption: 12%)
- Stable alternative: /api/v2/webhooks (multiple calls)

Recommendation: Use v2 until v3 reaches GA
```

**Fix:** Use stable version even if less convenient

### Step 6: Review Breaking Changes

**For each version migration:**

```typescript
report.breaking_changes.forEach(change => {
  console.log(`🔄 ${change.version_change}: ${change.endpoint}`);
  change.changes.forEach(c => {
    console.log(`   - ${c}`);
  });
  console.log(`   Migration guide: ${change.migration_guide}`);
});
```

**Example breaking changes:**

```
🔄 v1 → v2: /api/users
   - Field 'user_id' renamed to 'id'
   - Field 'created' changed from timestamp to ISO 8601
   - Pagination changed from offset to cursor
   - Authentication changed from API key to OAuth 2.0
   Migration guide: https://docs.provider.com/v1-to-v2

🔄 v2 → v3: /api/tickets
   - Response wrapped in 'data' envelope
   - Error format changed to RFC 7807
   - Rate limiting changed from IP to user-based
   Migration guide: https://docs.provider.com/v2-to-v3
```

### Step 7: Apply Recommendations

**Update endpoint versions in config:**

```yaml
# Before (discovered actions with mixed versions)
- actionId: list_users
  steps:
    - stepFunction:
        parameters:
          url: /api/v1/users  # ❌ Deprecated

- actionId: search_users
  steps:
    - stepFunction:
        parameters:
          url: /api/v3/users/search  # ❌ Beta version

# After (version-validated)
- actionId: list_users
  steps:
    - stepFunction:
        parameters:
          url: /api/v2/users  # ✅ Stable, recommended

- actionId: search_users
  steps:
    - stepFunction:
        parameters:
          url: /api/v2/users/search  # ✅ Stable, recommended
```

## Version Analysis Criteria

### Version Status Types

| Status | Description | Usage Recommendation |
|--------|-------------|---------------------|
| **stable** | Production-ready, widely adopted | ✅ Use for all endpoints |
| **deprecated** | Scheduled for removal | ⚠️ Migrate away immediately |
| **beta** | Testing phase, may change | ⚠️ Avoid unless necessary |
| **experimental** | Early preview, unstable | ❌ Do not use |
| **sunset** | Past end-of-life date | ❌ Non-functional |

### Adoption Rate Indicators

| Rate | Description | Confidence |
|------|-------------|-----------|
| **High (>70%)** | Widely used by developers | ✅ Safe to use |
| **Medium (30-70%)** | Moderate adoption | ⚠️ Verify stability |
| **Low (<30%)** | Limited adoption | ⚠️ May be experimental |

### Recommendation Logic

**Choose version based on:**

1. **Stability** (most important)
   - Stable > Beta > Experimental
   - Avoid deprecated versions

2. **Adoption Rate** (indicates maturity)
   - High adoption = battle-tested
   - Low adoption = risky

3. **Feature Coverage** (business value)
   - More endpoints = better coverage
   - Newer features may justify beta use

4. **Breaking Changes** (migration cost)
   - Fewer breaking changes = easier migration
   - Major rewrites favor staying on old version temporarily

5. **Sunset Dates** (urgency)
   - Close sunset = migrate immediately
   - Distant sunset = plan migration

## Common Scenarios

### Scenario 1: All Stable Version

```json
{
  "recommended_version": "v2",
  "version_summary": {
    "v2": {
      "status": "stable",
      "endpoints_count": 95,
      "adoption_rate": "high"
    }
  },
  "conflicts": [],
  "breaking_changes": []
}
```

**Action:** Use v2 for all endpoints. No conflicts!

### Scenario 2: Mixed Stable Versions

```json
{
  "conflicts": [
    {
      "issue": "Two stable versions in use",
      "details": {
        "v1_endpoints": ["/api/v1/legacy-feature"],
        "v2_endpoints": ["/api/v2/users", "/api/v2/tickets"],
        "recommendation": "Migrate /api/v1/legacy-feature to v2 equivalent"
      }
    }
  ]
}
```

**Action:** Find v2 equivalent for v1 endpoint, or document as legacy-only.

### Scenario 3: Deprecated Version in Use

```json
{
  "conflicts": [
    {
      "issue": "Deprecated version in use",
      "details": {
        "endpoint": "/api/v1/reports",
        "status": "deprecated",
        "sunset_date": "2025-12-31",
        "alternative": "/api/v2/analytics"
      }
    }
  ],
  "breaking_changes": [
    {
      "version_change": "v1 → v2",
      "endpoint": "/api/reports",
      "changes": ["Response format changed", "New auth required"]
    }
  ]
}
```

**Action:** Migrate to v2 immediately. Update auth if needed. Test thoroughly.

### Scenario 4: Beta Version Available

```json
{
  "recommended_version": "v2",
  "version_summary": {
    "v2": {
      "status": "stable",
      "endpoints_count": 75
    },
    "v3": {
      "status": "beta",
      "endpoints_count": 85,
      "adoption_rate": "low"
    }
  }
}
```

**Action:** Use v2 (stable) even if v3 has more endpoints. Wait for v3 GA.

## Integration with Workflow

### After Action Discovery (Step 3)

```typescript
// Step 2: Action Discovery complete
const discoveredActions = discoverResult.result;

// Step 3: Version Validation (REQUIRED)
console.log("Validating API versions...");

// Extract endpoints
const endpoints = discoveredActions.categories
  .flatMap(cat => cat.actions)
  .map(action => action.endpoints[0]);

// Launch version analysis
const { taskId } = analyze_versioning({
  provider: "provider_name",
  endpoints: endpoints,
  maxIterations: 5
});

// Poll for completion
let status;
do {
  await sleep(45000);  // 45 seconds
  status = get_analyze_versioning_task_status(taskId, "provider_name");
  console.log(`Version validation: ${status.status}`);
} while (status.status !== "complete");

// Extract version analysis
const versionReport = status.result;

// Step 4: Config Building (use validated versions)
buildConfig(discoveredActions, versionReport);
```

### Before Config Building (Step 4)

**CRITICAL:** Do NOT start config building without version validation.

```typescript
// ❌ WRONG - Using discovered endpoints directly
actions:
  - actionId: list_users
    steps:
      - url: ${discoveredAction.endpoint}  // May be wrong version!

// ✅ CORRECT - Using version-validated endpoints
actions:
  - actionId: list_users
    steps:
      - url: ${versionReport.endpoint_recommendations.find(...).recommended_endpoint}
```

## Version Validation Checklist

### Before Building Config

- [ ] Action discovery completed
- [ ] Endpoints extracted from discovered actions
- [ ] Version analysis launched
- [ ] Status polled until complete
- [ ] Version report reviewed
- [ ] All conflicts identified
- [ ] Breaking changes documented
- [ ] Recommended version selected

### During Config Building

- [ ] Using recommended version for all endpoints
- [ ] No mixed versions within same resource
- [ ] No deprecated endpoints used
- [ ] No beta/experimental versions (unless documented)
- [ ] Breaking changes handled in config
- [ ] Alternative endpoints used where recommended

### After Config Building

- [ ] Config uses consistent API version
- [ ] No version conflicts in YAML
- [ ] Sunset dates documented (if applicable)
- [ ] Migration plan created (if using deprecated version)

## Output Report

```markdown
## Version Validation Report: <provider>

### Summary
- Recommended Version: v2
- Conflicts Detected: 2
- Breaking Changes: 3
- Endpoints Analyzed: 47

### Version Overview
| Version | Status | Endpoints | Adoption | Recommendation |
|---------|--------|-----------|----------|----------------|
| v1 | Deprecated | 15 | High | Migrate to v2 |
| v2 | Stable | 89 | High | ✅ Use this |
| v3 | Beta | 23 | Low | Wait for GA |

### Conflicts
1. **Mixed versions in User Management**
   - Issue: v2 and v3 endpoints both used
   - Resolution: Standardize on v2 (stable)
   - Affected: list_users, search_users

2. **Deprecated endpoint in Reports**
   - Issue: /api/v1/reports still in use
   - Resolution: Migrate to /api/v2/analytics
   - Sunset Date: 2025-12-31

### Breaking Changes
1. **v1 → v2: /api/users**
   - Field 'user_id' renamed to 'id'
   - Pagination changed to cursor-based
   - Auth changed to OAuth 2.0

2. **v1 → v2: /api/reports**
   - Response format restructured
   - New required parameters added

3. **v2 → v3: /api/tickets**
   - Response wrapped in 'data' envelope
   - Rate limiting changed

### Endpoint Recommendations
| Endpoint | Current | Recommended | Reason |
|----------|---------|-------------|--------|
| /api/v1/reports | v1 | v2 | Deprecated |
| /api/v3/users/search | v3 | v2 | Beta version |
| /api/v2/users | v2 | v2 | ✅ Already correct |

### Migration Guide
- v1 → v2: https://docs.provider.com/v1-to-v2
- v2 → v3: https://docs.provider.com/v2-to-v3 (not recommended yet)

### Next Steps
- [x] Version analysis complete
- [ ] Update config to use recommended versions
- [ ] Test migrated endpoints
- [ ] Document version decisions
```

## Key Principles

1. **Always run after action discovery** - Critical step in workflow
2. **Use recommended stable version** - Avoid beta/experimental
3. **Resolve all conflicts** - Don't ignore version issues
4. **Document breaking changes** - Important for maintenance
5. **Plan for migrations** - Handle deprecated versions proactively

## Anti-Patterns (NEVER DO THESE)

- ❌ Skipping version validation
- ❌ Using mixed versions without justification
- ❌ Ignoring deprecation warnings
- ❌ Using beta versions in production configs
- ❌ Not documenting version decisions
- ❌ Building config before version validation completes
