---
description: Refine and improve existing tasks with expansion, architectural review, and QA enhancement
argument-hint: <id> ["refinement hints"] [--expand] [--qa] [--architecture] [--research]
allowed-tools: mcp__task_master_ai__*, Read, Grep, Glob
---

# Task Refine: $ARGUMENTS

Intelligently refine and improve existing Task Master tasks through expansion, architectural review, and QA enhancement.

**Reference:** See [~/.claude/guides/agents.task-master.md](../../guides/agents.task-master.md) for Task Master integration details.

## Workflow Summary

This command:

1. **Parse arguments** - Extract task ID and refinement hints
2. **Analyze current state** - Check if task is expanded, assess quality
3. **Determine refinement needs** - Expansion, architecture review, QA improvements
4. **Apply refinements** - Execute improvements with operator confirmation
5. **Validate results** - Ensure refinements improve task quality
6. **Present summary** - Show before/after comparison

## Phase 1: Parse Arguments and Validate Task

### 1.1 Parse Arguments

```javascript
// Parse $ARGUMENTS
const args = $ARGUMENTS.trim();

// Extract task ID and refinement hints
let taskId = null;
let refinementHints = null;
let options = {
  expand: false, // --expand flag
  qa: false, // --qa flag
  architecture: false, // --architecture flag
  research: true, // --research flag (default true)
};

// Parse arguments
const parts = args.split(/\s+/);
taskId = parts[0];

// Check for flags
if (args.includes('--expand')) options.expand = true;
if (args.includes('--qa')) options.qa = true;
if (args.includes('--architecture')) options.architecture = true;
if (args.includes('--no-research')) options.research = false;

// Extract refinement hints (quoted text)
const hintsMatch = args.match(/"([^"]+)"/);
if (hintsMatch) {
  refinementHints = hintsMatch[1];
}
```

**Argument validation:**

```javascript
if (!taskId) {
  console.log('## ❌ Missing Task ID\n');
  console.log('**Usage:** `/task:refine <id> ["hints"]`\n');
  console.log('**Examples:**');
  console.log('  /task:refine 25');
  console.log('  /task:refine 25 "Add security considerations"');
  console.log('  /task:refine 25 --expand --qa');
  console.log('  /task:refine 31 --architecture --research');
  return;
}

// Validate task ID format
if (!taskId.match(/^\d+(\.\d+)?$/)) {
  console.log(`## ❌ Invalid Task ID: ${taskId}\n`);
  console.log('**Expected:** Numeric ID (e.g., "25" or "25.3")\n');
  return;
}
```

### 1.2 Fetch Task Details

```javascript
// Get task details with subtasks
const task = mcp__task_master_ai__get_task({
  projectRoot: process.cwd(),
  id: taskId,
});

if (!task) {
  console.log(`## ❌ Task Not Found: ${taskId}\n`);
  console.log('**Available tasks:**');

  const allTasks = mcp__task_master_ai__get_tasks({
    projectRoot: process.cwd(),
    withSubtasks: false,
  });

  allTasks.slice(0, 10).forEach((t) => {
    console.log(`- [${t.id}] ${t.title} (${t.status})`);
  });

  console.log('\n**View all:** `/task:status`');
  return;
}
```

### 1.3 Present Current Task State

```bash
## 🔍 Task Analysis: [${taskId}] ${task.title}

**Status:** ${task.status}
**Priority:** ${task.priority || 'medium'}
**Complexity:** ${task.complexity || 'not analyzed'}

**Current State:**
- Description: ${task.description ? '✅' : '❌ Missing'}
- Details: ${task.details ? '✅' : '❌ Missing'}
- Test Strategy: ${task.testStrategy ? '✅' : '❌ Missing'}
- Subtasks: ${task.subtasks?.length || 0} subtasks
- Dependencies: ${task.dependencies?.length || 0} dependencies

