Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:56:16 +08:00
commit 19b5d00a1f
23 changed files with 6153 additions and 0 deletions

View File

@@ -0,0 +1,541 @@
---
name: ado-multi-project
description: Expert at organizing specs and splitting tasks across multiple Azure DevOps projects. Handles project-per-team, area-path-based, and team-based architectures. Intelligently maps increments and specs to correct projects based on content analysis. Activates for multi-project Azure DevOps setups, task splitting, spec organization, team allocation, cross-project coordination.
allowed-tools: Read, Write, Edit, Glob
---
# Azure DevOps Multi-Project Skill
**Purpose**: Organize specs and increments across multiple Azure DevOps projects with intelligent mapping and folder organization.
## What This Skill Does
This skill handles complex multi-project Azure DevOps organizations by:
1. **Analyzing increment content** to determine which project it belongs to
2. **Creating project-specific folder structures** in `.specweave/docs/internal/specs/`
3. **Mapping user stories to correct projects** based on keywords and context
4. **Splitting tasks across projects** when increments span multiple teams
5. **Maintaining bidirectional sync** between local specs and Azure DevOps work items
## Supported Architectures
### 1. Project-per-team (Recommended for Microservices)
```
Organization: mycompany
├── AuthService (Project)
├── UserService (Project)
├── PaymentService (Project)
└── NotificationService (Project)
Local Structure:
.specweave/docs/internal/specs/
├── AuthService/
├── UserService/
├── PaymentService/
└── NotificationService/
```
### 2. Area-path-based (Monolithic Applications)
```
Organization: enterprise
└── ERP (Project)
├── Finance (Area Path)
├── HR (Area Path)
├── Inventory (Area Path)
└── Sales (Area Path)
Local Structure:
.specweave/docs/internal/specs/ERP/
├── Finance/
├── HR/
├── Inventory/
└── Sales/
```
### 3. Team-based (Small Organizations)
```
Organization: startup
└── Platform (Project)
├── Alpha Team
├── Beta Team
└── Gamma Team
Local Structure:
.specweave/docs/internal/specs/Platform/
├── AlphaTeam/
├── BetaTeam/
└── GammaTeam/
```
## Intelligent Project Detection
The skill analyzes increment content to determine the correct project:
### Detection Patterns
```typescript
const projectPatterns = {
'AuthService': {
keywords: ['authentication', 'login', 'oauth', 'jwt', 'session', 'password'],
filePatterns: ['auth/', 'login/', 'security/'],
confidence: 0.0
},
'UserService': {
keywords: ['user', 'profile', 'account', 'registration', 'preferences'],
filePatterns: ['users/', 'profiles/', 'accounts/'],
confidence: 0.0
},
'PaymentService': {
keywords: ['payment', 'stripe', 'billing', 'invoice', 'subscription'],
filePatterns: ['payment/', 'billing/', 'checkout/'],
confidence: 0.0
}
};
// Analyze spec content
const spec = readSpec(incrementId);
for (const [project, pattern] of Object.entries(projectPatterns)) {
pattern.confidence = calculateConfidence(spec, pattern);
}
// Select project with highest confidence
const selectedProject = Object.entries(projectPatterns)
.sort((a, b) => b[1].confidence - a[1].confidence)[0][0];
```
### Confidence Calculation
- **Keyword match**: +0.2 per keyword found
- **File pattern match**: +0.3 per pattern
- **Explicit mention**: +1.0 if project name in spec
- **Team mention**: +0.5 if team name matches
**Threshold**: Confidence > 0.7 = auto-assign, otherwise prompt user
## Usage Examples
### Example 1: Single-Project Increment
**Scenario**: Authentication feature for AuthService
**Spec Analysis**:
```
Title: "Add OAuth 2.0 authentication"
Keywords found: authentication, oauth, jwt
File patterns: src/auth/oauth-provider.ts
Confidence: AuthService = 0.9 ✅
```
**Action**:
```bash
# Auto-creates folder structure
.specweave/docs/internal/specs/AuthService/
└── spec-001-oauth-authentication.md
# Maps to Azure DevOps
Project: AuthService
Work Item: Epic "OAuth 2.0 Authentication"
```
### Example 2: Multi-Project Increment
**Scenario**: Checkout flow spanning multiple services
**Spec Analysis**:
```
Title: "Implement checkout flow with payment processing"
Keywords found: user, cart, payment, stripe, notification
Confidence:
- UserService = 0.6
- PaymentService = 0.8 ✅
- NotificationService = 0.5
```
**Action**:
```bash
# Creates multi-project structure
.specweave/docs/internal/specs/
├── PaymentService/
│ └── spec-002-checkout-payment.md (primary)
├── UserService/
│ └── spec-002-checkout-user.md (linked)
└── NotificationService/
└── spec-002-checkout-notifications.md (linked)
# Creates linked work items in Azure DevOps
PaymentService: Epic "Checkout Payment Processing" (primary)
UserService: Feature "User Cart Management" (links to primary)
NotificationService: Feature "Order Notifications" (links to primary)
```
### Example 3: Area Path Organization
**Scenario**: ERP system with module-based organization
**Configuration**:
```bash
AZURE_DEVOPS_STRATEGY=area-path-based
AZURE_DEVOPS_PROJECT=ERP
AZURE_DEVOPS_AREA_PATHS=Finance,HR,Inventory
```
**Spec Analysis**:
```
Title: "Add payroll calculation engine"
Keywords found: payroll, salary, tax, employee
Area match: HR (confidence = 0.85)
```
**Action**:
```bash
# Creates area-based structure
.specweave/docs/internal/specs/ERP/HR/
└── spec-003-payroll-engine.md
# Maps to Azure DevOps
Project: ERP
Area Path: ERP\HR
Work Item: Epic "Payroll Calculation Engine"
```
## Task Splitting Across Projects
When an increment spans multiple projects, tasks are intelligently split:
### Input: Unified tasks.md
```markdown
# Tasks for Checkout Flow
- T-001: Create shopping cart API (UserService)
- T-002: Implement Stripe integration (PaymentService)
- T-003: Add order confirmation email (NotificationService)
- T-004: Update user order history (UserService)
- T-005: Process payment webhook (PaymentService)
```
### Output: Project-specific work items
**UserService** (2 tasks):
- Task: Create shopping cart API
- Task: Update user order history
**PaymentService** (2 tasks):
- Task: Implement Stripe integration
- Task: Process payment webhook
**NotificationService** (1 task):
- Task: Add order confirmation email
## Folder Structure Creation
The skill automatically creates and maintains folder structure:
### On Increment Creation
```typescript
async function createProjectFolders(increment: Increment) {
const projects = detectProjects(increment);
for (const project of projects) {
const specPath = `.specweave/docs/internal/specs/${project}/`;
await ensureDir(specPath);
// Create project-specific spec
const spec = extractProjectSpec(increment, project);
await writeSpec(`${specPath}/spec-${increment.number}-${increment.name}.md`, spec);
// Create README if first spec in project
if (isFirstSpec(project)) {
await createProjectReadme(project);
}
}
}
```
### Project README Template
```markdown
# {Project} Specifications
## Overview
This folder contains specifications for the {Project} project.
## Architecture
{Brief description of project architecture}
## Team
- Team Lead: {name}
- Developers: {list}
## Specifications
- [spec-001-feature.md](spec-001-feature.md) - {description}
## External Links
- Azure DevOps: https://dev.azure.com/{org}/{project}
- Repository: {git-url}
```
## Sync Commands
### Sync Increment to Projects
```bash
/specweave-ado:sync-increment 0014
# Detects projects from spec
# Creates work items in each project
# Links work items together
```
### Sync Spec to Project
```bash
/specweave-ado:sync-spec AuthService/spec-001
# Syncs single spec to specific project
# Updates existing work item or creates new
```
### Sync All Specs
```bash
/specweave-ado:sync-all
# Syncs all specs across all projects
# Maintains relationships
# Updates bidirectionally
```
## Project Mapping Configuration
### Manual Mapping (config.json)
```json
{
"ado": {
"projectMappings": {
"auth-.*": "AuthService",
"user-.*": "UserService",
"payment-.*": "PaymentService",
"notification-.*": "NotificationService"
},
"defaultProject": "Platform",
"crossProjectLinking": true
}
}
```
### Auto-Detection Rules
```typescript
const autoDetectionRules = [
{
pattern: /auth|login|oauth|security/i,
project: "AuthService"
},
{
pattern: /user|profile|account/i,
project: "UserService"
},
{
pattern: /payment|billing|stripe/i,
project: "PaymentService"
}
];
```
## Cross-Project Coordination
### Dependency Management
When increments span projects, dependencies are tracked:
```yaml
# .specweave/increments/0014-checkout-flow/metadata.yml
projects:
primary: PaymentService
dependencies:
- UserService: [T-001, T-004]
- NotificationService: [T-003]
ado_mappings:
PaymentService:
epic: 12345
work_items: [12346, 12347]
UserService:
feature: 12348
work_items: [12349, 12350]
NotificationService:
feature: 12351
work_items: [12352]
```
### Cross-Project Queries
```typescript
// Find all work items for an increment across projects
async function getIncrementWorkItems(incrementId: string) {
const metadata = await readMetadata(incrementId);
const workItems = [];
for (const [project, mapping] of Object.entries(metadata.ado_mappings)) {
const items = await adoClient.getWorkItems(project, mapping.work_items);
workItems.push(...items);
}
return workItems;
}
```
## Best Practices
### 1. Consistent Naming
Use consistent naming across projects:
```
spec-001-oauth-authentication.md # Good
spec-001-auth.md # Too vague
SPEC_001_OAuth.md # Inconsistent format
```
### 2. Clear Project Boundaries
Define clear boundaries between projects:
```yaml
AuthService:
owns: [authentication, authorization, sessions]
not: [user profiles, user preferences]
UserService:
owns: [profiles, preferences, user data]
not: [authentication, passwords]
```
### 3. Link Related Specs
Link specs that span projects:
```markdown
# spec-002-checkout-payment.md
Related Specs:
- [User Cart](../UserService/spec-002-checkout-user.md)
- [Notifications](../NotificationService/spec-002-checkout-notifications.md)
```
### 4. Use Project Prefixes
Prefix increment names with primary project:
```bash
/specweave:increment "payment-stripe-integration"
/specweave:increment "auth-oauth-provider"
/specweave:increment "user-profile-redesign"
```
## Error Handling
### Project Not Found
```
❌ Project "AuthService" not found in Azure DevOps
Options:
1. Create project "AuthService"
2. Map to existing project
3. Skip this project
Your choice [1]:
```
### Ambiguous Project Detection
```
⚠️ Cannot determine project for increment 0014
Multiple projects detected:
- UserService (confidence: 0.6)
- PaymentService (confidence: 0.6)
Please select primary project:
1. UserService
2. PaymentService
3. Both (multi-project)
Your choice [3]:
```
### Sync Conflicts
```
⚠️ Sync conflict detected
Local: spec-001 updated 2 hours ago
Azure DevOps: Work item updated 1 hour ago
Options:
1. Use local version
2. Use Azure DevOps version
3. Merge changes
4. View diff
Your choice [3]:
```
## Integration with CI/CD
### Auto-sync on Commit
```yaml
# .github/workflows/specweave-sync.yml
on:
push:
paths:
- '.specweave/docs/internal/specs/**'
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npx specweave ado-sync-all
env:
AZURE_DEVOPS_PAT: ${{ secrets.ADO_PAT }}
```
### Project-specific Pipelines
```yaml
# azure-pipelines.yml
trigger:
paths:
include:
- .specweave/docs/internal/specs/$(System.TeamProject)/**
variables:
- name: project
value: $(System.TeamProject)
steps:
- script: npx specweave ado-sync-project $(project)
```
## Summary
This skill enables sophisticated multi-project Azure DevOps organizations by:
1.**Intelligent project detection** from spec content
2.**Automatic folder organization** by project/area/team
3.**Task splitting** across multiple projects
4.**Cross-project linking** and dependency tracking
5.**Bidirectional sync** with Azure DevOps work items
**Result**: Seamless multi-project coordination with zero manual overhead!
---
**Skill Version**: 1.0.0
**Introduced**: SpecWeave v0.17.0
**Last Updated**: 2025-11-11

