---
description: Commit current work, determine task state, complete work, or start next task
argument-hint: [quick|easy|important|continue] [--refine] [--skip-validation] [--no-commit]
allowed-tools: Bash(git *), mcp__task_master_ai__*, Read, Grep, Glob, SlashCommand(/commit *)
---

# Next Task: $ARGUMENTS

**CRITICAL: Always commit current work before moving to next task.** This command enforces clean git state through intelligent commit grouping, preventing technical debt and hook failures.

Analyze current task state, commit any uncommitted work to current task/subtask, complete in-progress work, or intelligently select and start the next available task based on dependencies, complexity, and project context.

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

## First Things First: Prioritization Principles

**Apply Covey's Time Management Matrix to task selection:**

Tasks are classified into four quadrants based on Urgency and Importance:

| Quadrant | Urgency    | Importance    | Action         | Examples                                            |
| -------- | ---------- | ------------- | -------------- | --------------------------------------------------- |
| **Q1**   | Urgent     | Important     | Do First       | Blocking bugs, CI failures, deadline tasks          |
| **Q2**   | Not Urgent | Important     | **Focus Here** | Core features, architecture, tests, PRD scope       |
| **Q3**   | Urgent     | Not Important | Defer/Delegate | Optional improvements, nice-to-haves with deadlines |
| **Q4**   | Not Urgent | Not Important | Eliminate      | Out-of-scope, polish, gold-plating                  |

**Core Principle: Spend most time in Q2 (Important but Not Urgent)**

Q2 tasks directly deliver value aligned with the branch scope. These are the "big rocks" that should be placed first before urgency fills your schedule with Q1 and Q3 tasks.

**Determining Importance (Branch Scope Alignment):**

A task is **Important** if it:

- Directly implements requirements from the PRD/branch scope
- Is explicitly mentioned in branch name or ticket description
- Unblocks other Important tasks
- Delivers user-facing value or fixes user-impacting bugs

A task is **Not Important** if it:

- Is "nice to have" but not in branch scope
- Could be done later without affecting the PR
- Is a refactoring or improvement unrelated to the feature
- Was discovered during work but not originally planned

**Determining Urgency:**

A task is **Urgent** if it:

- Blocks CI/CD (tests failing, build broken)
- Has an external deadline
- Blocks other team members
- Is a production bug

A task is **Not Urgent** if it:

- Can be deferred to a follow-up PR
- Has no external deadline
- Does not block other work

**Fast Workarounds for Deferred Blocking Tasks:**

When a Q3/Q4 task blocks a Q2 task, use a fast workaround instead of full implementation:

- Skip the optional feature, add TODO comment
- Use hardcoded value instead of configurable option
- Mock the dependency in tests
- Create follow-up issue/task instead of implementing now

## Governance Principles

**Small commits are key to governance:**

1. **Commit early, commit often** - Prevents hook processing backlog
2. **Group by context** - Files belong to task/subtask they relate to
3. **Never accumulate** - Large uncommitted sets = technical debt
4. **Hook compliance** - Tests and linting run on small changesets
5. **Clean transitions** - Always commit before switching tasks

**Why this matters:**

- Git hooks run tests and check coverage on commit
- Large uncommitted sets cause long processing times
- Failed hooks block commits, creating technical debt
- Small focused commits pass hooks quickly
- Clean git state = clear task boundaries

## Workflow Summary

This command operates in strict priority order, applying **First Things First** principles:

**0. COMMIT current work (Phase 1) - ALWAYS FIRST**

- Check for uncommitted changes
- Group files to current task/subtask
- Warn about unrelated files
- Use /commit for intelligent grouping
- Block proceeding until git is clean

**1. RESUME in-progress tasks (Phase 3) - Always address current work**

- Validate tasks aren't already complete
- Show progress and remaining work
- Prevent context switching

**2. VALIDATE project state (Phase 4) - Ensure dependencies current**

- Check and fix dependency issues
- Run complexity analysis if missing/stale
- Auto-expand high-complexity tasks (≤3)

**3. SELECT next task (Phase 5-6) - First Things First ranking**

- Gather branch scope context from PRD/ticket
- Classify tasks into quadrants (Q1-Q4)
- Filter by keywords within Q1/Q2 (important tasks only)
- Rank by quadrant, then strategic value
- Flag Q3/Q4 tasks blocking Q2 work (suggest workarounds)

**4. REFINE if needed (Phase 7) - Optional --refine flag**

- Load documentation context
- Expand with research mode
- Ask design questions

**5. PRESENT recommendation (Phase 8) - Rich context with quadrant**

