---
name: sp-task
description: Generate and manage task breakdowns using AI-optimized templates
allowed_tools:
  - Read
  - Write
  - Edit
  - Bash
  - TodoWrite
---

# /sp-task Command

Generate task breakdowns from implementation plans using SpecPulse methodology with AI-optimized templates and enhanced validation.

## CRITICAL: LLM Workflow Rules

**PRIMARY WORKFLOW: Use CLI when available**
- Prefer `specpulse` CLI commands when they exist
- Use Bash tool ONLY for CLI commands, not for file editing
- Only use Read/Write/Edit tools when CLI doesn't cover the operation

**PROTECTED DIRECTORIES (NEVER EDIT):**
- `templates/` - Template files
- `.specpulse/` - Internal config
- `specpulse/` - Package code
- `.claude/` and `.gemini/` - AI configuration
- **ONLY EDIT**: specs/, plans/, tasks/, memory/
- Templates are COPIED to tasks/ folder, then edited there

## Usage
```
/sp-task [action] [feature-directory]
```

Actions: `breakdown`, `update`, `status`, `execute` (defaults to `breakdown`)

## Implementation

When called with `/sp-task $ARGUMENTS`, I will:

1. **Detect current feature context**:
   - Read `memory/context.md` for current feature metadata
   - Use git branch name if available (e.g., `001-user-authentication`)
   - Fall back to most recently created feature directory
   - If no context found, ask user to specify feature or run `/sp-pulse` first

2. **Parse arguments** to determine action:
   - If `update`: Update task status and dependencies
   - If `status`: Show comprehensive progress with metrics
   - If `execute`: Execute task with script integration
   - Otherwise: Generate task breakdown

3. **For `/sp-task breakdown` or `/sp-task`:**
   
   a. **Check for decomposition**: Look for `specs/XXX-feature/decomposition/` directory
   b. **If decomposed**:
      - Read service definitions from decomposition
      - Show service-specific plan files (auth-service-plan.md, user-service-plan.md, etc.)
      - Generate tasks per service with service prefix (AUTH-T001, USER-T001)
      - Create integration tasks (INT-T001) for cross-service work
      - Structure: `tasks/XXX-feature/auth-service-tasks.md`, `integration-tasks.md`
   c. **If not decomposed**:
      - Show existing plan files and ask user to select
      - Generate single task file with standard IDs (T001, T002)
   c. **Validation** using CLI:
      ```bash
      specpulse --no-color validate task --verbose
      ```
   
   d. **Read implementation plan** from selected plan file:
      ```
      Read: plans/XXX-feature/plan-YYY.md
      ```

   e. **Generate AI-optimized tasks using File Operations**:
      - **Step 1: Read Task Template**
        ```
        Read: templates/task.md
        ```

      - **Step 2: Parse Plan and Create Task Files**
        ```
        For each phase/component in plan:
          Write: tasks/XXX-feature/task-001.md
          Write: tasks/XXX-feature/task-002.md
          ... (one file per task)

        Content includes:
          - Metadata (feature ID, task number, status: pending)
          - Task description from plan
          - Template structure for expansion
        ```

      - **IMPORTANT**: Can EDIT files in tasks/ folder, but NEVER modify templates/ or commands/ folders

   f. **Generate structured task categories based on architecture**:
      - **For decomposed services**:
        * Service-specific tasks with bounded context
        * Inter-service integration tasks
        * Service deployment order tasks
        * Contract testing tasks between services
      - **For monolithic architecture**:
        * Layer-based tasks (data, business, API)
        * Module-specific tasks
      - **Common categories**:
        * SDD Gates Compliance
        * Critical Path identification
        * Parallel vs Sequential grouping
        * Progress Tracking configuration

   g. **For each task**, generate comprehensive metadata:
      - **ID**: T[XXX] format (T001, T002)
      - **Type**: setup, development, testing, documentation
      - **Priority**: HIGH, MEDIUM, LOW
      - **Estimate**: Hours or complexity points
      - **Dependencies**: Task ID dependencies
      - **Description**: Clear what needs to be done
      - **Acceptance**: How to verify completion
      - **Files**: Files to be created/modified
      - **Assignable**: Role/skill required
      - **Parallel**: Whether can run in parallel [P]

   h. **Generate AI execution guidelines** with workflow integration:
      ```markdown
      ## AI Execution Strategy
      ### Parallel Tasks (can be worked on simultaneously):
      - T001, T002, T003: Independent tasks, no dependencies
      ### Sequential Tasks (must be completed in order):
      - T004 → T005 → T006: Dependency chain
      ```

   i. **Version management**: Check existing task files and create next version (task-001.md, task-002.md, etc.)
   j. **Write comprehensive task breakdown** to `tasks/XXX-feature/task-XXX.md`

