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

25
commands/refresh-cache.js Executable file
View File

@@ -0,0 +1,25 @@
#!/usr/bin/env node
import { existsSync, unlinkSync, readdirSync } from "fs";
import { join } from "path";
async function refreshAdoCache(projectRoot = process.cwd()) {
const cacheDir = join(projectRoot, ".specweave", "cache", "ado");
if (!existsSync(cacheDir)) {
console.log("\u2705 No ADO cache found");
return;
}
console.log("\u{1F9F9} Clearing ADO cache...");
const files = readdirSync(cacheDir);
let cleared = 0;
for (const file of files) {
const filePath = join(cacheDir, file);
unlinkSync(filePath);
cleared++;
}
console.log(`\u2705 Cleared ${cleared} cache files`);
}
if (require.main === module) {
refreshAdoCache().catch(console.error);
}
export {
refreshAdoCache
};

40
commands/refresh-cache.ts Normal file
View File

@@ -0,0 +1,40 @@
#!/usr/bin/env node
/**
* refresh-cache.ts - Azure DevOps Plugin Cache Refresh
*
* Clears and refreshes ADO sync cache to prevent stale data issues
*
* Usage:
* /specweave-ado:refresh-cache
*/
import { existsSync, unlinkSync, readdirSync } from 'fs';
import { join } from 'path';
export async function refreshAdoCache(projectRoot: string = process.cwd()): Promise<void> {
const cacheDir = join(projectRoot, '.specweave', 'cache', 'ado');
if (!existsSync(cacheDir)) {
console.log('✅ No ADO cache found');
return;
}
console.log('🧹 Clearing ADO cache...');
const files = readdirSync(cacheDir);
let cleared = 0;
for (const file of files) {
const filePath = join(cacheDir, file);
unlinkSync(filePath);
cleared++;
}
console.log(`✅ Cleared ${cleared} cache files`);
}
// CLI entry
if (require.main === module) {
refreshAdoCache().catch(console.error);
}

View File

@@ -0,0 +1,52 @@
---
name: specweave-ado:close-workitem
description: Close Azure DevOps work item when increment complete
---
# Close ADO Work Item Command
**Usage**: `/specweave-ado:close-workitem <increment-id>`
**Purpose**: Close ADO work item and add completion summary
---
## Command Behavior
When user runs this command, invoke `ado-manager` agent to:
1. Validate increment is 100% complete (all tasks done)
2. Generate completion summary
3. PATCH work item state → Closed
4. POST final comment with deliverables
5. Display confirmation
**Agent Invocation**:
```
Use Task tool with subagent_type: "specweave-ado:ado-manager:ado-manager"
Prompt: "Close ADO work item for completed increment 0005-payment-integration.
Steps:
1. Validate: All tasks in tasks.md complete
2. Generate: Completion summary (duration, deliverables)
3. Load work item ID from increment-metadata.json
4. PATCH work item: state = Closed
5. POST final comment with summary
6. Display: Closure confirmation"
```
---
## Example Output
```
✅ Closed ADO Epic #12345
Increment: 0005-payment-integration
Status: 100% complete (10/10 tasks)
Duration: 3 days
Summary posted to ADO work item
URL: https://dev.azure.com/myorg/MyProject/_workitems/edit/12345
```

View File

