---
description: Synchronize Task Master task statuses based on conversation history and git state
argument-hint: [--all] [--dry-run] [--verbose]
allowed-tools: Bash(git *), mcp__task_master_ai__*, Read, Grep, Glob
---

# Task Sync: $ARGUMENTS

**Purpose:** When the AI agent has not updated Task Master task statuses during work, this command analyzes conversation history, git state (committed/uncommitted/unpushed changes), and codebase evidence to synchronize task statuses for tracking and traceability.

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

## When to Use

Use this command when:

- Tasks were completed but not marked as done in Task Master
- Work was done but task status wasn't updated to "in-progress"
- Commits reference tasks that are still marked as pending
- Conversation context shows completed work not reflected in Task Master
- Git history shows task-related commits but statuses are stale

## Workflow Summary

1. **GATHER** conversation context and recent work
2. **ANALYZE** git state (uncommitted, committed, unpushed)
3. **CORRELATE** changes to Task Master tasks
4. **PROPOSE** status updates with evidence
5. **APPLY** updates (or dry-run preview)

## Phase 0: Parse Arguments

Extract from `$ARGUMENTS`:

- **--all**: Sync all tasks (not just in-progress/pending)
- **--dry-run**: Preview changes without applying
- **--verbose**: Show detailed evidence for each status change

### Argument Examples

```bash
# Sync task statuses based on context
/task:sync

# Preview what would change
/task:sync --dry-run

# Show detailed evidence
/task:sync --verbose

# Check all tasks including completed ones
/task:sync --all
```

## Phase 1: Gather Context

### 1.1 Get Conversation Context

**Analyze recent conversation for completed work:**

- Review messages for task completions mentioned
- Look for "done", "completed", "finished", "implemented" language
- Identify file changes discussed in conversation
- Note any subtasks or tasks referenced by ID

**Key patterns to identify:**

```text
- "I've implemented X" → Task/subtask likely complete
- "Fixed the issue with Y" → Bug fix task likely complete
- "Added tests for Z" → Testing subtask likely complete
- "Refactored A to use B" → Refactoring task likely complete
- "Working on X now" → Task should be in-progress
```

### 1.2 Get Current Task Master State

```javascript
// Get all tasks with current statuses
const allTasks = mcp__task_master_ai__get_tasks({
  projectRoot: process.cwd(),
  withSubtasks: true,
});

// Separate by status
const inProgressTasks = allTasks.filter((t) => t.status === 'in-progress');
const pendingTasks = allTasks.filter((t) => t.status === 'pending');
const doneTasks = allTasks.filter((t) => t.status === 'done');

// Count tasks needing review
console.log(`Task Master State:`);
console.log(`  In-Progress: ${inProgressTasks.length}`);
console.log(`  Pending: ${pendingTasks.length}`);
console.log(`  Done: ${doneTasks.length}`);
```

## Phase 2: Analyze Git State

### 2.1 Check Uncommitted Changes

```bash
# Get uncommitted changes
UNCOMMITTED=$(git status --porcelain)
UNCOMMITTED_COUNT=$(echo "$UNCOMMITTED" | grep -c . || echo 0)

echo "📋 Uncommitted Changes: $UNCOMMITTED_COUNT files"

if [ "$UNCOMMITTED_COUNT" -gt 0 ]; then
  echo ""
  echo "Files with uncommitted changes:"
  git status --porcelain | while read -r line; do
    echo "  $line"
  done
fi
```

### 2.2 Check Recent Commits

```bash
# Get commits since last push
UNPUSHED=$(git log @{u}..HEAD --oneline 2>/dev/null || git log --oneline -10)
UNPUSHED_COUNT=$(echo "$UNPUSHED" | grep -c . || echo 0)

echo ""
echo "📋 Recent Commits: $UNPUSHED_COUNT"

if [ "$UNPUSHED_COUNT" -gt 0 ]; then
  echo ""
  echo "Recent commits:"
  git log @{u}..HEAD --oneline 2>/dev/null || git log --oneline -10
fi
```

### 2.3 Extract Task References from Commits