4. **For `/sp-task update`:**
   a. **Show existing task files**: List all task-XXX.md files in current feature directory
   b. **Ask user to select**: Which task file to update
   c. **Analysis** using script:
     ```bash
     specpulse task breakdown "$PLAN_ID"
     ```
   d. **Parse current tasks** from selected file with comprehensive status:
     - Total tasks, completed, pending, blocked
     - Parallel tasks identification
     - SDD gates status
     - Completion percentage calculation
   e. **Interactive task updates**:
     - Mark tasks as completed/in-progress/blocked
     - Update dependencies and blockers
     - Add newly discovered tasks with proper metadata
     - Adjust estimates based on actual progress
   f. **Generate updated progress tracking** YAML

5. **For `/sp-task status`:**
   a. **Show existing task files**: List all task-XXX.md files in current feature directory
   b. **Ask user to select**: Which task file to show status for
   c. **Enhanced reporting** from script output:
     ```bash
     TOTAL_TASKS=25
     COMPLETED_TASKS=10
     COMPLETION_PERCENTAGE=40%
     SDD_GATES_PENDING=2
     ```
   d. **Display comprehensive progress**:
     - Overall completion percentage
     - Phase-by-phase progress
     - Blocker identification and resolution
     - Velocity metrics and estimates
     - SDD gates compliance status

6. **For `/sp-task execute`:**
   a. **Show existing task files**: List all task-XXX.md files in current feature directory
   b. **Ask user to select**: Which task file to execute from
   c. **Ask user to specify**: Which specific task ID to execute
   d. **Validate task readiness** using SDD gates
   e. **Execute task** using AI assistant capabilities:
     ```markdown
     ## Task Execution: {{ TASK_ID }}
     **AI Assistant**: Claude/Gemini
     **Method**: Direct implementation within AI session
     **Status**: [ ] Pending → [-] In Progress → [x] Completed
     ```
   f. **Track execution results** and update status
   g. **Update progress tracking** automatically

## Standardized Task Format

All task files must follow this exact YAML frontmatter format:

```yaml
---
id: task-[slug]
status: todo | in-progress | blocked | done
title: "Short but clear task title"
description: |
  *Answer these 4 questions with sufficient detail:*
  - What problem does this solve?
  - Why is this necessary?
  - How will this be done? (step-by-step, include function/file names when possible)
  - When is this considered complete?

files_touched:
  - path: src/...
    reason: "What changes in this file, briefly"
  - path: ...
    reason: "..."

goals:
  - "Concrete goal 1 achieved when this task completes"
  - "Concrete goal 2"

success_criteria:
  - "Test/acceptance criteria 1 (measurable or verifiable)"
  - "Test/acceptance criteria 2"

dependencies:
  - task-[id-1]
  - task-[id-2]

next_tasks:
  - task-[id-x]
  - task-[id-y]

risk_level: low | medium | high
risk_notes: |
  "Important risks, edge cases, technical debt notes for this task"

# MoSCoW breakdown for this task
moscow:
  must:
    - "Must-have requirements/behaviors for this task"
    - "Without these, task is not considered complete"
  should:
    - "Additional improvements if time/budget allows"
    - "Performance, UX, DX improvements, etc."
  know:
    - "Critical knowledge, context, or domain details developer must know"
    - "Documentation links, rationale for specific decisions"
  wont:
    - "Things we WILL NOT do in this task scope - out of scope"
    - "Topics for future tasks"

priority_overall: must | should | could | wont
priority_reason: "Why this task has this priority - short, clear explanation."

---
```

