# Task Management System

## Overview

All tasks and subtasks across all modes (MSP, Development, Normal) are tracked using **Claude Code's native task management tools** (TaskCreate, TaskUpdate, TaskList, TaskGet). The orchestrator (main Claude session) manages tasks, updating status as work progresses. Task data is persisted to `.claude/active-tasks.json` for cross-session continuity.

**Native Task Integration (NEW - 2026-01-23):**
- **Session Layer:** TaskCreate/Update/List for real-time coordination
- **Persistence Layer:** `.claude/active-tasks.json` file for cross-session recovery
- **Agent Pattern:** Agents report status → Main Claude updates tasks
- **See:** `.claude/NATIVE_TASK_INTEGRATION.md` for complete guide

## Core Principles

### 1. Everything is Tracked
- User requests → Tasks
- Agent operations → Subtasks
- Code implementations → Tasks
- Research activities → Tasks
- Client work → Tasks (linked to client)
- Development features → Tasks (linked to project)

### 2. Orchestrator Maintains Checklist
The main Claude session (not agents) is responsible for:
- Creating tasks from user requests
- Breaking down complex tasks into subtasks
- Updating task status as agents report progress
- Marking tasks complete when work finishes
- Providing visibility to user on progress

### 3. Agents Report Progress
Agents don't manage tasks directly - they report to orchestrator:
- Agent starts work → Orchestrator marks task 'in_progress'
- Agent completes work → Orchestrator marks task 'completed'
- Agent encounters blocker → Orchestrator marks task 'blocked' with reason

### 4. Context is Preserved
Every task stores rich context in `.claude/active-tasks.json`:
- What was requested (subject, description)
- Task status (pending, in_progress, completed)
- Which agent is working (owner field)
- Task dependencies (blocks, blockedBy)
- Timestamps (created_at, started_at, completed_at)
- Metadata (client, project, complexity)
- Cross-session persistence for recovery

## Workflow

### Step 1: User Makes Request
```
User: "Implement authentication for the API"
```

### Step 2: Orchestrator Creates Task(s)
Main Claude analyzes request and creates task structure using native tools:

```javascript
// Orchestrator thinks:
// This is a complex task - break it down

// Create parent task
TaskCreate({
  subject: "Implement API authentication",
  description: "Complete JWT-based authentication system with Argon2 hashing",
  activeForm: "Implementing API authentication"
})
// Returns: Task #7

// Create subtasks with dependencies
design = TaskCreate({
  subject: "Design authentication schema",
  description: "Define users, tokens, and refresh_tokens tables",
  activeForm: "Designing auth schema"
})
// Returns: Task #8

generate = TaskCreate({
  subject: "Generate JWT authentication code",
  description: "Implement FastAPI endpoints with JWT token generation",
  activeForm: "Generating auth code",
  addBlockedBy: ["8"]  // Depends on design
})
// Returns: Task #9

review = TaskCreate({
  subject: "Review authentication code",
  description: "Code review for security and standards compliance",
  activeForm: "Reviewing auth code",
  addBlockedBy: ["9"]  // Depends on code generation
})
// Returns: Task #10

tests = TaskCreate({
  subject: "Write authentication tests",
  description: "Create pytest tests for auth flow",
  activeForm: "Writing auth tests",
  addBlockedBy: ["10"]  // Depends on review
})
// Returns: Task #11

// Persist all tasks to file
Write(".claude/active-tasks.json", tasks_data)
```

### Step 3: Orchestrator Shows Checklist to User
```markdown
## Task Breakdown

I'll implement API authentication in these steps:

- [ ] Design authentication schema
- [ ] Generate code for JWT authentication
- [ ] Review authentication code
- [ ] Write authentication tests

Starting with the design phase...
```

### Step 4: Orchestrator Launches Agents
```javascript
// Update task status to in_progress
TaskUpdate({
  taskId: "8",  // Design task
  status: "in_progress",
  owner: "Coding Agent"
})

// Update file
Update active-tasks.json with new status

// Launch agent
Coding Agent: analyze_and_design_auth_schema(...)
```