**Refinement Hints Provided:** ${refinementHints || 'None'}
```

## Phase 2: Assess Refinement Needs

### 2.1 Check if Task Needs Expansion

```javascript
// Determine if task should be expanded
const needsExpansion = {
  noSubtasks: !task.subtasks || task.subtasks.length === 0,
  highComplexity: task.complexity && task.complexity > 5,
  detailsLong: task.details && task.details.length > 1000,
  multiplePhases: task.description && task.description.match(/\d+\.\s/g)?.length > 3,
  explicitRequest:
    options.expand || (refinementHints && refinementHints.toLowerCase().includes('expand')),
};

const shouldExpand = Object.values(needsExpansion).some((v) => v);
```

**Present expansion assessment:**

```bash
## 📊 Expansion Assessment

**Indicators:**
- ${needsExpansion.noSubtasks ? '⚠️' : '✅'} No subtasks defined (${task.subtasks?.length || 0} subtasks)
- ${needsExpansion.highComplexity ? '⚠️' : '✅'} Complexity score: ${task.complexity || 'not assessed'}
- ${needsExpansion.detailsLong ? '⚠️' : '✅'} Details length: ${task.details?.length || 0} characters
- ${needsExpansion.multiplePhases ? '⚠️' : '✅'} Multiple implementation phases detected
- ${needsExpansion.explicitRequest ? '⚠️' : '✅'} Explicit expansion request

**Recommendation:** ${shouldExpand ? 'Expand into subtasks' : 'Expansion not needed'}
```

### 2.2 Check Repository Context

**Read repository guidelines:**

```javascript
// Check for docs/QA.md
let qaGuidelines = null;
try {
  qaGuidelines = await Read({ file_path: 'docs/QA.md' });
} catch {
  // QA.md not found
}

// Check for CLAUDE.md or similar architecture docs
let architectureGuidelines = null;
try {
  architectureGuidelines = await Read({ file_path: 'CLAUDE.md' });
} catch {
  try {
    architectureGuidelines = await Read({ file_path: 'docs/ARCHITECTURE.md' });
  } catch {
    // No architecture docs found
  }
}

// Check for docs/guides/
const guideFiles = await Glob({ pattern: 'docs/guides/*.md' });
```

**Present repository context:**

```bash
## 📚 Repository Context Available

**Quality Assurance:**
- ${qaGuidelines ? '✅' : '❌'} docs/QA.md (${qaGuidelines ? qaGuidelines.length + ' chars' : 'not found'})

**Architecture Standards:**
- ${architectureGuidelines ? '✅' : '❌'} Project guidelines (${architectureGuidelines ? 'CLAUDE.md' : 'not found'})
- ${guideFiles.length > 0 ? '✅' : '❌'} Development guides (${guideFiles.length} files)

**Available Refinements:**
1. ${shouldExpand ? '✅' : '⊘'} Expand task into subtasks
2. ${architectureGuidelines ? '✅' : '⊘'} Assess architectural standards
3. ${qaGuidelines ? '✅' : '⊘'} Enhance QA/testing strategy
```

### 2.3 Determine Refinement Actions

**If no specific flags provided, ask operator:**

```bash
## 🎯 Refinement Options

**Available improvements for task [${taskId}]:**

${shouldExpand ? `
1. **Expand into subtasks** - Break down complex task for easier implementation
   - Estimated subtasks: ${estimateSubtaskCount(task)}
   - Research mode: ${options.research ? 'Enabled' : 'Disabled'}
` : ''}

${architectureGuidelines ? `
2. **Assess architectural standards** - Review against project guidelines
   - Compare with: CLAUDE.md patterns
   - Ensure: TypeScript conventions, error handling, testing practices
   - Validate: Integration points, security considerations
` : ''}

${qaGuidelines ? `
3. **Enhance QA strategy** - Improve test coverage and validation
   - Align with: docs/QA.md requirements
   - Add: Test scenarios, edge cases, integration tests
   - Specify: Coverage targets, validation steps
` : ''}

