# ORCH-115: Task dispatch from coordinator

## Objective

Implement orchestrator API endpoint POST /agents/spawn to receive spawn requests from coordinator, queue tasks in Valkey, and spawn agents.

## Acceptance Criteria

- [ ] Orchestrator API endpoint: POST /agents/spawn
- [ ] Coordinator calls orchestrator after quality pre-check
- [ ] Task queued in Valkey
- [ ] Agent spawned
- [ ] Return agentId to coordinator

## Approach

1. Create NestJS controller: `src/api/agents/agents.controller.ts`
2. Create DTO for spawn request validation
3. Integrate with QueueService (ORCH-108) and AgentSpawnerService (ORCH-105)
4. Write comprehensive unit tests following TDD
5. Create module and register in AppModule

## API Specification

```typescript
POST /agents/spawn
Request: {
  taskId: string,
  agentType: 'worker' | 'reviewer' | 'tester',
  context: {
    repository: string,
    branch: string,
    workItems: string[],
    skills?: string[]
  }
}
Response: {
  agentId: string,
  status: 'spawning' | 'queued'
}
```

## Progress

- [x] Write controller tests (RED)
- [x] Implement controller (GREEN)
- [x] Refactor if needed
- [x] Create module
- [x] Register in AppModule
- [x] Integration test
- [x] Add class-validator and class-transformer dependencies
- [x] All tests passing (14/14)
- [x] Test coverage 100%

## Testing Strategy

- Mock QueueService.addTask()
- Mock AgentSpawnerService.spawnAgent()
- Test success scenarios
- Test validation errors (missing fields, invalid types)
- Test service integration errors
- Ensure coverage >= 85%

## Notes

- Following existing patterns from health.controller.ts
- Using NestJS dependency injection
- DTOs will validate request payload
- Return agentId from spawner service
- Queue status reflects whether agent is spawning or queued

## Implementation Summary

### Files Created:

1. `src/api/agents/agents.controller.ts` - Main controller with POST /agents/spawn endpoint
2. `src/api/agents/agents.controller.spec.ts` - Comprehensive unit tests (14 tests, 100% coverage)
3. `src/api/agents/dto/spawn-agent.dto.ts` - Request/response DTOs with validation
4. `src/api/agents/agents.module.ts` - NestJS module

### Files Modified:

1. `src/app.module.ts` - Added AgentsModule import
2. `package.json` - Added class-validator and class-transformer dependencies

### Test Results:

- All 238 tests passing
- Controller tests: 14/14 passing
- Coverage: 100% (statements, branches, functions, lines)

### Key Features:

- Spawns agents using AgentSpawnerService
- Queues tasks using QueueService with default priority of 5
- Validates request payload (taskId, agentType, context)
- Supports all agent types: worker, reviewer, tester
- Proper error handling and propagation
- Returns agentId and status to coordinator