### Step 5: Agent Completes, Orchestrator Updates
```javascript
// Agent returns design
agent_result = {
  status: "completed",
  outcome: "Schema designed with users, tokens, refresh_tokens tables",
  files_created: ["docs/auth_schema.md"]
}

// Orchestrator updates task
TaskUpdate({
  taskId: "8",
  status: "completed"
})

// Update file
Update active-tasks.json with completion

// Next task (dependency cleared automatically)
TaskUpdate({
  taskId: "9",  // Generate code task
  status: "in_progress"
})

// Update checklist shown to user via TaskList()
```

### Step 6: Progress Visibility
```markdown
## Task Progress

- [✓] Design authentication schema (completed)
- [→] Generate code for JWT authentication (in progress)
- [ ] Review authentication code
- [ ] Write authentication tests
```

### Step 7: All Tasks Complete
```python
# When all subtasks done, mark parent complete
Database Agent: complete_task(
  task_id="parent-task-uuid",
  completed_at=now(),
  task_context={
    "outcome": "Authentication fully implemented and reviewed",
    "subtasks_completed": 4,
    "files_modified": ["auth.py", "user.py", "test_auth.py"],
    "production_ready": true
  }
)
```

## Task Status Flow

```
pending
  ↓ (agent starts work)
in_progress
  ↓
  ├─→ completed (success)
  ├─→ blocked (encountered issue)
  │     ↓ (issue resolved)
  │   in_progress (resume)
  └─→ cancelled (no longer needed)
```

## Task Types

### implementation
Code generation, feature building, system creation
- Assigned to: Coding Agent → Code Review Agent
- Context includes: files modified, dependencies added, review status

### research
Information gathering, codebase exploration, documentation reading
- Assigned to: Explore Agent, general-purpose agent
- Context includes: findings, relevant files, key information

### review
Code review, quality assurance, specification verification
- Assigned to: Code Review Agent
- Context includes: approval status, issues found, fixes applied

### testing
Test creation, test execution, validation
- Assigned to: Coding Agent (creates tests), potentially Test Agent (future)
- Context includes: tests created, pass/fail status, coverage

### deployment
Deploying code, configuring servers, setting up infrastructure
- Assigned to: DevOps Agent (future) or general-purpose agent
- Context includes: deployment steps, environment, verification

### documentation
Writing docs, creating guides, updating README files
- Assigned to: general-purpose agent
- Context includes: docs created, format, location

### bugfix
Fixing defects, resolving issues, patching problems
- Assigned to: Coding Agent → Code Review Agent
- Context includes: bug description, root cause, fix applied

### analysis
Understanding problems, investigating issues, exploring options
- Assigned to: Explore Agent, general-purpose agent
- Context includes: analysis results, options identified, recommendations

## Context Data Structure

Each task stores rich context as JSON:

```json
{
  "user_request": "Original user message",
  "environment": {
    "os": "Windows",
    "runtime": "Python 3.11",
    "project_type": "FastAPI",
    "client": "Dataforth"  // if MSP mode
  },
  "requirements": [
    "Must use JWT tokens",
    "Must integrate with existing users table",
    "Must include refresh token support"
  ],
  "constraints": [
    "Must work on Server 2019",
    "Cannot use PowerShell 7 cmdlets"
  ],
  "assigned_agents": [
    {
      "agent": "Coding Agent",
      "started": "2026-01-15T20:30:00Z",
      "completed": "2026-01-15T20:40:00Z"
    },
    {
      "agent": "Code Review Agent",
      "started": "2026-01-15T20:40:00Z",
      "completed": "2026-01-15T20:42:00Z",
      "status": "approved"
    }
  ],
  "files_modified": [
    "api/auth.py",
    "models/user.py",
    "tests/test_auth.py"
  ],
  "dependencies_added": [
    "python-jose[cryptography]==3.3.0",
    "passlib[bcrypt]==1.7.4"
  ],
  "blockers_encountered": [],
  "outcome": "Authentication system implemented and approved",
  "production_ready": true,
  "billable": true,  // if MSP mode
  "billable_minutes": 30  // if MSP mode
}
```

## Mode-Specific Task Features

### MSP Mode
Tasks automatically linked to client context:
```python
{
  "operation": "create_task",
  "title": "Fix WINS service on D2TESTNAS",
  "client_id": "dataforth-uuid",
  "infrastructure_ids": ["d2testnas-uuid"],
  "billable_minutes": 45,
  "task_context": {
    "problem": "WINS service not responding",
    "impact": "DOS machines can't resolve NetBIOS names"
  }
}
```

