All files / src/test harness.ts

81.42% Statements 57/70
30% Branches 3/10
86.11% Functions 31/36
81.15% Lines 56/69

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 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621                                                                                              80x 80x             12x       20x           20x 20x                                                           22x         22x 22x 12x     10x                     80x 80x                           80x     366x 366x             173x             124x                     8x                                                                                                                                                                                                                                                                                                                                                                                                                                                                     80x     80x     80x 80x     80x 80x     80x             80x             80x                 80x                             80x     80x                                           48x     13x       2x             5x                 1x             2x     5x   46x   5x   44x     80x 80x 80x       14x                     3x                     1x                     5x                     6x                     2x                                       2x       19x             12x       7x                     4x       80x    
/**
 * Test Harness for E2E Testing
 *
 * Wires up the full system with mocks for E2E testing.
 * Uses real managers (DispatchManager, CoordinationManager) with
 * MockAgentManager and MockWorktreeManager for isolation.
 */
 
import { randomUUID } from 'crypto';
import { vi } from 'vitest';
import type { DrizzleDatabase } from '../db/index.js';
import type { EventBus, DomainEvent } from '../events/types.js';
import { EventEmitterBus } from '../events/bus.js';
import type { AgentManager } from '../agent/types.js';
import { MockAgentManager, type MockAgentScenario } from '../agent/mock-manager.js';
import type { PendingQuestions, QuestionItem } from '../agent/types.js';
import type { WorktreeManager, Worktree, WorktreeDiff, MergeResult } from '../git/types.js';
import type { DispatchManager, PhaseDispatchManager } from '../dispatch/types.js';
import { DefaultDispatchManager } from '../dispatch/manager.js';
import { DefaultPhaseDispatchManager } from '../dispatch/phase-manager.js';
import type { CoordinationManager } from '../coordination/types.js';
import { DefaultCoordinationManager } from '../coordination/manager.js';
import type { TaskRepository } from '../db/repositories/task-repository.js';
import type { MessageRepository } from '../db/repositories/message-repository.js';
import type { AgentRepository } from '../db/repositories/agent-repository.js';
import type { InitiativeRepository } from '../db/repositories/initiative-repository.js';
import type { PhaseRepository } from '../db/repositories/phase-repository.js';
import type { Initiative, Phase, Task } from '../db/schema.js';
import { createTestDatabase } from '../db/repositories/drizzle/test-helpers.js';
import { createRepositories } from '../container.js';
import {
  seedFixture,
  type InitiativeFixture,
  type SeededFixture,
} from './fixtures.js';
import { appRouter, createCallerFactory } from '../trpc/router.js';
import { createContext, type TRPCContext } from '../trpc/context.js';
 
// =============================================================================
// MockWorktreeManager
// =============================================================================
 
/**
 * Simple in-memory WorktreeManager for testing.
 * Creates fake worktrees without actual git operations.
 */
export class MockWorktreeManager implements WorktreeManager {
  private worktrees: Map<string, Worktree> = new Map();
  private mergeResults: Map<string, MergeResult> = new Map();
 
  /**
   * Set a custom merge result for a specific worktree.
   * Used to test conflict scenarios.
   */
  setMergeResult(worktreeId: string, result: MergeResult): void {
    this.mergeResults.set(worktreeId, result);
  }
 
  async create(id: string, branch: string, baseBranch?: string): Promise<Worktree> {
    const worktree: Worktree = {
      id,
      branch,
      path: `/tmp/test-worktrees/${id}`,
      isMainWorktree: false,
    };
    this.worktrees.set(id, worktree);
    return worktree;
  }
 
  async remove(id: string): Promise<void> {
    if (!this.worktrees.has(id)) {
      throw new Error(`Worktree not found: ${id}`);
    }
    this.worktrees.delete(id);
    this.mergeResults.delete(id);
  }
 
  async list(): Promise<Worktree[]> {
    return Array.from(this.worktrees.values());
  }
 
  async get(id: string): Promise<Worktree | null> {
    return this.worktrees.get(id) ?? null;
  }
 
  async diff(id: string): Promise<WorktreeDiff> {
    if (!this.worktrees.has(id)) {
      throw new Error(`Worktree not found: ${id}`);
    }
    return {
      files: [],
      summary: 'No changes (mock)',
    };
  }
 