- Show primary recommendation with quadrant classification
- Explain why it's important (scope alignment)
- Provide Q1/Q2 alternatives only
- Flag deferred Q3/Q4 tasks for later

## Phase 0: Parse Arguments

Extract from `$ARGUMENTS`:

- **Filter Keywords**:
  - `quick` - Find task estimated <2 hours
  - `easy` - Find low complexity task
  - `important` - Find high priority regardless of complexity
  - `continue` - Resume last worked task (in-progress or recently completed)
- **--refine**: Expand task into subtasks with design questions before starting
- **--skip-validation**: Skip tag/branch validation checks
- **--no-commit**: Skip commit phase (DANGEROUS - only for emergency use)

### Argument Examples

```bash
# Get next task (commits current work first)
/task:next

# Find a quick task after committing
/task:next quick

# Resume last task (commits current work first)
/task:next continue

# Get next task, refine, and commit current work
/task:next --refine

# Emergency: skip commit phase (NOT recommended)
/task:next --no-commit
```

## Phase 1: Commit Current Work (CRITICAL)

**ALWAYS execute this phase unless --no-commit flag is present.**

### 1.1 Check Git Status

```bash
# Check for uncommitted changes
git status --porcelain

# Count staged files
STAGED_COUNT=$(git diff --cached --name-only | wc -l | tr -d ' ')

# Count unstaged files
UNSTAGED_COUNT=$(git diff --name-only | wc -l | tr -d ' ')

# Count untracked files
UNTRACKED_COUNT=$(git ls-files --others --exclude-standard | wc -l | tr -d ' ')

TOTAL_UNCOMMITTED=$((STAGED_COUNT + UNSTAGED_COUNT + UNTRACKED_COUNT))
```

**If no uncommitted changes:**

```bash
echo "✅ Git state clean, proceeding to task selection"
# Continue to Phase 2
```

**If uncommitted changes found:**

```bash
echo "⚠️  Found $TOTAL_UNCOMMITTED uncommitted files"
echo "   - Staged: $STAGED_COUNT"
echo "   - Modified: $UNSTAGED_COUNT"
echo "   - Untracked: $UNTRACKED_COUNT"
echo ""
echo "🔒 GOVERNANCE: Commit before moving to next task"
echo ""
```

### 1.2 Get Current Task/Subtask Context

**Use MCP to get current work context:**

```javascript
// Get in-progress tasks
const inProgressTasks = mcp__task_master_ai__get_tasks({
  projectRoot: process.cwd(),
  status: 'in-progress',
  withSubtasks: true,
});

// Determine current task context
let currentTaskContext = null;

if (inProgressTasks.length > 0) {
  const task = inProgressTasks[0]; // Primary in-progress task

  // Find current subtask (first pending or in-progress subtask)
  const currentSubtask = task.subtasks?.find(
    (st) => st.status === 'in-progress' || st.status === 'pending'
  );

  currentTaskContext = {
    taskId: task.id,
    taskTitle: task.title,
    taskScope: extractScope(task), // e.g., "cli", "auth", "paths"
    subtaskId: currentSubtask?.id,
    subtaskTitle: currentSubtask?.title,
  };
}
```

### 1.3 Analyze Uncommitted Files vs. Task Context

**Match files to current task/subtask:**

```bash
# Get all uncommitted files
ALL_FILES=($(git status --porcelain | awk '{print $2}'))

RELATED_FILES=()
UNRELATED_FILES=()

for file in "${ALL_FILES[@]}"; do
  # Extract file directory and keywords
  FILE_DIR=$(dirname "$file")
  FILE_NAME=$(basename "$file")

  MATCHED=false

  if [ -n "$currentTaskContext" ]; then
    # Check if file path contains task scope
    if [[ "$file" =~ ${currentTaskContext.taskScope} ]]; then
      MATCHED=true
    fi

    # Check if file mentioned in task/subtask details
    if [ -n "$currentTaskContext.subtaskTitle" ]; then
      SUBTASK_KEYWORDS=$(echo "$currentTaskContext.subtaskTitle" |
        tr '[:upper:]' '[:lower:]' | tr -s '[:space:]' '\n')

      for keyword in $SUBTASK_KEYWORDS; do
        if [[ "$file" =~ $keyword ]]; then
          MATCHED=true
          break
        fi
      done
    fi

    # Check if test file for implementation file
    if [[ "$file" =~ test\.ts$ ]]; then
      IMPL_FILE=$(echo "$file" | sed 's|tests/||; s|\.test\.ts$|.ts|')
      # Check if impl file in related files
      if [[ " ${RELATED_FILES[@]} " =~ " ${IMPL_FILE} " ]]; then
        MATCHED=true
      fi
    fi
  fi

  if [ "$MATCHED" = true ]; then
    RELATED_FILES+=("$file")
  else
    UNRELATED_FILES+=("$file")
  fi
done
```