View File

@@ -0,0 +1,906 @@
---
name: ado-resource-validator
description: Validates Azure DevOps projects and resources exist, creates missing resources automatically. Smart enough to prompt user to select existing or create new projects. Supports multiple projects for project-per-team strategy, area paths for area-path-based strategy, and teams for team-based strategy. NEW - Per-project configuration support - AZURE_DEVOPS_AREA_PATHS_{ProjectName} and AZURE_DEVOPS_TEAMS_{ProjectName} for hierarchical organization. Activates for ado setup, ado validation, ado configuration, missing ado project, azure devops .env setup, per-project area paths, per-project teams.
allowed-tools: Read, Bash, Write, Edit
---
# Azure DevOps Resource Validator Skill
**Purpose**: Validate and auto-create Azure DevOps projects and resources, ensuring .env configuration is correct.
**Auto-Activation**: Triggers when Azure DevOps setup or validation is needed.
## What This Skill Does
This skill ensures your Azure DevOps configuration in `.env` is valid and all resources exist. It's **smart enough** to:
1. **Validate Azure DevOps projects** - Check if projects exist (multiple for project-per-team)
2. **Prompt for action** - Select existing project or create new one
3. **Validate area paths** - Check if area paths exist (for area-path-based strategy)
4. **Create missing area paths** - Auto-create area paths if missing
5. **Validate teams** - Check if teams exist (for team-based strategy)
6. **Update .env with correct values** - Ensure configuration is valid
## When This Skill Activates
**Automatically activates when**:
- You set up Azure DevOps integration for the first time
- You run `/specweave-ado:sync` and resources are missing
- Your `.env` has invalid Azure DevOps configuration
- You mention "ado setup" or "azure devops validation"
## Azure DevOps Configuration Structure
### Required .env Variables
```bash
AZURE_DEVOPS_PAT=your_token_here
AZURE_DEVOPS_ORG=yourorganization
AZURE_DEVOPS_STRATEGY=project-per-team # or area-path-based, team-based
```
### Strategy-Specific Variables
**Strategy 1: Project-per-team** (Multiple Projects)
```bash
AZURE_DEVOPS_STRATEGY=project-per-team
AZURE_DEVOPS_PROJECTS=WebApp,MobileApp,Platform
```
→ Validates that WebApp, MobileApp, and Platform projects exist
**Strategy 2: Area-path-based** (One Project, Multiple Area Paths)
```bash
AZURE_DEVOPS_STRATEGY=area-path-based
AZURE_DEVOPS_PROJECT=MainProduct
AZURE_DEVOPS_AREA_PATHS=Frontend,Backend,Mobile
```
→ Validates MainProduct project exists
→ Creates area paths if missing: MainProduct\Frontend, MainProduct\Backend, MainProduct\Mobile
**Strategy 3: Team-based** (One Project, Multiple Teams)
```bash
AZURE_DEVOPS_STRATEGY=team-based
AZURE_DEVOPS_PROJECT=MainProduct
AZURE_DEVOPS_TEAMS=Alpha Team,Beta Team,Gamma Team
```
→ Validates MainProduct project exists
→ Creates teams if missing: Alpha Team, Beta Team, Gamma Team
**NEW: Per-Project Configuration** (Advanced - Multiple Projects × Resources)
```bash
# Multiple projects with their own area paths and teams
AZURE_DEVOPS_STRATEGY=project-per-team
AZURE_DEVOPS_PROJECTS=Backend,Frontend,Mobile
# Per-project area paths (hierarchical naming)
AZURE_DEVOPS_AREA_PATHS_Backend=API,Database,Cache
AZURE_DEVOPS_AREA_PATHS_Frontend=Web,Admin,Public
AZURE_DEVOPS_AREA_PATHS_Mobile=iOS,Android,Shared
# Per-project teams (optional)
AZURE_DEVOPS_TEAMS_Backend=Alpha,Beta
AZURE_DEVOPS_TEAMS_Frontend=Gamma
```
→ Validates 3 projects exist: Backend, Frontend, Mobile
→ Creates area paths per project:
- Backend\API, Backend\Database, Backend\Cache
- Frontend\Web, Frontend\Admin, Frontend\Public
- Mobile\iOS, Mobile\Android, Mobile\Shared
→ Creates teams per project:
- Backend: Alpha, Beta
- Frontend: Gamma
**Naming Convention**: `{PROVIDER}_{RESOURCE_TYPE}_{PROJECT_NAME}`
## Validation Flow
### Step 1: Strategy Detection
**Read .env and detect strategy**:
```bash
AZURE_DEVOPS_STRATEGY=project-per-team
```
**Result**:
```
🔍 Detected strategy: Project-per-team
Projects to validate: WebApp, MobileApp, Platform
```
### Step 2: Project Validation (Project-per-team)
**Check if projects exist**:
```bash
# API calls to Azure DevOps
GET https://dev.azure.com/{org}/_apis/projects/WebApp
GET https://dev.azure.com/{org}/_apis/projects/MobileApp
GET https://dev.azure.com/{org}/_apis/projects/Platform
```
**If all projects exist**:
```
✅ All projects validated:
• WebApp (ID: abcd1234)
• MobileApp (ID: efgh5678)
• Platform (ID: ijkl9012)
```
**If some projects don't exist**:
```
⚠️ Projects not found:
✅ WebApp (exists)
❌ MobileApp (not found)
❌ Platform (not found)
What would you like to do?
1. Create missing projects
2. Select existing projects
3. Fix project names manually
4. Cancel
Your choice [1]:
```
**Option 1: Create Missing Projects**:
```
📦 Creating Azure DevOps projects...
Creating project: MobileApp...
✅ Project created: MobileApp (ID: mnop3456)
Creating project: Platform...
✅ Project created: Platform (ID: qrst7890)
✅ All projects now exist!
```
**Option 2: Select Existing Projects**:
```
Available projects in organization:
1. WebApp
2. ApiGateway
3. AuthService
4. NotificationService
5. DataPipeline
Select projects (comma-separated numbers) [2,3]:
✅ Updated .env: AZURE_DEVOPS_PROJECTS=WebApp,ApiGateway,AuthService
```
### Step 3: Area Path Validation (Area-path-based)
**Scenario**: One project with area paths
```bash
AZURE_DEVOPS_STRATEGY=area-path-based
AZURE_DEVOPS_PROJECT=MainProduct
AZURE_DEVOPS_AREA_PATHS=Frontend,Backend,Mobile,QA
```
**Validation**:
```
Checking project: MainProduct...
✅ Project "MainProduct" exists
Checking area paths...
✅ MainProduct\Frontend (exists)
✅ MainProduct\Backend (exists)
⚠️ MainProduct\Mobile (not found)
⚠️ MainProduct\QA (not found)
📦 Creating missing area paths...
✅ Created: MainProduct\Mobile
✅ Created: MainProduct\QA
✅ All area paths validated/created successfully
```
### Step 4: Team Validation (Team-based)
**Scenario**: One project with multiple teams
```bash
AZURE_DEVOPS_STRATEGY=team-based
AZURE_DEVOPS_PROJECT=MainProduct
AZURE_DEVOPS_TEAMS=Alpha Team,Beta Team,Gamma Team
```
**Validation**:
```
Checking project: MainProduct...
✅ Project "MainProduct" exists
Checking teams...
✅ Alpha Team (exists)
⚠️ Beta Team (not found)
⚠️ Gamma Team (not found)
📦 Creating missing teams...
✅ Created: Beta Team
✅ Created: Gamma Team
✅ All teams validated/created successfully
```
## Usage Examples
### Example 1: Fresh Azure DevOps Setup (Project-per-team)
**Scenario**: New setup with multiple projects for different teams
**Action**: Run `/specweave-ado:sync`
**What Happens**:
```bash
🔍 Validating Azure DevOps configuration...
Strategy: Project-per-team
Checking projects: WebApp, MobileApp, Platform...
⚠️ Projects not found:
• WebApp
• MobileApp
• Platform
What would you like to do?
1. Create new projects
2. Select existing projects
3. Cancel
Your choice [1]: 1
📦 Creating Azure DevOps projects...
Creating project: WebApp
Description: Web application frontend
Process template: Agile
✅ Created: WebApp (ID: proj-001)
Creating project: MobileApp
Description: Mobile application
Process template: Agile
✅ Created: MobileApp (ID: proj-002)
Creating project: Platform
Description: Backend platform services
Process template: Agile
✅ Created: Platform (ID: proj-003)
🎉 Azure DevOps configuration complete! All resources ready.
```
### Example 2: Migrate from Single to Multi-Project
**Scenario**: Currently using single project, want to split into multiple
**Current .env**:
```bash
AZURE_DEVOPS_PROJECT=MainProduct
```
**New .env**:
```bash
AZURE_DEVOPS_STRATEGY=project-per-team
AZURE_DEVOPS_PROJECTS=MainProduct-Frontend,MainProduct-Backend,MainProduct-Mobile
```
**What Happens**:
```bash
🔍 Detected strategy change: team-based → project-per-team
Validating new projects...
✅ MainProduct-Frontend (exists from previous split)
⚠️ MainProduct-Backend (not found)
⚠️ MainProduct-Mobile (not found)
Would you like to:
1. Create missing projects
2. Keep single project with area paths instead
3. Cancel
Your choice [1]: 1
📦 Creating projects...
✅ Created: MainProduct-Backend
✅ Created: MainProduct-Mobile
💡 Tip: You can now organize specs by project:
.specweave/docs/internal/specs/MainProduct-Frontend/
.specweave/docs/internal/specs/MainProduct-Backend/
.specweave/docs/internal/specs/MainProduct-Mobile/
```
### Example 3: Area Path Setup
**Scenario**: Large monolithic project with area-based organization
**Action**: Setup area paths for team organization
**What Happens**:
```bash
🔍 Validating Azure DevOps configuration...
Strategy: Area-path-based
Project: EnterpriseApp
Area Paths: Core, UserManagement, Billing, Reports, Analytics
Checking project: EnterpriseApp...
✅ Project exists
Checking area paths...
✅ EnterpriseApp\Core
✅ EnterpriseApp\UserManagement
⚠️ EnterpriseApp\Billing (not found)
⚠️ EnterpriseApp\Reports (not found)
⚠️ EnterpriseApp\Analytics (not found)
📦 Creating area paths...
Creating: EnterpriseApp\Billing
✅ Area path created with default team
Creating: EnterpriseApp\Reports
✅ Area path created with default team
Creating: EnterpriseApp\Analytics
✅ Area path created with default team
✅ All area paths ready!
Work items will be organized by area:
• Billing features → EnterpriseApp\Billing
• Report features → EnterpriseApp\Reports
• Analytics features → EnterpriseApp\Analytics
```
## Implementation Details
**Location**: `src/utils/external-resource-validator.ts`
**Core Classes**:
```typescript
// Main validator class
export class AzureDevOpsResourceValidator {
private pat: string;
private organization: string;
private envPath: string;
constructor(envPath: string = '.env') {
this.envPath = envPath;
const env = this.loadEnv();
this.pat = env.AZURE_DEVOPS_PAT || '';
this.organization = env.AZURE_DEVOPS_ORG || '';
}
// Main validation entry point
async validate(): Promise<AzureDevOpsValidationResult> {
const env = this.loadEnv();
const strategy = env.AZURE_DEVOPS_STRATEGY || 'project-per-team';
// Validate based on strategy
if (strategy === 'project-per-team') {
return this.validateMultipleProjects(projectNames);
} else if (strategy === 'area-path-based') {
return this.validateAreaPaths(projectName, areaPaths);
} else if (strategy === 'team-based') {
return this.validateTeams(projectName, teams);
}
}
}
// Public API function
export async function validateAzureDevOpsResources(
envPath: string = '.env'
): Promise<AzureDevOpsValidationResult> {
const validator = new AzureDevOpsResourceValidator(envPath);
return validator.validate();
}
```
**Key Implementation Features**:
1. **Async Project Creation** (ADO-specific):
```typescript
// ADO creates projects asynchronously - need to poll for completion
async createProject(name: string): Promise<AzureDevOpsProject> {
const result = await this.callAzureDevOpsApi('projects?api-version=7.0', 'POST', body);
// Wait for project to be fully created (ADO async behavior)
await this.waitForProjectCreation(result.id);
return { id: result.id, name, description };
}
// Poll until project is in 'wellFormed' state
private async waitForProjectCreation(projectId: string): Promise<void> {
const maxAttempts = 30; // 30 seconds max wait
for (let i = 0; i < maxAttempts; i++) {
const project = await this.getProject(projectId);
if (project.state === 'wellFormed') {
return; // Project is ready!
}
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
}
throw new Error('Project creation timeout');
}
```
2. **Interactive Prompts** (when resources missing):
```typescript
const { action } = await inquirer.prompt([
{
type: 'select',
name: 'action',
message: `Project "${projectName}" not found. What would you like to do?`,
choices: [
{ name: 'Create new project', value: 'create' },
{ name: 'Select existing project', value: 'select' },
{ name: 'Skip this project', value: 'skip' },
{ name: 'Cancel', value: 'cancel' }
]
}
]);
```
3. **Automatic .env Updates**:
```typescript
// After creating projects, update .env
updateEnv(key: string, value: string): void {
const envContent = fs.readFileSync(this.envPath, 'utf-8');
const updated = envContent.replace(
new RegExp(`^${key}=.*$`, 'm'),
`${key}=${value}`
);
fs.writeFileSync(this.envPath, updated);
}
```
## CLI Command
**Automatic validation** (during setup):
```bash
# Runs automatically during specweave init
npx specweave init
# Also runs automatically before sync
/specweave-ado:sync 0014
```
**Manual validation**:
```bash
# Via skill activation
"Can you validate my Azure DevOps configuration?"
# Via TypeScript directly
npx tsx -e "import { validateAzureDevOpsResources } from './dist/utils/external-resource-validator.js'; await validateAzureDevOpsResources();"
# Via CLI (future command - planned)
specweave validate-ado
```
**Validation output**:
```typescript
interface AzureDevOpsValidationResult {
valid: boolean;
strategy: 'project-per-team' | 'area-path-based' | 'team-based';
projects: Array<{
name: string;
id: string;
exists: boolean;
}>;
created: string[]; // Names of newly created resources
envUpdated: boolean; // Whether .env was modified
}
// Example output:
{
valid: true,
strategy: 'project-per-team',
projects: [
{ name: 'WebApp', id: 'proj-001', exists: true },
{ name: 'MobileApp', id: 'proj-002', exists: true, created: true },
{ name: 'Platform', id: 'proj-003', exists: true, created: true }
],
created: ['MobileApp', 'Platform'],
envUpdated: false
}
```
## Smart Project Detection
### Auto-detect Based on Work Item Patterns
The skill can intelligently suggest project organization based on your existing work items:
```typescript
// Analyze existing work items
const workItems = await analyzeWorkItems(org, project);
// Detect patterns
const patterns = {
byArea: workItems.groupBy('areaPath'), // Area-based organization
byTeam: workItems.groupBy('assignedTeam'), // Team-based organization
byType: workItems.groupBy('workItemType') // Type-based organization
};
// Suggest strategy
if (patterns.byArea.length > 3) {
console.log('💡 Detected area-based organization');
console.log(' Suggested strategy: area-path-based');
} else if (patterns.byTeam.length > 2) {
console.log('💡 Detected team-based organization');
console.log(' Suggested strategy: team-based or project-per-team');
}
```
## Project Creation API
**Azure DevOps REST API** (v7.0):
### Create Project
```bash
POST https://dev.azure.com/{org}/_apis/projects?api-version=7.0
Content-Type: application/json
Authorization: Basic {base64(":PAT")}
{
"name": "MobileApp",
"description": "Mobile application project",
"capabilities": {
"versioncontrol": {
"sourceControlType": "Git"
},
"processTemplate": {
"templateTypeId": "adcc42ab-9882-485e-a3ed-7678f01f66bc" # Agile
}
}
}
Response:
{
"id": "proj-002",
"name": "MobileApp",
"state": "wellFormed"
}
```
### Create Area Path
```bash
POST https://dev.azure.com/{org}/{project}/_apis/wit/classificationnodes/areas?api-version=7.0
Content-Type: application/json
{
"name": "Frontend",
"attributes": {
"startDate": null,
"finishDate": null
}
}
Response:
{
"id": 123,
"name": "Frontend",
"path": "\\MainProduct\\Area\\Frontend"
}
```
### Create Team
```bash
POST https://dev.azure.com/{org}/_apis/projects/{projectId}/teams?api-version=7.0
Content-Type: application/json
{
"name": "Alpha Team",
"description": "Alpha development team"
}
Response:
{
"id": "team-001",
"name": "Alpha Team",
"projectName": "MainProduct"
}
```
## Configuration Examples
### Example 1: Microservices Architecture (Project-per-team)
**Before** (`.env`):
```bash
AZURE_DEVOPS_ORG=mycompany
AZURE_DEVOPS_PAT=xxx
```
**After validation**:
```bash
AZURE_DEVOPS_ORG=mycompany
AZURE_DEVOPS_PAT=xxx
AZURE_DEVOPS_STRATEGY=project-per-team
AZURE_DEVOPS_PROJECTS=AuthService,UserService,PaymentService,NotificationService
```
**Folder structure created**:
```
.specweave/docs/internal/specs/
├── AuthService/
│ └── spec-001-oauth-implementation.md
├── UserService/
│ └── spec-001-user-management.md
├── PaymentService/
│ └── spec-001-stripe-integration.md
└── NotificationService/
└── spec-001-email-notifications.md
```
### Example 2: Monolithic Application (Area-path-based)
**Before** (`.env`):
```bash
AZURE_DEVOPS_PROJECT=ERP
```
**After validation**:
```bash
AZURE_DEVOPS_ORG=enterprise
AZURE_DEVOPS_PAT=xxx
AZURE_DEVOPS_STRATEGY=area-path-based
AZURE_DEVOPS_PROJECT=ERP
AZURE_DEVOPS_AREA_PATHS=Finance,HR,Inventory,Sales,Reports
```
**Work item organization**:
```
ERP
├── Finance/ → Finance module features
├── HR/ → HR module features
├── Inventory/ → Inventory management
├── Sales/ → Sales module features
└── Reports/ → Reporting features
```
### Example 3: Platform Teams (Team-based)
**Before** (`.env`):
```bash
AZURE_DEVOPS_PROJECT=Platform
```
**After validation**:
```bash
AZURE_DEVOPS_ORG=techcorp
AZURE_DEVOPS_PAT=xxx
AZURE_DEVOPS_STRATEGY=team-based
AZURE_DEVOPS_PROJECT=Platform
AZURE_DEVOPS_TEAMS=Infrastructure,Security,Data,DevOps
```
**Team assignments**:
- Infrastructure Team → Cloud resources, networking
- Security Team → Auth, compliance, auditing
- Data Team → Databases, analytics, ML
- DevOps Team → CI/CD, monitoring, tooling
## Error Handling
### Error 1: Invalid Credentials
**Symptom**: API calls fail with 401 Unauthorized
**Solution**:
```
❌ Azure DevOps API authentication failed
Please check:
1. AZURE_DEVOPS_PAT is correct
2. Token has not expired
3. AZURE_DEVOPS_ORG is correct
Generate new token at:
https://dev.azure.com/{org}/_usersSettings/tokens
```
### Error 2: Insufficient Permissions
**Symptom**: Cannot create projects (403 Forbidden)
**Solution**:
```
❌ Insufficient permissions to create projects
You need:
- Project Collection Administrator role (for creating projects)
- Project Administrator role (for area paths and teams)
Contact your Azure DevOps administrator to request permissions.
```
### Error 3: Project Name Conflicts
**Symptom**: Project creation fails (name exists)
**Solution**:
```
❌ Project name "WebApp" already exists
Options:
1. Use a different project name
2. Select the existing project
3. Add a suffix (e.g., WebApp-v2)
Your choice [2]:
```
### Error 4: Organization Limits
**Symptom**: Cannot create more projects
**Solution**:
```
❌ Organization project limit reached (250 projects)
Consider:
1. Using area-path-based strategy (one project)
2. Archiving old projects
3. Upgrading organization plan
Contact Azure DevOps support for limit increases.
```
## Integration with SpecWeave Workflow
### Automatic Validation
When using `/specweave-ado:sync`, validation runs automatically:
```bash
/specweave-ado:sync 0014
# Internally calls:
1. validateAzureDevOpsResources()
2. Fix missing projects/area paths/teams
3. Create folder structure for specs
4. Proceed with sync
```
### Manual Validation
Run validation independently:
```bash
# Via skill
"Validate my Azure DevOps configuration"
# Via TypeScript
npx tsx src/utils/external-resource-validator.ts --provider=ado
# Via CLI (future)
specweave validate-ado
```
## Best Practices
✅ **Choose the right strategy**:
- **Project-per-team**: Best for autonomous teams, microservices
- **Area-path-based**: Best for monolithic apps, shared codebase
- **Team-based**: Best for small organizations, simple structure
✅ **Use descriptive names**:
```bash
# Good
AZURE_DEVOPS_PROJECTS=UserManagement,PaymentProcessing,NotificationEngine
# Bad
AZURE_DEVOPS_PROJECTS=Proj1,Proj2,Proj3
```
✅ **Document project mapping** (in README):
```markdown
## Azure DevOps Projects
- UserManagement: User authentication and profile management
- PaymentProcessing: Payment gateway integrations
- NotificationEngine: Email, SMS, and push notifications
```
✅ **Keep .env in version control** (gitignored tokens):
```bash
# Commit project structure
AZURE_DEVOPS_STRATEGY=project-per-team
AZURE_DEVOPS_PROJECTS=WebApp,MobileApp,Platform
# Don't commit sensitive data
AZURE_DEVOPS_PAT=<redacted>
```
## Folder Organization
Based on strategy, the skill creates appropriate folder structure:
### Project-per-team Structure
```
.specweave/docs/internal/specs/
├── WebApp/
│ ├── spec-001-user-interface.md
│ └── spec-002-responsive-design.md
├── MobileApp/
│ ├── spec-001-ios-features.md
│ └── spec-002-android-features.md
└── Platform/
├── spec-001-api-design.md
└── spec-002-database-schema.md
```
### Area-path-based Structure
```
.specweave/docs/internal/specs/MainProduct/
├── Frontend/
│ └── spec-001-ui-components.md
├── Backend/
│ └── spec-001-api-endpoints.md
└── Mobile/
└── spec-001-mobile-sync.md
```
### Team-based Structure
```
.specweave/docs/internal/specs/MainProduct/
├── AlphaTeam/
│ └── spec-001-feature-a.md
├── BetaTeam/
│ └── spec-001-feature-b.md
└── GammaTeam/
└── spec-001-feature-c.md
```
## Key Differences from JIRA
**Azure DevOps vs JIRA Resource Creation**:
| Aspect | Azure DevOps | JIRA |
|--------|-------------|------|
| **Project Creation** | Asynchronous (polling required) | Synchronous (immediate) |
| **Creation Time** | 5-30 seconds | <1 second |
| **Status Tracking** | Poll `state` field ('wellFormed') | No polling needed |
| **API Complexity** | Higher (async handling) | Lower (sync operations) |
| **Board Creation** | Auto-created with project | Requires separate API call |
| **Process Templates** | Required (Agile, Scrum, CMMI) | Not applicable |
**Why Async Matters**:
When you create an ADO project, the API returns immediately with `state: 'new'`, but the project isn't usable yet. The validator polls every 1 second (max 30 attempts) until `state: 'wellFormed'`:
```typescript
// Create project (returns immediately)
const project = await createProject('MobileApp'); // state: 'new'
// Poll until ready
await waitForProjectCreation(project.id); // Polls until state: 'wellFormed'
// Now safe to use!
console.log('✅ Project ready for work items');
```
**Impact on UX**:
- JIRA: "✅ Project created" (instant)
- ADO: "📦 Creating project... ⏳ Waiting for Azure DevOps to complete setup... ✅ Project ready!" (5-30s)
## Summary
This skill ensures your Azure DevOps configuration is **always valid** by:
1.**Validating projects** - Check if projects exist, prompt to select or create
2.**Supporting multiple strategies** - Project-per-team, area-path-based, team-based
3.**Auto-creating resources** - Projects, area paths, teams (with async handling)
4.**Organizing specs** - Create folder structure based on projects
5.**Clear error messages** - Actionable guidance for all failures
6.**Handles ADO async behavior** - Polls for project creation completion
**Result**: Zero manual Azure DevOps setup - system handles everything, including ADO's async project creation!
---
**Skill Version**: 1.1.0
**Introduced**: SpecWeave v0.17.0
**Last Updated**: 2025-11-11
**Key Changes v1.1.0**: Added implementation details, async project creation handling, JIRA comparison

