feat: wire quality review into orchestrator handleAgentStopped

When an agent stops, check whether a quality review should run before
auto-completing the task. If shouldRunQualityReview returns run:true,
delegate to runQualityReview (which transitions task to quality_review
and spawns a review agent) instead of calling completeTask directly.

Falls back to completeTask when agentRepository or agentManager are
not injected, or when the task lacks phaseId/initiativeId context.

- Add agentManager optional param to ExecutionOrchestrator constructor
- Extract tryQualityReview() private method to compute branch names and
  repo path before delegating to the quality-review service
- Pass agentManager to ExecutionOrchestrator in container.ts
- Add orchestrator integration tests for the agent:stopped quality hook

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lukas May
2026-03-06 22:05:42 +01:00
parent 9200891a5d
commit 4bc65bfe3d
3 changed files with 203 additions and 6 deletions

View File

@@ -251,6 +251,7 @@ export async function createContainer(options?: ContainerOptions): Promise<Conta
eventBus, eventBus,
workspaceRoot, workspaceRoot,
repos.agentRepository, repos.agentRepository,
agentManager,
); );
executionOrchestrator.start(); executionOrchestrator.start();
log.info('execution orchestrator started'); log.info('execution orchestrator started');

View File

@@ -8,17 +8,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ExecutionOrchestrator } from './orchestrator.js'; import { ExecutionOrchestrator } from './orchestrator.js';
import { ensureProjectClone } from '../git/project-clones.js'; import { ensureProjectClone } from '../git/project-clones.js';
import type { BranchManager } from '../git/branch-manager.js'; import type { BranchManager } from '../git/branch-manager.js';
import type { AgentManager } from '../agent/types.js';
import type { AgentRepository } from '../db/repositories/agent-repository.js';
vi.mock('../git/project-clones.js', () => ({ vi.mock('../git/project-clones.js', () => ({
ensureProjectClone: vi.fn().mockResolvedValue('/tmp/test-workspace/clones/test'), ensureProjectClone: vi.fn().mockResolvedValue('/tmp/test-workspace/clones/test'),
})); }));
vi.mock('./quality-review.js', () => ({
shouldRunQualityReview: vi.fn().mockResolvedValue({ run: false, qualifyingFiles: [] }),
runQualityReview: vi.fn().mockResolvedValue(undefined),
computeQualifyingFiles: vi.fn().mockResolvedValue([]),
}));
import type { PhaseRepository } from '../db/repositories/phase-repository.js'; import type { PhaseRepository } from '../db/repositories/phase-repository.js';
import type { TaskRepository } from '../db/repositories/task-repository.js'; import type { TaskRepository } from '../db/repositories/task-repository.js';
import type { InitiativeRepository } from '../db/repositories/initiative-repository.js'; import type { InitiativeRepository } from '../db/repositories/initiative-repository.js';
import type { ProjectRepository } from '../db/repositories/project-repository.js'; import type { ProjectRepository } from '../db/repositories/project-repository.js';
import type { DispatchManager, PhaseDispatchManager } from '../dispatch/types.js'; import type { DispatchManager, PhaseDispatchManager } from '../dispatch/types.js';
import type { ConflictResolutionService } from '../coordination/conflict-resolution-service.js'; import type { ConflictResolutionService } from '../coordination/conflict-resolution-service.js';
import type { EventBus, TaskCompletedEvent, DomainEvent } from '../events/types.js'; import type { EventBus, TaskCompletedEvent, AgentStoppedEvent, DomainEvent } from '../events/types.js';
import { shouldRunQualityReview, runQualityReview } from './quality-review.js';
function createMockEventBus(): EventBus & { handlers: Map<string, Function[]>; emitted: DomainEvent[] } { function createMockEventBus(): EventBus & { handlers: Map<string, Function[]>; emitted: DomainEvent[] } {
const handlers = new Map<string, Function[]>(); const handlers = new Map<string, Function[]>();
@@ -108,6 +117,33 @@ function createMocks() {
handleConflict: vi.fn(), handleConflict: vi.fn(),
}; };
const agentRepository = {
create: vi.fn(),
findById: vi.fn().mockResolvedValue(null),
findByName: vi.fn(),
findByTaskId: vi.fn(),
findBySessionId: vi.fn(),
findAll: vi.fn(),
findByStatus: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
} as unknown as AgentRepository;
const agentManager = {
spawn: vi.fn().mockResolvedValue({ id: 'review-agent-1', name: 'review-agent' }),
stop: vi.fn(),
list: vi.fn().mockResolvedValue([]),
get: vi.fn(),
getByName: vi.fn(),
resume: vi.fn(),
getResult: vi.fn(),
getPendingQuestions: vi.fn(),
delete: vi.fn(),
dismiss: vi.fn(),
resumeForConversation: vi.fn(),
sendUserMessage: vi.fn(),
} as unknown as AgentManager;
const eventBus = createMockEventBus(); const eventBus = createMockEventBus();
return { return {
@@ -119,11 +155,13 @@ function createMocks() {
phaseDispatchManager, phaseDispatchManager,
dispatchManager, dispatchManager,
conflictResolutionService, conflictResolutionService,
agentRepository,
agentManager,
eventBus, eventBus,
}; };
} }
function createOrchestrator(mocks: ReturnType<typeof createMocks>) { function createOrchestrator(mocks: ReturnType<typeof createMocks>, opts: { withAgentManager?: boolean; withAgentRepository?: boolean } = {}) {
const orchestrator = new ExecutionOrchestrator( const orchestrator = new ExecutionOrchestrator(
mocks.branchManager, mocks.branchManager,
mocks.phaseRepository, mocks.phaseRepository,
@@ -135,6 +173,8 @@ function createOrchestrator(mocks: ReturnType<typeof createMocks>) {
mocks.conflictResolutionService, mocks.conflictResolutionService,
mocks.eventBus, mocks.eventBus,
'/tmp/test-workspace', '/tmp/test-workspace',
opts.withAgentRepository !== false ? mocks.agentRepository : undefined,
opts.withAgentManager !== false ? mocks.agentManager : undefined,
); );
orchestrator.start(); orchestrator.start();
return orchestrator; return orchestrator;
@@ -369,4 +409,89 @@ describe('ExecutionOrchestrator', () => {
expect(mocks.branchManager.updateRef).not.toHaveBeenCalled(); expect(mocks.branchManager.updateRef).not.toHaveBeenCalled();
}); });
}); });
describe('handleAgentStopped quality review hook', () => {
function emitAgentStopped(eventBus: ReturnType<typeof createMockEventBus>, payload: { taskId?: string; agentId: string; reason: AgentStoppedEvent['payload']['reason'] }) {
const event: AgentStoppedEvent = {
type: 'agent:stopped',
timestamp: new Date(),
payload: { taskId: payload.taskId ?? null, agentId: payload.agentId, name: 'test-agent', reason: payload.reason },
};
eventBus.emit(event);
}
function setupQualityReviewMocks() {
const task = { id: 'task-1', phaseId: 'phase-1', initiativeId: 'init-1', category: 'execute', status: 'in_progress' };
const initiative = { id: 'init-1', branch: 'cw/test-initiative', executionMode: 'yolo', qualityReview: true };
const phase = { id: 'phase-1', initiativeId: 'init-1', name: 'Phase 1', status: 'in_progress' };
const project = { id: 'proj-1', name: 'test', url: 'https://example.com', defaultBranch: 'main' };
vi.mocked(mocks.taskRepository.findById).mockResolvedValue(task as any);
vi.mocked(mocks.initiativeRepository.findById).mockResolvedValue(initiative as any);
vi.mocked(mocks.phaseRepository.findById).mockResolvedValue(phase as any);
vi.mocked(mocks.projectRepository.findProjectsByInitiativeId).mockResolvedValue([project] as any);
vi.mocked(ensureProjectClone).mockResolvedValue('/tmp/test-workspace/clones/test');
}
beforeEach(() => {
vi.mocked(shouldRunQualityReview).mockClear().mockResolvedValue({ run: false, qualifyingFiles: [] });
vi.mocked(runQualityReview).mockClear().mockResolvedValue(undefined);
});
it('should not call shouldRunQualityReview when reason is user_requested', async () => {
createOrchestrator(mocks);
emitAgentStopped(mocks.eventBus, { taskId: 'task-1', agentId: 'agent-1', reason: 'user_requested' });
await new Promise((r) => setTimeout(r, 50));
expect(shouldRunQualityReview).not.toHaveBeenCalled();
expect(mocks.dispatchManager.completeTask).not.toHaveBeenCalled();
});
it('should call dispatchManager.completeTask when shouldRunQualityReview returns run: false', async () => {
setupQualityReviewMocks();
vi.mocked(shouldRunQualityReview).mockResolvedValue({ run: false, qualifyingFiles: [] });
createOrchestrator(mocks);
emitAgentStopped(mocks.eventBus, { taskId: 'task-1', agentId: 'agent-1', reason: 'task_complete' });
await vi.waitFor(() => {
expect(mocks.dispatchManager.completeTask).toHaveBeenCalledWith('task-1', 'agent-1');
});
expect(runQualityReview).not.toHaveBeenCalled();
});
it('should call runQualityReview and NOT call completeTask when shouldRunQualityReview returns run: true', async () => {
setupQualityReviewMocks();
vi.mocked(shouldRunQualityReview).mockResolvedValue({ run: true, qualifyingFiles: ['src/foo.ts'] });
createOrchestrator(mocks);
emitAgentStopped(mocks.eventBus, { taskId: 'task-1', agentId: 'agent-1', reason: 'task_complete' });
await vi.waitFor(() => {
expect(runQualityReview).toHaveBeenCalledWith(
expect.objectContaining({
taskId: 'task-1',
qualifyingFiles: ['src/foo.ts'],
taskRepository: mocks.taskRepository,
}),
);
});
expect(mocks.dispatchManager.completeTask).not.toHaveBeenCalled();
});
it('should fall back to completeTask when agentRepository is not available', async () => {
createOrchestrator(mocks, { withAgentRepository: false, withAgentManager: false });
emitAgentStopped(mocks.eventBus, { taskId: 'task-1', agentId: 'agent-1', reason: 'task_complete' });
await vi.waitFor(() => {
expect(mocks.dispatchManager.completeTask).toHaveBeenCalledWith('task-1', 'agent-1');
});
expect(shouldRunQualityReview).not.toHaveBeenCalled();
});
});
}); });