  async merge(id: string, targetBranch: string): Promise<MergeResult> {
    Iif (!this.worktrees.has(id)) {
      throw new Error(`Worktree not found: ${id}`);
    }
 
    // Return custom result if set, otherwise success
    const customResult = this.mergeResults.get(id);
    if (customResult) {
      return customResult;
    }
 
    return {
      success: true,
      message: `Merged ${id} into ${targetBranch} (mock)`,
    };
  }
 
  /**
   * Clear all worktrees.
   * Useful for test cleanup.
   */
  clear(): void {
    this.worktrees.clear();
    this.mergeResults.clear();
  }
}
 
// =============================================================================
// CapturingEventBus
// =============================================================================
 
/**
 * EventBus wrapper that captures all emitted events.
 * Extends EventEmitterBus with event capture functionality.
 */
export class CapturingEventBus extends EventEmitterBus {
  /** All emitted events */
  emittedEvents: DomainEvent[] = [];
 
  emit<T extends DomainEvent>(event: T): void {
    this.emittedEvents.push(event);
    super.emit(event);
  }
 
  /**
   * Get events by type.
   */
  getEventsByType(type: string): DomainEvent[] {
    return this.emittedEvents.filter((e) => e.type === type);
  }
 
  /**
   * Clear captured events.
   */
  clearEvents(): void {
    this.emittedEvents = [];
  }
}
 
// =============================================================================
// tRPC Caller Type
// =============================================================================
 
/**
 * Create caller factory for the app router.
 */
const createCaller = createCallerFactory(appRouter);
 
/**
 * Type for the tRPC caller.
 */
export type TRPCCaller = ReturnType<typeof createCaller>;
 
// =============================================================================
// TestHarness Interface
// =============================================================================
 
/**
 * Test harness for E2E testing.
 * Provides access to all system components and helper methods.
 */
export interface TestHarness {
  // Core components
  /** In-memory SQLite database */
  db: DrizzleDatabase;
  /** Event bus with event capture */
  eventBus: CapturingEventBus;
  /** Mock agent manager */
  agentManager: MockAgentManager;
  /** Alias for agentManager - used in tests for clarity */
  mockAgentManager: MockAgentManager;
  /** Mock worktree manager */
  worktreeManager: MockWorktreeManager;
  /** Real dispatch manager wired to mocks */
  dispatchManager: DispatchManager;
  /** Real phase dispatch manager wired to phaseRepository */
  phaseDispatchManager: PhaseDispatchManager;
  /** Real coordination manager wired to mocks */
  coordinationManager: CoordinationManager;
 
  // Repositories
  /** Task repository */
  taskRepository: TaskRepository;
  /** Message repository */
  messageRepository: MessageRepository;
  /** Agent repository */
  agentRepository: AgentRepository;
  /** Initiative repository */
  initiativeRepository: InitiativeRepository;
  /** Phase repository */
  phaseRepository: PhaseRepository;
 
  // tRPC Caller
  /** tRPC caller for direct procedure calls */
  caller: TRPCCaller;
 
  // Helpers
  /**
   * Seed a fixture into the database.
   */
  seedFixture(fixture: InitiativeFixture): Promise<SeededFixture>;
 
  /**
   * Set scenario for a specific agent name.
   */
  setAgentScenario(agentName: string, scenario: MockAgentScenario): void;
 
  /**
   * Convenience: Set agent to complete with done status.
   */
  setAgentDone(agentName: string, result?: string): void;
 
  /**
   * Convenience: Set agent to ask questions (array form).
   */
  setAgentQuestions(
    agentName: string,
    questions: QuestionItem[]
  ): void;
 
  /**
   * Convenience: Set agent to ask a single question.
   * Wraps the question in an array internally.
   */
  setAgentQuestion(
    agentName: string,
    questionId: string,
    question: string,
    options?: Array<{ label: string; description?: string }>
  ): void;
 
  /**
   * Convenience: Set agent to fail with unrecoverable error.
   */
  setAgentError(agentName: string, error: string): void;
 
  /**
   * Get pending questions for an agent.
   */
  getPendingQuestions(agentId: string): Promise<PendingQuestions | null>;
 
  /**
   * Get events by type.
   */
  getEventsByType(type: string): DomainEvent[];
 
  /**
   * Get emitted events by type (alias for getEventsByType).
   */
  getEmittedEvents(type: string): DomainEvent[];
 