### 1.4 Present Commit Analysis

**If all files are related:**

```bash
echo "📋 Uncommitted Changes Analysis"
echo ""
echo "Current Context:"
if [ -n "$currentTaskContext" ]; then
  echo "  - Task: $currentTaskContext.taskId - $currentTaskContext.taskTitle"
  if [ -n "$currentTaskContext.subtaskId" ]; then
    echo "  - Subtask: $currentTaskContext.subtaskId - $currentTaskContext.subtaskTitle"
  fi
else
  echo "  - No active task/subtask"
fi
echo ""
echo "Files to commit: ${#RELATED_FILES[@]} (all related to current work)"
for file in "${RELATED_FILES[@]}"; do
  echo "  ✓ $file"
done
echo ""
echo "Committing changes to current task context..."
```

**If unrelated files found:**

```bash
echo "⚠️  Uncommitted Changes Analysis"
echo ""
echo "Current Context:"
echo "  - Task: $currentTaskContext.taskId - $currentTaskContext.taskTitle"
if [ -n "$currentTaskContext.subtaskId" ]; then
  echo "  - Subtask: $currentTaskContext.subtaskId - $currentTaskContext.subtaskTitle"
fi
echo ""
echo "Related files (${#RELATED_FILES[@]}):"
for file in "${RELATED_FILES[@]}"; do
  echo "  ✓ $file"
done
echo ""
echo "⚠️  Unrelated files (${#UNRELATED_FILES[@]}):"
for file in "${UNRELATED_FILES[@]}"; do
  echo "  ⚠️  $file"
done
echo ""
echo "🔒 GOVERNANCE WARNING:"
echo "   Unrelated files found. These will NOT be committed."
echo "   Consider committing them separately with proper context."
echo ""
echo "Options:"
echo "  1. Commit related files only (recommended)"
echo "  2. Commit all files (creates unfocused commit)"
echo "  3. Cancel and manually organize commits"
echo ""
read -p "Choose [1/2/3]: " CHOICE
```

### 1.5 Execute Commit via /commit Command

**If user chooses to commit related files:**

```bash
# Stage only related files
git reset >/dev/null 2>&1 || true  # Clear staging
for file in "${RELATED_FILES[@]}"; do
  git add "$file"
done

echo ""
echo "Committing ${#RELATED_FILES[@]} files using intelligent grouping..."
echo ""

# Call /commit slash command (will intelligently group and create commits)
/commit
```

**The /commit command will:**

1. Use Task Master context to understand current work
2. Group files by current task/subtask
3. Generate conventional commit messages
4. Run QA hooks (linting, tests, type checking)
5. Create focused commit(s)

**If user chooses to commit all files:**

```bash
echo ""
echo "⚠️  Committing all files (including unrelated)"
echo ""

# Call /commit with --all flag
/commit --all
```

**If user cancels:**

```bash
echo ""
echo "❌ Commit cancelled"
echo ""
echo "Please organize commits manually before proceeding:"
echo "  1. Stage related files: git add <files>"
echo "  2. Run /commit to create focused commits"
echo "  3. Run /task:next again when git is clean"
echo ""
exit 1
```

### 1.6 Verify Clean Git State

```bash
# After commit, verify git is clean
UNCOMMITTED=$(git status --porcelain | wc -l | tr -d ' ')

if [ "$UNCOMMITTED" -gt 0 ]; then
  echo ""
  echo "⚠️  Warning: Git still has uncommitted changes"
  echo "   Files remaining: $UNCOMMITTED"
  echo ""
  echo "This may be due to:"
  echo "  - Commit hooks modified files (auto-formatting)"
  echo "  - User chose to skip unrelated files"
  echo "  - Commit failed (check errors above)"
  echo ""

  if [ ${#UNRELATED_FILES[@]} -gt 0 ]; then
    echo "Unrelated files were intentionally skipped:"
    for file in "${UNRELATED_FILES[@]}"; do
      echo "  - $file"
    done
    echo ""
    echo "Commit these separately with proper context before next work."
  fi

  echo "Proceed to next task anyway? (y/N): "
  read -r PROCEED

  if [[ ! "$PROCEED" =~ ^[Yy]$ ]]; then
    echo "Cancelled. Clean git state before proceeding."
    exit 1
  fi
fi

echo ""
echo "✅ Git state clean, proceeding to task selection"
echo ""
```

### 1.7 Update Task/Subtask with Commit Info

