# All files / src/coordination manager.ts

93.97% Statements 78/83
85.71% Branches 24/28
86.66% Functions 13/15
95.06% Lines 77/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333

    105x

    105x

    105x

    105x
    105x
    105x
    105x
    105x

    105x

    105x
    103x

    40x
    1x

    39x
    39x
    1x

    38x
    1x

    37x
    37x
    1x

    36x

    36x

    36x

    36x

    36x

    54x
    37x

    54x
    24x

    30x
    37x

    30x

    30x

    30x
    9x
    9x
    7x

    2x

    30x
    30x

    24x
    1x

    23x

    23x

    23x
    27x

    27x

    27x

    27x

    27x

    27x

    15x
    15x

    15x

    15x

    15x

    12x
    12x
    12x

    12x

    12x

    12x

    12x

    27x

    23x

    14x

    14x

    11x

    11x
    3x
    3x

    11x
    3x

    11x

    11x

    11x

     /**
     * Default Coordination Manager - Adapter Implementation
     *
     * Implements CoordinationManager interface with in-memory merge queue
     * and dependency-ordered merging.
     *
     * This is the ADAPTER for the CoordinationManager PORT.
     */

    import type {
      EventBus,
      MergeQueuedEvent,
      MergeStartedEvent,
      MergeCompletedEvent,
      MergeConflictedEvent,
    } from '../events/index.js';
    import type { WorktreeManager } from '../git/types.js';
    import type { TaskRepository } from '../db/repositories/task-repository.js';
    import type { AgentRepository } from '../db/repositories/agent-repository.js';
    import type { MessageRepository } from '../db/repositories/message-repository.js';
    import type { CoordinationManager, MergeQueueItem, MergeResult } from './types.js';
    import type { ConflictResolutionService } from './conflict-resolution-service.js';
    import { DefaultConflictResolutionService } from './conflict-resolution-service.js';

    // =============================================================================
    // Internal Types
    // =============================================================================

    /**
     * Internal representation of a merge queue item with status.
     */
    interface InternalMergeQueueItem extends MergeQueueItem {
      status: 'queued' | 'in_progress';
    }

    // =============================================================================
    // DefaultCoordinationManager Implementation
    // =============================================================================

    /**
     * In-memory implementation of CoordinationManager.
     *
     * Uses Map for queue management and processes merges in dependency order.
     * Handles conflicts by creating resolution tasks.
     */
    export class DefaultCoordinationManager implements CoordinationManager {
      /** Internal merge queue */
      private mergeQueue: Map<string, InternalMergeQueueItem> = new Map();

      /** Task IDs that have been successfully merged */
      private mergedTasks: Set<string> = new Set();

      /** Tasks with conflicts awaiting resolution */
      private conflictedTasks: Map<string, string[]> = new Map();

      /** Service for handling merge conflicts */
      private conflictResolutionService?: ConflictResolutionService;

      constructor(
        private worktreeManager?: WorktreeManager,
        private taskRepository?: TaskRepository,
        private agentRepository?: AgentRepository,
        private messageRepository?: MessageRepository,
        private eventBus?: EventBus,
        conflictResolutionService?: ConflictResolutionService
      ) {
        // Create default conflict resolution service if none provided
        Iif (conflictResolutionService) {
          this.conflictResolutionService = conflictResolutionService;
        } else if (taskRepository && agentRepository) {
          this.conflictResolutionService = new DefaultConflictResolutionService(
            taskRepository,
            agentRepository,
            messageRepository,
            eventBus
          );
        }
      }

      /**
       * Queue a completed task for merge.
       * Extracts agent/worktree information from the task.
       */
      async queueMerge(taskId: string): Promise<void> {
        // Look up task to get dependencies
        if (!this.taskRepository) {
          throw new Error('TaskRepository not configured');
        }

        const task = await this.taskRepository.findById(taskId);
        if (!task) {
          throw new Error(`Task not found: ${taskId}`);
        }

        // Look up agent assigned to task to get worktreeId
        if (!this.agentRepository) {
          throw new Error('AgentRepository not configured');
        }

        const agent = await this.agentRepository.findByTaskId(taskId);
        if (!agent) {
          throw new Error(`No agent found for task: ${taskId}`);
        }

        // For now, dependsOn is empty - would need to query task_dependencies table
        // to get actual dependencies
        const dependsOn: string[] = [];

        const queueItem: InternalMergeQueueItem = {
          taskId,
          agentId: agent.id,
          worktreeId: agent.worktreeId,
          priority: task.priority,
          queuedAt: new Date(),
          dependsOn,
          status: 'queued',
        };

        this.mergeQueue.set(taskId, queueItem);

        // Emit MergeQueuedEvent
        const event: MergeQueuedEvent = {
          type: 'merge:queued',
          timestamp: new Date(),
          payload: {
            taskId,
            agentId: agent.id,
            worktreeId: agent.worktreeId,
            priority: task.priority,
          },
        };
        this.eventBus?.emit(event);
      }

      /**
       * Get next task ready to merge.
       * Returns task with all dependency tasks already merged.
       */
      async getNextMergeable(): Promise<MergeQueueItem | null> {
        const queuedItems = Array.from(this.mergeQueue.values()).filter(
          (item) => item.status === 'queued'
        );

        if (queuedItems.length === 0) {
          return null;
        }

        // Filter to only items where ALL dependsOn tasks are in mergedTasks
        const readyItems = queuedItems.filter((item) =>
          item.dependsOn.every((depTaskId) => this.mergedTasks.has(depTaskId))
        );

        Iif (readyItems.length === 0) {
          return null;
        }

        // Sort by priority (high > medium > low), then by queuedAt (oldest first)
        const priorityOrder: Record<string, number> = { high: 0, medium: 1, low: 2 };

        readyItems.sort((a, b) => {
          const priorityDiff = priorityOrder[a.priority] - priorityOrder[b.priority];
          if (priorityDiff !== 0) {
            return priorityDiff;
          }
          return a.queuedAt.getTime() - b.queuedAt.getTime();
        });

        // Return as MergeQueueItem (without internal status)
        const item = readyItems[0];
        return {
          taskId: item.taskId,
          agentId: item.agentId,
          worktreeId: item.worktreeId,
          priority: item.priority,
          queuedAt: item.queuedAt,
          dependsOn: item.dependsOn,
        };
      }

      /**
       * Process all ready merges in dependency order.
       * Merges each ready task into the target branch.
       */
      async processMerges(targetBranch: string): Promise<MergeResult[]> {
        if (!this.worktreeManager) {
          throw new Error('WorktreeManager not configured');
        }

        const results: MergeResult[] = [];

        // Loop while there are mergeable items
        let nextItem = await this.getNextMergeable();

        while (nextItem) {
          const queueItem = this.mergeQueue.get(nextItem.taskId)!;

          // Mark as in_progress
          queueItem.status = 'in_progress';

          // Emit MergeStartedEvent
          const startEvent: MergeStartedEvent = {
            type: 'merge:started',
            timestamp: new Date(),
            payload: {
              taskId: nextItem.taskId,
              agentId: nextItem.agentId,
              worktreeId: nextItem.worktreeId,
              targetBranch,
            },
          };
          this.eventBus?.emit(startEvent);

          // Attempt merge via worktreeManager
          const mergeResult = await this.worktreeManager.merge(nextItem.worktreeId, targetBranch);

          if (mergeResult.success) {
            // Success - add to mergedTasks and remove from queue
            this.mergedTasks.add(nextItem.taskId);
            this.mergeQueue.delete(nextItem.taskId);

            // Emit MergeCompletedEvent
            const completedEvent: MergeCompletedEvent = {
              type: 'merge:completed',
              timestamp: new Date(),
              payload: {
                taskId: nextItem.taskId,
                agentId: nextItem.agentId,
                worktreeId: nextItem.worktreeId,
                targetBranch,
              },
            };
            this.eventBus?.emit(completedEvent);

            results.push({
              taskId: nextItem.taskId,
              success: true,
              message: mergeResult.message,
            });
          } else {
            // Conflict - add to conflictedTasks and remove from queue
            const conflicts = mergeResult.conflicts || [];
            this.conflictedTasks.set(nextItem.taskId, conflicts);
            this.mergeQueue.delete(nextItem.taskId);

            // Emit MergeConflictedEvent
            const conflictEvent: MergeConflictedEvent = {
              type: 'merge:conflicted',
              timestamp: new Date(),
              payload: {
                taskId: nextItem.taskId,
                agentId: nextItem.agentId,
                worktreeId: nextItem.worktreeId,
                targetBranch,
                conflictingFiles: conflicts,
              },
            };
            this.eventBus?.emit(conflictEvent);

            // Handle conflict - create resolution task
            await this.handleConflict(nextItem.taskId, conflicts);

            results.push({
              taskId: nextItem.taskId,
              success: false,
              conflicts,
              message: mergeResult.message,
            });
          }

          // Get next item
          nextItem = await this.getNextMergeable();
        }

        return results;
      }

      /**
       * Handle a merge conflict.
       * Delegates to the ConflictResolutionService.
       */
      async handleConflict(taskId: string, conflicts: string[]): Promise<void> {
        Iif (!this.conflictResolutionService) {
          throw new Error('ConflictResolutionService not configured');
        }

        await this.conflictResolutionService.handleConflict(taskId, conflicts);
      }

      /**
       * Get current state of the merge queue.
       */
      async getQueueState(): Promise<{
        queued: MergeQueueItem[];
        inProgress: MergeQueueItem[];
        merged: string[];
        conflicted: Array<{ taskId: string; conflicts: string[] }>;
      }> {
        const allItems = Array.from(this.mergeQueue.values());

        // Filter by status
        const queued = allItems
          .filter((item) => item.status === 'queued')
          .map((item) => ({
            taskId: item.taskId,
            agentId: item.agentId,
            worktreeId: item.worktreeId,
            priority: item.priority,
            queuedAt: item.queuedAt,
            dependsOn: item.dependsOn,
          }));

        const inProgress = allItems
          .filter((item) => item.status === 'in_progress')
          .map((item) => ({
            taskId: item.taskId,
            agentId: item.agentId,
            worktreeId: item.worktreeId,
            priority: item.priority,
            queuedAt: item.queuedAt,
            dependsOn: item.dependsOn,
          }));

        const merged = Array.from(this.mergedTasks);

        const conflicted = Array.from(this.conflictedTasks.entries()).map(([taskId, conflicts]) => ({
          taskId,
          conflicts,
        }));

        return { queued, inProgress, merged, conflicted };
      }
    }