```bash
# Look for task references in commit messages
# Patterns: "task 1.2", "subtask 1.2.3", "(task 1)", "Task #1"
TASK_REFS=$(git log --oneline -20 | grep -iE 'task[: #]*[0-9]+(\.[0-9]+)*' || true)

echo ""
echo "📋 Commits Referencing Tasks:"
if [ -n "$TASK_REFS" ]; then
  echo "$TASK_REFS"
else
  echo "  (No explicit task references found in recent commits)"
fi
```

### 2.4 Analyze Commit Scopes

```bash
# Extract conventional commit scopes
COMMIT_SCOPES=$(git log --oneline -20 | grep -oE '\([a-z-]+\)' | sort | uniq -c | sort -rn)

echo ""
echo "📋 Commit Scopes (may correlate to tasks):"
if [ -n "$COMMIT_SCOPES" ]; then
  echo "$COMMIT_SCOPES"
fi
```

## Phase 3: Correlate Changes to Tasks

### 3.1 Match Files to Tasks

For each task with status pending or in-progress:

```javascript
function correlateFilesToTask(task, changedFiles) {
  const matches = [];

  // Extract keywords from task title and description
  const taskKeywords = extractKeywords(task.title + ' ' + (task.description || ''));

  for (const file of changedFiles) {
    const filePath = file.toLowerCase();
    const fileName = path.basename(filePath);

    // Check if file path contains task-related keywords
    for (const keyword of taskKeywords) {
      if (filePath.includes(keyword.toLowerCase())) {
        matches.push({
          file: file,
          reason: `File path contains "${keyword}" from task title/description`,
        });
        break;
      }
    }

    // Check for test files matching implementation
    if (filePath.includes('test') || filePath.includes('spec')) {
      const implPath = filePath.replace(/\.test\.|\.spec\./, '.').replace('tests/', 'src/');
      if (changedFiles.includes(implPath)) {
        matches.push({
          file: file,
          reason: 'Test file for changed implementation',
        });
      }
    }
  }

  return matches;
}
```

### 3.2 Search Codebase for Task Completion Evidence

For each in-progress or pending task:

```javascript
async function findCompletionEvidence(task) {
  const evidence = [];

  // Search for implementations mentioned in task
  const searchTerms = extractImplementationTerms(task);

  for (const term of searchTerms) {
    // Use Grep to find implementations
    const results = await grep({
      pattern: term,
      glob: '*.ts',
      path: 'src/',
    });

    if (results.length > 0) {
      evidence.push({
        type: 'implementation',
        term: term,
        files: results,
      });
    }
  }

  // Check for test files
  const testResults = await grep({
    pattern: task.id,
    glob: '*.test.ts',
  });

  if (testResults.length > 0) {
    evidence.push({
      type: 'tests',
      files: testResults,
    });
  }

  return evidence;
}
```

### 3.3 Analyze Conversation for Task Work

**Review conversation history for:**

1. **Explicit completions**: "I've finished task 1.2" or "Done implementing X"
2. **Code changes discussed**: File edits, new functions, bug fixes
3. **Test results shared**: "Tests passing" or "Coverage increased"
4. **Commits mentioned**: Commit messages referencing tasks

**Build task-to-evidence mapping:**

```javascript
const taskEvidence = {};

for (const task of [...inProgressTasks, ...pendingTasks]) {
  taskEvidence[task.id] = {
    task: task,
    conversationEvidence: [], // From conversation analysis
    gitEvidence: [], // From commit analysis
    codeEvidence: [], // From codebase search
    suggestedStatus: null,
    confidence: 'low', // low, medium, high
  };

  // Gather all evidence types
  // ... (from previous phases)

  // Determine suggested status based on evidence
  taskEvidence[task.id].suggestedStatus = determineSuggestedStatus(taskEvidence[task.id]);
  taskEvidence[task.id].confidence = calculateConfidence(taskEvidence[task.id]);
}
```

## Phase 4: Propose Status Updates

### 4.1 Generate Recommendations

```bash
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "📊 TASK STATUS SYNC RECOMMENDATIONS"
echo "═══════════════════════════════════════════════════════════════"
echo ""
```

For each task with evidence of status change:

```bash
echo "Task $TASK_ID: $TASK_TITLE"
echo "  Current Status: $CURRENT_STATUS"
echo "  Suggested Status: $SUGGESTED_STATUS"
echo "  Confidence: $CONFIDENCE"
echo ""
echo "  Evidence:"

# Show evidence based on --verbose flag
if [ "$VERBOSE" = true ]; then
  for evidence in "${EVIDENCE[@]}"; do
    echo "    ✓ $evidence"
  done
else
  echo "    ✓ ${EVIDENCE_COUNT} pieces of evidence found (use --verbose for details)"
fi

echo ""
echo "───────────────────────────────────────────────────────────────"
```

### 4.2 Categorize Changes

**Organize proposed changes by confidence:**

```bash
echo ""
echo "📋 SUMMARY"
echo ""

echo "High Confidence (will apply):"
for task in "${HIGH_CONFIDENCE[@]}"; do
  echo "  • Task $task.id: $task.currentStatus → $task.suggestedStatus"
done

echo ""
echo "Medium Confidence (review recommended):"
for task in "${MEDIUM_CONFIDENCE[@]}"; do
  echo "  ⚠️ Task $task.id: $task.currentStatus → $task.suggestedStatus"
done

echo ""
echo "Low Confidence (manual review required):"
for task in "${LOW_CONFIDENCE[@]}"; do
  echo "  ? Task $task.id: $task.currentStatus → $task.suggestedStatus"
done
```

### 4.3 Handle Dry Run

If `--dry-run` flag is set:

```bash
echo ""
echo "🔍 DRY RUN MODE - No changes applied"
echo ""
echo "To apply these changes, run:"
echo "  /task:sync"
echo ""
exit 0
```

## Phase 5: Apply Updates

### 5.1 Confirm with User

```bash
echo ""
echo "Apply status updates?"
echo ""
echo "  High confidence changes: $HIGH_CONFIDENCE_COUNT"
echo "  Medium confidence changes: $MEDIUM_CONFIDENCE_COUNT (will prompt)"
echo "  Low confidence changes: $LOW_CONFIDENCE_COUNT (skipped, manual review)"
echo ""
echo "Proceed? (y/N): "
```

### 5.2 Apply High Confidence Changes

```javascript
for (const update of highConfidenceUpdates) {
  console.log(
    `Updating Task ${update.taskId}: ${update.currentStatus} → ${update.suggestedStatus}`
  );

  mcp__task_master_ai__set_task_status({
    projectRoot: process.cwd(),
    id: update.taskId,
    status: update.suggestedStatus,
  });

  // Log evidence to task
  mcp__task_master_ai__update_subtask({
    projectRoot: process.cwd(),
    id: update.taskId,
    prompt: `Status synced to "${update.suggestedStatus}" based on:
${update.evidence.map((e) => `- ${e}`).join('\n')}

Synced via /task:sync command.`,
  });

  console.log(`  ✓ Updated`);
}
```

### 5.3 Handle Medium Confidence Changes

```bash
echo ""
echo "📋 Medium Confidence Changes (Review Each)"
echo ""

for task in "${MEDIUM_CONFIDENCE[@]}"; do
  echo "Task $task.id: $task.title"
  echo "  Current: $task.currentStatus"
  echo "  Suggested: $task.suggestedStatus"
  echo ""
  echo "  Evidence:"
  for evidence in "${task.evidence[@]}"; do
    echo "    • $evidence"
  done
  echo ""
  echo "Apply this change? (y/n/s=skip all): "
  read -r RESPONSE

  case $RESPONSE in
    y|Y)
      # Apply update
      mcp__task_master_ai__set_task_status({
        projectRoot: process.cwd(),
        id: task.id,
        status: task.suggestedStatus,
      })
      echo "  ✓ Applied"
      ;;
    s|S)
      echo "Skipping remaining medium confidence changes"
      break
      ;;
    *)
      echo "  ⏭️ Skipped"
      ;;
  esac
  echo ""
done
```

### 5.4 Report Low Confidence Items

```bash
echo ""
echo "📋 Low Confidence - Manual Review Required"
echo ""
echo "These tasks may need status updates but lack sufficient evidence:"
echo ""

for task in "${LOW_CONFIDENCE[@]}"; do
  echo "Task $task.id: $task.title"
  echo "  Current: $task.currentStatus"
  echo "  Possible: $task.suggestedStatus"
  echo "  Reason: $task.reason"
  echo ""
done

echo "Review these manually with:"
echo "  mcp__task_master_ai__get_task({ id: '<task-id>' })"
echo "  mcp__task_master_ai__set_task_status({ id: '<task-id>', status: '<status>' })"
```