```javascript
// Log commit to current subtask
if (currentTaskContext && currentTaskContext.subtaskId) {
  const commitSHA = execSync('git rev-parse HEAD').toString().trim().substring(0, 7);
  const commitMsg = execSync('git log -1 --pretty=%B').toString().trim().split('\n')[0];

  mcp__task_master_ai__update_subtask({
    projectRoot: process.cwd(),
    id: currentTaskContext.subtaskId,
    prompt: `Committed changes: ${commitSHA} - ${commitMsg}

Files committed: ${RELATED_FILES.join(', ')}

Implementation progress logged.`,
  });
}
```

## Phase 2: Context Gathering

### 2.1 Verify Tag Context (unless --skip-validation)

```bash
# Get current git branch
BRANCH=$(git branch --show-current)

# Extract ticket ID from branch name (e.g., feature/GRC-44-desc → GRC-44)
TICKET_ID=$(echo "$BRANCH" | grep -oE '[A-Z]+-[0-9]+' | head -1)
```

**Use MCP to check current tag:**

```javascript
// List all tags
const tags = mcp__task_master_ai__list_tags({ projectRoot: process.cwd() });

// Check if ticket tag exists and is active
```

**If ticket tag doesn't match branch:**

- Show warning: "⚠️ Current Task Master tag doesn't match git branch"
- Show current tag vs expected tag
- Suggest: "Switch to correct tag with: mcp**task_master_ai**use_tag"
- Ask if should continue anyway or switch first

### 2.2 Get Current Task State

**Use MCP to gather comprehensive state:**

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

// Get tasks by status
const inProgressTasks = mcp__task_master_ai__get_tasks({
  projectRoot: process.cwd(),
  status: 'in-progress',
  withSubtasks: true,
});

const pendingTasks = mcp__task_master_ai__get_tasks({
  projectRoot: process.cwd(),
  status: 'pending',
  withSubtasks: true,
});

const blockedTasks = mcp__task_master_ai__get_tasks({
  projectRoot: process.cwd(),
  status: 'blocked',
  withSubtasks: true,
});
```

**Collect information:**

- Total tasks by status (in-progress, pending, blocked, done)
- Recently completed tasks (done status, recent activity)
- Tasks with no dependencies vs. blocked tasks
- Tasks near completion (high % done subtasks)

### 2.3 Analyze Recent Activity

```bash
# Check git log for recent commits
git log --oneline -10

# Look for patterns in recent work
RECENT_SCOPES=$(git log --oneline -10 | grep -oE '\([a-z]+\)' |
  sort | uniq -c | sort -rn | head -3)
```

**Extract patterns:**

- Last worked task/subtask (from commit metadata in Phase 1.7)
- Time since last activity
- Common scopes/areas worked on
- Task completion velocity

## Phase 3: Resume In-Progress Work (Priority)

### 3.1 Check for In-Progress Tasks

**CRITICAL: In-progress tasks MUST be addressed before starting new work.**

```javascript
// Get details of in-progress tasks
const inProgressDetails = [];
for (const task of inProgressTasks) {
  const details = mcp__task_master_ai__get_task({
    projectRoot: process.cwd(),
    id: task.id,
  });
  inProgressDetails.push(details);
}
```

**If in-progress tasks exist, this becomes a RESUME command:**

### 3.2 Analyze In-Progress State

**For each in-progress task:**

```bash
# Check recent commits for this task
git log --oneline --all --grep="$TASK_SCOPE" -10

# Check time since last commit
LAST_COMMIT=$(git log --oneline -1 --format=%ct)
CURRENT_TIME=$(date +%s)
IDLE_HOURS=$(( (CURRENT_TIME - LAST_COMMIT) / 3600 ))
```

**Completion analysis:**

```javascript
// Calculate completion percentage
const totalSubtasks = task.subtasks?.length || 0;
const doneSubtasks = task.subtasks?.filter((st) => st.status === 'done').length || 0;
const completionPercent = totalSubtasks > 0 ? (doneSubtasks / totalSubtasks) * 100 : 0;
```

### 3.3 Validate Task Legitimacy

**Check if task appears complete but not marked:**

```bash
# Search for implementation evidence
# Look for files/functions mentioned in task description
```

**Use Grep/Glob to search:**

- Files matching task scope
- Functions/classes mentioned in task
- Test files for this feature
- Related documentation

**If evidence suggests completion:**

```bash
echo "⚠️  Task Appears Complete"
echo ""
echo "Task $TASK_ID: $TASK_TITLE (status: in-progress)"
echo ""
echo "Evidence Found:"
echo "  ✅ Implementation: [files found]"
echo "  ✅ Tests: [test files found]"
echo "  ✅ Documentation: [docs found]"
echo ""
echo "Mark this task as done? (y/N): "
```

### 3.4 Present In-Progress Task

**If task legitimately in-progress:**

```bash
echo "🔄 Resume In-Progress Task"
echo ""
echo "Task $TASK_ID: $TASK_TITLE"
echo "Status: in-progress (${COMPLETION_PERCENT}% complete)"
echo "Last Activity: ${IDLE_HOURS} hours ago"
echo ""
echo "Progress:"
for subtask in "${SUBTASKS[@]}"; do
  if [ "$subtask.status" = "done" ]; then
    echo "  ✅ Subtask $subtask.id: $subtask.title (done)"
  elif [ "$subtask.status" = "in-progress" ]; then
    echo "  ⏳ Subtask $subtask.id: $subtask.title (in-progress)"
  else
    echo "  ⭕ Subtask $subtask.id: $subtask.title (pending)"
  fi