**Which refinements should be applied?**
- All: Apply all available refinements
- Specific: Choose 1, 2, 3 (comma-separated)
- Cancel: Exit without changes
```

**Wait for operator input.**

**Process operator selection:**

```javascript
// Update options based on selection
if (selection === 'all') {
  options.expand = shouldExpand;
  options.architecture = !!architectureGuidelines;
  options.qa = !!qaGuidelines;
} else if (selection.match(/\d/)) {
  const choices = selection.split(',').map((s) => s.trim());
  options.expand = choices.includes('1') && shouldExpand;
  options.architecture = choices.includes('2') && !!architectureGuidelines;
  options.qa = choices.includes('3') && !!qaGuidelines;
}
```

## Phase 3: Apply Refinements

### 3.1 Expand Task (if needed)

**If options.expand:**

```bash
## 🔄 Expanding Task into Subtasks

**Task:** [${taskId}] ${task.title}
**Complexity:** ${task.complexity || 'Analyzing...'}

${refinementHints ? `**Refinement Hints:** ${refinementHints}` : ''}

**Analyzing task to determine optimal subtask count...**
```

**Determine subtask count:**

```javascript
// Estimate subtask count based on complexity
let numSubtasks = 5; // Default

if (task.complexity) {
  numSubtasks = Math.min(Math.max(task.complexity, 4), 12);
} else {
  // Run quick complexity analysis
  const analysis = mcp__task_master_ai__analyze_project_complexity({
    projectRoot: process.cwd(),
    ids: taskId,
    research: options.research,
    threshold: 5,
  });

  numSubtasks = analysis.recommendedSubtasks || 5;
}
```

**Execute expansion:**

```javascript
mcp__task_master_ai__expand_task({
  projectRoot: process.cwd(),
  id: taskId,
  num: numSubtasks.toString(),
  research: options.research,
  prompt: refinementHints || 'Break down task following project patterns and best practices',
});

console.log('## ✅ Task Expansion Complete\n');
console.log(`**Generated:** ${numSubtasks} subtasks`);
console.log(`**Research Mode:** ${options.research ? 'Enabled' : 'Disabled'}`);
```

### 3.2 Assess Architectural Standards

**If options.architecture:**

```bash
## 🏗️ Assessing Architectural Standards

**Reviewing task against project guidelines...**

**Context:**
- Project: ${extractProjectName(architectureGuidelines)}
- Tech Stack: ${extractTechStack(architectureGuidelines)}
- Patterns: ${extractPatterns(architectureGuidelines)}
```

**Build architectural context:**

```javascript
// Extract key architectural requirements
const architecturalContext = `
Task: ${task.title}

Current Description:
${task.description}

Current Details:
${task.details}

Project Guidelines Summary:
${extractArchitecturalRequirements(architectureGuidelines)}

Refinement Hints: ${refinementHints || 'Ensure task follows project patterns'}

Review this task implementation against the project's architectural standards.
Focus on:
1. Technology stack alignment (${extractTechStack(architectureGuidelines)})
2. Code organization patterns (${extractPatterns(architectureGuidelines)})
3. Error handling requirements
4. Security considerations
5. Integration points with existing systems
6. Cross-platform compatibility if relevant

Provide updated task details that incorporate these architectural standards.
Do not change the core task objective, only enhance implementation details.
`;
```

**Execute architectural review:**

```javascript
mcp__task_master_ai__update_task({
  projectRoot: process.cwd(),
  id: taskId,
  prompt: architecturalContext,
  research: options.research,
});

console.log('## ✅ Architectural Review Complete\n');
console.log('**Enhanced:**');
console.log('- Implementation details aligned with project patterns');
console.log('- Security and error handling considerations added');
console.log('- Integration points validated');
```

### 3.3 Enhance QA Strategy

**If options.qa:**

```bash
## 🧪 Enhancing QA Strategy

**Reviewing test strategy against project standards...**

**QA Guidelines:**
${summarizeQAGuidelines(qaGuidelines)}
```

**Build QA enhancement context:**

```javascript
// Extract QA requirements
const qaContext = `
Task: ${task.title}

Current Test Strategy:
${task.testStrategy || 'Not defined'}

Current Implementation Details:
${task.details}

Project QA Guidelines:
${qaGuidelines}

Refinement Hints: ${refinementHints || 'Enhance test coverage and validation'}

Enhance the test strategy for this task following the project's QA guidelines.
Include:
1. Unit test requirements with specific scenarios
2. Integration test needs
3. Edge cases and error scenarios
4. Coverage targets (minimum 80% as per project standards)
5. Validation steps for completion
6. Test data requirements if applicable

Provide a comprehensive test strategy that aligns with docs/QA.md.
Update both the testStrategy field and add testing details to the implementation.
`;
```

**Execute QA enhancement:**

```javascript
mcp__task_master_ai__update_task({
  projectRoot: process.cwd(),
  id: taskId,
  prompt: qaContext,
  research: options.research,
});