3
skills/ado-sync/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
test-results/
*.log
.DS_Store

414
skills/ado-sync/README.md Normal file
View File

@@ -0,0 +1,414 @@
# ado-sync Skill
**Status**: To be developed
**Priority**: Medium
## Purpose
Bidirectional sync between SpecWeave increments and Azure DevOps (ADO)
**Note**: This skill handles ONLY Azure DevOps. For JIRA, see `jira-sync` skill.
## Features
### Export to ADO
- Create ADO work items from SpecWeave increments
- Map spec.md user stories → ADO User Stories
- Map tasks.md tasks → ADO Tasks
- Create Features if specified in spec.md
- Set Area Paths, Iterations, priorities
### Import from ADO
- Sync ADO updates back to SpecWeave
- Import existing ADO work items as increments
- Update status, assignees, comments
### Bidirectional Sync
- Keep status in sync (New, Active, Resolved, Closed)
- Sync descriptions and acceptance criteria
- Sync comments and attachments
- Handle conflicts intelligently
## ADO-Specific Concepts
### Mapping: SpecWeave → Azure DevOps
| SpecWeave | Azure DevOps |
|-----------|--------------|
| spec.md (with Feature) | Feature |
| spec.md User Story | User Story |
| tasks.md Task | Task |
| Acceptance Tests (spec.md) | Acceptance Criteria (User Story) |
| Acceptance Criteria (tasks.md) | Task checklist |
| Status: planned | New |
| Status: in-progress | Active |
| Status: completed | Closed |
### ADO Structure Example
**spec.md with ADO structure**:
```markdown
---
increment: 002-payment-processing
status: planned
structure: ado
ado_feature: 456
---
## Feature: Payment Processing
**ADO**: 456
**Area Path**: Platform/Payments
**Iteration**: Sprint 12
### User Story: Subscribe to Plan
**ADO**: 789
**Priority**: 1
**Area Path**: Platform/Payments
**Iteration**: Sprint 12
**Description**:
As a user, I want to subscribe to a monthly plan...
**Acceptance Criteria**:
- User can select plan
- Payment processed
- Subscription activated
```
**tasks.md creates Tasks**:
```markdown
## Tasks for ADO-789 (Subscribe to Plan)
### Task T001: Create StripeService
**ADO**: 790 (Task under User Story 789)
**Agent**: nodejs-backend
**Area Path**: Platform/Payments/Backend
**Iteration**: Sprint 12
**Description**: Create Stripe service class...
**Acceptance Criteria**:
- [ ] StripeService class exists
- [ ] Unit tests passing
```
## Authentication
**Personal Access Token (PAT)**:
**OAuth 2.0** (for apps):
```yaml
ado_sync:
url: "https://dev.azure.com/your-org"
project: "YourProject"
auth_type: "oauth"
client_id: "${ADO_CLIENT_ID}"
client_secret: "${ADO_CLIENT_SECRET}"
```
## Configuration
## Workflow
### Export Workflow (SpecWeave → ADO)
```
User: Creates increment in SpecWeave
.specweave/increments/0002-payment/
spec.md (with structure: ado)
tasks.md
↓ ado-sync detects new increment
Creates in ADO:
Feature: 456 "Payment Processing"
Area Path: Platform/Payments
Iteration: Sprint 12
User Story: 789 "Subscribe to Plan"
Area Path: Platform/Payments
Iteration: Sprint 12
Task: 790 "Create StripeService"
Area Path: Platform/Payments/Backend
Iteration: Sprint 12
Task: 791 "Create API endpoints"
Links created:
spec.md → ADO-789
tasks.md T001 → ADO-790
tasks.md T002 → ADO-791
```
### Import Workflow (ADO → SpecWeave)
```
User: Updates ADO work item status to "Active"
↓ ADO service hook triggers
ado-sync:
Detects change to ADO-789
Finds linked increment: 002-payment
Updates: .specweave/increments/0002-payment/spec.md
status: planned → in-progress
```
### Bidirectional Sync
```
User: Checks off task in tasks.md
- [x] T001: Create StripeService
↓ ado-sync detects change
Updates ADO:
Work Item 790 status → Closed
User: Changes ADO-789 to "Closed" in Azure DevOps
↓ ADO service hook triggers
ado-sync updates SpecWeave:
.specweave/increments/0002-payment/spec.md
status: in-progress → completed
```
## API Integration
### Azure DevOps REST API Endpoints Used
```typescript
// Create Feature
POST https://dev.azure.com/{org}/{project}/_apis/wit/workitems/$Feature?api-version=7.0
Content-Type: application/json-patch+json
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Payment Processing"
},
{
"op": "add",
"path": "/fields/System.AreaPath",
"value": "Platform/Payments"
},
{
"op": "add",
"path": "/fields/System.IterationPath",
"value": "Sprint 12"
}
]
// Create User Story (linked to Feature)
POST https://dev.azure.com/{org}/{project}/_apis/wit/workitems/$User%20Story?api-version=7.0
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Subscribe to Plan"
},
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Hierarchy-Reverse",
"url": "https://dev.azure.com/{org}/_apis/wit/workItems/456"
}
}
]
// Create Task (linked to User Story)
POST https://dev.azure.com/{org}/{project}/_apis/wit/workitems/$Task?api-version=7.0
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Create StripeService"
},
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Hierarchy-Reverse",
"url": "https://dev.azure.com/{org}/_apis/wit/workItems/789"
}
}
]
// Update status
PATCH https://dev.azure.com/{org}/{project}/_apis/wit/workitems/{id}?api-version=7.0
[
{
"op": "add",
"path": "/fields/System.State",
"value": "Active"
}
]
```
## Service Hooks (Webhooks)
### Setup ADO Service Hook
1. Go to Project Settings → Service hooks
2. Create new service hook:
- Service: Web Hooks
- Trigger: Work item updated
- URL: `https://your-app.com/api/webhooks/ado`
- Filters: Area path = Platform/Payments (optional)
### Service Hook Handler
```typescript
// Receives ADO service hook
POST /api/webhooks/ado
// ado-sync processes:
1. Verify request (optional: check secret)
2. Extract work item data
3. Find linked SpecWeave increment
4. Update spec.md or tasks.md
5. Commit changes (optional)
```
## ADO-Specific Features
### Area Paths
**Organize work by area**:
```markdown
# spec.md
---
ado_area_path: "Platform/Payments"
---
```
Maps to ADO Area Path for organization.
### Iterations/Sprints
**Assign to sprint**:
```markdown
# spec.md
---
ado_iteration: "Sprint 12"
---
```
Or auto-detect current sprint:
```yaml
# config.yaml
ado_sync:
auto_detect_iteration: true
```
### Work Item Types
**ADO supports custom work item types**:
- Epic → Feature → User Story → Task (default)
- Custom types supported via config
```yaml
ado_sync:
work_item_types:
epic: "Epic"
feature: "Feature"
story: "User Story"
task: "Task"
```
### Custom Fields
**Sync custom fields**:
```yaml
ado_sync:
custom_fields:
- name: "Custom.Priority"
map_from: "priority" # From spec.md frontmatter
- name: "Custom.Estimate"
map_from: "estimate"
```
## Conflict Resolution
**Scenario**: Both SpecWeave and ADO updated simultaneously
**Strategy**:
1. **Timestamp-based**: Latest change wins
2. **User prompt**: Ask user which to keep (via Ping.aiff)
3. **Merge**: Combine changes if possible
**Example**:
```
SpecWeave: status → in-progress (10:00 AM)
ADO: status → closed (10:05 AM)
ado-sync:
Latest is ADO (10:05 AM)
Update SpecWeave → completed
🔔 Ping.aiff: "ADO conflict resolved - ADO version used"
```
## Error Handling
**Common errors**:
- ADO API rate limits → Retry with exponential backoff
- Authentication failed → Notify user, check PAT
- Work item not found → Create if export, skip if import
- Network errors → Queue for retry
- Area Path invalid → Use default or notify user
## Testing
**Test scenarios**:
1. Create increment → Creates ADO work items
2. Update ADO → Updates SpecWeave
3. Update SpecWeave → Updates ADO
4. Area Path mapping
5. Iteration mapping
6. Conflict resolution
7. Service hook handling
8. Custom fields sync
## Integration with Other Skills
- **task-builder**: Reads ADO structure from spec.md
- **increment-planner**: Can specify structure: ado
## Comparison: JIRA vs ADO
| Feature | JIRA (jira-sync) | Azure DevOps (ado-sync) |
|---------|------------------|-------------------------|
| **Epic level** | Epic | Feature |
| **Story level** | Story | User Story |
| **Task level** | Sub-task | Task |
| **Organization** | Components, Labels | Area Paths |
| **Sprints** | Sprints (board-based) | Iterations (path-based) |
| **API** | JIRA REST API v3 | Azure DevOps REST API v7.0 |
| **Auth** | API Token | PAT or OAuth |
| **Webhooks** | JIRA Webhooks | Service Hooks |
| **Custom fields** | Custom fields | Work item fields |
## Future Enhancements
- Support for ADO Boards/Backlogs
- Sprint burndown sync
- Test case sync (ADO Test Plans)
- Build/release pipeline integration
- Wiki sync
- Git repo integration (link commits to work items)
---
**To implement**: See task in .specweave/increments/
**See also**: `jira-sync` skill for JIRA integration