When completed, automatically creates work_item:
```python
{
  "operation": "create_work_item",
  "category": "troubleshooting",
  "problem": "WINS service not responding",
  "solution": "Fixed smb.conf.overrides, restarted nmbd",
  "billable_minutes": 45,
  "linked_task_id": "task-uuid"
}
```

### Development Mode
Tasks linked to project:
```python
{
  "operation": "create_task",
  "title": "Add dark mode toggle",
  "project_id": "gururmm-uuid",
  "task_context": {
    "feature_spec": "User-requested dark mode for dashboard",
    "repository": "azcomputerguru/gururmm"
  }
}
```

### Normal Mode
Tasks not linked to client or project:
```python
{
  "operation": "create_task",
  "title": "Research Rust async patterns",
  "task_type": "research",
  "task_context": {
    "reason": "General learning, not for specific client/project"
  }
}
```

## Checklist Display Format

### Compact (During Execution)
```markdown
## Progress

- [✓] Analyze requirements (completed)
- [→] Generate code (in progress - Coding Agent)
- [ ] Review code
- [ ] Deploy to staging
```

### Detailed (On Request)
```markdown
## Task Status: Implement API Authentication

**Overall Status:** In Progress (2 of 4 complete)

### Completed ✓
1. **Design authentication schema** (5 min)
   - Schema designed with JWT approach
   - Files: docs/auth_schema.md

2. **Generate authentication code** (20 min)
   - Code generated by Coding Agent
   - Approved by Code Review Agent
   - Files: api/auth.py, models/user.py

### In Progress →
3. **Write authentication tests** (in progress)
   - Assigned to: Coding Agent
   - Started: 2 minutes ago

### Pending
4. **Deploy to staging**
   - Blocked by: Need staging environment credentials
```

## File-Based Storage

Tasks are persisted to `.claude/active-tasks.json` for cross-session continuity.

**File Structure:**
```json
{
  "last_updated": "2026-01-23T10:30:00Z",
  "tasks": [
    {
      "id": "7",
      "subject": "Implement API authentication",
      "description": "Complete JWT-based authentication...",
      "activeForm": "Implementing API authentication",
      "status": "in_progress",
      "owner": "Coding Agent",
      "created_at": "2026-01-23T10:00:00Z",
      "started_at": "2026-01-23T10:05:00Z",
      "completed_at": null,
      "blocks": [],
      "blockedBy": [],
      "metadata": {
        "client": "Dataforth",
        "project": "ClaudeTools",
        "complexity": "moderate"
      }
    }
  ]
}
```

**Key Fields:**
- `id` - Task number from TaskCreate
- `subject` - Brief task title
- `description` - Detailed description
- `status` - pending, in_progress, completed
- `owner` - Which agent is working (from TaskUpdate)
- `blocks`/`blockedBy` - Task dependencies
- `metadata` - Client, project, complexity

## Agent Interaction Pattern

### Agents Don't Manage Tasks Directly
```javascript
// [ERROR] WRONG - Agent uses TaskUpdate directly
// Inside Coding Agent:
TaskUpdate({ taskId: "7", status: "completed" })

// ✓ CORRECT - Agent reports to orchestrator
// Inside Coding Agent:
return {
  "status": "completed",
  "outcome": "Authentication code generated",
  "files_created": ["auth.py"]
}

// Orchestrator receives agent result, then updates task
TaskUpdate({
  taskId: "7",
  status: "completed"
})

// Update file
Update active-tasks.json with completion data
```

### Orchestrator Sequence
```javascript
// 1. Create task
task_id = TaskCreate({
  subject: "Generate auth code",
  description: "Create JWT authentication endpoints",
  activeForm: "Generating auth code"
})
// Returns: "7"

// 2. Update status before launching agent
TaskUpdate({
  taskId: "7",
  status: "in_progress",
  owner: "Coding Agent"
})
Update active-tasks.json

// 3. Launch agent
result = Coding_Agent.generate_auth_code(...)

// 4. Update task with result
TaskUpdate({
  taskId: "7",
  status: "completed"
})
Update active-tasks.json with outcome

// 5. Show updated checklist to user
TaskList()  // Shows current state
```

## Benefits

### For User
- **Visibility** - Always know what's happening
- **Progress tracking** - See how far along work is
- **Context** - Understand what was done and why
- **Billability** - (MSP mode) Clear record of time spent