done
echo ""
echo "Remaining Work: [describe based on pending subtasks]"
echo ""
echo "Resume now? Continue with subtask $CURRENT_SUBTASK_ID"
```

**STOP HERE if in-progress tasks found. Do not proceed unless:**

- User explicitly declines to resume
- In-progress task is marked as done
- In-progress task is marked as blocked

## Phase 4: Validate Dependencies and Complexity

**Before selecting next task, ensure project analysis is complete.**

### 4.1 Check Dependency Validation

```javascript
// Validate dependencies
mcp__task_master_ai__validate_dependencies({
  projectRoot: process.cwd(),
});
```

**If issues found, auto-fix:**

```javascript
mcp__task_master_ai__fix_dependencies({
  projectRoot: process.cwd(),
});
```

### 4.2 Check Complexity Analysis

```bash
# Check if complexity report exists and is recent
if [ ! -f .taskmaster/reports/task-complexity-report.json ] || \
   [ $(find .taskmaster/reports/task-complexity-report.json -mtime +7) ]; then
  echo "📊 Running complexity analysis..."

  # Run analysis with research mode
  mcp__task_master_ai__analyze_project_complexity({
    projectRoot: process.cwd(),
    research: true,
    threshold: 5,
  })
fi
```

### 4.3 Auto-Expand High-Complexity Tasks

```javascript
// Find tasks needing expansion (≤3 at a time)
const needsExpansion = pendingTasks
  .filter((task) => !task.subtasks || task.subtasks.length === 0)
  .filter((task) => /* check complexity report */ true)
  .slice(0, 3);

// Expand each
for (const task of needsExpansion) {
  mcp__task_master_ai__expand_task({
    projectRoot: process.cwd(),
    id: task.id,
    research: true,
  });
}
```

## Phase 5: Select Next Task (First Things First)

### 5.1 Gather Branch Scope Context

**Before ranking, understand what the branch is trying to achieve:**

```bash
# Extract branch scope from branch name and ticket
BRANCH=$(git branch --show-current)
TICKET_ID=$(echo "$BRANCH" | grep -oE '[A-Z]+-[0-9]+' | head -1)

# Look for PRD or requirements file
PRD_FILE=$(ls -1 docs/requirements/prd.*.md .taskmaster/docs/prd.* 2>/dev/null | head -1)

# Extract core scope keywords from PRD title/summary
if [ -f "$PRD_FILE" ]; then
  SCOPE_KEYWORDS=$(head -20 "$PRD_FILE" | grep -iE 'title|summary|scope|goal' |
    tr '[:upper:]' '[:lower:]' | tr -cs 'a-z' '\n' | sort -u)
fi
```

### 5.2 Classify Tasks by Quadrant

**Apply First Things First classification:**

```javascript
function classifyTask(task, branchScope, blockedTasks) {
  // Determine Importance (alignment with branch scope)
  const isImportant =
    branchScope.keywords.some((kw) => task.title.toLowerCase().includes(kw)) ||
    branchScope.keywords.some((kw) => task.description?.toLowerCase().includes(kw)) ||
    task.priority === 'high' ||
    task.priority === 'critical' ||
    // Unblocks other important tasks
    blockedTasks.some((bt) => bt.dependencies?.includes(task.id) && bt.priority === 'high');

  // Determine Urgency
  const isUrgent =
    task.tags?.includes('bug') ||
    task.tags?.includes('blocker') ||
    task.title.toLowerCase().includes('fix') ||
    task.title.toLowerCase().includes('broken') ||
    // Blocks other tasks
    blockedTasks.some((bt) => bt.dependencies?.includes(task.id));

  // Classify into quadrant
  if (isUrgent && isImportant) return 'Q1'; // Do First
  if (!isUrgent && isImportant) return 'Q2'; // Focus Here (core scope)
  if (isUrgent && !isImportant) return 'Q3'; // Defer/Delegate
  return 'Q4'; // Eliminate/Skip
}