View File

@@ -18,12 +18,14 @@ import type { TaskRepository } from '../db/repositories/task-repository.js';
import type { InitiativeRepository } from '../db/repositories/initiative-repository.js'; import type { InitiativeRepository } from '../db/repositories/initiative-repository.js';
import type { ProjectRepository } from '../db/repositories/project-repository.js'; import type { ProjectRepository } from '../db/repositories/project-repository.js';
import type { AgentRepository } from '../db/repositories/agent-repository.js'; import type { AgentRepository } from '../db/repositories/agent-repository.js';
import type { AgentManager } from '../agent/types.js';
import type { DispatchManager, PhaseDispatchManager } from '../dispatch/types.js'; import type { DispatchManager, PhaseDispatchManager } from '../dispatch/types.js';
import type { ConflictResolutionService } from '../coordination/conflict-resolution-service.js'; import type { ConflictResolutionService } from '../coordination/conflict-resolution-service.js';
import { phaseBranchName, taskBranchName } from '../git/branch-naming.js'; import { phaseBranchName, taskBranchName } from '../git/branch-naming.js';
import { ensureProjectClone } from '../git/project-clones.js'; import { ensureProjectClone } from '../git/project-clones.js';
import { createModuleLogger } from '../logger/index.js'; import { createModuleLogger } from '../logger/index.js';
import { phaseMetaCache, fileDiffCache } from '../review/diff-cache.js'; import { phaseMetaCache, fileDiffCache } from '../review/diff-cache.js';
import { shouldRunQualityReview, runQualityReview } from './quality-review.js';
const log = createModuleLogger('execution-orchestrator'); const log = createModuleLogger('execution-orchestrator');
@@ -50,6 +52,7 @@ export class ExecutionOrchestrator {
private eventBus: EventBus, private eventBus: EventBus,
private workspaceRoot: string, private workspaceRoot: string,
private agentRepository?: AgentRepository, private agentRepository?: AgentRepository,
private agentManager?: AgentManager,
) {} ) {}
/** /**
@@ -108,15 +111,17 @@ export class ExecutionOrchestrator {
private async handleAgentStopped(event: AgentStoppedEvent): Promise<void> { private async handleAgentStopped(event: AgentStoppedEvent): Promise<void> {
const { taskId, reason, agentId } = event.payload; const { taskId, reason, agentId } = event.payload;
// Auto-complete task for successful agent completions, not manual stops
if (taskId && reason !== 'user_requested') { if (taskId && reason !== 'user_requested') {
try { try {
const result = await this.tryQualityReview(taskId, agentId, reason);
if (!result.reviewStarted) {
await this.dispatchManager.completeTask(taskId, agentId); await this.dispatchManager.completeTask(taskId, agentId);
log.info({ taskId, agentId, reason }, 'task auto-completed on agent stop'); log.info({ taskId, agentId, reason }, 'task auto-completed on agent stop');
}
} catch (err) { } catch (err) {
log.warn( log.warn(
{ taskId, agentId, reason, err: err instanceof Error ? err.message : String(err) }, { taskId, agentId, reason, err: err instanceof Error ? err.message : String(err) },
'failed to auto-complete task on agent stop', 'failed to handle agent stop',
); );
} }
} }
@@ -124,6 +129,72 @@ export class ExecutionOrchestrator {
this.scheduleDispatch(); this.scheduleDispatch();
} }
/**
* Attempt to run quality review for a stopping agent.
* Returns { reviewStarted: true } if quality review was initiated (callers must NOT call completeTask).
* Returns { reviewStarted: false } if no review needed (caller should call completeTask).
*/
private async tryQualityReview(taskId: string, agentId: string, reason: string): Promise<{ reviewStarted: boolean }> {
if (!this.agentRepository || !this.agentManager) {
return { reviewStarted: false };
}
const task = await this.taskRepository.findById(taskId);
if (!task?.phaseId || !task.initiativeId) {
return { reviewStarted: false };
}
const initiative = await this.initiativeRepository.findById(task.initiativeId);
if (!initiative?.branch) {
return { reviewStarted: false };
}
const phase = await this.phaseRepository.findById(task.phaseId);
if (!phase) {
return { reviewStarted: false };
}
const taskBranch = taskBranchName(initiative.branch, taskId);
const baseBranch = phaseBranchName(initiative.branch, phase.name);
const projects = await this.projectRepository.findProjectsByInitiativeId(task.initiativeId);
if (projects.length === 0) {
return { reviewStarted: false };
}
const repoPath = await ensureProjectClone(projects[0], this.workspaceRoot);
const result = await shouldRunQualityReview({
agentId,
taskId,
stopReason: reason,
repoPath,
taskBranch,
baseBranch,
agentRepository: this.agentRepository,
taskRepository: this.taskRepository,
initiativeRepository: this.initiativeRepository,
branchManager: this.branchManager,
});
if (!result.run) {
return { reviewStarted: false };
}
await runQualityReview({
taskId,
taskBranch,
baseBranch,
initiativeId: task.initiativeId,
qualifyingFiles: result.qualifyingFiles,
taskRepository: this.taskRepository,
agentManager: this.agentManager,
log,
});
return { reviewStarted: true };
}
private async handleAgentCrashed(event: AgentCrashedEvent): Promise<void> { private async handleAgentCrashed(event: AgentCrashedEvent): Promise<void> {
const { taskId, agentId, error } = event.payload; const { taskId, agentId, error } = event.payload;
if (!taskId) return; if (!taskId) return;