### For Orchestrator (Main Claude)
- **Organization** - Structured approach to complex requests
- **Memory** - Database stores context between sessions
- **Resumption** - Can pick up where left off
- **Accountability** - Clear record of what agents did

### For System
- **Learning** - Analyze patterns across tasks
- **Estimation** - Build data for complexity estimates
- **Optimization** - Identify bottlenecks
- **Quality** - Track review pass/fail rates

## Example: Complex Request

**User Request:**
> "Set up monitoring for the Dataforth NAS, alert if sync fails"

**Orchestrator Creates Tasks:**
```markdown
## Implementation Plan

I'll set up NAS monitoring in these steps:

- [ ] Research current sync system (Dataforth)
- [ ] Design monitoring approach
- [ ] Implement monitoring script
- [ ] Review monitoring code
- [ ] Test monitoring alerts
- [ ] Deploy to production
- [ ] Document for team

Starting with research...
```

**Task Breakdown in Database:**
```python
parent_task = {
  "title": "Set up NAS monitoring for Dataforth",
  "client_id": "dataforth-uuid",
  "status": "in_progress",
  "subtasks": [
    {
      "title": "Research current sync system",
      "task_type": "research",
      "assigned_agent": "Explore Agent",
      "status": "in_progress"
    },
    # ... 6 more subtasks
  ]
}
```

**As Work Progresses:**
```markdown
## Progress Update

- [✓] Research current sync system (completed - 5 min)
  - Found: PowerShell script on AD2, syncs every 15 min
  - Files: C:\Shares\test\scripts\Sync-FromNAS.ps1

- [✓] Design monitoring approach (completed - 3 min)
  - Approach: Check _SYNC_STATUS.txt age via DattoRMM
  - Alert if >30 min old or status != "OK"

- [→] Implement monitoring script (in progress - Coding Agent)
- [ ] Review monitoring code
- [ ] Test monitoring alerts
- [ ] Deploy to production
- [ ] Document for team
```

**On Completion:**
```markdown
## Implementation Complete [OK]

NAS monitoring set up for Dataforth:

**Work Summary:**
- Total time: 45 minutes (billable)
- Tasks completed: 7
- Files created: monitor-nas-sync.ps1
- Deployed to: DattoRMM component
- Alert threshold: 30 minutes

**What was built:**
[code blocks]

**Testing:**
[test results]

**Documentation:**
[docs created]
```

**Stored in File:**
```javascript
// Parent task marked complete in active-tasks.json
// Task removed from active list (or status updated to completed)
// Context preserved for session logs
// Can be archived to tasks/archive/ directory
```

---

## Cross-Session Recovery

**When a new session starts:**

1. **Check for active tasks file**
   ```javascript
   if (file_exists(".claude/active-tasks.json")) {
     tasks_data = read_json(".claude/active-tasks.json")
   }
   ```

2. **Filter incomplete tasks**
   ```javascript
   incomplete_tasks = tasks_data.tasks.filter(t => t.status !== "completed")
   ```

3. **Recreate native tasks**
   ```javascript
   for (task of incomplete_tasks) {
     new_id = TaskCreate({
       subject: task.subject,
       description: task.description,
       activeForm: task.activeForm
     })
     // Map old task.id → new_id for dependencies
   }
   ```

4. **Restore dependencies**
   ```javascript
   for (task of incomplete_tasks) {
     if (task.blockedBy.length > 0) {
       TaskUpdate({
         taskId: mapped_id(task.id),
         addBlockedBy: task.blockedBy.map(mapped_id)
       })
     }
   }
   ```

5. **Show recovered state**
   ```javascript
   TaskList()
   // User sees: "Continuing from previous session: 3 tasks in progress"
   ```

---

## Summary

**Orchestrator (main Claude) manages tasks**
- Creates tasks using TaskCreate for complex work
- Updates status as agents report using TaskUpdate
- Provides progress visibility via TaskList
- Persists to `.claude/active-tasks.json` file

**Agents report progress**
- Don't manage tasks directly
- Return results to orchestrator
- Orchestrator updates tasks and file

**File-based persistence**
- All active task data stored in JSON
- Cross-session recovery on startup
- Human-readable and editable

**Result: Complete visibility and context preservation**
