---
phase: 06-coordination
plan: 02
type: execute
wave: 2
depends_on: ["06-01"]
files_modified: [src/coordination/manager.ts, src/coordination/manager.test.ts, src/coordination/index.ts]
autonomous: true
---

<objective>
Implement DefaultCoordinationManager adapter with dependency-ordered merging and conflict bounce-back.

Purpose: Orchestrate merges in dependency order and handle conflicts by creating resolution tasks.
Output: Working CoordinationManager implementation with comprehensive tests.
</objective>

<execution_context>
@~/.claude/get-shit-done/workflows/execute-plan.md
@~/.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md

# This plan's dependency
@.planning/phases/06-coordination/06-01-SUMMARY.md

# Interfaces we implement/use
@src/coordination/types.ts
@src/git/types.ts
@src/agent/types.ts
@src/db/schema.ts

# Patterns to follow
@src/dispatch/manager.ts
@src/git/manager.ts
</context>

<tasks>

<task type="auto">
  <name>Task 1: Implement DefaultCoordinationManager with dependency-ordered merging</name>
  <files>src/coordination/manager.ts</files>
  <action>
Create DefaultCoordinationManager class implementing CoordinationManager:

**Constructor dependencies (optional injection, same pattern as DispatchManager):**
- worktreeManager?: WorktreeManager
- taskRepository?: TaskRepository
- agentRepository?: AgentRepository
- eventBus?: EventBus

**State:**
- mergeQueue: Map<string, MergeQueueItem> (in-memory, same as DispatchManager)
- mergedTasks: Set<string> (tracks successfully merged task IDs)
- conflictedTasks: Map<string, string[]> (taskId -> conflicting files)

**queueMerge(taskId):**
1. Look up task from repository to get dependencies
2. Look up agent assigned to task to get worktreeId
3. Create MergeQueueItem with dependsOn from task dependencies
4. Add to mergeQueue
5. Emit MergeQueuedEvent

**getNextMergeable():**
1. Filter queue for items where ALL dependsOn tasks are in mergedTasks
2. Sort by priority (high > medium > low), then by queuedAt (FIFO)
3. Return first item or null

**processMerges(targetBranch):**
1. Loop while getNextMergeable() returns items:
   a. Mark item as in_progress
   b. Emit MergeStartedEvent
   c. Call worktreeManager.merge(item.worktreeId, targetBranch)
   d. If success:
      - Add taskId to mergedTasks
      - Remove from queue
      - Emit MergeCompletedEvent
   e. If conflict:
      - Add to conflictedTasks
      - Remove from queue
      - Emit MergeConflictedEvent
      - Call handleConflict()
2. Return all MergeResults

**handleConflict(taskId, conflicts):**
1. Create a new task in the same plan as original task:
   - name: "Resolve merge conflicts for {originalTaskName}"
   - description: "Conflicts in: {conflicts.join(', ')}"
   - type: 'auto'
   - dependsOn: [] (no dependencies - can start immediately)
2. Assign new task to same agent that had the conflict
3. Emit TaskQueuedEvent for the new conflict-resolution task

**getQueueState():**
Return current state of all tracking structures.
  </action>
  <verify>npm run build passes</verify>
  <done>DefaultCoordinationManager implements all CoordinationManager methods</done>
</task>

<task type="auto">
  <name>Task 2: Implement conflict bounce-back task creation</name>
  <files>src/coordination/manager.ts</files>
  <action>
Enhance handleConflict to properly create conflict-resolution tasks:

1. Generate unique task ID (nanoid or uuid pattern from existing code)
2. Create task via taskRepository.create() with:
   - planId: same as original task's planId
   - name: "Resolve conflicts: {originalTask.name}"
   - description: Include:
     - List of conflicting files
     - Original task context
     - Instructions: "Resolve merge conflicts in the listed files, then mark task complete"
   - type: 'auto'
   - priority: 'high' (conflicts should be resolved quickly)
   - status: 'pending'

3. Create message to agent via message system (if messageRepository available):
   - senderType: 'user' (system-generated)
   - recipientType: 'agent'
   - recipientId: original agent ID
   - type: 'info'
   - content: Conflict details and resolution instructions
   - requiresResponse: false

4. Update original task status to 'blocked' with reason

This enables the agent to pick up conflict resolution work automatically.
  </action>
  <verify>npm run build passes</verify>
  <done>Conflict bounce-back creates new task and notifies agent</done>
</task>

<task type="auto">
  <name>Task 3: Write tests for CoordinationManager</name>
  <files>src/coordination/manager.test.ts, src/coordination/index.ts</files>
  <action>
Create comprehensive tests following patterns from src/dispatch/manager.test.ts:

**Test categories:**

1. Queue management:
   - queueMerge adds item to queue
   - queueMerge emits MergeQueuedEvent
   - getQueueState returns correct counts

2. Dependency ordering:
   - getNextMergeable returns null when dependencies not met
   - getNextMergeable returns item when all dependencies merged
   - processMerges handles dependency chain correctly (A -> B -> C)

3. Priority ordering:
   - High priority merges before medium/low
   - Same priority follows FIFO

4. Conflict handling:
   - processMerges detects conflicts from WorktreeManager
   - handleConflict creates new task
   - MergeConflictedEvent emitted with correct payload
   - Conflicted task tracked in getQueueState

5. Success path:
   - processMerges completes clean merges
   - MergeCompletedEvent emitted
   - Merged tasks tracked correctly

**Test setup:**
- Mock WorktreeManager (return success or conflict as needed)
- Mock repositories (in-memory or jest mocks)
- Use EventEmitterBus for event verification

Export DefaultCoordinationManager from index.ts.
  </action>
  <verify>npm test -- src/coordination passes with all tests green</verify>
  <done>14+ tests covering queue, dependencies, conflicts, and success paths</done>
</task>

</tasks>

<verification>
Before declaring plan complete:
- [ ] npm run build succeeds
- [ ] npm test -- src/coordination passes
- [ ] DefaultCoordinationManager exported from src/coordination/index.ts
- [ ] All four merge events emitted at correct lifecycle points
</verification>

<success_criteria>
- All tasks completed
- All verification checks pass
- No TypeScript errors
- Tests cover dependency ordering and conflict bounce-back
- Patterns match DispatchManager implementation style
</success_criteria>

<output>
After completion, create `.planning/phases/06-coordination/06-02-SUMMARY.md`
</output>
