# Agent Teams Workflow - Claude Code Integration

> **Scope:** universal
> **Layer:** 0 (always load)
> **Keywords:** agent, team, orchestration, claude code, parallel
> **Load When:** always

**Status:** EXPERIMENTAL - Enable via `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`

Orchestrate multiple Claude Code instances as a coordinated team for parallel development workflows

---

## Overview

**Agent Teams** are a Claude Code feature that coordinates multiple independent Claude instances working together on complex tasks. Unlike subagents (which run within a single context and only report back), Agent Teams members can communicate directly with each other, share findings, challenge each other's approaches, and coordinate through a shared task list.

### Core Architecture

| Component | Role |
|-----------|------|
| **Team Lead** | Main Claude session that creates the team, spawns teammates, coordinates work |
| **Teammates** | Independent Claude Code instances, each with own context window |
| **Shared Task List** | Coordinated work items with dependencies and state (pending/in-progress/completed) |
| **Mailbox** | Direct messaging system between agents |

**Storage:**
- Team config: `~/.claude/teams/{team-name}/config.json`
- Task list: `~/.claude/tasks/{team-name}/`

---

## Agent Teams vs Subagents

| Aspect | Subagents | Agent Teams |
|--------|-----------|-------------|
| **Context** | Own context, results return to caller | Fully independent contexts |
| **Communication** | Report back to main agent only | Direct inter-teammate messaging + broadcast |
| **Coordination** | Main agent manages all work | Shared task list with self-claiming |
| **Best for** | Focused research, verification, isolated tasks | Complex work requiring discussion & collaboration |
| **Token cost** | Lower (results summarized) | Higher (each teammate = separate Claude instance) |
| **Use in MORPH** | Quick analysis, validation, isolated research | Parallel feature implementation, multi-module refactoring |

---

## When to Use Agent Teams in MORPH-SPEC

### ✅ **Strong Use Cases**

1. **Parallel Feature Implementation (FASE 5)**
   - Multiple independent features in the same release
   - Each teammate owns 1-2 modules (e.g., Auth, Payments, Reporting)
   - No file conflicts (each module has distinct files)

2. **Architecture Review & Debugging**
   - Multiple teammates investigate competing hypotheses
   - Each applies different lens (security, performance, maintainability)
   - Teams debate and converge on best solution

3. **Cross-Stack Coordination**
   - Frontend teammate (Blazor/Next.js)
   - Backend teammate (API + EF Core)
   - Infrastructure teammate (Bicep + Azure)
   - Testing teammate (unit + integration)

4. **Research & Standards Validation (FASE 0-2)**
   - Investigate multiple integration options (Clerk vs Azure AD vs custom)
   - Compare UI libraries (Fluent UI vs MudBlazor vs Radzen)
   - Validate architecture patterns (CQRS vs simple Repository)

### ❌ **Not Recommended**

- Single-file edits or small bug fixes
- Sequential tasks with many dependencies
- Same-file modifications by multiple teammates (causes conflicts)
- Routine tasks where coordination overhead > benefit

---

## Setup & Configuration

### 1. Enable Agent Teams

Add to `.claude/settings.local.json` (or env variable):

```json
{
  "env": {
    "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  },
  "teammateMode": "auto"  // or "in-process" / "tmux"
}
```

**Display Modes:**
- `"auto"`: Split panes if in tmux, otherwise in-process
- `"in-process"`: All teammates in main terminal (Shift+Up/Down to switch)
- `"tmux"`: Each teammate in separate pane (requires tmux or iTerm2)

### 2. Start a Team

**Natural Language Request:**
```
Create an agent team to implement the scheduled-reports feature.
Spawn 3 teammates:
- Backend engineer: EF Core models + Hangfire jobs (uses ef-modeler, hangfire-orchestrator skills)
- Frontend engineer: Blazor dashboard + report viewer (uses blazor-builder, ui-ux-designer skills)
- Testing specialist: Unit + integration tests (uses testing-specialist skill)

Require plan approval for each teammate before implementation.
```