console.log('## ✅ QA Enhancement Complete\n');
console.log('**Added:**');
console.log('- Comprehensive test strategy');
console.log('- Edge case scenarios');
console.log('- Coverage targets');
console.log('- Validation steps');
```

## Phase 4: Validate Results

### 4.1 Fetch Refined Task

```javascript
// Get updated task details
const refinedTask = mcp__task_master_ai__get_task({
  projectRoot: process.cwd(),
  id: taskId,
});
```

### 4.2 Compare Before/After

```bash
## 📊 Refinement Results

### Before Refinement

**Description:** ${task.description?.substring(0, 100)}...
**Details:** ${task.details?.length || 0} characters
**Test Strategy:** ${task.testStrategy?.length || 0} characters
**Subtasks:** ${task.subtasks?.length || 0}

### After Refinement

**Description:** ${refinedTask.description?.substring(0, 100)}...
**Details:** ${refinedTask.details?.length || 0} characters
**Test Strategy:** ${refinedTask.testStrategy?.length || 0} characters
**Subtasks:** ${refinedTask.subtasks?.length || 0}

### Improvements Applied

${options.expand ? `
- ✅ **Expanded into subtasks** (${refinedTask.subtasks?.length || 0} subtasks)
  ${refinedTask.subtasks?.slice(0, 3).map(st => `  - ${st.title}`).join('\n') || ''}
  ${refinedTask.subtasks?.length > 3 ? `  ... and ${refinedTask.subtasks.length - 3} more` : ''}
` : ''}

${options.architecture ? `
- ✅ **Architectural review applied**
  - Implementation details enhanced
  - Project patterns incorporated
  - Security considerations added
` : ''}

${options.qa ? `
- ✅ **QA strategy enhanced**
  - Test scenarios defined
  - Edge cases identified
  - Coverage targets specified
` : ''}
```

### 4.3 Validate Quality Improvements

```javascript
// Quality metrics
const improvements = {
  detailsExpanded: refinedTask.details?.length > (task.details?.length || 0),
  testStrategyEnhanced: refinedTask.testStrategy?.length > (task.testStrategy?.length || 0),
  subtasksAdded: (refinedTask.subtasks?.length || 0) > (task.subtasks?.length || 0),
  complexityAssessed: !!refinedTask.complexity,
};

const improvementCount = Object.values(improvements).filter((v) => v).length;
const improvementPercentage = (improvementCount / 4) * 100;
```

**Present quality assessment:**

```bash
## ✅ Quality Improvement Score: ${improvementPercentage}%

**Metrics:**
- ${improvements.detailsExpanded ? '✅' : '⊘'} Implementation details expanded
- ${improvements.testStrategyEnhanced ? '✅' : '⊘'} Test strategy enhanced
- ${improvements.subtasksAdded ? '✅' : '⊘'} Subtasks added for breakdown
- ${improvements.complexityAssessed ? '✅' : '⊘'} Complexity assessed

**Task is now:** ${improvementPercentage >= 75 ? 'Well-defined and ready for implementation' : 'Improved but may need additional refinement'}
```

## Phase 5: Present Next Steps

### 5.1 Show Task Details

```bash
## 📋 Refined Task Details

**To view complete task:**
\`\`\`bash
/task show ${taskId}
\`\`\`

**To start working:**
\`\`\`bash
/task:next
\`\`\`

**To further refine:**
\`\`\`bash
/task:refine ${taskId} "additional hints"
\`\`\`
```

### 5.2 Recommend Next Actions

