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 | 9x 126x 126x 126x 126x 63x 1x 126x 126x 126x 79x 1x 125x 125x 125x 125x 125x 126x 126x 126x 126x 124x 124x 125x 125x 137x 137x 107x 137x 137x 137x 74x 4x 3x 7x 60x 107x 107x 107x 107x 74x 74x 74x 74x 74x 74x 74x 74x 13x 13x 13x 13x 13x 13x 13x 20x 20x 20x 20x 20x 20x 20x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 79x 31x 31x 12x 11x 11x 1x 14x 14x 1x 13x 1x 12x 12x 12x 12x 12x 12x 12x 12x 14x 14x 9x 9x 15x 15x 2x 2x 2x 2x 2x 129x 125x 124x 129x 129x | /**
* Mock Agent Manager Adapter
*
* Implementation of AgentManager port for test scenarios.
* Simulates configurable agent behaviors (success, crash, waiting_for_input)
* without spawning real Claude agents.
*/
import { randomUUID } from 'crypto';
import type {
AgentManager,
AgentInfo,
AgentMode,
SpawnAgentOptions,
AgentResult,
AgentStatus,
PendingQuestions,
QuestionItem,
} from './types.js';
import type {
EventBus,
AgentSpawnedEvent,
AgentStoppedEvent,
AgentCrashedEvent,
AgentResumedEvent,
AgentDeletedEvent,
AgentWaitingEvent,
} from '../events/index.js';
/**
* Scenario configuration for mock agent behavior.
* Matches the simplified agent signal schema: done, questions, or error.
* Mode-specific stopped reasons are derived from the agent's mode.
*/
export type MockAgentScenario =
| {
status: 'done';
result?: string;
filesModified?: string[];
delay?: number;
}
| {
status: 'questions';
questions: QuestionItem[];
delay?: number;
}
| {
status: 'error';
error: string;
delay?: number;
};
/**
* Internal agent record with scenario and timer tracking.
*/
interface MockAgentRecord {
info: AgentInfo;
scenario: MockAgentScenario;
result?: AgentResult;
pendingQuestions?: PendingQuestions;
completionTimer?: ReturnType<typeof setTimeout>;
}
/**
* Default scenario: immediate success with generic message.
*/
const DEFAULT_SCENARIO: MockAgentScenario = {
status: 'done',
result: 'Task completed successfully',
filesModified: [],
delay: 0,
};
/**
* MockAgentManager - Adapter implementing AgentManager port for testing.
*
* Enables E2E testing of dispatch/coordination flows without spawning
* real Claude agents. Simulates configurable agent behaviors and
* emits proper lifecycle events.
*/
export class MockAgentManager implements AgentManager {
private agents: Map<string, MockAgentRecord> = new Map();
private scenarioOverrides: Map<string, MockAgentScenario> = new Map();
private defaultScenario: MockAgentScenario;
private eventBus?: EventBus;
constructor(options?: { eventBus?: EventBus; defaultScenario?: MockAgentScenario }) {
this.eventBus = options?.eventBus;
this.defaultScenario = options?.defaultScenario ?? DEFAULT_SCENARIO;
}
/**
* Set scenario override for a specific agent name.
* When spawn() is called with this name, the override takes precedence.
*/
setScenario(agentName: string, scenario: MockAgentScenario): void {
this.scenarioOverrides.set(agentName, scenario);
}
/**
* Clear scenario override for a specific agent name.
*/
clearScenario(agentName: string): void {
this.scenarioOverrides.delete(agentName);
}
/**
* Spawn a new mock agent.
*
* Creates agent record in internal Map, schedules completion based on scenario.
* Completion happens async via setTimeout (even if delay=0).
*/
async spawn(options: SpawnAgentOptions): Promise<AgentInfo> {
const { taskId, prompt } = options;
const name = options.name ?? `agent-${taskId?.slice(0, 6) ?? 'noTask'}`;
// Check name uniqueness
for (const record of this.agents.values()) {
if (record.info.name === name) {
throw new Error(`Agent with name '${name}' already exists`);
}
}
const agentId = randomUUID();
const sessionId = randomUUID();
const worktreeId = randomUUID();
const now = new Date();
// Determine scenario (override takes precedence — use original name or generated)
const scenario = this.scenarioOverrides.get(name) ?? this.defaultScenario;
const info: AgentInfo = {
id: agentId,
name: name ?? `mock-${agentId.slice(0, 6)}`,
taskId: taskId ?? null,
initiativeId: options.initiativeId ?? null,
sessionId,
worktreeId,
status: 'running',
mode: options.mode ?? 'execute',
provider: options.provider ?? 'claude',
accountId: null,
createdAt: now,
updatedAt: now,
};
const record: MockAgentRecord = {
info,
scenario,
};
this.agents.set(agentId, record);
// Emit spawned event
if (this.eventBus) {
const event: AgentSpawnedEvent = {
type: 'agent:spawned',
timestamp: new Date(),
payload: {
agentId,
name,
taskId: taskId ?? null,
worktreeId,
provider: options.provider ?? 'claude',
},
};
this.eventBus.emit(event);
}
// Schedule completion async (even with delay=0, uses setTimeout for async behavior)
this.scheduleCompletion(agentId, scenario);
return info;
}
/**
* Schedule agent completion based on scenario.
*/
private scheduleCompletion(agentId: string, scenario: MockAgentScenario): void {
const delay = scenario.delay ?? 0;
const timer = setTimeout(() => {
this.completeAgent(agentId, scenario);
}, delay);
const record = this.agents.get(agentId);
Eif (record) {
record.completionTimer = timer;
}
}
/**
* Map agent mode to stopped event reason.
*/
private getStoppedReason(mode: AgentMode): AgentStoppedEvent['payload']['reason'] {
switch (mode) {
case 'discuss': return 'context_complete';
case 'plan': return 'plan_complete';
case 'detail': return 'detail_complete';
case 'refine': return 'refine_complete';
default: return 'task_complete';
}
}
/**
* Complete agent based on scenario status.
*/
private completeAgent(agentId: string, scenario: MockAgentScenario): void {
const record = this.agents.get(agentId);
Iif (!record) return;
const { info } = record;
switch (scenario.status) {
case 'done':
record.result = {
success: true,
message: scenario.result ?? 'Task completed successfully',
filesModified: scenario.filesModified,
};
record.info.status = 'idle';
record.info.updatedAt = new Date();
Eif (this.eventBus) {
const reason = this.getStoppedReason(info.mode);
const event: AgentStoppedEvent = {
type: 'agent:stopped',
timestamp: new Date(),
payload: {
agentId,
name: info.name,
taskId: info.taskId,
reason,
},
};
this.eventBus.emit(event);
}
break;
case 'error':
record.result = {
success: false,
message: scenario.error,
};
record.info.status = 'crashed';
record.info.updatedAt = new Date();
Eif (this.eventBus) {
const event: AgentCrashedEvent = {
type: 'agent:crashed',
timestamp: new Date(),
payload: {
agentId,
name: info.name,
taskId: info.taskId,
error: scenario.error,
},
};
this.eventBus.emit(event);
}
break;
case 'questions':
record.info.status = 'waiting_for_input';
record.info.updatedAt = new Date();
record.pendingQuestions = {
questions: scenario.questions,
};
Eif (this.eventBus) {
const event: AgentWaitingEvent = {
type: 'agent:waiting',
timestamp: new Date(),
payload: {
agentId,
name: info.name,
taskId: info.taskId,
sessionId: info.sessionId ?? '',
questions: scenario.questions,
},
};
this.eventBus.emit(event);
}
break;
}
}
/**
* Stop a running agent.
*
* Cancels scheduled completion, marks agent stopped, emits agent:stopped event.
*/
async stop(agentId: string): Promise<void> {
const record = this.agents.get(agentId);
if (!record) {
throw new Error(`Agent '${agentId}' not found`);
}
// Cancel any pending completion
Eif (record.completionTimer) {
clearTimeout(record.completionTimer);
record.completionTimer = undefined;
}
record.info.status = 'stopped';
record.info.updatedAt = new Date();
Eif (this.eventBus) {
const event: AgentStoppedEvent = {
type: 'agent:stopped',
timestamp: new Date(),
payload: {
agentId,
name: record.info.name,
taskId: record.info.taskId,
reason: 'user_requested',
},
};
this.eventBus.emit(event);
}
}
/**
* Delete an agent and clean up.
* Removes from internal map and emits agent:deleted event.
*/
async delete(agentId: string): Promise<void> {
const record = this.agents.get(agentId);
if (!record) {
throw new Error(`Agent '${agentId}' not found`);
}
// Cancel any pending completion
if (record.completionTimer) {
clearTimeout(record.completionTimer);
record.completionTimer = undefined;
}
const name = record.info.name;
this.agents.delete(agentId);
if (this.eventBus) {
const event: AgentDeletedEvent = {
type: 'agent:deleted',
timestamp: new Date(),
payload: {
agentId,
name,
},
};
this.eventBus.emit(event);
}
}
/**
* List all agents with their current status.
*/
async list(): Promise<AgentInfo[]> {
return Array.from(this.agents.values()).map((record) => record.info);
}
/**
* Get a specific agent by ID.
*/
async get(agentId: string): Promise<AgentInfo | null> {
const record = this.agents.get(agentId);
return record ? record.info : null;
}
/**
* Get a specific agent by name.
*/
async getByName(name: string): Promise<AgentInfo | null> {
for (const record of this.agents.values()) {
Eif (record.info.name === name) {
return record.info;
}
}
return null;
}
/**
* Resume an agent that's waiting for input.
*
* Re-runs the scenario for the resumed agent. Emits agent:resumed event.
* Agent must be in 'waiting_for_input' status.
*
* @param agentId - Agent to resume
* @param answers - Map of question ID to user's answer
*/
async resume(agentId: string, answers: Record<string, string>): Promise<void> {
const record = this.agents.get(agentId);
if (!record) {
throw new Error(`Agent '${agentId}' not found`);
}
if (record.info.status !== 'waiting_for_input') {
throw new Error(
`Agent '${record.info.name}' is not waiting for input (status: ${record.info.status})`
);
}
Iif (!record.info.sessionId) {
throw new Error(`Agent '${record.info.name}' has no session to resume`);
}
// Update status to running, clear pending questions
record.info.status = 'running';
record.info.updatedAt = new Date();
record.pendingQuestions = undefined;
// Emit resumed event
Eif (this.eventBus) {
const event: AgentResumedEvent = {
type: 'agent:resumed',
timestamp: new Date(),
payload: {
agentId,
name: record.info.name,
taskId: record.info.taskId,
sessionId: record.info.sessionId,
},
};
this.eventBus.emit(event);
}
// Re-run scenario (after resume, typically completes successfully)
// For testing, we use a new scenario that defaults to success
// Extract filesModified from original scenario if it was a 'done' type
const originalFilesModified =
record.scenario.status === 'done' ? record.scenario.filesModified : undefined;
const resumeScenario: MockAgentScenario = {
status: 'done',
delay: record.scenario.delay ?? 0,
result: 'Resumed and completed successfully',
filesModified: originalFilesModified,
};
this.scheduleCompletion(agentId, resumeScenario);
}
/**
* Get the result of an agent's work.
*
* Only available after agent completes or crashes.
*/
async getResult(agentId: string): Promise<AgentResult | null> {
const record = this.agents.get(agentId);
return record?.result ?? null;
}
/**
* Get pending questions for an agent waiting for input.
*/
async getPendingQuestions(agentId: string): Promise<PendingQuestions | null> {
const record = this.agents.get(agentId);
return record?.pendingQuestions ?? null;
}
/**
* Dismiss an agent.
* Mock implementation just marks the agent as dismissed.
*/
async dismiss(agentId: string): Promise<void> {
const record = this.agents.get(agentId);
Iif (!record) {
throw new Error(`Agent '${agentId}' not found`);
}
const now = new Date();
record.info.userDismissedAt = now;
record.info.updatedAt = now;
}
/**
* Clear all agents and pending timers.
* Useful for test cleanup.
*/
clear(): void {
for (const record of this.agents.values()) {
if (record.completionTimer) {
clearTimeout(record.completionTimer);
}
}
this.agents.clear();
this.scenarioOverrides.clear();
}
}
|