  /**
   * Clear all captured events.
   */
  clearEvents(): void;
 
  /**
   * Clean up all resources.
   */
  cleanup(): void;
 
  /**
   * Advance fake timers (wrapper for vi.runAllTimersAsync).
   * Only works when vi.useFakeTimers() is active.
   */
  advanceTimers(): Promise<void>;
 
  // ==========================================================================
  // Architect Mode Helpers
  // ==========================================================================
 
  /**
   * Set up scenario where architect completes discussion.
   */
  setArchitectDiscussComplete(
    agentName: string,
    _decisions: unknown[],
    summary: string
  ): void;
 
  /**
   * Set up scenario where architect needs more questions in discuss mode.
   */
  setArchitectDiscussQuestions(
    agentName: string,
    questions: QuestionItem[]
  ): void;
 
  /**
   * Set up scenario where architect completes plan.
   */
  setArchitectPlanComplete(
    agentName: string,
    _phases: unknown[]
  ): void;
 
  /**
   * Set up scenario where architect completes detail.
   */
  setArchitectDetailComplete(
    agentName: string,
    _tasks: unknown[]
  ): void;
 
  /**
   * Set up scenario where architect needs questions in detail mode.
   */
  setArchitectDetailQuestions(
    agentName: string,
    questions: QuestionItem[]
  ): void;
 
  // ==========================================================================
  // Initiative/Phase/Plan Convenience Helpers
  // ==========================================================================
 
  /**
   * Get initiative by ID through tRPC.
   */
  getInitiative(id: string): Promise<Initiative | null>;
 
  /**
   * Get phases for initiative through tRPC.
   */
  getPhases(initiativeId: string): Promise<Phase[]>;
 
  /**
   * Create initiative through tRPC.
   */
  createInitiative(name: string): Promise<Initiative>;
 
  /**
   * Create phases from plan output through tRPC.
   */
  createPhasesFromPlan(
    initiativeId: string,
    phases: Array<{ name: string }>
  ): Promise<Phase[]>;
 
  /**
   * Create a detail task through tRPC (replaces createPlan).
   */
  createDetailTask(
    phaseId: string,
    name: string,
    description?: string
  ): Promise<Task>;
 
  /**
   * Get child tasks of a parent task through tRPC.
   */
  getChildTasks(parentTaskId: string): Promise<Task[]>;
}
 
// =============================================================================
// createTestHarness Factory
// =============================================================================
 
/**
 * Create a fully wired test harness for E2E testing.
 *
 * Wires:
 * - In-memory SQLite database
 * - CapturingEventBus (captures all events)
 * - MockAgentManager (simulates agent behavior)
 * - MockWorktreeManager (fake worktrees)
 * - Real DefaultDispatchManager (with mock agent manager)
 * - Real DefaultCoordinationManager (with mock worktree manager)
 * - All repositories (Drizzle implementations)
 * - tRPC caller with full context
 */
