---
description: Add new task with AI-powered validation and research
argument-hint: [path/to/file.md|"task description"]
allowed-tools: mcp__task_master_ai__*, Read, Grep, Glob
---

# Add Task: $ARGUMENTS

Intelligently add a new task to Task Master with critical validation, priority assessment, and research-backed recommendations.

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

## Workflow Summary

This command:

1. **Parse input** - Extract task context from file, text, or conversation history
2. **Validate necessity** - Critically assess if task is needed and beneficial
3. **Assess priority** - Determine appropriate priority level
4. **Verify completeness** - Ensure sufficient information and test/QA details
5. **Add with research** - Use Task Master MCP with research mode enabled
6. **Recommend next steps** - Suggest expansion or immediate start

## Phase 1: Parse Arguments and Extract Context

### 1.1 Determine Input Source

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

if (!args) {
  // No arguments - use recent conversation history
  inputSource = 'conversation';
  console.log('ℹ️ No input provided - analyzing recent conversation history...\n');
} else if (args.match(/\.(md|txt)$/)) {
  // File path provided
  inputSource = 'file';
  filePath = args;
} else {
  // Text description provided
  inputSource = 'text';
  taskDescription = args;
}
```

### 1.2 Extract Task Context

**From File:**

```javascript
// Read file contents
const fileContents = Read({ file_path: filePath });

// Extract structured information
taskContext = {
  source: 'file',
  path: filePath,
  contents: fileContents,
};
```

**From Text:**

```javascript
taskContext = {
  source: 'text',
  description: taskDescription,
};
```

**From Conversation History:**

```javascript
// Analyze recent conversation (last 10-20 messages)
// Look for feature discussions, requirements, or action items

taskContext = {
  source: 'conversation',
  recentTopics: [
    // Extract discussed features/improvements
  ],
  actionItems: [
    // Extract mentioned action items
  ],
};

// Present findings to user for confirmation
console.log('## 📋 Recent Conversation Analysis\n');
console.log('**Topics discussed:**');
recentTopics.forEach((topic, i) => {
  console.log(`${i + 1}. ${topic}`);
});

console.log('\n**Which topic should become a task?**');
console.log('Enter number or provide description:');
// Wait for user input
```

## Phase 2: Critical Validation

**Think critically before proceeding - apply rigorous analysis:**

### 2.1 Assess Task Necessity

**Ask critical questions:**

1. **Is this task actually needed?**
   - Does it solve a real problem?
   - Is there a workaround that's sufficient?
   - Does it align with project goals?

2. **Does it duplicate existing work?**
   - Search existing tasks for similar functionality
   - Check if already implemented
   - Verify not in current backlog

```javascript
// Search for similar tasks
const existingTasks = mcp__task_master_ai__get_tasks({
  projectRoot: process.cwd(),
  withSubtasks: false,
});

// Check for duplicates or related work
const similarTasks = existingTasks.filter((task) => {
  // Compare task titles and descriptions
  // Look for keyword overlap
});

if (similarTasks.length > 0) {
  console.log('## ⚠️ Similar Tasks Found\n');
  similarTasks.forEach((task) => {
    console.log(`- [${task.id}] ${task.title} (${task.status})`);
  });
  console.log('\n**Continue adding new task? (y/N)**');
  // Wait for confirmation
}
```

### 2.2 Evaluate Information Completeness

**Check if we have sufficient information:**

```javascript
const completeness = {
  problem: false, // Clear problem statement?
  solution: false, // Proposed solution approach?
  acceptance: false, // Clear acceptance criteria?
  testing: false, // Test strategy defined?
  priority: false, // Priority level justified?
};

// Analyze task context for each dimension
// Set flags based on information availability

const completenessScore = Object.values(completeness).filter((v) => v).length;
const completenessPercentage = (completenessScore / 5) * 100;

console.log('## 📊 Information Completeness Assessment\n');
console.log(`**Score:** ${completenessPercentage}% (${completenessScore}/5)\n`);
console.log(`- ${completeness.problem ? '✅' : '❌'} Problem statement`);
console.log(`- ${completeness.solution ? '✅' : '❌'} Solution approach`);
console.log(`- ${completeness.acceptance ? '✅' : '❌'} Acceptance criteria`);
console.log(`- ${completeness.testing ? '✅' : '❌'} Test strategy`);
console.log(`- ${completeness.priority ? '✅' : '❌'} Priority justification`);

if (completenessPercentage < 60) {
  console.log('\n⚠️ **Low completeness score**');
  console.log('Consider gathering more information before adding task.');
  console.log('\n**Continue anyway? (y/N)**');
  // Wait for confirmation
}
```

### 2.3 Determine Appropriate Priority

**Critical priority assessment:**

```javascript
// Analyze priority factors
const priorityFactors = {
  // Impact
  affectsUsers: false, // User-facing impact?
  blocksOtherWork: false, // Blocking other tasks?
  securityCritical: false, // Security implications?

  // Urgency
  hasDeadline: false, // Time constraint?
  customerRequest: false, // Customer demand?

  // Effort
  quickWin: false, // Can be done quickly?
  complexityHigh: false, // High complexity?
};

