# All files / src/dispatch phase-manager.ts

83.14% Statements 74/89
65.78% Branches 25/38
100% Functions 9/9
82.95% Lines 73/88

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

    9x

    103x

    103x

    103x
    103x
    103x
    103x
    103x
    103x
    103x
    103x

    38x
    38x
    1x

    37x
    4x

    33x

    33x

    33x

    33x

    33x

    23x

    23x
    3x

    20x

    20x
    37x
    37x
    20x

    20x
    4x

    16x

    16x

    19x

    19x
    5x

    14x
    14x

    14x

    14x

    14x

    14x
    14x

    14x

    14x

    14x

    11x
    11x
    1x

    10x

    10x

    10x

    10x

    10x

    6x

    6x

    6x

    6x

    6x

    22x

    22x
    22x
    31x
    31x
    14x

    22x

    68x
    18x

    50x
    56x
    56x
    34x

    16x

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

    import type {
      EventBus,
      PhaseQueuedEvent,
      PhaseStartedEvent,
      PhaseCompletedEvent,
      PhaseBlockedEvent,
    } from '../events/index.js';
    import type { PhaseRepository } from '../db/repositories/phase-repository.js';
    import type { TaskRepository } from '../db/repositories/task-repository.js';
    import type { InitiativeRepository } from '../db/repositories/initiative-repository.js';
    import type { ProjectRepository } from '../db/repositories/project-repository.js';
    import type { BranchManager } from '../git/branch-manager.js';
    import type { PhaseDispatchManager, DispatchManager, QueuedPhase, PhaseDispatchResult } from './types.js';
    import { phaseBranchName, isPlanningCategory } from '../git/branch-naming.js';
    import { ensureProjectClone } from '../git/project-clones.js';
    import { createModuleLogger } from '../logger/index.js';

    const log = createModuleLogger('phase-dispatch');

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

    /**
     * Internal representation of a blocked phase.
     */
    interface BlockedPhase {
      phaseId: string;
      reason: string;
    }

    // =============================================================================
    // DefaultPhaseDispatchManager Implementation
    // =============================================================================

    /**
     * In-memory implementation of PhaseDispatchManager.
     *
     * Uses Map for queue management and checks phase_dependencies table
     * for dependency resolution.
     */
    export class DefaultPhaseDispatchManager implements PhaseDispatchManager {
      /** Internal queue of phases pending dispatch */
      private phaseQueue: Map<string, QueuedPhase> = new Map();

      /** Blocked phases with their reasons */
      private blockedPhases: Map<string, BlockedPhase> = new Map();

      constructor(
        private phaseRepository: PhaseRepository,
        private taskRepository: TaskRepository,
        private dispatchManager: DispatchManager,
        private eventBus: EventBus,
        private initiativeRepository?: InitiativeRepository,
        private projectRepository?: ProjectRepository,
        private branchManager?: BranchManager,
        private workspaceRoot?: string,
      ) {}

      /**
       * Queue a phase for dispatch.
       * Only approved phases can be queued.
       * Fetches phase dependencies and adds to internal queue.
       */
      async queuePhase(phaseId: string): Promise<void> {
        // Fetch phase to verify it exists and get initiativeId
        const phase = await this.phaseRepository.findById(phaseId);
        if (!phase) {
          throw new Error(`Phase not found: ${phaseId}`);
        }

        // Approval gate: only approved phases can be queued
        if (phase.status !== 'approved') {
          throw new Error(`Phase '${phaseId}' must be approved before queuing (current status: ${phase.status})`);
        }

        // Get dependencies for this phase
        const dependsOn = await this.phaseRepository.getDependencies(phaseId);

        const queuedPhase: QueuedPhase = {
          phaseId,
          initiativeId: phase.initiativeId,
          queuedAt: new Date(),
          dependsOn,
        };

        this.phaseQueue.set(phaseId, queuedPhase);

        // Emit PhaseQueuedEvent
        const event: PhaseQueuedEvent = {
          type: 'phase:queued',
          timestamp: new Date(),
          payload: {
            phaseId,
            initiativeId: phase.initiativeId,
            dependsOn,
          },
        };
        this.eventBus.emit(event);
      }

      /**
       * Get next dispatchable phase.
       * Returns phase with all dependencies complete, sorted by queuedAt (oldest first).
       */
      async getNextDispatchablePhase(): Promise<QueuedPhase | null> {
        const queuedPhases = Array.from(this.phaseQueue.values());

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

        // Filter to only phases with all dependencies complete
        const readyPhases: QueuedPhase[] = [];

        for (const qp of queuedPhases) {
          const allDepsComplete = await this.areAllPhaseDependenciesComplete(qp.dependsOn);
          if (allDepsComplete) {
            readyPhases.push(qp);
          }
        }

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

        // Sort by queuedAt (oldest first)
        readyPhases.sort((a, b) => a.queuedAt.getTime() - b.queuedAt.getTime());

        return readyPhases[0];
      }

      /**
       * Dispatch next available phase.
       * Updates phase status to 'in_progress', queues its tasks, and emits PhaseStartedEvent.
       */
      async dispatchNextPhase(): Promise<PhaseDispatchResult> {
        // Get next dispatchable phase
        const nextPhase = await this.getNextDispatchablePhase();

        if (!nextPhase) {
          return {
            success: false,
            phaseId: '',
            reason: 'No dispatchable phases',
          };
        }

        // Get phase details for event
        const phase = await this.phaseRepository.findById(nextPhase.phaseId);
        Iif (!phase) {
          return {
            success: false,
            phaseId: nextPhase.phaseId,
            reason: 'Phase not found',
          };
        }

        // Update phase status to 'in_progress'
        await this.phaseRepository.update(nextPhase.phaseId, { status: 'in_progress' });

        // Create phase branch in all linked project clones
        Iif (this.initiativeRepository && this.projectRepository && this.branchManager && this.workspaceRoot) {
          try {
            const initiative = await this.initiativeRepository.findById(phase.initiativeId);
            if (initiative?.branch) {
              const initBranch = initiative.branch;
              const phBranch = phaseBranchName(initBranch, phase.name);
              const projects = await this.projectRepository.findProjectsByInitiativeId(phase.initiativeId);
              for (const project of projects) {
                const clonePath = await ensureProjectClone(project, this.workspaceRoot);
                await this.branchManager.ensureBranch(clonePath, initBranch, project.defaultBranch);
                await this.branchManager.ensureBranch(clonePath, phBranch, initBranch);
              }
              log.info({ phaseId: nextPhase.phaseId, phBranch, initBranch }, 'phase branch created');
            }
          } catch (err) {
            log.error({ phaseId: nextPhase.phaseId, err: err instanceof Error ? err.message : String(err) }, 'failed to create phase branch');
          }
        }

        // Remove from queue (now being worked on)
        this.phaseQueue.delete(nextPhase.phaseId);

        // Auto-queue pending execution tasks for this phase (skip planning-category tasks)
        const phaseTasks = await this.taskRepository.findByPhaseId(nextPhase.phaseId);
        for (const task of phaseTasks) {
          if (task.status === 'pending' && !isPlanningCategory(task.category)) {
            await this.dispatchManager.queue(task.id);
          }
        }

        // Emit PhaseStartedEvent
        const event: PhaseStartedEvent = {
          type: 'phase:started',
          timestamp: new Date(),
          payload: {
            phaseId: nextPhase.phaseId,
            initiativeId: phase.initiativeId,
          },
        };
        this.eventBus.emit(event);

        return {
          success: true,
          phaseId: nextPhase.phaseId,
        };
      }

      /**
       * Mark a phase as complete.
       * Updates phase status and removes from queue.
       */
      async completePhase(phaseId: string): Promise<void> {
        // Get phase for event
        const phase = await this.phaseRepository.findById(phaseId);
        if (!phase) {
          throw new Error(`Phase not found: ${phaseId}`);
        }

        // Update phase status to 'completed'
        await this.phaseRepository.update(phaseId, { status: 'completed' });

        // Remove from queue
        this.phaseQueue.delete(phaseId);

        // Also remove from blocked if it was there
        this.blockedPhases.delete(phaseId);

        // Emit PhaseCompletedEvent
        const event: PhaseCompletedEvent = {
          type: 'phase:completed',
          timestamp: new Date(),
          payload: {
            phaseId,
            initiativeId: phase.initiativeId,
            success: true,
            message: 'Phase completed',
          },
        };
        this.eventBus.emit(event);
      }

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

        // Record in blocked map
        this.blockedPhases.set(phaseId, { phaseId, reason });

        // Remove from queue (blocked phases aren't dispatchable)
        this.phaseQueue.delete(phaseId);

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

      /**
       * Get current phase queue state.
       */
      async getPhaseQueueState(): Promise<{
        queued: QueuedPhase[];
        ready: QueuedPhase[];
        blocked: Array<{ phaseId: string; reason: string }>;
      }> {
        const allQueued = Array.from(this.phaseQueue.values());

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

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

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

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

        for (const depPhaseId of dependsOn) {
          const depPhase = await this.phaseRepository.findById(depPhaseId);
          if (!depPhase || depPhase.status !== 'completed') {
            return false;
          }
        }

        return true;
      }
    }