**What Claude Does:**
1. Creates team config in `~/.claude/teams/scheduled-reports/`
2. Spawns 3 independent Claude instances
3. Each teammate loads project context (CLAUDE.md, MCP servers, skills)
4. Lead assigns initial tasks from shared task list
5. Teammates work in plan mode until lead approves
6. After approval, teammates implement independently

### 3. Control the Team

**Delegate Mode** (Lead focuses on coordination only):
```
Press Shift+Tab to cycle into delegate mode
```
- Lead can't use code tools (Edit/Write/Bash)
- Only coordination tools: spawn, message, task management

**Direct Teammate Communication:**
- In-process mode: Shift+Up/Down to select, type to message
- Split-pane mode: Click teammate pane to interact directly

**Task Management:**
```
# Lead assigns task
Assign task T003 (implement report scheduler) to the backend engineer

# Teammate self-claims next available task
After completing T001, backend engineer claims T004 (add report repository)
```

**Shutdown:**
```
Ask the backend teammate to shut down gracefully
```

---

## MORPH-SPEC Integration Patterns

### Pattern 1: Parallel Feature Implementation (FASE 5)

**Scenario:** Multi-module feature with independent components

```bash
# 1. Complete FASES 0-4 normally (proposal → design → tasks)
morph-spec state set scheduled-reports phase implement

# 2. Claude creates agent team based on tasks.json structure
# Example tasks.json with module grouping:
{
  "tasks": [
    { "id": "T001", "module": "backend", "title": "Create ReportDefinition entity" },
    { "id": "T002", "module": "backend", "title": "Implement Hangfire scheduler" },
    { "id": "T003", "module": "frontend", "title": "Create report dashboard UI" },
    { "id": "T004", "module": "frontend", "title": "Add report preview component" },
    { "id": "T005", "module": "infra", "title": "Provision Blob Storage for reports" },
    { "id": "T006", "module": "tests", "title": "Unit tests for scheduler", "dependsOn": ["T002"] }
  ]
}
```

**Team Structure:**
- **Lead:** Standards Architect (coordinates, validates contracts, syncs decisions.md)
- **Backend Teammate:** .NET Senior + Hangfire Orchestrator + EF Modeler
- **Frontend Teammate:** Blazor Builder + UI/UX Designer
- **Infra Teammate:** Azure Architect + Bicep Architect
- **Testing Teammate:** Testing Specialist

**Workflow:**
1. Lead assigns tasks by module
2. Each teammate implements their tasks independently
3. Teammates run `morph-spec task done {feature} {task-id}` after each task
4. Validation pipeline runs automatically (contract compliance, decisions constraints)
5. Lead synthesizes recap.md after all tasks complete

### Pattern 2: Architecture Decision Debate (FASE 2)

**Scenario:** Multiple valid approaches for complex problem

```
Create an agent team to decide on the authentication architecture.
Spawn 3 debate teammates:
- Pro-Clerk: Argue for Clerk.com (ease of use, modern UI, MFA built-in)
- Pro-Azure AD: Argue for Azure AD B2C (enterprise compliance, existing infra)
- Pro-Custom: Argue for custom JWT + Passkeys (full control, no vendor lock-in)

Have them debate, challenge each other's assumptions, and document pros/cons.
Update decisions.md with consensus.
```

**Output:** Structured ADR in `decisions.md` with all perspectives considered

### Pattern 3: Code Review by Concern (Post-FASE 5)

**Scenario:** Thorough review before production deployment

```
Create an agent team to review the scheduled-reports implementation.
Spawn 4 reviewers:
- Security reviewer: Auth, SQL injection, XSS, secrets management
- Performance reviewer: Query efficiency, caching, background job overhead
- Standards reviewer: Blazor patterns, EF Core best practices, contract compliance
- UX reviewer: Accessibility, responsive design, error handling

Each reviewer reports findings to the lead, then synthesize into review.md
```

