---
description: Create a Task Master task from conversation context, validate, expand into subtasks, and optionally start work
argument-hint: ["task title or description"] [--priority=high|medium|low] [--no-expand] [--start]
allowed-tools: Bash(git *), mcp__task_master_ai__*, Read, Write, Grep, Glob, SlashCommand(/task:next *)
---

# Create Task: $ARGUMENTS

Create a new Task Master task from the current conversation context, plan, or discussion. The task is validated for duplicates, expanded into subtasks, and a summary report is generated.

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

## Workflow Summary

This command:

1. **Extract context** - Analyze conversation for task requirements
2. **Check duplicates** - Search existing tasks for similar work
3. **Create task** - Add to Task Master with appropriate priority
4. **Validate** - Verify task was created successfully
5. **Expand** - Break down into subtasks with dependencies
6. **Generate report** - Create markdown summary in `.tmp/`
7. **Open report** - Show user the created task details
8. **Prompt for work** - Ask if user wants to start the task

## Phase 0: Parse Arguments

Extract from `$ARGUMENTS`:

- **Task description**: Optional explicit title/description
- **--priority=<level>**: Override priority (high, medium, low). Default: medium
- **--no-expand**: Skip automatic subtask expansion
- **--start**: Automatically start work after creation (skip confirmation)

```javascript
// Parse arguments
const args = '$ARGUMENTS'.trim();
let taskDescription = '';
let priority = 'medium';
let shouldExpand = true;
let autoStart = false;

// Extract flags
if (args.includes('--priority=')) {
  const match = args.match(/--priority=(high|medium|low)/);
  if (match) priority = match[1];
}
if (args.includes('--no-expand')) {
  shouldExpand = false;
}
if (args.includes('--start')) {
  autoStart = true;
}

// Remaining text is the task description
taskDescription = args
  .replace(/--priority=(high|medium|low)/g, '')
  .replace(/--no-expand/g, '')
  .replace(/--start/g, '')
  .trim();
```

## Phase 1: Extract Task Context from Conversation

### 1.1 Analyze Recent Conversation

**If no explicit description provided:**

Analyze the recent conversation history to identify:

- Problem being discussed
- Proposed solution or approach
- Requirements mentioned
- Technical decisions made
- Files or components affected

```javascript
// Build task context from conversation
const taskContext = {
  problem: '', // What problem are we solving?
  solution: '', // What approach was discussed?
  requirements: [], // Specific requirements mentioned
  files: [], // Files/components affected
  acceptance: [], // Success criteria discussed
  testStrategy: '', // Testing approach mentioned
};

// Extract key information from recent messages
// Look for patterns like:
// - "we need to..." / "should implement..."
// - "the issue is..." / "the problem is..."
// - "requirements:" / "must have:"
// - "test by..." / "verify that..."
```

### 1.2 Formulate Task Description

**Build comprehensive task prompt:**

```javascript
const taskPrompt =
  taskDescription ||
  `
## Problem
${taskContext.problem}

## Solution
${taskContext.solution}

## Requirements
${taskContext.requirements.map((r) => `- ${r}`).join('\n')}

## Affected Components
${taskContext.files.map((f) => `- ${f}`).join('\n')}

## Acceptance Criteria
${taskContext.acceptance.map((a) => `- ${a}`).join('\n')}

## Test Strategy
${taskContext.testStrategy}
`.trim();
```

## Phase 2: Check for Duplicate Tasks

### 2.1 Search Existing Tasks

```bash
# Get all existing tasks
cat .taskmaster/tasks/tasks.json | jq -r '.master.tasks[] | "\(.id): \(.title) [\(.status)]"'
```

### 2.2 Compare for Similarity

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

// Extract keywords from new task
const keywords = extractKeywords(taskPrompt);

// Find similar tasks
const similarTasks = existingTasks.filter((task) => {
  const taskKeywords = extractKeywords(task.title + ' ' + task.description);
  const overlap = keywords.filter((k) => taskKeywords.includes(k));
  return overlap.length >= 3; // Significant overlap
});
```

### 2.3 Handle Duplicates

**If similar tasks found:**

```markdown
## Potential Duplicate Tasks Found

The following existing tasks appear similar:

| ID  | Title                  | Status      |
| --- | ---------------------- | ----------- |
| 42  | Implement auth system  | in-progress |
| 38  | Add JWT authentication | pending     |

**Options:**

1. **Continue** - Create new task anyway (may be intentional)
2. **Cancel** - Don't create, work on existing task instead
3. **Merge** - Add details to existing task

**What would you like to do?**
```

**Wait for user confirmation before proceeding.**

## Phase 3: Create Task in Task Master

### 3.1 Add Task with Research

```javascript
// Create the task using Task Master MCP
const newTask = mcp__task_master_ai__add_task({
  projectRoot: process.cwd(),
  prompt: taskPrompt,
  priority: priority,
  research: true, // Enable research for comprehensive task details
});

// Capture the task ID
const taskId = newTask.id;
```

### 3.2 Verify Task Creation

```javascript
// Verify task was created successfully
const createdTask = mcp__task_master_ai__get_task({
  projectRoot: process.cwd(),
  id: taskId,
});

if (!createdTask) {
  console.error('Task creation failed');
  // Exit with error
}
```

**Show creation confirmation:**

```markdown
## Task Created Successfully

**ID:** ${taskId}
**Title:** ${createdTask.title}
**Priority:** ${createdTask.priority}
**Status:** ${createdTask.status}
```

## Phase 4: Expand Task into Subtasks

**Skip if --no-expand flag present.**

### 4.1 Analyze Complexity

```javascript
// Determine appropriate number of subtasks based on task complexity
let numSubtasks = 5; // Default