// Calculate suggested priority
let suggestedPriority = 'medium';

if (priorityFactors.securityCritical || priorityFactors.blocksOtherWork) {
  suggestedPriority = 'high';
} else if (
  priorityFactors.quickWin &&
  (priorityFactors.affectsUsers || priorityFactors.customerRequest)
) {
  suggestedPriority = 'high';
} else if (!priorityFactors.affectsUsers && !priorityFactors.hasDeadline) {
  suggestedPriority = 'low';
}

console.log('## 🎯 Priority Assessment\n');
console.log(`**Suggested Priority:** ${suggestedPriority}\n`);
console.log('**Rationale:**');
// Explain priority reasoning based on factors
```

## Phase 3: Gather Additional Context (Research Mode)

**Use research to enhance task quality:**

```javascript
// If task relates to specific technologies or patterns
// Use research to gather best practices and considerations

if (taskRequiresResearch) {
  console.log('## 🔍 Gathering Research Context\n');
  console.log('Researching best practices and implementation considerations...\n');

  // Example research queries based on task content
  const researchQueries = [
    // Extract technical terms from task description
    // Form research queries
  ];

  // Perform research if PERPLEXITY_API_KEY available
  // Enrich task details with findings
}
```

## Phase 4: Add Task with Task Master MCP

### 4.1 Prepare Task Data

```javascript
// Build task prompt from gathered information
const taskPrompt = `
${taskContext.description || taskContext.contents}

Priority: ${suggestedPriority}

${researchFindings ? `Research Context:\n${researchFindings}` : ''}
`.trim();
```

### 4.2 Add Task with Research

```javascript
// Add task using Task Master MCP
const result = mcp__task_master_ai__add_task({
  projectRoot: process.cwd(),
  prompt: taskPrompt,
  priority: suggestedPriority,
  research: true, // ALWAYS enable research for better task quality
});

console.log('## ✅ Task Added Successfully\n');
console.log(`**Task ID:** [${result.id}]`);
console.log(`**Title:** ${result.title}`);
console.log(`**Priority:** ${result.priority}`);
```

## Phase 5: Recommend Next Steps

### 5.1 Analyze Task Complexity

```javascript
// Quick complexity assessment
const complexityIndicators = {
  hasMultipleSteps: false,
  requiresResearch: false,
  hasIntegrations: false,
  affectsMultipleComponents: false,
};

const shouldExpand = Object.values(complexityIndicators).filter((v) => v).length >= 2;
```

### 5.2 Present Recommendations

```markdown
## 📈 Next Steps

${shouldExpand ? `
**Recommendation: Expand task into subtasks**

This task appears complex and would benefit from breakdown.

\`\`\`bash
/task:next --refine

# or

mcp**task_master_ai**expand_task({
projectRoot: process.cwd(),
id: "${result.id}",
num: "5",
research: true
})
\`\`\`
`:`
**Recommendation: Task is ready to start**

This task appears well-scoped for immediate implementation.

\`\`\`bash
/task:next

# or

/task show ${result.id}
\`\`\`
`}

### Task Details

\`\`\`bash
/task show ${result.id}
\`\`\`

### View All Tasks

\`\`\`bash
/task
\`\`\`
```

## Examples

### Add task from file

```bash
/task:add .taskmaster/docs/feature-request.md
```

### Add task from description

```bash
/task:add "Implement user authentication with JWT tokens"
```

### Add task from conversation

```bash
# After discussing a feature
/task:add
# Will analyze recent conversation and prompt for confirmation
```

## Critical Thinking Checklist

Before adding the task, ensure you've considered:

- [ ] **Necessity:** Is this task actually needed?
- [ ] **Duplication:** Does this duplicate existing work?
- [ ] **Scope:** Is the scope clear and well-defined?
- [ ] **Priority:** Is the priority level justified?
- [ ] **Information:** Do we have enough details to proceed?
- [ ] **Testing:** Is the test strategy clear?
- [ ] **Dependencies:** Are dependencies identified?
- [ ] **Impact:** Is the impact/benefit understood?

## Important Notes

- **Always use research mode** (`research: true`) for better task quality
- **Question assumptions** - Don't blindly accept user requests
- **Verify completeness** - Ensure sufficient information before adding
- **Check for duplicates** - Search existing tasks first
- **Assess priority critically** - Don't default to "high" priority
- **Recommend expansion** - Suggest breaking down complex tasks
- **Provide rationale** - Explain priority and scope decisions

## Integration with Other Commands

**After adding a task:**

```bash
# Expand complex task
/task:next --refine

# Start immediately
/task:next

# Review task details
/task show <id>

# View all tasks
/task
```

---

**For comprehensive Task Master documentation:**

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