# All files / src/dispatch manager.ts

69.62% Statements 94/135
56.57% Branches 43/76
92.3% Functions 12/13
69.4% Lines 93/134

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
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486

    9x

    96x

    96x

    96x
    96x
    96x
    96x
    96x
    96x

    67x
    67x
    1x

    66x

    66x

    66x

    66x

    66x

    66x

    47x

    47x
    4x

    43x

    43x

    43x

    75x
    75x
    12x

    63x
    63x

    63x

    63x

    43x

    43x

    43x

    43x
    30x
    30x
    25x

    5x

    43x

    16x
    16x

    16x

    16x

    16x

    16x

    16x

    16x

    16x

    16x

    7x

    7x

    7x

    7x

    7x

    7x

    39x

    39x
    2x
    2x

    37x
    37x

    37x
    2x
    2x

    35x
    35x

    35x

    35x

    35x

    35x

    35x

    35x

    35x

    35x

    17x

    17x
    17x
    31x
    31x
    22x

    17x

    106x
    79x

    27x
    31x
    31x
    21x

    6x

    129x

    16x

    16x

    16x

     /**
     * Default Dispatch Manager - Adapter Implementation
     *
     * Implements DispatchManager interface with in-memory queue
     * and dependency-ordered dispatch.
     *
     * This is the ADAPTER for the DispatchManager PORT.
     */

    import type {
      EventBus,
      TaskQueuedEvent,
      TaskCompletedEvent,
      TaskBlockedEvent,
      TaskDispatchedEvent,
      TaskPendingApprovalEvent,
    } from '../events/index.js';
    import type { AgentManager } from '../agent/types.js';
    import type { TaskRepository } from '../db/repositories/task-repository.js';
    import type { MessageRepository } from '../db/repositories/message-repository.js';
    import type { InitiativeRepository } from '../db/repositories/initiative-repository.js';
    import type { PhaseRepository } from '../db/repositories/phase-repository.js';
    import type { Task } from '../db/schema.js';
    import type { DispatchManager, QueuedTask, DispatchResult } from './types.js';
    import { phaseBranchName, taskBranchName, isPlanningCategory, generateInitiativeBranch } from '../git/branch-naming.js';
    import { buildExecutePrompt } from '../agent/prompts/index.js';
    import { createModuleLogger } from '../logger/index.js';

    const log = createModuleLogger('dispatch');

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

    /**
     * Internal representation of a blocked task.
     */
    interface BlockedTask {
      taskId: string;
      reason: string;
    }

    // =============================================================================
    // DefaultDispatchManager Implementation
    // =============================================================================

    /**
     * In-memory implementation of DispatchManager.
     *
     * Uses Map for queue management and checks task_dependencies table
     * for dependency resolution.
     */
    export class DefaultDispatchManager implements DispatchManager {
      /** Internal queue of tasks pending dispatch */
      private taskQueue: Map<string, QueuedTask> = new Map();

      /** Blocked tasks with their reasons */
      private blockedTasks: Map<string, BlockedTask> = new Map();

      constructor(
        private taskRepository: TaskRepository,
        private messageRepository: MessageRepository,
        private agentManager: AgentManager,
        private eventBus: EventBus,
        private initiativeRepository?: InitiativeRepository,
        private phaseRepository?: PhaseRepository,
      ) {}

      /**
       * Queue a task for dispatch.
       * Fetches task dependencies and adds to internal queue.
       * Checkpoint tasks are queued but won't auto-dispatch.
       */
      async queue(taskId: string): Promise<void> {
        // Fetch task to verify it exists and get priority
        const task = await this.taskRepository.findById(taskId);
        if (!task) {
          throw new Error(`Task not found: ${taskId}`);
        }

        // Get dependencies for this task from the repository
        const dependsOn = await this.taskRepository.getDependencies(taskId);

        const queuedTask: QueuedTask = {
          taskId,
          priority: task.priority,
          queuedAt: new Date(),
          dependsOn,
        };

        this.taskQueue.set(taskId, queuedTask);

        log.info({ taskId, priority: task.priority, isCheckpoint: this.isCheckpointTask(task) }, 'task queued');

        // Emit TaskQueuedEvent
        const event: TaskQueuedEvent = {
          type: 'task:queued',
          timestamp: new Date(),
          payload: {
            taskId,
            priority: task.priority,
            dependsOn,
          },
        };
        this.eventBus.emit(event);
      }

      /**
       * Get next dispatchable task.
       * Returns task with all dependencies complete, highest priority first.
       * Checkpoint tasks are excluded (require human action).
       */
      async getNextDispatchable(): Promise<QueuedTask | null> {
        const queuedTasks = Array.from(this.taskQueue.values());

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

        // Filter to only tasks with all dependencies complete and not checkpoint tasks
        const readyTasks: QueuedTask[] = [];

        log.debug({ queueSize: queuedTasks.length }, 'evaluating dispatchable tasks');

        for (const qt of queuedTasks) {
          // Check dependencies
          const allDepsComplete = await this.areAllDependenciesComplete(qt.dependsOn);
          if (!allDepsComplete) {
            continue;
          }

          // Check if this is a checkpoint task (requires human action)
          const task = await this.taskRepository.findById(qt.taskId);
          Iif (task && this.isCheckpointTask(task)) {
            log.debug({ taskId: qt.taskId, type: task.type }, 'skipping checkpoint task');
            continue;
          }

          // Skip planning-category tasks (handled by architect flow)
          Iif (task && isPlanningCategory(task.category)) {
            log.debug({ taskId: qt.taskId, category: task.category }, 'skipping planning-category task');
            continue;
          }

          readyTasks.push(qt);
        }

        log.debug({ queueSize: queuedTasks.length, readyCount: readyTasks.length }, 'dispatchable evaluation complete');

        Iif (readyTasks.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 };

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

        return readyTasks[0];
      }

      /**
       * Mark a task as complete.
       * If the task requires approval, sets status to 'pending_approval' instead.
       * Updates task status and removes from queue.
       *
       * @param taskId - ID of the task to complete
       * @param agentId - Optional ID of the agent that completed the task
       */
      async completeTask(taskId: string, agentId?: string): Promise<void> {
        const task = await this.taskRepository.findById(taskId);
        Iif (!task) {
          throw new Error(`Task not found: ${taskId}`);
        }

        // Determine if approval is required
        const requiresApproval = await this.taskRequiresApproval(task);

        Iif (requiresApproval) {
          // Set to pending_approval instead of completed
          await this.taskRepository.update(taskId, { status: 'pending_approval' });

          // Remove from queue
          this.taskQueue.delete(taskId);

          log.info({ taskId, category: task.category }, 'task pending approval');

          // Emit TaskPendingApprovalEvent
          const event: TaskPendingApprovalEvent = {
            type: 'task:pending_approval',
            timestamp: new Date(),
            payload: {
              taskId,
              agentId: agentId ?? '',
              category: task.category,
              name: task.name,
            },
          };
          this.eventBus.emit(event);
        } else {
          // Complete directly
          await this.taskRepository.update(taskId, { status: 'completed' });

          // Remove from queue
          this.taskQueue.delete(taskId);

          log.info({ taskId }, 'task completed');

          // Emit TaskCompletedEvent
          const event: TaskCompletedEvent = {
            type: 'task:completed',
            timestamp: new Date(),
            payload: {
              taskId,
              agentId: agentId ?? '',
              success: true,
              message: 'Task completed',
            },
          };
          this.eventBus.emit(event);
        }

        // Also remove from blocked if it was there
        this.blockedTasks.delete(taskId);
      }

      /**
       * Approve a task that is pending approval.
       * Sets status to 'completed' and emits completion event.
       */
      async approveTask(taskId: string): Promise<void> {
        const task = await this.taskRepository.findById(taskId);
        if (!task) {
          throw new Error(`Task not found: ${taskId}`);
        }

        if (task.status !== 'pending_approval') {
          throw new Error(`Task ${taskId} is not pending approval (status: ${task.status})`);
        }

        // Complete the task
        await this.taskRepository.update(taskId, { status: 'completed' });

        log.info({ taskId }, 'task approved and completed');

        // Emit TaskCompletedEvent
        const event: TaskCompletedEvent = {
          type: 'task:completed',
          timestamp: new Date(),
          payload: {
            taskId,
            agentId: '',
            success: true,
            message: 'Task approved',
          },
        };
        this.eventBus.emit(event);
      }

      /**
       * Mark a task as blocked.
       * Updates task status and records block reason.
       */
      async blockTask(taskId: string, reason: string): Promise<void> {
        // Update task status to 'blocked'
        await this.taskRepository.update(taskId, { status: 'blocked' });

        // Record in blocked map
        this.blockedTasks.set(taskId, { taskId, reason });

        log.warn({ taskId, reason }, 'task blocked');

        // Remove from queue (blocked tasks aren't dispatchable)
        this.taskQueue.delete(taskId);

        // Emit TaskBlockedEvent
        const event: TaskBlockedEvent = {
          type: 'task:blocked',
          timestamp: new Date(),
          payload: {
            taskId,
            reason,
          },
        };
        this.eventBus.emit(event);
      }

      /**
       * Dispatch next available task to an agent.
       */
      async dispatchNext(): Promise<DispatchResult> {
        // Get next dispatchable task
        const nextTask = await this.getNextDispatchable();

        if (!nextTask) {
          log.debug('no dispatchable tasks');
          return {
            success: false,
            taskId: '',
            reason: 'No dispatchable tasks',
          };
        }

        // Find available agent (status='idle')
        const agents = await this.agentManager.list();
        const idleAgent = agents.find((a) => a.status === 'idle');

        if (!idleAgent) {
          log.debug('no available agents');
          return {
            success: false,
            taskId: nextTask.taskId,
            reason: 'No available agents',
          };
        }

        // Get task details
        const task = await this.taskRepository.findById(nextTask.taskId);
        Iif (!task) {
          return {
            success: false,
            taskId: nextTask.taskId,
            reason: 'Task not found',
          };
        }

        // Compute branch info for branch-aware spawning
        let baseBranch: string | undefined;
        let branchName: string | undefined;

        Iif (task.initiativeId && this.initiativeRepository) {
          try {
            if (isPlanningCategory(task.category)) {
              // Planning tasks run on project default branches — no initiative branch needed.
              // baseBranch and branchName remain undefined; ProcessManager uses per-project defaults.
            } else if (task.phaseId && this.phaseRepository) {
              // Execution task — ensure initiative has a branch
              const initiative = await this.initiativeRepository.findById(task.initiativeId);
              if (initiative) {
                let initBranch = initiative.branch;
                if (!initBranch) {
                  initBranch = generateInitiativeBranch(initiative.name);
                  await this.initiativeRepository.update(initiative.id, { branch: initBranch });
                }

                const phase = await this.phaseRepository.findById(task.phaseId);
                if (phase) {
                  if (task.category === 'merge') {
                    // Merge tasks work directly on the phase branch
                    baseBranch = initBranch;
                    branchName = phaseBranchName(initBranch, phase.name);
                  } else {
                    baseBranch = phaseBranchName(initBranch, phase.name);
                    branchName = taskBranchName(initBranch, task.id);
                  }
                }
              }
            }
          } catch {
            // Non-fatal: fall back to default branching
          }
        }

        // Spawn agent with task (alias auto-generated by agent manager)
        const agent = await this.agentManager.spawn({
          taskId: nextTask.taskId,
          initiativeId: task.initiativeId ?? undefined,
          phaseId: task.phaseId ?? undefined,
          prompt: buildExecutePrompt(task.description || task.name),
          baseBranch,
          branchName,
        });

        log.info({ taskId: nextTask.taskId, agentId: agent.id }, 'task dispatched');

        // Update task status to 'in_progress'
        await this.taskRepository.update(nextTask.taskId, { status: 'in_progress' });

        // Remove from queue (now being worked on)
        this.taskQueue.delete(nextTask.taskId);

        // Emit TaskDispatchedEvent
        const event: TaskDispatchedEvent = {
          type: 'task:dispatched',
          timestamp: new Date(),
          payload: {
            taskId: nextTask.taskId,
            agentId: agent.id,
            agentName: agent.name,
          },
        };
        this.eventBus.emit(event);

        return {
          success: true,
          taskId: nextTask.taskId,
          agentId: agent.id,
        };
      }

      /**
       * Get current queue state.
       */
      async getQueueState(): Promise<{
        queued: QueuedTask[];
        ready: QueuedTask[];
        blocked: Array<{ taskId: string; reason: string }>;
      }> {
        const allQueued = Array.from(this.taskQueue.values());

        // Determine which are ready
        const ready: QueuedTask[] = [];
        for (const qt of allQueued) {
          const allDepsComplete = await this.areAllDependenciesComplete(qt.dependsOn);
          if (allDepsComplete) {
            ready.push(qt);
          }
        }

        return {
          queued: allQueued,
          ready,
          blocked: Array.from(this.blockedTasks.values()),
        };
      }

      // =============================================================================
      // Private Helpers
      // =============================================================================

      /**
       * Check if all dependencies are complete.
       */
      private async areAllDependenciesComplete(dependsOn: string[]): Promise<boolean> {
        if (dependsOn.length === 0) {
          return true;
        }

        for (const depTaskId of dependsOn) {
          const depTask = await this.taskRepository.findById(depTaskId);
          if (!depTask || depTask.status !== 'completed') {
            return false;
          }
        }

        return true;
      }

      /**
       * Check if a task is a checkpoint task.
       * Checkpoint tasks require human action and don't auto-dispatch.
       */
      private isCheckpointTask(task: Task): boolean {
        return task.type.startsWith('checkpoint:');
      }

      /**
       * Determine if a task requires approval before being marked complete.
       * Checks task-level override first, then falls back to initiative setting.
       */
      private async taskRequiresApproval(task: Task): Promise<boolean> {
        // Task-level override takes precedence
        Iif (task.requiresApproval !== null) {
          return task.requiresApproval;
        }

        // Fall back to initiative setting if we have initiative access
        Iif (this.initiativeRepository && task.initiativeId) {
          const initiative = await this.initiativeRepository.findById(task.initiativeId);
          if (initiative) {
            return initiative.mergeRequiresApproval;
          }
        }

        // If task has a phaseId but no initiativeId, we could traverse up but for now default to false
        // Default: no approval required
        return false;
      }
    }