@@ -0,0 +1,53 @@
---
name: specweave-ado:create-workitem
description: Create Azure DevOps work item from SpecWeave increment
---
# Create ADO Work Item Command
**Usage**: `/specweave-ado:create-workitem <increment-id>`
**Purpose**: Create an Epic, Feature, or User Story in Azure DevOps from a SpecWeave increment
---
## Command Behavior
When user runs this command, Claude should:
1. **Validate Prerequisites**:
- Check ADO plugin installed
- Check AZURE_DEVOPS_PAT environment variable set
- Check ADO configured in .specweave/config.json
2. **Invoke ADO Manager Agent**:
```
Use Task tool with subagent_type: "specweave-ado:ado-manager:ado-manager"
Prompt: "Create ADO work item for increment 0005-payment-integration.
Steps:
1. Read .specweave/increments/0005-payment-integration/spec.md
2. Extract title and description
3. Load ADO config from .specweave/config.json
4. Create work item via ADO REST API
5. Store work item ID in increment-metadata.json
6. Display: Work Item ID, URL, and confirmation"
```
3. **Display Result**:
```
✅ Created ADO Epic
Work Item: #12345
URL: https://dev.azure.com/myorg/MyProject/_workitems/edit/12345
Linked to increment: 0005-payment-integration
```
---
## Example Usage
```
User: /specweave-ado:create-workitem 0005

View File

@@ -0,0 +1,358 @@
---
name: specweave-ado:import-areas
description: Import Azure DevOps area paths from a project and map them to SpecWeave projects. Creates 2-level directory structure with area path-based organization.
---
# Import ADO Area Paths Command
You are an Azure DevOps integration expert. Help the user import area paths from an ADO project and map them to SpecWeave projects.
## Command Usage
```bash
/specweave-ado:import-areas # Interactive mode (prompts for project)
/specweave-ado:import-areas --project MyProduct # Specific ADO project
/specweave-ado:import-areas --dry-run # Preview without creating directories
/specweave-ado:import-areas --include-children # Include child area paths
```
## Your Task
When the user runs this command:
### Step 1: Validate Prerequisites
1. **Check ADO credentials** exist in `.env`:
- `AZURE_DEVOPS_PAT`
- `AZURE_DEVOPS_ORG`
- `AZURE_DEVOPS_PROJECT`
2. **Check config.json** for existing area path mapping:
- If `sync.profiles.*.config.areaPathMapping` exists, warn user
### Step 2: Get Project Name
**If `--project` flag provided:**
- Use the provided project name
**If no flag (interactive mode):**
```
🔷 Azure DevOps Area Path Import
Enter the ADO project name to import area paths from:
> MyProduct
Fetching area paths from project MyProduct...
```
### Step 3: Fetch and Display Area Paths
```typescript
import { fetchAreaPathsForProject } from '../lib/ado-board-resolver';
const areaPaths = await fetchAreaPathsForProject(
process.env.AZURE_DEVOPS_ORG,
'MyProduct',
process.env.AZURE_DEVOPS_PAT
);
```
**Display area paths:**
```
Found 6 area paths in project MyProduct:
1. ☑ MyProduct\Frontend (45 active items)
2. ☑ MyProduct\Backend (78 active items)
3. ☑ MyProduct\Mobile (23 active items)
4. ☑ MyProduct\DevOps (12 active items)
5. ☐ MyProduct\Archive (0 items) [deselected - archive]
6. ☐ MyProduct (root) [deselected - root level]
Select area paths to import (Space to toggle, Enter to confirm)
```
### Step 4: Map Area Paths to SpecWeave Projects
For each selected area path, prompt for SpecWeave project ID:
```
🏷️ Mapping area paths to SpecWeave projects:
Area path "MyProduct\Frontend" → SpecWeave project ID: [fe]
→ Include child area paths? [Y/n]: y
→ Keywords for auto-classification (optional): frontend, ui, angular, css
Area path "MyProduct\Backend" → SpecWeave project ID: [be]
→ Include child area paths? [Y/n]: y
→ Keywords for auto-classification (optional): api, server, database, c#
Area path "MyProduct\Mobile" → SpecWeave project ID: [mobile]
→ Include child area paths? [Y/n]: y
→ Keywords for auto-classification (optional): ios, android, xamarin
Area path "MyProduct\DevOps" → SpecWeave project ID: [devops]
→ Include child area paths? [Y/n]: y
→ Keywords for auto-classification (optional): infrastructure, ci, cd, terraform
```
**Project ID validation:**
- Must be lowercase, alphanumeric with hyphens
- Must not collide with existing project IDs
- If collision detected, suggest prefixed version: `myproduct-fe` instead of `fe`
### Step 5: Create Directory Structure
Create 2-level directory structure:
```
.specweave/docs/internal/specs/
└── ADO-myproduct/ ← Level 1: ADO project
├── fe/ ← Level 2: SpecWeave project
│ └── .gitkeep
├── be/
│ └── .gitkeep
├── mobile/
│ └── .gitkeep
└── devops/
└── .gitkeep
```
### Step 6: Update config.json
Add area path mapping to config:
```json
{
"sync": {
"profiles": {
"ado-default": {
"provider": "ado",
"config": {
"organization": "myorg",
"areaPathMapping": {
"project": "MyProduct",
"mappings": [
{
"areaPath": "MyProduct\\Frontend",
"specweaveProject": "fe",
"includeChildren": true,
"keywords": ["frontend", "ui", "angular", "css"]
},
{
"areaPath": "MyProduct\\Backend",
"specweaveProject": "be",
"includeChildren": true,
"keywords": ["api", "server", "database", "c#"]
},
{
"areaPath": "MyProduct\\Mobile",
"specweaveProject": "mobile",
"includeChildren": true,
"keywords": ["ios", "android", "xamarin"]
},
{
"areaPath": "MyProduct\\DevOps",
"specweaveProject": "devops",
"includeChildren": true,
"keywords": ["infrastructure", "ci", "cd", "terraform"]
}
]
}
}
}
}
},
"multiProject": {
"enabled": true,
"activeProject": "fe",
"projects": {
"fe": {
"name": "Frontend",
"externalTools": {
"ado": {
"areaPath": "MyProduct\\Frontend",
"project": "MyProduct"
}
}
},
"be": {
"name": "Backend",
"externalTools": {
"ado": {
"areaPath": "MyProduct\\Backend",
"project": "MyProduct"
}
}
},
"mobile": {
"name": "Mobile",
"externalTools": {
"ado": {
"areaPath": "MyProduct\\Mobile",
"project": "MyProduct"
}
}
},
"devops": {
"name": "DevOps",
"externalTools": {
"ado": {
"areaPath": "MyProduct\\DevOps",
"project": "MyProduct"
}
}
}
}
}
}
```
### Step 7: Display Summary
```
✅ Azure DevOps Area Paths Import Complete!
🔷 ADO Project: MyProduct
📁 Created: .specweave/docs/internal/specs/ADO-myproduct/
Area paths imported:
✓ MyProduct\Frontend → fe (includes children)
Keywords: frontend, ui, angular, css
✓ MyProduct\Backend → be (includes children)
Keywords: api, server, database, c#
✓ MyProduct\Mobile → mobile (includes children)
Keywords: ios, android, xamarin
✓ MyProduct\DevOps → devops (includes children)
Keywords: infrastructure, ci, cd, terraform
💡 Next steps:
1. Use /specweave:switch-project fe to switch active project
2. Create increment: /specweave:increment "feature name"
3. User stories will auto-sync to the correct area path based on keywords
📖 Documentation: .specweave/docs/internal/architecture/adr/0143-jira-ado-multi-level-project-mapping.md
```
## Examples
### Example 1: Interactive Import
```
User: /specweave-ado:import-areas
You:
🔷 Azure DevOps Area Path Import
Enter the ADO project name: MyProduct
Fetching area paths...
Found 4 area paths:
☑ MyProduct\Frontend
☑ MyProduct\Backend
☑ MyProduct\Mobile
☐ MyProduct (root) [deselected]
Mapping to SpecWeave projects:
MyProduct\Frontend → fe
MyProduct\Backend → be
MyProduct\Mobile → mobile
✅ Import complete! 3 area paths mapped.
```
### Example 2: Dry Run
```
User: /specweave-ado:import-areas --project MyProduct --dry-run
You:
🔷 Azure DevOps Area Path Import (DRY RUN)
Would import from project: MyProduct
Would create:
.specweave/docs/internal/specs/ADO-myproduct/
.specweave/docs/internal/specs/ADO-myproduct/fe/
.specweave/docs/internal/specs/ADO-myproduct/be/
.specweave/docs/internal/specs/ADO-myproduct/mobile/
Would update config.json with area path mapping.
No changes made (dry run).
```
### Example 3: Already Configured
```
User: /specweave-ado:import-areas
You:
⚠️ Area path mapping already exists for project MyProduct
Current mappings:
MyProduct\Frontend → fe
MyProduct\Backend → be
Do you want to:
1. Add more area paths
2. Replace existing mapping
3. Cancel
> 1
Fetching additional area paths...
☐ MyProduct\Frontend (already mapped)
☐ MyProduct\Backend (already mapped)
☑ MyProduct\Mobile (new)
☑ MyProduct\DevOps (new)
Added:
MyProduct\Mobile → mobile
MyProduct\DevOps → devops
✅ Updated! Now 4 area paths mapped.
```
## Error Handling
**Missing credentials:**
```
❌ Azure DevOps credentials not found
Please add to .env:
AZURE_DEVOPS_PAT=your_personal_access_token
AZURE_DEVOPS_ORG=your_organization
AZURE_DEVOPS_PROJECT=your_project
Or run: specweave init . (to configure Azure DevOps)
```
**Project not found:**
```
❌ ADO project "INVALID" not found in organization "myorg"
Available projects you have access to:
- MyProduct (My Product Development)
- Infrastructure (DevOps & Infrastructure)
- Legacy (Legacy Systems)
Tip: Use /specweave-ado:import-areas --project MyProduct
```
**No area paths found:**
```
⚠️ No child area paths found in project MyProduct
The project only has the root area path. This means:
1. Teams aren't using area paths for organization
2. You can create area paths in ADO Project Settings
Suggestions:
- Use single-project mode (no area path mapping)
- Create area paths in ADO: Project Settings → Work → Areas
- Run this command again after creating area paths
```
## Related Commands
- `/specweave-ado:import-projects` - Import multiple ADO projects
- `/specweave-ado:sync` - Sync increments with ADO
- `/specweave:switch-project` - Switch active SpecWeave project
- `/specweave:init-multiproject` - Initialize multi-project mode

View File

@@ -0,0 +1,331 @@
---
name: specweave-ado:import-projects
description: Import additional Azure DevOps projects post-init with area path mapping, filtering, and dry-run preview
---
# Import Azure DevOps Projects Command
You are an Azure DevOps project import expert. Help users add additional ADO projects to their SpecWeave workspace after initial setup.
## Purpose
This command allows users to import additional Azure DevOps projects **after** initial SpecWeave setup (`specweave init`), with area path mapping, filtering, and dry-run preview.
**Use Cases**:
- Adding new ADO projects to existing workspace
- Importing projects from different organizations
- Selective import with area path granularity
- Multi-project organization (Backend, Frontend, Mobile, Infrastructure)
## Command Syntax
```bash
# Basic import (interactive)
/specweave-ado:import-projects
# With area path granularity
/specweave-ado:import-projects --granularity two-level
# Dry-run (preview)
/specweave-ado:import-projects --dry-run
# Resume interrupted import
/specweave-ado:import-projects --resume
# Combined
/specweave-ado:import-projects --granularity top-level --dry-run
```
## Your Task
When the user runs this command:
### Step 1: Validate Prerequisites
```typescript
import { readEnvFile, parseEnvFile } from '../../../src/utils/env-file.js';
// 1. Check if ADO credentials exist
const envContent = readEnvFile(process.cwd());
const parsed = parseEnvFile(envContent);
if (!parsed.AZURE_DEVOPS_PAT || !parsed.AZURE_DEVOPS_ORG) {
console.log('❌ Missing Azure DevOps credentials. Run `specweave init` first.');
return;
}
// 2. Get existing configuration
const org = parsed.AZURE_DEVOPS_ORG;
const existingProject = parsed.AZURE_DEVOPS_PROJECT;
console.log(`\n📋 Organization: ${org}`);
console.log(` Current project: ${existingProject || 'None'}\n`);
```
### Step 2: Fetch Available Projects
```typescript
import { getProjectCount } from '../../../src/cli/helpers/project-count-fetcher.js';
import { AsyncProjectLoader } from '../../../src/cli/helpers/async-project-loader.js';
// Count check (< 1 second)
const countResult = await getProjectCount({
provider: 'ado',
credentials: {
organization: org,
pat: parsed.AZURE_DEVOPS_PAT
}
});
console.log(`✓ Found ${countResult.accessible} accessible project(s)`);
// Fetch all projects (with smart pagination)
const loader = new AsyncProjectLoader(
{
organization: org,
pat: parsed.AZURE_DEVOPS_PAT
},
'ado',
{
batchSize: 50,
updateFrequency: 5,
showEta: true
}
);
const result = await loader.fetchAllProjects(countResult.accessible);
const allProjects = result.projects;
```
### Step 3: Area Path Mapping (Multi-Project Organization)
```typescript
import { AreaPathMapper } from '../../../src/integrations/ado/area-path-mapper.js';
const { selectedProject } = await inquirer.prompt([{
type: 'select',
name: 'selectedProject',
message: 'Select ADO project to import area paths from:',
choices: allProjects.map(p => ({ name: p.name, value: p.name }))
}]);
const mapper = new AreaPathMapper({
credentials: { organization: org, pat: parsed.AZURE_DEVOPS_PAT },
project: selectedProject
});
// Fetch area path tree
const areaPathTree = await mapper.fetchAreaPaths();
// Get granularity suggestion
const suggestion = mapper.suggestGranularity(areaPathTree);
console.log(`\n💡 Suggestion: ${suggestion.suggested}`);
console.log(` ${suggestion.reasoning}\n`);
// Prompt for granularity (if not provided via CLI)
const granularity = args.granularity || await mapper.promptAreaPathGranularity(areaPathTree);
// Flatten area paths with selected granularity
const areaPaths = mapper.flattenAreaPaths(areaPathTree, granularity);
console.log(`\n📊 ${areaPaths.length} project(s) will be created from area paths:\n`);
areaPaths.forEach(ap => {
const projectId = mapper.mapToProjectId(ap.path);
console.log(`${ap.path}${projectId}`);
});
```
### Step 4: Dry-Run or Execute
```typescript
if (args.dryRun) {
console.log('\n🔎 DRY RUN: No changes will be made.\n');
console.log('The following projects would be configured:');
areaPaths.forEach(ap => {
const projectId = mapper.mapToProjectId(ap.path);
console.log(`${projectId} (${ap.path})`);
});
console.log(`\nTotal: ${areaPaths.length} projects would be configured\n`);
return;
}
// Confirm import
const { confirmed } = await inquirer.prompt([{
type: 'confirm',
name: 'confirmed',
message: `Configure ${areaPaths.length} project(s) from area paths?`,
default: true
}]);
if (!confirmed) {
console.log('⏭️ Import cancelled.');
return;
}
```
### Step 5: Update Configuration
```typescript
import { getConfigManager } from '../../../src/core/config/index.js';
const configManager = getConfigManager(process.cwd());
// Build area path configuration
const areaPathConfig: Record<string, string[]> = {};
for (const ap of areaPaths) {
const projectId = mapper.mapToProjectId(ap.path);
areaPathConfig[projectId] = [ap.path];
}
// Update configuration
await configManager.update({
issueTracker: {
provider: 'ado',
ado: {
organization: org,
project: selectedProject,
areaPathMapping: areaPathConfig,
granularity
}
}
});
// Update .env file
import { updateEnvFile } from '../../../src/utils/env-manager.js';
await updateEnvFile('AZURE_DEVOPS_PROJECT', selectedProject);
// Write area paths to .env (comma-separated)
const areaPathList = areaPaths.map(ap => ap.path).join(',');
await updateEnvFile('AZURE_DEVOPS_AREA_PATHS', areaPathList);
console.log('\n✅ Projects configured successfully!\n');
console.log(`Organization: ${org}`);
console.log(`Project: ${selectedProject}`);
console.log(`Granularity: ${granularity}`);
console.log(`\nArea paths configured:\n ${areaPathList.split(',').join('\n ')}\n`);
```
### Step 6: Resume Support
```typescript
if (args.resume) {
const { CacheManager } = await import('../../../src/core/cache/cache-manager.js');
const cacheManager = new CacheManager(process.cwd());
const importState = await cacheManager.get('ado-import-state');
if (!importState) {
console.log('⚠️ No import state found. Use without --resume to start fresh.');
return;
}
console.log(`\n📂 Resuming from: ${importState.lastAreaPath} (${importState.completed}/${importState.total})`);
// Skip already-processed area paths
const remainingPaths = areaPaths.filter(ap => !importState.processed.includes(ap.path));
// Continue import with remaining paths
// (use same logic as Step 5)
}
```
## Examples
### Example 1: Basic Import with Area Paths
**User**: `/specweave-ado:import-projects`
**Output**:
```
📋 Organization: mycompany
Current project: Platform
✓ Found 5 accessible project(s)
Select ADO project to import area paths from:
> Platform
💡 Suggestion: two-level
Balanced hierarchy (8 two-level areas). Recommended granularity.
Select area path granularity for project organization:
> Two-level (8 projects) - e.g., Backend-API, Backend-Database
📊 8 project(s) will be created from area paths:
✨ Platform/Backend/API → backend-api
✨ Platform/Backend/Database → backend-database
✨ Platform/Frontend/Web → frontend-web
✨ Platform/Frontend/Admin → frontend-admin
✨ Platform/Mobile/iOS → mobile-ios
✨ Platform/Mobile/Android → mobile-android
✨ Platform/Infrastructure/Cloud → infrastructure-cloud
✨ Platform/Infrastructure/Network → infrastructure-network
Configure 8 project(s) from area paths? (Y/n)
✅ Projects configured successfully!
Organization: mycompany
Project: Platform
Granularity: two-level
Area paths configured:
Platform/Backend/API
Platform/Backend/Database
Platform/Frontend/Web
Platform/Frontend/Admin
Platform/Mobile/iOS
Platform/Mobile/Android
Platform/Infrastructure/Cloud
Platform/Infrastructure/Network
```
### Example 2: Top-Level Only
**User**: `/specweave-ado:import-projects --granularity top-level`
**Output**:
```
Select area path granularity: top-level (forced via CLI)
📊 3 project(s) will be created from area paths:
✨ Platform/Backend → backend
✨ Platform/Frontend → frontend
✨ Platform/Mobile → mobile
```
### Example 3: Dry-Run
**User**: `/specweave-ado:import-projects --dry-run`
**Output**:
```
🔎 DRY RUN: No changes will be made.
The following projects would be configured:
✨ backend-api (Platform/Backend/API)
✨ backend-database (Platform/Backend/Database)
✨ frontend-web (Platform/Frontend/Web)
Total: 8 projects would be configured
```
## Important Notes
- **Multi-Project Organization**: Uses area paths to create logical project separation
- **Granularity Control**: Top-level, two-level, or full-tree based on hierarchy complexity
- **Atomic Updates**: Uses temp file + rename to prevent corruption
- **Progress Tracking**: Shows progress bar for large hierarchies (> 50 area paths)
- **Resume Support**: Interrupted imports can be resumed with `--resume`
## Related Commands
- `/specweave:init` - Initial SpecWeave setup
- `/specweave-ado:sync` - Sync increments with ADO work items
- `/specweave-ado:refresh-cache` - Clear cached ADO data
## Error Handling
- **Missing Credentials**: Prompt user to run `specweave init` first
- **API Errors**: Show clear error message with suggestion
- **No Area Paths**: Fallback to single-project mode
- **Permission Errors**: Check ADO PAT scopes
---
**Multi-Project Excellence**: This command enables sophisticated multi-project organization in Azure DevOps using area paths, perfect for large teams with complex hierarchies.

View File

@@ -0,0 +1,53 @@
---
name: specweave-ado:status
description: Check Azure DevOps sync status for increment
---
# ADO Status Command
**Usage**: `/specweave-ado:status <increment-id>`
**Purpose**: Display ADO sync status and work item details
---
## Command Behavior
When user runs this command, invoke `ado-manager` agent to:
1. Read increment-metadata.json
2. Fetch work item from ADO API
3. Display: ID, URL, state, completion %, last sync time
4. Check for sync issues
**Agent Invocation**:
```
Use Task tool with subagent_type: "specweave-ado:ado-manager:ado-manager"
Prompt: "Check ADO sync status for increment 0005-payment-integration.
Steps:
1. Read increment-metadata.json
2. Extract: work item ID, last sync time
3. GET work item from ADO API
4. Display status information
5. Check for any sync issues"
```
---
## Example Output
```
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 (5 minutes ago)
Sync Enabled: ✅
Next Sync: Automatic on task completion
```

View File

@@ -0,0 +1,148 @@
---
name: specweave-ado:sync
description: Two-way sync between SpecWeave increment and Azure DevOps work item (push & pull by default)
---
# Sync ADO Work Item Command
**Usage**: `/specweave-ado:sync <increment-id> [options]`
**Purpose**: Two-way synchronization between SpecWeave increment and Azure DevOps work item
**Default**: Two-way sync (push & pull)
---
## Options
- `--direction <mode>`: Sync direction (default: `two-way`)
- `two-way`: SpecWeave ↔ ADO (default - recommended)
- `to-ado`: SpecWeave → ADO only (push progress)
- `from-ado`: ADO → SpecWeave only (pull updates)
## Examples
```bash
# Two-way sync (default - both directions)
/specweave-ado:sync 0005
# Push only (one-way to ADO)
/specweave-ado:sync 0005 --direction to-ado
# Pull only (one-way from ADO)
/specweave-ado:sync 0005 --direction from-ado
```
---
## Command Behavior
When user runs this command, invoke `ado-manager` agent to perform two-way sync:
### Phase 1: Pull FROM ADO (default behavior)
1. Fetch work item state from ADO API
2. Detect changes in ADO:
- State changes (New → Active → Resolved → Closed)
- Priority changes
- Iteration/sprint changes
- Comments from team members
- Field updates
3. Apply ADO changes to SpecWeave increment:
- Update increment status to match ADO state
- Update priority in metadata
- Import team comments to increment notes
- Update iteration tracking
### Phase 2: Push TO ADO (default behavior)
1. Read tasks.md from increment
2. Calculate completion percentage
3. Identify recently completed tasks
4. Format progress update comment
5. POST comment to ADO work item
6. Update work item state if needed (New → Active → Resolved)
7. Update custom fields (completion %, current task, etc.)
**Agent Invocation**:
```
Use Task tool with subagent_type: "specweave-ado:ado-manager:ado-manager"
Prompt: "Two-way sync for increment 0005-payment-integration with ADO.
Phase 1 - Pull FROM ADO:
1. Fetch work item #12345 from ADO API
2. Detect changes: state, priority, iteration, comments
3. Apply ADO changes to increment metadata
4. Import team comments to increment notes
Phase 2 - Push TO ADO:
1. Read .specweave/increments/0005/tasks.md
2. Calculate: X/Y tasks complete (Z%)
3. Identify: Recently completed tasks
4. Format comment with progress update
5. Load work item ID from increment-metadata.json
6. POST comment to ADO API
7. Update work item state/fields
Display: Two-way sync summary"
```
---
## Example Output
### Two-way Sync (Default)
```
🔄 Two-way sync for increment 0005...
✓ Azure DevOps work item: #12345
✓ Sync direction: Two-way (push & pull)
Detecting changes (both directions)...
FROM ADO:
✓ Work item state changed: Active → Resolved
✓ Iteration updated: Sprint 23 → Sprint 24
✓ Priority changed: 2 → 1
✓ 3 new comments from team
FROM SpecWeave:
✓ 2 new tasks completed (T-005, T-006)
✓ Progress: 40% → 60% (6/10 tasks)
✓ Current task: T-007
Syncing TO ADO...
✓ Posted progress comment (ID: 98765)
✓ Updated completion: 60%
✓ Updated current task field: T-007
Syncing FROM ADO...
✓ Updated increment status: active → completed
✓ Updated priority: P2 → P1
✓ Updated iteration tracking: Sprint 24
✓ Imported 3 team comments to increment notes
✅ Bidirectional Sync Complete!
SpecWeave ↔ ADO synchronized
• Pushed: Progress (60%), 2 task updates
• Pulled: State (Resolved), priority (P1), iteration, 3 comments
ADO Work Item: https://dev.azure.com/myorg/MyProject/_workitems/edit/12345
Last synced: just now
Next sync: Automatic (hook-based) or manual when ready
```
### One-Way Sync (to-ado)
```
✅ Pushed to ADO Work Item #12345
Progress: 60% complete (6/10 tasks)
Recently Completed:
- T-005: Add payment tests
- T-006: Update documentation
URL: https://dev.azure.com/myorg/MyProject/_workitems/edit/12345
```