406
skills/ado-sync/SKILL.md Normal file
View File

@@ -0,0 +1,406 @@
---
name: ado-sync
description: Bidirectional synchronization between SpecWeave increments and Azure DevOps work items (two-way sync by default). Activates ONLY when user asks questions about Azure DevOps integration or needs help configuring ADO sync. Does NOT activate for slash commands. For syncing, use /specweave-ado:sync command instead.
---
# Azure DevOps Sync Skill
**Purpose**: Seamlessly sync SpecWeave increments with Azure DevOps work items for unified project tracking.
**Default Behavior**: **Bidirectional (two-way) sync** - Changes in either system are automatically synchronized
**⚠️ IMPORTANT**: This skill provides HELP and GUIDANCE about Azure DevOps sync. For actual syncing, users should use the `/specweave-ado:sync` command directly. This skill should NOT auto-activate when the command is being invoked.
**Capabilities**:
- Bidirectional sync: SpecWeave ↔ ADO (default)
- Create ADO work items from increments
- Sync task progress → ADO comments
- Update increment status ← ADO state changes
- Pull ADO comments and field updates → SpecWeave
- Close work items when increments complete
- Support for Epics, Features, User Stories
---
## When This Skill Activates
**Do activate when**:
- User asks: "How do I set up Azure DevOps sync?"
- User asks: "What ADO credentials do I need?"
- User asks: "How does ADO integration work?"
- User needs help configuring Azure DevOps integration
**Do NOT activate when**:
- User invokes `/specweave-ado:sync` command (command handles it)
- Command is already running (avoid duplicate invocation)
- Task completion hook is syncing (automatic process)
- "Close ADO work item when done"
---
## Prerequisites
### 1. ADO Plugin Installed
```bash
# Check if installed
/plugin list --installed | grep specweave-ado
# Install if needed
/plugin install specweave-ado
```
### 2. Azure DevOps Personal Access Token (PAT)
**Create PAT**:
1. Go to https://dev.azure.com/{organization}/_usersSettings/tokens
2. Click "New Token"
3. Name: "SpecWeave Sync"
4. Scopes: Work Items (Read & Write), Comments (Read & Write)
5. Copy token → Set environment variable
**Set Token**:
```bash
export AZURE_DEVOPS_PAT="your-token-here"
```
### 3. ADO Configuration
Add to `.specweave/config.json`:
```json
{
"externalPM": {
"tool": "ado",
"enabled": true,
"config": {
"organization": "myorg",
"project": "MyProject",
"workItemType": "Epic",
"areaPath": "MyProject\\Team A",
"syncOnTaskComplete": true
}
}
}
```
---
## Commands Available
### `/specweave-ado:create-workitem <increment-id>`
**Purpose**: Create ADO work item from increment
**Example**:
```bash
/specweave-ado:create-workitem 0005
```
**Result**:
- Creates Epic/Feature/User Story in ADO
- Links work item to increment (metadata)
- Adds initial comment with spec summary
- Sets tags: `specweave`, `increment-0005`
---
### `/specweave-ado:sync <increment-id>`
**Purpose**: Sync increment progress with ADO work item
**Example**:
```bash
/specweave-ado:sync 0005
```
**Result**:
- Calculates task completion (%)
- Updates work item description
- Adds comment with progress update
- Updates state (New → Active → Resolved)
---
### `/specweave-ado:close-workitem <increment-id>`
**Purpose**: Close ADO work item when increment complete
**Example**:
```bash
/specweave-ado:close-workitem 0005
```
**Result**:
- Updates work item state → Closed
- Adds completion comment with summary
- Marks work item as resolved
---
### `/specweave-ado:status <increment-id>`
**Purpose**: Check ADO sync status for increment
**Example**:
```bash
/specweave-ado:status 0005
```
**Result**:
```
ADO Sync Status
===============
Increment: 0005-payment-integration
Work Item: #12345
URL: https://dev.azure.com/myorg/MyProject/_workitems/edit/12345
State: Active
Completion: 60% (6/10 tasks)
Last Synced: 2025-11-04 10:30:00
Sync Enabled: ✅
```
---
## Automatic Sync
### When Task Completes
**Trigger**: Post-task-completion hook fires
**Flow**:
1. User marks task complete: `[x] T-005: Add payment tests`
2. Hook detects ADO sync enabled
3. Calculate new completion %
4. Update ADO work item comment:
```markdown
## Progress Update
**Increment**: 0005-payment-integration
**Status**: 60% complete (6/10 tasks)
### Recently Completed
- [x] T-005: Add payment tests
### Remaining
- [ ] T-007: Add refund functionality
- [ ] T-008: Implement subscriptions
- [ ] T-009: Add analytics
- [ ] T-010: Security audit
---
🤖 Auto-updated by SpecWeave
```
### When Increment Completes
**Trigger**: `/specweave:done` command
**Flow**:
1. User runs `/specweave:done 0005`
2. Validate all tasks complete
3. Close ADO work item automatically
4. Add completion comment with summary
---
## Work Item Types
### Epic (Recommended)
**Use When**: Large feature spanning multiple sprints
**Mapping**:
- SpecWeave increment → ADO Epic
- Tasks → Epic description (checklist)
- Progress → Epic comments
---
### Feature
**Use When**: Medium-sized feature within a sprint
**Mapping**:
- SpecWeave increment → ADO Feature
- Tasks → Feature description (checklist)
- Progress → Feature comments
---
### User Story
**Use When**: Small, single-sprint work
**Mapping**:
- SpecWeave increment → ADO User Story
- Tasks → User Story description (checklist)
- Progress → User Story comments
---
## Bidirectional Sync (Optional)
**Enable**: Set `bidirectional: true` in config
**Flow**: ADO → SpecWeave
1. User updates work item state in ADO (Active → Resolved)
2. SpecWeave detects change (polling or webhook)
3. Updates increment status locally
4. Notifies user: "Work item #12345 resolved → Increment 0005 marked complete"
**Note**: Bidirectional sync requires webhook or polling setup
---
## Configuration Options
**`.specweave/config.json`**:
```json
{
"externalPM": {
"tool": "ado",
"enabled": true,
"config": {
"organization": "myorg",
"project": "MyProject",
"personalAccessToken": "${AZURE_DEVOPS_PAT}",
"workItemType": "Epic",
"areaPath": "MyProject\\Team A",
"iterationPath": "MyProject\\Sprint 1",
"syncOnTaskComplete": true,
"syncOnIncrementComplete": true,
"createWorkItemsAutomatically": true,
"bidirectional": false,
"tags": ["specweave", "increment"],
"customFields": {
"incrementId": "Custom.IncrementId"
}
}
}
}
```
---
## Troubleshooting
### Error: "Personal Access Token invalid"
**Solution**:
1. Verify token is set: `echo $AZURE_DEVOPS_PAT`
2. Check token scopes: Work Items (Read & Write)
3. Ensure token not expired
4. Regenerate token if needed
---
### Error: "Work item not found"
**Solution**:
1. Check work item ID is correct
2. Verify you have access to the project
3. Ensure work item not deleted
---
### Error: "Organization or project not found"
**Solution**:
1. Verify organization name: https://dev.azure.com/{organization}
2. Check project name (case-sensitive)
3. Ensure you have access to the project
---
## API Rate Limits
**Azure DevOps**:
- Rate limit: 200 requests per minute per PAT
- Burst limit: 5000 requests per hour
- Recommendation: Enable rate limiting in config
**Config**:
```json
{
"externalPM": {
"config": {
"rateLimiting": {
"enabled": true,
"maxRequestsPerMinute": 150
}
}
}
}
```
---
## Security Best Practices
### DO:
- ✅ Store PAT in environment variable (`AZURE_DEVOPS_PAT`)
- ✅ Use `.env` file (gitignored)
- ✅ Set minimum required scopes
- ✅ Rotate PAT every 90 days
### DON'T:
- ❌ Commit PAT to git
- ❌ Share PAT via Slack/email
- ❌ Use PAT with excessive permissions
- ❌ Log PAT to console/files
---
## Related Commands
- `/specweave:inc` - Create increment (auto-creates ADO work item if enabled)
- `/specweave:do` - Execute tasks (auto-syncs progress to ADO)
- `/specweave:done` - Complete increment (auto-closes ADO work item)
- `/specweave:status` - Show increment status (includes ADO sync status)
---
## Examples
### Example 1: Create Increment with ADO Sync
```bash
# User
"Create increment for payment integration"
# SpecWeave (if ADO enabled)
1. PM agent generates spec.md
2. Auto-create ADO Epic #12345
3. Link Epic to increment metadata
4. Display: "Created increment 0005 → ADO Epic #12345"
```
### Example 2: Manual Sync
```bash
# User completed 3 tasks manually
# Now sync to ADO
/specweave-ado:sync 0005
# Result: ADO Epic #12345 updated with 30% progress
```
### Example 3: Check Sync Status
```bash
/specweave-ado:status 0005
# Output:
# Work Item: #12345
# URL: https://dev.azure.com/myorg/MyProject/_workitems/edit/12345
# State: Active
# Completion: 60%
# Last Synced: 5 minutes ago
```
---
**Status**: Ready to use
**Version**: 0.1.0
**Plugin**: specweave-ado