### Example Task File
```markdown
---
id: task-001
status: todo
title: "User authentication system setup"
description: |
  - **What problem does this solve?**: User login/logout and token-based authentication
  - **Why is this necessary?**: Foundation for secure system access
  - **How will this be done?**: JWT implementation, middleware, auth routes
  - **When is this complete?**: All tests pass and documentation ready

files_touched:
  - path: src/auth/jwt.py
    reason: "JWT token generation/validation"
  - path: src/auth/middleware.py
    reason: "Authentication middleware for protected routes"
  - path: src/routes/auth.py
    reason: "Login/logout endpoints"

goals:
  - "JWT-based authentication system"
  - "Secure password hashing"
  - "Authentication middleware"

success_criteria:
  - "Login/logout responds under 200ms"
  - "JWT token passes security tests"
  - "Rate limiting is active"

dependencies: []
next_tasks:
  - task-002  # User management
  - task-003  # Role system

risk_level: medium
risk_notes: "JWT secret management requires careful handling in production"

moscow:
  must:
    - "JWT token implementation"
    - "Password hashing (bcrypt)"
    - "Basic auth middleware"
  should:
    - "Rate limiting"
    - "Token refresh mechanism"
    - "Authentication logs"
  know:
    - "JWT standards and security best practices"
    - "OWASP authentication guidelines"
  wont:
    - "OAuth implementation (separate task)"
    - "2FA (separate task)"

priority_overall: must
priority_reason: "All features depend on authentication system"
---
```

## Enhanced Task Format

### For Decomposed Services
```markdown
### Auth Service Tasks
#### AUTH-T001: Initialize auth service structure
- **Service**: Authentication
- **Type**: setup
- **Priority**: HIGH
- **Dependencies**: None

### User Service Tasks  
#### USER-T001: Initialize user service structure
- **Service**: User Management
- **Type**: setup
- **Priority**: HIGH
- **Dependencies**: None

### Integration Tasks
#### INT-T001: Set up service communication
- **Services**: Auth ↔ User
- **Type**: integration
- **Priority**: HIGH
- **Dependencies**: AUTH-T001, USER-T001
```

### For Monolithic Architecture
```markdown
### Parallel Group A
#### T001: Initialize project structure
- **Type**: setup
- **Priority**: HIGH
- **Estimate**: 2 hours
- **Dependencies**: None
- **Description**: Set up project directory structure and configuration
- **Acceptance**: All directories exist and config files are valid
- **Files**: package.json, README.md, .gitignore
- **Assignable**: developer
- **Parallel**: [P]

## Progress Tracking
```yaml
status:
  total: 25
  completed: 10
  in_progress: 3
  blocked: 0
  
metrics:
  velocity: 2-3 tasks/day
  estimated_completion: 2025-09-15
  completion_percentage: 40%
```

## SDD Gates Integration

Each task breakdown includes SDD compliance validation:
- **Specification First**: Tasks trace to specifications
- **Task Decomposition**: Concrete, actionable tasks
- **Quality Assurance**: Appropriate testing tasks included
- **Traceable Implementation**: Clear linkage to requirements

## Examples

### Generate tasks for decomposed spec
```
User: /sp-task breakdown
```
Detecting decomposition in `specs/001-authentication/decomposition/`...
I will create:
- `tasks/001-authentication/auth-service-tasks.md`
- `tasks/001-authentication/user-service-tasks.md`
- `tasks/001-authentication/integration-tasks.md`

### Generate tasks for monolithic spec
```
User: /sp-task breakdown
```
No decomposition found. Creating single task file:
- `tasks/001-authentication/task-001.md`

### Execute service-specific task
```
User: /sp-task execute AUTH-T001
```
I will:
- Run: Cross-platform detection and execution
  ```bash
  specpulse task breakdown "$PLAN_ID"
  ```
- Create: AI-optimized task structure with template variables
- Output: `TOTAL_TASKS=25, PARALLEL_TASKS=8, STATUS=generated`

### Update task status
```
User: /sp-task update mark T001-T005 as completed
```
I will update task status and recalculate progress metrics.

### Show comprehensive status
```
User: /sp-task status
```
I will display detailed progress with SDD gates compliance.

### Execute specific task
```
User: /sp-task execute T001
```
I will:
- Validate: SDD gates compliance and task readiness
- Execute: Cross-platform task execution
  ```bash
  specpulse task breakdown "$PLAN_ID" "execute:$TASK_ID"
  ```
- Track: Results and update progress automatically

## Enhanced Features

- **Script execution** with Bash
- **AI-optimized templates** with Jinja2-style variables
- **Script integration** for validation and execution
- **SDD gates compliance** tracking
- **Parallel task identification** and execution
- **Comprehensive progress tracking** with YAML configuration
- **Automatic percentage calculation** and velocity metrics
- **Task dependency management** with conflict detection
- **Execution command generation** with script integration
- **Cross-platform operation** with Bash

## Error Handling

- Plan existence validation before task generation
- SDD gates compliance checking
- Template structure validation
- Dependency conflict detection
- Task execution error handling with rollback
- Progress tracking validation and correction