// Classify all pending tasks
const classifiedTasks = pendingTasks.map((task) => ({
  ...task,
  quadrant: classifyTask(task, branchScope, blockedTasks),
}));
```

### 5.3 Handle Filter Keywords

**Apply user filters within quadrant priority:**

```javascript
let candidates = classifiedTasks;

if (filterKeyword === 'quick') {
  // Quick tasks within Q1/Q2 only
  candidates = candidates
    .filter((t) => t.quadrant === 'Q1' || t.quadrant === 'Q2')
    .filter((t) => !t.subtasks || t.subtasks.length <= 3);
} else if (filterKeyword === 'easy') {
  // Low complexity within Q1/Q2
  candidates = candidates.filter(
    (t) => t.quadrant === 'Q1' || t.quadrant === 'Q2'
    /* && check complexity report for low complexity */
  );
} else if (filterKeyword === 'important') {
  // Q1 and Q2 only (already important by definition)
  candidates = candidates.filter((t) => t.quadrant === 'Q1' || t.quadrant === 'Q2');
} else if (filterKeyword === 'continue') {
  // Find task related to recent work within Q1/Q2
  const recentScope = /* extract from git log */;
  candidates = candidates
    .filter((t) => t.quadrant === 'Q1' || t.quadrant === 'Q2')
    .filter((t) => /* matches recent scope */);
}
```

### 5.4 Check Dependencies

```javascript
// Filter out blocked tasks
const availableTasks = candidates.filter((task) => {
  const deps = task.dependencies || [];
  return deps.every((depId) => {
    const dep = allTasks.find((t) => t.id === depId);
    return dep?.status === 'done';
  });
});
```

### 5.5 Apply First Things First Ranking

**Ranking by quadrant, then by strategic value:**

```javascript
const rankedTasks = availableTasks.sort((a, b) => {
  // 1. Quadrant priority (Q1 > Q2 > Q3 > Q4)
  const quadrantOrder = { Q1: 1, Q2: 2, Q3: 3, Q4: 4 };
  if (quadrantOrder[a.quadrant] !== quadrantOrder[b.quadrant]) {
    return quadrantOrder[a.quadrant] - quadrantOrder[b.quadrant];
  }

  // 2. Within same quadrant: tasks that unblock most other Q1/Q2 tasks
  const aUnblocks = allTasks.filter(
    (t) => t.dependencies?.includes(a.id) && (t.quadrant === 'Q1' || t.quadrant === 'Q2')
  ).length;
  const bUnblocks = allTasks.filter(
    (t) => t.dependencies?.includes(b.id) && (t.quadrant === 'Q1' || t.quadrant === 'Q2')
  ).length;
  if (aUnblocks !== bUnblocks) return bUnblocks - aUnblocks;

  // 3. Priority within quadrant
  const priorityOrder = { critical: 1, high: 2, medium: 3, low: 4 };
  return (priorityOrder[a.priority] || 3) - (priorityOrder[b.priority] || 3);
});
```

### 5.6 Handle Q3/Q4 Blocking Tasks

**When a Q3/Q4 task blocks a Q2 task, suggest workaround:**

```javascript
const blockedQ2Tasks = classifiedTasks.filter(
  (t) =>
    t.quadrant === 'Q2' &&
    t.dependencies?.some((depId) => {
      const dep = classifiedTasks.find((d) => d.id === depId);
      return dep && (dep.quadrant === 'Q3' || dep.quadrant === 'Q4') && dep.status !== 'done';
    })
);

if (blockedQ2Tasks.length > 0) {
  console.log('⚠️  Important tasks blocked by optional dependencies:');
  for (const task of blockedQ2Tasks) {
    const blockingDeps = task.dependencies
      .map((id) => classifiedTasks.find((t) => t.id === id))
      .filter((d) => d && (d.quadrant === 'Q3' || d.quadrant === 'Q4'));

    console.log(`  Q2 Task ${task.id}: ${task.title}`);
    console.log(`  Blocked by: ${blockingDeps.map((d) => `${d.id} (${d.quadrant})`).join(', ')}`);
    console.log(`  💡 Consider: Fast workaround instead of full implementation`);
  }
}
```

## Phase 6: Validate Recommendation

### 6.1 Double-Check Completion

```javascript
// Verify task isn't already done
const taskDetails = mcp__task_master_ai__get_task({
  projectRoot: process.cwd(),
  id: recommendedTask.id,
});