View File

@@ -0,0 +1,501 @@
---
name: specweave-ado-mapper
description: Expert in bidirectional conversion between SpecWeave increments and Azure DevOps (ADO) Epics/Features/User Stories/Tasks. Handles export (increment → ADO), import (ADO → increment), and bidirectional sync with conflict resolution. Activates for ADO sync, Azure DevOps sync, work item creation, import from ADO.
tools: Read, Write, Edit, Bash
model: claude-sonnet-4-5-20250929
---
# Specweave Ado Mapper Skill
You are an expert in mapping SpecWeave concepts to Azure DevOps (ADO) and vice versa with precision and traceability.
## Core Responsibilities
1. **Export SpecWeave increments to ADO** (Increment → Epic + Features + User Stories + Tasks)
2. **Import ADO Epics as SpecWeave increments** (Epic → Increment structure)
3. **Bidirectional sync** with conflict detection and resolution
4. **Maintain traceability** (store IDs, URLs, timestamps)
5. **Validate mapping accuracy** using test cases
6. **Handle edge cases** (missing fields, custom workflows, API errors)
---
## Azure DevOps Work Item Hierarchy
ADO uses a **4-level hierarchy** (one more level than JIRA):
```
Epic
└── Feature
└── User Story
└── Task
```
**Key Difference from JIRA**: ADO has **Feature** between Epic and User Story.
---
## Concept Mappings
### SpecWeave → ADO
| SpecWeave Concept | ADO Concept | Mapping Rules |
|-------------------|-------------|---------------|
| **Increment** | Epic | Title: `[Increment ###] [Title]` |
| **User Story** (from spec.md) | Feature (if large) OR User Story | Decision based on size |
| **Task** (from tasks.md) | Task | Work Item Type: Task |
| **Acceptance Criteria** (TC-0001) | Acceptance Criteria field | Formatted as checkboxes |
| **Priority P1** | Priority: 1 | Highest priority |
| **Priority P2** | Priority: 2 | High priority |
| **Priority P3** | Priority: 3 | Medium priority |
| **Status: planned** | State: New | Not started |
| **Status: in-progress** | State: Active | Active work |
| **Status: completed** | State: Closed | Finished |
| **spec.md** | Epic Description | Summary + link to spec (if repo) |
### ADO → SpecWeave
| ADO Concept | SpecWeave Concept | Import Rules |
|-------------|-------------------|--------------|
| **Epic** | Increment | Auto-number next available |
| **Feature** | User Story (large) | Extract title, description |
| **User Story** | User Story (small) | Extract acceptance criteria |
| **Task** | Task | Map to tasks.md checklist |
| **Acceptance Criteria** | TC-0001 format | Parse as test cases |
| **Priority 1** | Priority P1 | Critical |
| **Priority 2** | Priority P2 | Important |
| **Priority 3/4** | Priority P3 | Nice to have |
| **State: New** | Status: planned | Not started |
| **State: Active** | Status: in-progress | Active |
| **State: Closed** | Status: completed | Finished |
| **Area Path** | Context metadata | Store in frontmatter |
| **Iteration** | Context metadata | Store in frontmatter |
---
## Conversion Workflows
### 1. Export: Increment → ADO Epic
**Input**: `.specweave/increments/0001-feature-name/`
**Prerequisites**:
- Increment folder exists
- `spec.md` exists with valid frontmatter
- `tasks.md` exists
- ADO connection configured (PAT, organization, project)
**Process**:
1. **Read increment files**:
```bash
# Read spec.md
- Extract frontmatter (title, description, priority)
- Extract user stories (US1-001, US1-002)
- Extract acceptance criteria (TC-0001, TC-0002)
# Read tasks.md
- Extract task checklist
- Group tasks by user story
```
2. **Create ADO Epic**:
```
Title: [Increment 0001] Feature Name
Description:
{spec.md summary}
Specification: {link to spec.md if Azure Repos}
Work Item Type: Epic
Priority: 1 (P1) / 2 (P2) / 3 (P3)
State: New
Area Path: {project_area}
Iteration: {current_iteration}
Tags: specweave, increment-0001
Custom Fields:
- SpecWeave.IncrementID: 0001-feature-name
- SpecWeave.SpecURL: https://dev.azure.com/.../spec.md
```
3. **Create ADO Features OR User Stories**:
**Decision Logic**:
- If user story has >5 acceptance criteria → Create as Feature (large work)
- If user story has ≤5 acceptance criteria → Create as User Story (small work)
**Feature (large user story)**:
```
Title: {User Story title}
Description:
**As a** {role}
**I want to** {goal}
**So that** {benefit}
Acceptance Criteria:
- TC-0001: {criteria}
- TC-0002: {criteria}
...
Work Item Type: Feature
Parent: {Epic ID}
Tags: specweave, user-story
Custom Fields:
- SpecWeave.UserStoryID: US1-001
- SpecWeave.TestCaseIDs: TC-0001, TC-0002
```
**User Story (small user story)**:
```
(Same structure as Feature, but Work Item Type: User Story)
```
4. **Create ADO Tasks**:
```
Title: {Task description}
Work Item Type: Task
Parent: {Feature or User Story ID}
State: New
Tags: specweave, task
```
5. **Update increment frontmatter**:
```yaml
ado:
epic_id: "12345"
epic_url: "https://dev.azure.com/{org}/{project}/_workitems/edit/12345"
features:
- id: "12346"
user_story_id: "US1-001"
- id: "12347"
user_story_id: "US1-002"
area_path: "MyProject\\TeamA"
iteration: "Sprint 24"
last_sync: "2025-10-26T14:00:00Z"
sync_direction: "export"
```
**Output**:
```
✅ Exported to Azure DevOps!
Epic: 12345
URL: https://dev.azure.com/{org}/{project}/_workitems/edit/12345
Features: 3 created
User Stories: 2 created
Tasks: 12 created
Area Path: MyProject\TeamA
Iteration: Sprint 24
Last Sync: 2025-10-26T14:00:00Z
```
---
### 2. Import: ADO Epic → Increment
**Input**: ADO Epic ID (e.g., `12345`)
**Prerequisites**:
- Valid ADO Epic ID
- Epic exists and is accessible
- ADO connection configured
**Process**:
1. **Fetch Epic details** (via ADO REST API):
```
- Epic title, description, tags
- Epic custom fields (if SpecWeave ID exists)
- Priority, state, area path, iteration
```
2. **Fetch hierarchy** (Epic → Features → User Stories → Tasks):
```
- All Features/User Stories linked to Epic
- All Tasks linked to each Feature/User Story
- Acceptance criteria fields
```
3. **Auto-number next increment**:
```bash
# Scan .specweave/increments/ for highest number
ls .specweave/increments/ | grep -E '^[0-9]{4}' | sort -n | tail -1
# Increment by 1 → 0003
```
4. **Create increment folder**:
```
.specweave/increments/0003-imported-feature/
```
5. **Generate spec.md**:
```yaml
---
increment_id: "0003"
title: "{Epic title}"
status: "{mapped from ADO state}"
priority: "{mapped from ADO priority}"
created_at: "{Epic created date}"
ado:
epic_id: "12345"
epic_url: "https://dev.azure.com/{org}/{project}/_workitems/edit/12345"
features:
- id: "12346"
user_story_id: "US3-001"
area_path: "{area path}"
iteration: "{iteration}"
imported_at: "2025-10-26T14:00:00Z"
sync_direction: "import"
---
# {Epic title}
{Epic description}
## Context
- **Area Path**: {area_path}
- **Iteration**: {iteration}
- **ADO Epic**: [12345](https://dev.azure.com/.../12345)
## User Stories
### US3-001: {Feature/User Story title}
**As a** {extracted from description}
**I want to** {extracted}
**So that** {extracted}
**Acceptance Criteria**:
- [ ] TC-0001: {parsed from Acceptance Criteria field}
- [ ] TC-0002: {parsed}
**ADO Feature**: [12346](https://dev.azure.com/.../12346)
```
6. **Generate tasks.md**:
```markdown
# Tasks: {Increment title}
## User Story: US3-001
- [ ] {Task 1 title} (ADO: 12350)
- [ ] {Task 2 title} (ADO: 12351)
```
7. **Generate context-manifest.yaml** (default)
8. **Update ADO Epic** (add custom field):
```
Custom Field: SpecWeave.IncrementID = 0003-imported-feature
```
**Output**:
```
✅ Imported from Azure DevOps!
Increment: 0003-imported-feature
Location: .specweave/increments/0003-imported-feature/
User Stories: 5 imported
Tasks: 12 imported
ADO Epic: 12345
Area Path: MyProject\TeamA
Iteration: Sprint 24
```
---
### 3. Bidirectional Sync
**Process**: Similar to JIRA sync, with ADO-specific fields:
- Sync Area Path changes
- Sync Iteration changes
- Handle ADO-specific states (New, Active, Resolved, Closed)
- Sync Acceptance Criteria field
---
## ADO-Specific Concepts
### Area Path
**Definition**: Organizational hierarchy (e.g., `MyProject\TeamA\Backend`)
**Mapping**:
- Store in increment frontmatter: `ado.area_path`
- Not a direct SpecWeave concept
- Used for organizational context
### Iteration
**Definition**: Sprint/time period (e.g., `Sprint 24`)
**Mapping**:
- Store in increment frontmatter: `ado.iteration`
- Not a direct SpecWeave concept
- Used for planning context
### Work Item States
ADO uses **State** (not Status):
| ADO State | SpecWeave Status |
|-----------|------------------|
| New | planned |
| Active | in-progress |
| Resolved | in-progress (testing) |
| Closed | completed |
### Priority Values
ADO uses numeric priorities:
| ADO Priority | SpecWeave Priority |
|--------------|-------------------|
| 1 | P1 |
| 2 | P2 |
| 3 | P3 |
| 4 | P3 |
---
## Edge Cases and Error Handling
### Feature vs User Story Decision
**Problem**: SpecWeave user story → Should it be ADO Feature or User Story?
**Solution**:
```
Decision Logic:
- User story has >5 acceptance criteria → Feature (large work)
- User story has ≤5 acceptance criteria → User Story (small work)
- User can override with flag: --force-feature or --force-user-story
```
### Custom Area Paths
**Problem**: Project has custom Area Path structure
**Solution**:
```
Ask user:
"Select Area Path for this increment:
[1] MyProject\TeamA
[2] MyProject\TeamB
[3] Custom (enter path)"
```
### Custom Iterations
**Problem**: Sprint naming varies
**Solution**:
```
Ask user:
"Select Iteration for this increment:
[1] Sprint 24 (current)
[2] Sprint 25 (next)
[3] Backlog
[4] Custom (enter iteration)"
```
### ADO API Errors
**Problem**: Rate limit, authentication failure, network error
**Solution**:
```
❌ ADO API Error: Unauthorized (401)
Check your Personal Access Token (PAT):
1. Go to https://dev.azure.com/{org}/_usersSettings/tokens
2. Create new PAT with Work Items (Read, Write) scope
3. Update .env: ADO_PAT=your-token
```
---
## Templates
Use templates in `templates/` folder:
- `epic-from-increment.md` - Epic creation template
- `feature-from-user-story.md` - Feature creation template
- `user-story-from-small-story.md` - User Story creation template
- `increment-from-epic.md` - Increment import template
---
## References
Consult references in `references/` folder:
- `ado-concepts.md` - ADO structure (Epic, Feature, User Story, Task)
- `specweave-concepts.md` - SpecWeave structure
- `mapping-examples.md` - Real-world conversions with Area Paths and Iterations
---
## Test Cases
Validate all conversions using test cases in `test-cases/`:
1. **test-1-increment-to-epic.yaml** - Export with Feature/User Story decision
2. **test-2-epic-to-increment.yaml** - Import with Area Path and Iteration
3. **test-3-bidirectional-sync.yaml** - Sync with ADO-specific fields
**Run tests**:
```bash
npm run test:agents:specweave-ado-mapper
```
---
## Best Practices
1. **Respect ADO hierarchy** - Use Feature for large work, User Story for small
2. **Store Area Path and Iteration** - Important for organizational context
3. **Handle custom workflows** - Many ADO projects customize states
4. **Use PAT securely** - Store in .env, never commit
5. **Preserve traceability** - Store ADO IDs in frontmatter, SpecWeave IDs in ADO
---
## Usage Examples
### Export to ADO
```
User: "Export increment 0001 to Azure DevOps"
You:
1. Read increment files
2. Ask: "Area Path? [TeamA] [TeamB] [Custom]"
3. Ask: "Iteration? [Sprint 24] [Sprint 25] [Backlog]"
4. Create Epic
5. Decide Feature vs User Story (based on size)
6. Create Work Items
7. Update frontmatter
8. Present summary
```
### Import from ADO
```
User: "Import ADO epic 12345"
You:
1. Fetch Epic + hierarchy
2. Extract Area Path and Iteration
3. Auto-number increment
4. Generate spec.md with ADO metadata
5. Generate tasks.md
6. Update ADO Epic with SpecWeave ID
7. Present summary
```
---
**You are the authoritative mapper between SpecWeave and Azure DevOps. Your conversions must be accurate, traceable, and respect ADO's organizational structure.**