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

@@ -8,17 +8,26 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ExecutionOrchestrator } from './orchestrator.js';
import { ensureProjectClone } from '../git/project-clones.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', () => ({
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 { 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 { DispatchManager, PhaseDispatchManager } from '../dispatch/types.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[] } {
const handlers = new Map<string, Function[]>();
@@ -108,6 +117,33 @@ function createMocks() {
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();
return {
@@ -119,11 +155,13 @@ function createMocks() {
phaseDispatchManager,
dispatchManager,
conflictResolutionService,
agentRepository,
agentManager,
eventBus,
};
}
function createOrchestrator(mocks: ReturnType<typeof createMocks>) {
function createOrchestrator(mocks: ReturnType<typeof createMocks>, opts: { withAgentManager?: boolean; withAgentRepository?: boolean } = {}) {
const orchestrator = new ExecutionOrchestrator(
mocks.branchManager,
mocks.phaseRepository,
@@ -135,6 +173,8 @@ function createOrchestrator(mocks: ReturnType<typeof createMocks>) {
mocks.conflictResolutionService,
mocks.eventBus,
'/tmp/test-workspace',
opts.withAgentRepository !== false ? mocks.agentRepository : undefined,
opts.withAgentManager !== false ? mocks.agentManager : undefined,
);
orchestrator.start();
return orchestrator;
@@ -369,4 +409,89 @@ describe('ExecutionOrchestrator', () => {
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();
});
});
});