export function createTestHarness(): TestHarness {
  // Create database
  const db = createTestDatabase();
 
  // Create event bus with capture
  const eventBus = new CapturingEventBus();
 
  // Create mock managers
  const agentManager = new MockAgentManager({ eventBus });
  const worktreeManager = new MockWorktreeManager();
 
  // Create repositories
  const repos = createRepositories(db);
  const { taskRepository, messageRepository, agentRepository, initiativeRepository, phaseRepository } = repos;
 
  // Create real managers wired to mocks
  const dispatchManager = new DefaultDispatchManager(
    taskRepository,
    messageRepository,
    agentManager,
    eventBus
  );
 
  const phaseDispatchManager = new DefaultPhaseDispatchManager(
    phaseRepository,
    taskRepository,
    dispatchManager,
    eventBus
  );
 
  const coordinationManager = new DefaultCoordinationManager(
    worktreeManager,
    taskRepository,
    agentRepository,
    messageRepository,
    eventBus
  );
 
  // Create tRPC context with all dependencies
  const ctx: TRPCContext = createContext({
    eventBus,
    serverStartedAt: new Date(),
    processCount: 0,
    agentManager,
    taskRepository,
    messageRepository,
    dispatchManager,
    phaseDispatchManager,
    coordinationManager,
    initiativeRepository,
    phaseRepository,
  });
 
  // Create tRPC caller
  const caller = createCaller(ctx);
 
  // Build harness
  const harness: TestHarness = {
    // Core components
    db,
    eventBus,
    agentManager,
    mockAgentManager: agentManager, // Alias for clarity in tests
    worktreeManager,
    dispatchManager,
    phaseDispatchManager,
    coordinationManager,
 
    // Repositories
    taskRepository,
    messageRepository,
    agentRepository,
    initiativeRepository,
    phaseRepository,
 
    // tRPC Caller
    caller,
 
    // Helpers
    seedFixture: (fixture: InitiativeFixture) => seedFixture(db, fixture),
 
    setAgentScenario: (agentName: string, scenario: MockAgentScenario) => {
      agentManager.setScenario(agentName, scenario);
    },
 
    setAgentDone: (agentName: string, result?: string) => {
      agentManager.setScenario(agentName, { status: 'done', result });
    },
 
    setAgentQuestions: (
      agentName: string,
      questions: QuestionItem[]
    ) => {
      agentManager.setScenario(agentName, { status: 'questions', questions });
    },
 
    setAgentQuestion: (
      agentName: string,
      questionId: string,
      question: string,
      options?: Array<{ label: string; description?: string }>
    ) => {
      agentManager.setScenario(agentName, {
        status: 'questions',
        questions: [{ id: questionId, question, options }],
      });
    },
 
    setAgentError: (agentName: string, error: string) => {
      agentManager.setScenario(agentName, { status: 'error', error });
    },
 
    getPendingQuestions: (agentId: string) => agentManager.getPendingQuestions(agentId),
 
    getEventsByType: (type: string) => eventBus.getEventsByType(type),
 
    getEmittedEvents: (type: string) => eventBus.getEventsByType(type),
 
    clearEvents: () => eventBus.clearEvents(),
 
    cleanup: () => {
      agentManager.clear();
      worktreeManager.clear();
      eventBus.clearEvents();
    },
 
    // Timer helper - requires vi.useFakeTimers() to be active
    advanceTimers: () => vi.runAllTimersAsync(),
 
    // ========================================================================
    // Architect Mode Helpers
    // ========================================================================
 
    setArchitectDiscussComplete: (
      agentName: string,
      _decisions: unknown[],
      summary: string
    ) => {
      agentManager.setScenario(agentName, {
        status: 'done',
        result: summary,
        delay: 0,
      });
    },
 
    setArchitectDiscussQuestions: (
      agentName: string,
      questions: QuestionItem[]
    ) => {
      agentManager.setScenario(agentName, {
        status: 'questions',
        questions,
        delay: 0,
      });
    },
 
    setArchitectPlanComplete: (
      agentName: string,
      _phases: unknown[]
    ) => {
      agentManager.setScenario(agentName, {
        status: 'done',
        result: 'Plan complete',
        delay: 0,
      });
    },
 
    setArchitectDetailComplete: (
      agentName: string,
      _tasks: unknown[]
    ) => {
      agentManager.setScenario(agentName, {
        status: 'done',
        result: 'Detail complete',
        delay: 0,
      });
    },
 
    setArchitectDetailQuestions: (
      agentName: string,
      questions: QuestionItem[]
    ) => {
      agentManager.setScenario(agentName, {
        status: 'questions',
        questions,
        delay: 0,
      });
    },
 
    // ========================================================================
    // Initiative/Phase/Plan Convenience Helpers
    // ========================================================================
 
    getInitiative: async (id: string) => {
      try {
        return await caller.getInitiative({ id });
      } catch {
        return null;
      }
    },
 
    getPhases: (initiativeId: string) => {
      return caller.listPhases({ initiativeId });
    },
 
    createInitiative: (name: string) => {
      return caller.createInitiative({ name });
    },
 
    createPhasesFromPlan: (
      initiativeId: string,
      phases: Array<{ name: string }>
    ) => {
      return caller.createPhasesFromPlan({ initiativeId, phases });
    },
 
    createDetailTask: async (phaseId: string, name: string, description?: string) => {
      return caller.createPhaseTask({
        phaseId,
        name,
        description,
        category: 'detail',
        type: 'auto',
        requiresApproval: true,
      });
    },
 
    getChildTasks: (parentTaskId: string) => {
      return caller.listTasks({ parentTaskId });
    },
  };
 
  return harness;
}