---

## Best Practices for MORPH-SPEC

### 1. Size Tasks Appropriately

**Good task granularity (5-6 tasks per teammate):**
```json
{
  "id": "T003",
  "title": "Implement report scheduling service",
  "module": "backend",
  "files": ["Services/ReportScheduler.cs", "Jobs/GenerateReportJob.cs"],
  "estimatedHours": 2
}
```

**Too small (coordination overhead > benefit):**
```json
{ "id": "T001", "title": "Add using statement" }
```

**Too large (teammate works too long without check-ins):**
```json
{ "id": "T099", "title": "Implement entire authentication system" }
```

### 2. Prevent File Conflicts

**Design task ownership to avoid overlapping edits:**

❌ **Bad (conflict risk):**
- Backend teammate modifies `Program.cs` for DI
- Frontend teammate modifies `Program.cs` for middleware

✅ **Good (isolated ownership):**
- Backend teammate: `Services/`, `Data/`, `Jobs/`
- Frontend teammate: `Pages/`, `Components/`, `wwwroot/`
- Lead handles shared files (`Program.cs`, `appsettings.json`) after review

### 3. Leverage Shared Context

**All teammates automatically load:**
- `CLAUDE.md` (MORPH-SPEC instructions)
- `.claude/skills/` (all available skills)
- `.morph/config.json` (project configuration)
- `framework/standards/` + `.morph/standards/`

**Pass task-specific context in spawn prompt:**
```
Spawn backend teammate with prompt: "Implement scheduled reports feature.
Active agents: ef-modeler, hangfire-orchestrator, dotnet-senior.
Read .morph/project/outputs/scheduled-reports/spec.md and contracts.cs.
Follow Blazor concurrency patterns from framework/standards/blazor-state.md.
All background jobs MUST use IDbContextFactory (scoped repository pattern)."
```

### 4. Use Hooks for Quality Gates

**Enforce validation before task completion:**

```json
// .claude/hooks.json
{
  "TaskCompleted": {
    "command": "morph-spec validate-task ${MORPH_FEATURE} ${TASK_ID}",
    "exitCode2Feedback": "Task validation failed. Fix violations before marking complete."
  },
  "TeammateIdle": {
    "command": "morph-spec check-teammate-progress ${TEAMMATE_ID}",
    "exitCode2Feedback": "Teammate has incomplete work. Continue implementation."
  }
}
```

### 5. Monitor Token Usage

**Agent Teams = High Token Cost:**
- Each teammate = separate Claude instance with full context
- 4 teammates on a 2-hour task ≈ 4x token usage vs single session

**When worth it:**
- Parallel implementation of 3+ independent modules
- Complex architecture decisions requiring debate
- Time-sensitive features where parallel work reduces calendar time

**When NOT worth it:**
- Single-module features
- Sequential refactoring
- Simple bug fixes

---

## Troubleshooting

### Issue: Lead Implements Instead of Delegating

**Symptom:** Lead starts coding tasks instead of waiting for teammates

**Solution:**
```
Wait for your teammates to complete their tasks before proceeding.
Use delegate mode to restrict yourself to coordination only.
```
Then press `Shift+Tab` to cycle into delegate mode.

### Issue: Task Not Marked Complete

**Symptom:** Teammate finished work but task still shows "in_progress"

**Solution:**
```
# Check if validation passed
morph-spec state get {feature}

# If validation failed, teammate must fix violations
Tell the frontend teammate to check validation output and fix contract violations

# If validation passed but task stuck, manually mark complete
morph-spec task done {feature} {task-id}
```

### Issue: Orphaned tmux Sessions

**Symptom:** `tmux ls` shows team sessions after cleanup

**Solution:**
```bash
tmux kill-session -t scheduled-reports-team
rm -rf ~/.claude/teams/scheduled-reports
```

### Issue: Permission Prompts Spam

**Symptom:** Too many permission requests for teammates