// Adjust based on description length and requirements
const wordCount = taskPrompt.split(/\s+/).length;
if (wordCount < 100) {
  numSubtasks = 3; // Simple task
} else if (wordCount < 300) {
  numSubtasks = 5; // Medium task
} else {
  numSubtasks = 8; // Complex task
}
```

### 4.2 Expand Task

```javascript
// Expand task into subtasks
mcp__task_master_ai__expand_task({
  projectRoot: process.cwd(),
  id: taskId,
  num: numSubtasks.toString(),
  research: true,
  prompt: 'Break down with clear dependencies and test considerations',
});
```

### 4.3 Retrieve Expanded Task

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

const subtasks = expandedTask.subtasks || [];
```

## Phase 5: Generate Report

### 5.1 Create Report File

```bash
# Generate timestamp and paths
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
REPORT_DIR=".tmp/tasks"
mkdir -p "$REPORT_DIR"
REPORT_FILE="${REPORT_DIR}/task-${TASK_ID}-${TIMESTAMP}.md"
```

### 5.2 Write Report Content

**Report Template:**

````markdown
# Task Created: ${taskTitle}

**Generated:** ${timestamp}
**Task ID:** ${taskId}
**Priority:** ${priority}
**Status:** pending

---

## Overview

${taskDescription}

## Details

${taskDetails}

---

## Subtasks

| ID              | Title | Status | Dependencies |
| --------------- | ----- | ------ | ------------ |
| ${subtask rows} |

---

## Execution Order

Based on dependencies, execute subtasks in this order:

1. ${firstSubtask} (no dependencies)
2. ${secondSubtask} (depends on: ${deps})
   ...

---

## Test Strategy

${testStrategy}

---

## Next Steps

**To start work on this task:**

```bash
/task:next ${taskId}
```
````

**To view task details:**

```bash
/task show ${taskId}
```

**To refine before starting:**

```bash
/task:refine ${taskId}
```

````markdown
### 5.3 Write Report to File

```bash
cat > "$REPORT_FILE" <<'EOF'
${reportContent}
EOF

echo ""
echo "Task report: $REPORT_FILE"
```
````

## Phase 6: Open Report in Editor

```bash
# Open report in VSCode
if command -v code &> /dev/null; then
  code "$REPORT_FILE"
else
  echo "Report saved to: $REPORT_FILE"
  echo "View with: cat $REPORT_FILE"
fi
```

## Phase 7: Prompt to Start Work

### 7.1 Auto-Start (if --start flag)

**If --start flag was provided:**

```javascript
// Automatically start work on the task
console.log('\n## Starting Work\n');
console.log(`Auto-starting task ${taskId} as requested...`);

// Execute /task:next with the task ID
SlashCommand('/task:next ' + taskId);
```

### 7.2 Interactive Prompt (default)

**If no --start flag:**

```markdown
## Ready to Start?

Task **${taskId}: ${taskTitle}** has been created with ${subtaskCount} subtasks.

**Would you like to start work on this task now?**

- **Yes** - Run `/task:next ${taskId}` to begin
- **No** - Task saved for later, view with `/task show ${taskId}`
- **Refine** - Run `/task:refine ${taskId}` to add more detail first

**Your choice:**
```

**Wait for user response.**

**If user says yes/start/y:**

```javascript
// Start work on the task
SlashCommand('/task:next ' + taskId);
```

## Examples

### Create task from explicit description

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

### Create high-priority task

```bash
/task:create "Fix critical security vulnerability in auth module" --priority=high
```

### Create task and immediately start

```bash
/task:create "Add unit tests for payment service" --start
```

### Create simple task without expansion

```bash
/task:create "Update README with new installation steps" --no-expand
```

### Create task from conversation context

```bash
# After discussing a feature in conversation
/task:create
# Will analyze recent messages and extract task details
```

## Report File Structure

Reports are saved to `.tmp/tasks/` with the following naming convention:

```text
.tmp/tasks/task-<ID>-<TIMESTAMP>.md

Example:
.tmp/tasks/task-47-20251130-143022.md
```

**Report contains:**

- Task overview and details
- Complete subtask list with dependencies
- Suggested execution order
- Test strategy
- Next step commands

## Error Handling

### Task Creation Failed

````markdown
## Task Creation Failed

Could not create task in Task Master.

**Possible Issues:**

- Task Master not initialized (run `ai-toolkit init`)
- API key missing (check ANTHROPIC_API_KEY)
- Invalid task description

**Retry:**

```bash
/task:create "your task description"
```
````

````markdown
### Expansion Failed

```markdown
## Subtask Expansion Failed

Task was created but subtask expansion failed.

**Task ID:** ${taskId}
**Status:** Created without subtasks

**Options:**

1. Manually expand: `/task:refine ${taskId} --expand`
2. Start without subtasks: `/task:next ${taskId}`
3. View task: `/task show ${taskId}`
```
````

### Report Generation Failed

````markdown
## Report Generation Warning

Task created successfully but report file could not be generated.

**Task ID:** ${taskId}
**Title:** ${taskTitle}

**View task directly:**

```bash
/task show ${taskId}
```
````

````markdown
## Integration with Other Commands

**After creating a task:**

```bash
# Start work immediately
/task:next <id>

# Refine with more detail
/task:refine <id>

# View task details
/task show <id>

# View all tasks
/task:status

# Add to current work
/task:next continue
```
````

---

**For comprehensive Task Master documentation:**

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