---
phase: 06-coordination
plan: 03
type: execute
wave: 3
depends_on: ["06-02"]
files_modified: [src/trpc/routers/coordination.ts, src/trpc/routers/index.ts, src/cli/commands/merge.ts, src/cli/commands/coordinate.ts, src/cli/index.ts]
autonomous: true
---

<objective>
Add tRPC procedures and CLI commands for merge coordination.

Purpose: Expose coordination capabilities through the CLI for user interaction.
Output: tRPC router for coordination and CLI commands (cw merge, cw coordinate).
</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 dependencies
@.planning/phases/06-coordination/06-01-SUMMARY.md
@.planning/phases/06-coordination/06-02-SUMMARY.md

# Patterns to follow
@src/trpc/routers/task.ts
@src/trpc/routers/dispatch.ts
@src/cli/commands/dispatch.ts
@src/cli/commands/agent.ts
</context>

<tasks>

<task type="auto">
  <name>Task 1: Add coordination tRPC procedures</name>
  <files>src/trpc/routers/coordination.ts, src/trpc/routers/index.ts</files>
  <action>
Create coordination router following patterns from dispatch.ts and task.ts:

**src/trpc/routers/coordination.ts:**

```typescript
import { z } from 'zod';
import { router, publicProcedure } from '../trpc';

export const coordinationRouter = router({
  // Queue a completed task for merge
  queueMerge: publicProcedure
    .input(z.object({ taskId: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // ctx.coordinationManager optional same pattern as other managers
      if (!ctx.coordinationManager) {
        throw new Error('CoordinationManager not available');
      }
      await ctx.coordinationManager.queueMerge(input.taskId);
      return { success: true };
    }),

  // Process all ready merges
  processMerges: publicProcedure
    .input(z.object({
      targetBranch: z.string().default('main')
    }))
    .mutation(async ({ ctx, input }) => {
      if (!ctx.coordinationManager) {
        throw new Error('CoordinationManager not available');
      }
      const results = await ctx.coordinationManager.processMerges(input.targetBranch);
      return { results };
    }),

  // Get merge queue status
  status: publicProcedure
    .query(async ({ ctx }) => {
      if (!ctx.coordinationManager) {
        throw new Error('CoordinationManager not available');
      }
      return ctx.coordinationManager.getQueueState();
    }),

  // Get next mergeable task (for inspection)
  nextMergeable: publicProcedure
    .query(async ({ ctx }) => {
      if (!ctx.coordinationManager) {
        throw new Error('CoordinationManager not available');
      }
      return ctx.coordinationManager.getNextMergeable();
    }),
});
```

**src/trpc/routers/index.ts:**
Add coordinationRouter to appRouter.

**src/trpc/context.ts (if exists):**
Add coordinationManager?: CoordinationManager to context type.
  </action>
  <verify>npm run build passes, coordinationRouter exported</verify>
  <done>Coordination tRPC procedures available: queueMerge, processMerges, status, nextMergeable</done>
</task>

<task type="auto">
  <name>Task 2: Add CLI commands for merge coordination</name>
  <files>src/cli/commands/merge.ts, src/cli/commands/coordinate.ts, src/cli/index.ts</files>
  <action>
Create CLI commands following patterns from dispatch.ts and agent.ts:

**src/cli/commands/merge.ts:**

```typescript
// cw merge queue <taskId> - Queue a task for merge
// cw merge status - Show merge queue status
// cw merge next - Show next mergeable task

import { Command } from 'commander';
import { createTRPCClient } from '../trpc-client';

export function createMergeCommand(): Command {
  const merge = new Command('merge')
    .description('Manage merge queue');

  merge
    .command('queue <taskId>')
    .description('Queue a completed task for merge')
    .action(async (taskId) => {
      const client = createTRPCClient();
      await client.coordination.queueMerge.mutate({ taskId });
      console.log(`Task ${taskId} queued for merge`);
    });

  merge
    .command('status')
    .description('Show merge queue status')
    .action(async () => {
      const client = createTRPCClient();
      const state = await client.coordination.status.query();
      console.log('Merge Queue Status:');
      console.log(`  Queued: ${state.queued.length}`);
      console.log(`  In Progress: ${state.inProgress.length}`);
      console.log(`  Merged: ${state.merged.length}`);
      console.log(`  Conflicted: ${state.conflicted.length}`);

      if (state.conflicted.length > 0) {
        console.log('\nConflicts:');
        for (const c of state.conflicted) {
          console.log(`  ${c.taskId}: ${c.conflicts.join(', ')}`);
        }
      }
    });

  merge
    .command('next')
    .description('Show next task ready to merge')
    .action(async () => {
      const client = createTRPCClient();
      const next = await client.coordination.nextMergeable.query();
      if (next) {
        console.log(`Next mergeable: ${next.taskId} (priority: ${next.priority})`);
      } else {
        console.log('No tasks ready to merge');
      }
    });

  return merge;
}
```

**src/cli/commands/coordinate.ts:**

```typescript
// cw coordinate [--target <branch>] - Process all ready merges

import { Command } from 'commander';
import { createTRPCClient } from '../trpc-client';

export function createCoordinateCommand(): Command {
  return new Command('coordinate')
    .description('Process all ready merges in dependency order')
    .option('-t, --target <branch>', 'Target branch for merges', 'main')
    .action(async (options) => {
      const client = createTRPCClient();
      console.log(`Processing merges to ${options.target}...`);

      const { results } = await client.coordination.processMerges.mutate({
        targetBranch: options.target
      });

      const succeeded = results.filter(r => r.success).length;
      const conflicted = results.filter(r => !r.success).length;

      console.log(`\nResults:`);
      console.log(`  Merged: ${succeeded}`);
      console.log(`  Conflicts: ${conflicted}`);

      if (conflicted > 0) {
        console.log('\nConflicted tasks (bounce-back tasks created):');
        for (const r of results.filter(r => !r.success)) {
          console.log(`  ${r.taskId}: ${r.conflicts?.join(', ')}`);
        }
      }
    });
}
```

**src/cli/index.ts:**
Register both commands with the CLI program.
  </action>
  <verify>npm run build passes, cw merge --help and cw coordinate --help work</verify>
  <done>CLI commands available: cw merge (queue/status/next), cw coordinate</done>
</task>

</tasks>

<verification>
Before declaring plan complete:
- [ ] npm run build succeeds
- [ ] cw merge --help shows subcommands
- [ ] cw coordinate --help shows options
- [ ] tRPC coordination router accessible via client
</verification>

<success_criteria>
- All tasks completed
- All verification checks pass
- No TypeScript errors
- CLI commands follow existing patterns (dispatch, agent)
- COORD-01 and COORD-02 requirements satisfied
</success_criteria>

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