**Solution:** Pre-approve common operations in `settings.local.json`:
```json
{
  "dangerouslySkipPermissions": {
    "allowedPaths": [".morph/project/outputs/**"],
    "allowedCommands": ["morph-spec task done", "morph-spec validate-*"]
  }
}
```

---

## Integration with MORPH Workflows

### Full MORPH (9 phases) + Agent Teams

| Phase | Team Usage |
|-------|------------|
| **0 PROPOSAL** | Single session (detect-agents) |
| **1 SETUP** | Single session |
| **1.5 UI/UX** | Optional: Spawn UI/UX designer teammate for mockup generation |
| **2 DESIGN** | Optional: Spawn debate team for DECISION POINTS |
| **3 CLARIFY** | Single session |
| **4 TASKS** | Single session (generate tasks.json) |
| **5 IMPLEMENT** | **Primary use case:** Spawn implementation team by module |
| **6 SYNC** | Single session (lead synthesizes decisions.md → standards/) |

### Fast Track + Agent Teams

**Not recommended:** Coordination overhead defeats purpose of fast workflow.

**Exception:** If fast-track task expands during implementation:
```
morph-spec state set {feature} workflow full-morph
# Then create agent team for expanded scope
```

---

## Limitations (as of 2026-02-12)

- **No session resumption:** `/resume` doesn't restore in-process teammates
- **Task status can lag:** Manual nudge may be needed
- **One team per session:** Clean up before starting new team
- **No nested teams:** Teammates can't spawn their own teams
- **Split panes require tmux/iTerm2:** Not available in VS Code terminal, Windows Terminal, Ghostty

---

## Example: Full MORPH Workflow with Agent Team

```bash
# FASES 0-4: Single Claude session
/morph-proposal scheduled-reports
# ... proposal approved, design approved, tasks generated ...

# FASE 5: Create agent team
morph-spec state set scheduled-reports phase implement
```

```
Create an agent team to implement scheduled-reports.

Team structure based on tasks.json modules:
- Backend teammate (T001-T005): EF models, Hangfire jobs, repositories
- Frontend teammate (T006-T010): Blazor pages, components, CSS
- Infra teammate (T011-T012): Bicep modules for Blob Storage + Service Bus

Require plan approval for each teammate.
Use delegate mode so I only coordinate.
```

**Claude creates team, spawns 3 teammates, each works independently:**

```bash
# Backend teammate
morph-spec task start scheduled-reports T001
# ... implements ReportDefinition.cs ...
morph-spec task done scheduled-reports T001
# Validation runs: contract-compliance, blazor-concurrency (IDbContextFactory check)
# ✅ Task T001 completed

# Frontend teammate (parallel)
morph-spec task start scheduled-reports T006
# ... implements ReportDashboard.razor ...
morph-spec task done scheduled-reports T006
# Validation runs: blazor-validator, css-validator, contrast-checker
# ✅ Task T006 completed
```

**After all tasks complete, lead synthesizes:**
```bash
morph-spec generate recap scheduled-reports
# Pulls data from state.json, validation results, contracts.cs
# Generates comprehensive recap.md

morph-spec phase advance scheduled-reports
# Validates FASE 5 → advances to FASE 6 → shows next steps
```

---

## Summary

**Agent Teams enable MORPH-SPEC to:**
- Implement multi-module features in parallel (reduces calendar time)
- Debate architecture decisions with multiple perspectives
- Conduct thorough reviews across security/performance/standards

**Use when:**
- 3+ independent modules/components
- Complex architecture decisions
- Cross-stack coordination (backend + frontend + infra)

**Avoid when:**
- Single-module features
- Sequential workflows
- Same-file modifications needed

**Key insight:** Agent Teams amplify MORPH-SPEC's strengths (structured workflows, spec-driven development, validation pipeline) by parallelizing implementation while maintaining quality gates and coordination.

---

*MORPH-SPEC by Polymorphism Tech - Integrated with Claude Code Agent Teams*