// Search codebase for evidence
// If found, ask to mark as done
```

### 6.2 Check Expansion Need

```javascript
const needsExpansion =
  (!taskDetails.subtasks || taskDetails.subtasks.length === 0) &&
  (taskDetails.description.length > 200 ||
   taskDetails.description.includes('implement') ||
   !taskDetails.details);

if (needsExpansion && !refineFlag) {
  echo "🔸 Complex task without subtasks"
  echo "   Recommend using --refine flag"
}
```

## Phase 7: Task Refinement (if --refine)

### 7.1 Gather Context

```bash
# Read planning documents
ls -la *.md 2>/dev/null | grep -iE 'plan|gap|prd'
ls -la docs/requirements/*.md 2>/dev/null
ls -la docs/architecture/*.md 2>/dev/null
```

### 7.2 Expand with Research

```javascript
mcp__task_master_ai__expand_task({
  projectRoot: process.cwd(),
  id: recommendedTask.id,
  num: '8',
  research: true,
  prompt: 'Context from documentation...',
});
```

### 7.3 Present Design Questions

Ask about:

- Architecture approach
- Implementation details
- Testing strategy
- Integration points
- Performance considerations
- Security implications

### 7.4 Refine Based on Feedback

```javascript
mcp__task_master_ai__update_task({
  projectRoot: process.cwd(),
  id: recommendedTask.id,
  prompt: 'Refined requirements based on feedback...',
});
```

## Phase 8: Present Recommendation (First Things First)

### 8.1 Show Primary Recommendation with Quadrant

```bash
echo "🎯 Recommended Task"
echo ""
echo "Task ID: $TASK_ID"
echo "Title: $TASK_TITLE"
echo "Quadrant: $TASK_QUADRANT"
echo "Priority: $TASK_PRIORITY"
echo ""

# Explain quadrant classification
case $TASK_QUADRANT in
  Q1)
    echo "⚡ Q1 (Urgent + Important): This task blocks other work or fixes a critical issue."
    ;;
  Q2)
    echo "🎯 Q2 (Important): Core scope task aligned with branch requirements."
    ;;
  Q3)
    echo "⏳ Q3 (Urgent but Optional): Consider deferring or using fast workaround."
    ;;
  Q4)
    echo "🚫 Q4 (Optional): Not recommended. Consider skipping or deferring."
    ;;
esac
echo ""

# Show scope alignment
echo "Branch Scope Alignment:"
echo "  Branch: $BRANCH"
if [ -n "$SCOPE_MATCH" ]; then
  echo "  ✓ Matches: $SCOPE_MATCH"
else
  echo "  ⚠️ Not directly in scope (may be supporting work)"
fi
echo ""

echo "Description:"
echo "$TASK_DESCRIPTION"
echo ""

echo "Dependencies:"
for dep in "${DEPENDENCIES[@]}"; do
  echo "  ✅ Task $dep (done)"
done
echo ""

echo "Subtasks: ${#SUBTASKS[@]} total"
for subtask in "${SUBTASKS[@]}"; do
  echo "  $subtask.id: $subtask.title (pending)"
done
```

### 8.2 Show Q1/Q2 Alternatives Only

```bash
echo ""
echo "🔀 Alternatives (Important Tasks Only)"
echo ""

# Show other Q1 tasks if any
if [ ${#Q1_TASKS[@]} -gt 1 ]; then
  echo "Q1 (Urgent + Important):"
  for task in "${Q1_TASKS[@]:1:2}"; do
    echo "  Task $task.id: $task.title"
  done
  echo ""
fi

# Show Q2 alternatives
if [ ${#Q2_TASKS[@]} -gt 0 ]; then
  echo "Q2 (Core Scope):"
  for task in "${Q2_TASKS[@]:0:3}"; do
    echo "  Task $task.id: $task.title"
    if [ -n "$task.unblocks" ]; then
      echo "    ↳ Unblocks $task.unblocks other tasks"
    fi
  done
fi
```

### 8.3 Show Deferred Tasks (Q3/Q4)

```bash
echo ""
echo "⏸️  Deferred Tasks (Not in Scope)"
echo ""

Q3_COUNT=${#Q3_TASKS[@]}
Q4_COUNT=${#Q4_TASKS[@]}

if [ $Q3_COUNT -gt 0 ] || [ $Q4_COUNT -gt 0 ]; then
  echo "These tasks are optional and should be deferred:"
  echo "  Q3 (Urgent but Optional): $Q3_COUNT tasks"
  echo "  Q4 (Not Important): $Q4_COUNT tasks"
  echo ""
  echo "If any of these block Q2 work, use fast workarounds."
else
  echo "No tasks deferred. All pending work is in scope."
fi
```

### 8.4 Show Blocked Important Tasks

```bash
# If Q2 tasks are blocked by Q3/Q4 dependencies
if [ ${#BLOCKED_Q2[@]} -gt 0 ]; then
  echo ""
  echo "⚠️  Important Tasks Blocked by Optional Dependencies"
  echo ""
  for blocked in "${BLOCKED_Q2[@]}"; do
    echo "  Q2 Task $blocked.id: $blocked.title"
    echo "    Blocked by: $blocked.blockers"
    echo "    💡 Workaround: Skip optional dependency, use TODO/mock"
  done
fi
```

### 8.5 Provide Next Steps

```bash
echo ""
echo "⚡ Next Steps"
echo ""
echo "Start recommended task (Q$TASK_QUADRANT):"
echo "  /task:start $TASK_ID"
echo ""

if [ ${#Q2_TASKS[@]} -gt 1 ]; then
  echo "Or choose another core scope task:"
  echo "  /task:start ${Q2_TASKS[1].id}"
fi

echo ""
echo "💡 Implementation Approach:"
echo "   For tasks requiring tests, consider TDD workflow:"
echo "   • Write failing test (RED)"
echo "   • Implement minimal fix (GREEN)"
echo "   • Refactor while tests pass (REFACTOR)"
echo ""
echo "   See: ~/.claude/guides/agents.tdd.md"
echo "   See: ~/.claude/guides/agents.tdd.ts.md"
```

## Error Handling

### No Available Tasks

```bash
echo "🎉 Status Check"
echo ""
echo "All pending tasks are blocked or in-progress"
echo ""
echo "In-Progress: $IN_PROGRESS_COUNT tasks"
echo "Blocked: $BLOCKED_COUNT tasks"
echo ""
echo "Recommendation: Complete in-progress tasks"
```

### Task Master Not Initialized

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

### Tag Mismatch Warning

```bash
echo "⚠️  Tag Context Mismatch"
echo ""
echo "Current Branch: $BRANCH"
echo "Expected Tag: $TICKET_ID"
echo "Current Tag: $CURRENT_TAG"
echo ""
echo "Switch tag? (y/N):"
```

## Key Improvements

### 1. Commit-First Enforcement

**CRITICAL governance principle:**

- Always commit before moving to next task
- Small commits prevent hook processing backlog
- Clean git state = clear task boundaries
- Prevents technical debt accumulation

### 2. Intelligent File Grouping

**Context-aware commits:**

- Groups files by current task/subtask
- Warns about unrelated files
- Delegates to /commit for intelligent grouping
- Prevents unfocused commits

### 3. Unrelated File Detection

**Prevents mixed-context commits:**

- Analyzes files against task scope
- Matches file paths to task keywords
- Links tests to implementations
- Asks user before committing unrelated files

### 4. Hook Compliance

**Small changesets pass hooks:**

- Tests run on focused commits
- Linting checks small file sets
- Coverage checks incremental changes
- Fast feedback loop

### 5. Technical Debt Prevention

**Governance through workflow:**

- No large uncommitted sets
- No context switching with dirty git
- No accumulation over time
- Clean state = maintainable project

## Best Practices

### Commit Governance

1. **Always commit first** - Never skip Phase 1 unless emergency
2. **Review unrelated files** - Commit them separately with context
3. **Small commits win** - Multiple focused commits > one large commit
4. **Trust the grouping** - /commit intelligently groups by task context
5. **Clean transitions** - Git clean = ready for next task

### First Things First

1. **Focus on Q2** - Most time should be spent on Important but Not Urgent tasks (core scope)
2. **Do Q1 immediately** - Urgent + Important tasks should not wait
3. **Defer Q3/Q4** - Optional tasks can wait for follow-up PRs
4. **Use workarounds** - When Q3/Q4 blocks Q2, use fast workaround instead of full implementation
5. **Check scope alignment** - Every task should connect to branch requirements
6. **Question urgency** - Just because something feels urgent doesn't make it important

### Workaround Patterns for Deferred Tasks

When an optional task blocks important work, use these patterns:

- **Skip with TODO**: `// TODO: Implement X in follow-up PR`
- **Hardcode**: Use constant instead of configurable option
- **Mock in tests**: Mock the dependency instead of implementing
- **Create issue**: Document the deferred work in GitHub issue
- **Minimal implementation**: Bare minimum to unblock, not full feature

---

**For comprehensive Task Master documentation:**

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