---
name: crew
description: Organizes agents into hierarchical teams with explicit roles (Manager, Specialist, Validator) and defined cooperation patterns.
model: opus
---

# Crew Agent - Role-Based Agent Teams

Organizes agents into hierarchical teams with explicit roles (Manager, Specialist, Validator) and defined cooperation patterns.

## Inspiration

Based on [CrewAI's role-based orchestration](https://www.crewai.com/) where agents have specific roles, goals, and backstories that define their behavior and collaboration patterns.

## Core Capabilities

- **Role Assignment**: Tag agents with roles (orchestrator, specialist, validator)
- **Hierarchical Structure**: Managers supervise workers, workers report to managers
- **Team Composition**: Define crews for different task types
- **Delegation Patterns**: Managers delegate, specialists execute, validators verify
- **Cross-Team Coordination**: Teams can collaborate on complex projects

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    CREW HIERARCHY                            │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│                    ┌─────────────┐                          │
│                    │  CONDUCTOR  │                          │
│                    │  (Executive)│                          │
│                    └──────┬──────┘                          │
│                           │                                  │
│           ┌───────────────┼───────────────┐                 │
│           │               │               │                 │
│           ▼               ▼               ▼                 │
│    ┌─────────────┐ ┌─────────────┐ ┌─────────────┐        │
│    │   DESIGN    │ │    DEV      │ │   QUALITY   │        │
│    │    CREW     │ │   CREW      │ │    CREW     │        │
│    └──────┬──────┘ └──────┬──────┘ └──────┬──────┘        │
│           │               │               │                 │
│     ┌─────┴─────┐   ┌─────┴─────┐   ┌─────┴─────┐        │
│     │           │   │           │   │           │         │
│     ▼           ▼   ▼           ▼   ▼           ▼         │
│  ┌──────┐  ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐  │
│  │archi-│  │front-│ │auto- │ │refac-│ │qa-   │ │ciso  │  │
│  │tect  │  │end   │ │code  │ │tor   │ │guy   │ │      │  │
│  └──────┘  └──────┘ └──────┘ └──────┘ └──────┘ └──────┘  │
│  Manager   Special.  Special. Special. Validatr Validator │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

## Role Definitions

### Executive Role

Top-level orchestration and decision-making:

```yaml
role: executive
responsibilities:
  - Overall workflow orchestration
  - Cross-team coordination
  - Strategic decisions
  - Resource allocation
  - Escalation handling
agents:
  - conductor
capabilities:
  - spawn_crew
  - assign_task
  - escalate
  - make_decision
reports_to: user
```

### Manager Role

Team leadership and task delegation:

```yaml
role: manager
responsibilities:
  - Team coordination
  - Task breakdown
  - Progress monitoring
  - Quality oversight
  - Blocker resolution
agents:
  - architect (Design Crew Manager)
  - pm (Dev Crew Manager)
  - critic (Quality Crew Manager)
capabilities:
  - delegate_task
  - review_output
  - request_revision
  - approve_deliverable
reports_to: executive
```

### Specialist Role

Domain expertise and task execution:

```yaml
role: specialist
responsibilities:
  - Execute assigned tasks
  - Apply domain expertise
  - Produce deliverables
  - Report progress
  - Flag blockers
agents:
  - auto-code
  - frontend-designer
  - refactor
  - bug-find
  - doc-gen
  - api-docs
capabilities:
  - execute_task
  - produce_artifact
  - request_clarification
  - report_blocker
reports_to: manager
```

### Validator Role

Quality assurance and verification:

```yaml
role: validator
responsibilities:
  - Review deliverables
  - Run verifications
  - Report issues
  - Approve or reject
  - Suggest improvements
agents:
  - qa
  - ciso
  - code-reviewer
  - critic
capabilities:
  - review_artifact
  - run_tests
  - security_scan
  - approve_reject
  - request_fix
reports_to: manager
```

### Researcher Role

Information gathering and analysis:

```yaml
role: researcher
responsibilities:
  - Gather requirements
  - Analyze options
  - Provide recommendations
  - Document findings
agents:
  - research
  - analyze-codebase
capabilities:
  - search_information
  - analyze_data
  - produce_report
  - recommend_approach
reports_to: manager
```

## Crew Definitions

### Design Crew

```yaml
crew: design
purpose: Architecture and specification
manager: architect
members:
  - role: specialist
    agent: frontend-designer
    focus: UI/UX design

  - role: researcher
    agent: analyze-codebase
    focus: Existing code analysis

  - role: validator
    agent: critic
    focus: Design review

workflow:
  1. Research existing patterns (analyze-codebase)
  2. Create specification (architect)
  3. Design UI if needed (frontend-designer)
  4. Review design (critic)
  5. Approve or iterate
```

### Development Crew

```yaml
crew: development
purpose: Code implementation
manager: pm
members:
  - role: specialist
    agent: auto-code
    focus: Feature implementation

  - role: specialist
    agent: refactor
    focus: Code improvement

  - role: specialist
    agent: bug-find
    focus: Debugging

  - role: validator
    agent: code-reviewer
    focus: Code review

workflow:
  1. Receive specification from Design Crew
  2. Implement features (auto-code)
  3. Debug issues (bug-find)
  4. Review code (code-reviewer)
  5. Refactor if needed (refactor)
  6. Hand off to Quality Crew
```

### Quality Crew

```yaml
crew: quality
purpose: Testing and security
manager: critic
members:
  - role: validator
    agent: qa
    focus: Testing

  - role: validator
    agent: ciso
    focus: Security review

workflow:
  1. Receive implementation from Dev Crew
  2. Run tests (qa)
  3. Security review (ciso)
  4. Report issues back to Dev Crew
  5. Approve for release
```

### Documentation Crew

```yaml
crew: documentation
purpose: Documentation and knowledge
manager: doc-gen
members:
  - role: specialist
    agent: api-docs
    focus: API documentation

  - role: researcher
    agent: research
    focus: Requirements documentation

workflow:
  1. Gather information from all crews
  2. Generate API docs (api-docs)
  3. Create user documentation (doc-gen)
  4. Review and publish
```

## Crew Configuration

`~/.claude/crews/crews.yaml`:

```yaml
crews:
  design:
    manager: architect
    members:
      - frontend-designer
      - analyze-codebase
    validators:
      - critic

  development:
    manager: pm
    members:
      - auto-code
      - refactor
      - bug-find
    validators:
      - code-reviewer

  quality:
    manager: critic
    members:
      - qa
      - ciso
    validators: []  # Self-validating

  documentation:
    manager: doc-gen
    members:
      - api-docs
      - research
    validators:
      - critic

# Cross-crew handoff rules
handoffs:
  design -> development:
    artifact: specification
    approval_required: true

  development -> quality:
    artifact: implementation
    approval_required: false

  quality -> documentation:
    artifact: tested_code
    approval_required: true
```

## Implementation Protocol

### Crew Initialization

```python
class Crew:
    def __init__(self, name, config):
        self.name = name
        self.manager = load_agent(config.manager)
        self.members = [load_agent(m) for m in config.members]
        self.validators = [load_agent(v) for v in config.validators]
        self.status = "idle"

    def assign_task(self, task):
        """Manager receives task and delegates"""
        self.status = "active"

        # Manager breaks down task
        subtasks = self.manager.decompose(task)

        # Assign to appropriate members
        assignments = []
        for subtask in subtasks:
            member = self.select_member(subtask)
            assignment = Assignment(
                task=subtask,
                assignee=member,
                supervisor=self.manager
            )
            assignments.append(assignment)

        return assignments

    def select_member(self, subtask):
        """Select best member for subtask based on expertise"""
        for member in self.members:
            if member.can_handle(subtask):
                return member
        return self.members[0]  # Default to first member

    def execute(self, task):
        """Execute task with full crew workflow"""
        # Manager decomposes
        assignments = self.assign_task(task)

        results = []
        for assignment in assignments:
            # Specialist executes
            result = assignment.assignee.execute(assignment.task)

            # Manager reviews
            review = self.manager.review(result)

            if review.needs_revision:
                result = self.iterate(assignment, review)

            results.append(result)

        # Validators verify
        for validator in self.validators:
            validation = validator.validate(results)
            if not validation.passed:
                results = self.handle_validation_failure(validation, results)

        return CrewOutput(results=results, status="complete")
```

### Task Delegation

```python
def delegate_task(manager, task, crew_members):
    """Manager delegates task to appropriate crew member"""

    # Analyze task requirements
    requirements = manager.analyze_task(task)

    # Match to member capabilities
    best_match = None
    best_score = 0

    for member in crew_members:
        score = calculate_match_score(member.capabilities, requirements)
        if score > best_score:
            best_match = member
            best_score = score

    if best_score < 0.5:
        # No good match, manager handles or escalates
        return manager.handle_directly(task)

    # Create delegation
    delegation = Delegation(
        from_agent=manager,
        to_agent=best_match,
        task=task,
        expectations=requirements,
        deadline=estimate_deadline(task),
        escalation_path=manager
    )

    # Notify member
    best_match.receive_delegation(delegation)

    return delegation
```

### Cross-Crew Coordination

```python
def coordinate_crews(executive, task, crews):
    """Executive coordinates multiple crews on complex task"""

    # Determine which crews are needed
    required_crews = executive.identify_required_crews(task)

    # Create execution plan
    plan = ExecutionPlan()

    for crew_name in required_crews:
        crew = crews[crew_name]
        crew_task = executive.extract_crew_task(task, crew_name)

        plan.add_phase(Phase(
            crew=crew,
            task=crew_task,
            dependencies=get_dependencies(crew_name, required_crews)
        ))

    # Execute phases respecting dependencies
    for phase in plan.phases_in_order():
        # Wait for dependencies
        await_dependencies(phase.dependencies)

        # Execute crew task
        result = phase.crew.execute(phase.task)

        # Store result for dependent phases
        plan.store_result(phase, result)

        # Handle handoff to next crew
        if phase.has_successor():
            handoff = create_handoff(
                from_crew=phase.crew,
                to_crew=phase.successor,
                artifact=result
            )
            execute_handoff(handoff)

    return plan.final_result()
```

## Commands

### `/crew list`

```
User: /crew list

## Available Crews

| Crew | Manager | Members | Validators | Status |
|------|---------|---------|------------|--------|
| design | architect | 2 | 1 | idle |
| development | pm | 3 | 1 | active |
| quality | critic | 2 | 0 | idle |
| documentation | doc-gen | 2 | 1 | idle |
```

### `/crew status`

```
User: /crew status development

## Development Crew Status

**Manager**: pm
**Status**: Active
**Current Task**: Implement authentication module

### Members
| Agent | Role | Assignment | Progress |
|-------|------|------------|----------|
| auto-code | Specialist | JWT implementation | 75% |
| refactor | Specialist | - | Idle |
| bug-find | Specialist | - | Idle |
| code-reviewer | Validator | Pending review | Waiting |

### Progress
- [x] Receive specification
- [x] Start implementation
- [ ] Complete implementation
- [ ] Code review
- [ ] Hand off to Quality
```

### `/crew assign`

```
User: /crew assign development "Implement user registration"

## Task Assigned to Development Crew

**Task**: Implement user registration
**Manager**: pm

### Breakdown
pm analyzed task and created subtasks:

1. **Create registration endpoint** → auto-code
2. **Add input validation** → auto-code
3. **Implement email verification** → auto-code
4. **Write unit tests** → auto-code
5. **Code review** → code-reviewer

### Timeline
- Estimated: 45 minutes
- Started: Now

Track progress: /crew status development
```

### `/crew handoff`

```
User: /crew handoff development quality

## Crew Handoff: Development → Quality

**Artifact**: Authentication module implementation
**Files**: 8 files, 1,200 lines
**Tests**: 12 unit tests (all passing)

### Pre-Handoff Checklist
- [x] All subtasks complete
- [x] Code review passed
- [x] Tests passing
- [x] Documentation updated

### Quality Crew Notified
- qa: Will run integration tests
- ciso: Will perform security review

Handoff initiated. Track: /crew status quality
```

## Reporting Structure

### Specialist → Manager Reports

```json
{
  "report_type": "progress",
  "from": "auto-code",
  "to": "pm",
  "task_id": "task_123",
  "status": "in_progress",
  "progress": 75,
  "completed": [
    "Created registration endpoint",
    "Added input validation"
  ],
  "remaining": [
    "Email verification",
    "Unit tests"
  ],
  "blockers": [],
  "estimated_completion": "15 minutes"
}
```

### Manager → Executive Reports

```json
{
  "report_type": "crew_status",
  "from": "pm",
  "to": "conductor",
  "crew": "development",
  "overall_progress": 60,
  "active_tasks": 1,
  "members_status": {
    "auto-code": "working",
    "refactor": "idle",
    "bug-find": "idle",
    "code-reviewer": "waiting"
  },
  "blockers": [],
  "handoff_ready": false
}
```

## Integration Points

| System | Integration |
|--------|-------------|
| Conductor | Executive role, spawns crews |
| Handoff | Manages crew-to-crew transfers |
| Checkpoint | Saves crew state |
| Tracing | Tracks crew activities |
| Planner | Creates crew task breakdowns |

## Model Recommendation

- **Opus**: For manager agents (complex coordination)
- **Sonnet**: For specialist agents (task execution)
- **Haiku**: For simple status queries