## Phase 6: Final Summary

### 6.1 Show Sync Results

```bash
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ TASK SYNC COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Changes Applied:"
echo "  • High confidence: $HIGH_APPLIED / $HIGH_TOTAL"
echo "  • Medium confidence: $MEDIUM_APPLIED / $MEDIUM_TOTAL"
echo "  • Low confidence: $LOW_TOTAL (manual review)"
echo ""
echo "Updated Task Master State:"
echo "  In-Progress: $NEW_IN_PROGRESS"
echo "  Pending: $NEW_PENDING"
echo "  Done: $NEW_DONE"
echo ""
```

### 6.2 Suggest Next Actions

```bash
echo "Next Steps:"
echo ""

if [ "$UNCOMMITTED_COUNT" -gt 0 ]; then
  echo "  1. Commit uncommitted changes:"
  echo "     /commit"
  echo ""
fi

if [ "$UNPUSHED_COUNT" -gt 0 ]; then
  echo "  2. Push committed changes:"
  echo "     git push"
  echo ""
fi

echo "  3. Continue with next task:"
echo "     /task:next"
echo ""
```

## Status Determination Logic

### Pending → In-Progress

Evidence that suggests a pending task is now in-progress:

- Files in task scope have uncommitted changes
- Conversation mentions "working on" or "starting" the task
- Recent commits touch files related to task
- Test files created but tests failing

### In-Progress → Done

Evidence that suggests an in-progress task is complete:

- Conversation says "completed", "finished", "done"
- All subtasks marked as done
- Implementation files exist and pass linting
- Tests exist and pass
- Commits reference task with completion language

### Pending → Done (Skipped In-Progress)

Sometimes tasks are completed without marking in-progress:

- Implementation exists in codebase
- Tests exist and pass
- No uncommitted changes in task scope
- Commits reference task completion

## Confidence Levels

### High Confidence

- Explicit mention in conversation: "Task 1.2 is done"
- All subtasks completed
- Commit message says "complete" or "finish" with task reference
- Implementation + tests exist and pass

### Medium Confidence

- Files changed match task scope
- Partial subtasks completed
- Implementation exists but tests unclear
- Conversation implies completion without explicit statement

### Low Confidence

- Only file changes without explicit task connection
- Task scope matches but no clear completion signal
- Stale task (no recent activity)

## Error Handling

### No Tasks Found

```bash
echo "⚠️ No tasks found requiring sync"
echo ""
echo "All tasks appear to be in the correct state."
echo ""
echo "If you believe tasks need updating, check manually:"
echo "  mcp__task_master_ai__get_tasks({ withSubtasks: true })"
```

### Task Master Not Initialized

```bash
echo "⚠️ Task Master Not Initialized"
echo ""
echo "Initialize Task Master first:"
echo "  /task:init"
```

### No Evidence Found

```bash
echo "⚠️ No clear evidence for status changes"
echo ""
echo "Could not find sufficient evidence to suggest status changes."
echo ""
echo "Possible reasons:"
echo "  - Work done in different branch"
echo "  - Tasks not clearly connected to file changes"
echo "  - Recent work not yet committed"
echo ""
echo "Update tasks manually if needed:"
echo "  mcp__task_master_ai__set_task_status({ id: '<id>', status: '<status>' })"
```

## Best Practices

### When to Sync

1. **After a work session** - Ensure all completed work is tracked
2. **Before context switches** - Clean up task state before new work
3. **Before /task:next** - Ensure accurate state for task selection
4. **After long conversations** - When many tasks were discussed

### Maintaining Task Hygiene

1. **Update in real-time** - Mark tasks in-progress when starting
2. **Commit with context** - Include task references in commits
3. **Complete subtasks first** - Mark subtasks done before parent
4. **Sync regularly** - Don't let state drift too far

### Avoiding Status Drift

1. **Use /task:next** - It enforces commit and status updates
2. **Reference task IDs** - In conversation and commits
3. **Check status after work** - Quick verification saves time
4. **Run /task:sync** - When unsure about state

---

**For comprehensive Task Master documentation:**

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