```javascript
// Determine recommended next actions
let recommendations = [];

if (refinedTask.subtasks?.length > 0) {
  recommendations.push('Review subtasks and start with first one');
  recommendations.push(`/task show ${taskId}.1`);
}

if (refinedTask.status === 'pending') {
  recommendations.push('Mark as in-progress when ready to start');
  recommendations.push(
    `mcp__task_master_ai__set_task_status({ id: "${taskId}", status: "in-progress" })`
  );
}

if (refinedTask.dependencies?.length > 0) {
  recommendations.push('Check dependency status before starting');
  refinedTask.dependencies.forEach((dep) => {
    recommendations.push(`/task show ${dep}`);
  });
}
```

**Present recommendations:**

```bash
## 🎯 Recommended Next Actions

${recommendations.map((rec, i) => `${i + 1}. ${rec}`).join('\n')}

**Project Context:**
- Total tasks: ${allTasks.length}
- Completed: ${completedCount}
- In progress: ${inProgressCount}
- Next available: ${nextTaskId}
```

## Examples

### Expand a task without subtasks

```bash
/task:refine 25
# Will analyze and suggest expansion
```

### Expand with specific guidance

```bash
/task:refine 25 "Focus on security and error handling"
```

### Apply all refinements

```bash
/task:refine 31 --expand --qa --architecture
```

### Quick architectural review only

```bash
/task:refine 15 --architecture
```

### QA enhancement without research (faster)

```bash
/task:refine 20 --qa --no-research
```

## Error Handling

### Task Already Well-Defined

```bash
## ℹ️ Task Already Well-Defined

**Task [${taskId}]** appears to be comprehensively defined:
- ${task.subtasks?.length || 0} subtasks
- ${task.details?.length || 0} characters of implementation details
- ${task.testStrategy?.length || 0} characters of test strategy

**Options:**
1. Proceed with refinement anyway
2. Cancel - task is ready for implementation
3. Review task: `/task show ${taskId}`

**Proceed? (y/N)**
```

### No Repository Guidelines Found

```bash
## ⚠️ Limited Repository Context

**Missing:**
- ❌ docs/QA.md - No QA guidelines available
- ❌ CLAUDE.md/ARCHITECTURE.md - No architecture docs

**Available refinements:**
- ✅ Task expansion (based on complexity)
- ❌ Architectural review (no guidelines)
- ❌ QA enhancement (no guidelines)

**Recommendation:** Focus on task expansion only.

**Continue? (y/N)**
```

### Research Mode Unavailable

```bash
## ⚠️ Research Mode Unavailable

**Issue:** No API key configured for research mode.

**Impact:**
- Refinements will use standard mode (less comprehensive)
- May miss industry best practices
- Faster execution (10-15s vs 30-60s)

**Configure research:**
- Set PERPLEXITY_API_KEY for research capabilities
- Or continue without research: already using --no-research

**Continue with standard mode? (y/N)**
```

## Integration with Other Commands

**Complete refinement workflow:**

```bash
# 1. Identify task needing refinement
/task:status

# 2. Review current state
/task show 25

# 3. Apply refinements
/task:refine 25 --expand --qa

# 4. Start working
/task:next

# 5. Complete task
/task:complete 25
```

## Important Notes

- **Always use research mode** for production work unless time-constrained
- **Iterative refinement** - You can refine multiple times as understanding evolves
- **Respect operator intent** - Use refinement hints to guide improvements
- **Context-aware** - Leverages repository docs (QA.md, CLAUDE.md, guides/)
- **Safe operation** - Updates are additive, original task context preserved
- **Quality-focused** - Ensures tasks are implementation-ready

## Critical Thinking Checklist

Before applying refinements:

- [ ] **Necessity:** Does this task actually need refinement?
- [ ] **Current Quality:** What's the current definition quality?
- [ ] **Repository Context:** Are guidelines available to reference?
- [ ] **Scope Preservation:** Will refinement change task objective?
- [ ] **Test Coverage:** Is test strategy comprehensive enough?
- [ ] **Architecture Alignment:** Does task follow project patterns?
- [ ] **Subtask Balance:** Are subtasks appropriately sized?

---

**For comprehensive Task Master documentation:**

See [guides/agents.task-master.md](~/.claude/guides/agents.task-master.md)
