# Agent Teams Protocol — APEX

> **Loaded by:** step-01 (analysis scan) and step-03 (parallel execution)
> **Condition:** NOT economy_mode
> **Purpose:** Reusable protocol for TeamCreate, coordination, and shutdown.

---

## Team Creation (T08)

```yaml
TeamCreate:
  team_name: "apex-{phase}"          # e.g., "apex-analyze", "apex-layer2", "apex-layer3"
  description: "{phase purpose}"      # e.g., "Scan SmartStack project for existing code"
```

Always provide both `team_name` and `description`.

---

## Teammate Spawning (T12)

```yaml
Task:
  subagent_type: "Explore" | "general-purpose"  # See assignment table below
  team_name: "apex-{phase}"          # Must match TeamCreate
  name: "{teammate-name}"            # e.g., "scan-backend", "entity-employee"
  model: "sonnet" | "opus"           # sonnet for scan, opus for dev (T02/T06)
  mode: "bypassPermissions"
  prompt: "{detailed task prompt}"
```

### Model & Agent Assignment (T02/T03/T06)

| Task Type | subagent_type | Model | Justification |
|-----------|---------------|-------|---------------|
| Scan/read files | Explore | Sonnet | Read-only (Glob, Grep, Read) |
| Read context (PRD, feature.json) | Explore | Sonnet | Read-only extraction |
| Code development | general-purpose | Opus | Full tools via skills/MCP |
| Fix/resolve | general-purpose | Opus | Requires reasoning + editing |

---

## Task List Coordination (T10)

Team lead manages the task list:

```
1. TaskCreate: create task for each work item, assign owner
2. Teammate: TaskUpdate(status: "in_progress") before starting
3. Teammate: TaskUpdate(status: "completed") after finishing
4. Lead: TaskList to monitor progress
```

---

## Communication (T09)

**Default:** Direct messages (DM) between specific agents.

```yaml
SendMessage:
  type: "message"                    # DM, not broadcast
  recipient: "{teammate-name}"       # By name, not UUID
  content: "{message}"
  summary: "{5-10 word preview}"
```

**Broadcast:** ONLY for emergency (all-stop, critical blocker).

```yaml
SendMessage:
  type: "broadcast"                  # Expensive: N teammates = N deliveries
  content: "{urgent message}"
  summary: "{critical issue summary}"
```

---

## Team Decomposition (C01)

### Step-01 Analyze: Split by scan scope

```
scan-backend  : Domain/ + Infrastructure/ + Application/ + Api/
scan-frontend : src/pages/ + src/components/ + src/locales/
scan-context  : .ralph/ + docs/business/
```

### Step-03 Execute: Split by entity WITHIN a layer

> **Cross-layer parallelism is FORBIDDEN.** Layers execute sequentially: 0 → 1 → 2 → 3 → 4.
> Agent teams parallelize **multi-entity work within a single layer.**

```
Layer 2 (Backend) — if multiple entities:
  entity-{name1} : Service + DTO + Controller for Entity1
  entity-{name2} : Service + DTO + Controller for Entity2
  ...

Layer 3 (Frontend) — if multiple entities:
  entity-{name1} : Pages + i18n + routes for Entity1
  entity-{name2} : Pages + i18n + routes for Entity2
  ...
```

Each teammate has an **isolated scope** (C02): handles one entity end-to-end within the layer.

---

## Coordination (C03)

### Step-01: Lead aggregates scan results

```
1. Spawn 3 scan teammates
2. Each reports findings via DM to lead
3. Lead merges into unified analysis
```

### Step-03: Lead verifies between ALL 5 layers

```
1. Layer 0: lead executes (domain + infra + migration)
2. Build gate: dotnet build → MUST PASS
3. Layer 1: lead executes (seed data — sequential, no teams)
4. Build gate: dotnet build → MUST PASS
5. Layer 2: spawn entity teammates (if multi-entity) OR lead executes (if single entity)
6. Build gate: dotnet build → MUST PASS
7. Backend tests inline (scaffold + run + fix max 3)
8. Layer 3: spawn entity teammates (if multi-entity) OR lead executes (if single entity)
9. Compliance gate: 5 frontend checks → MUST PASS
10. Frontend tests inline (scaffold + run + fix max 3)
11. Layer 4 (optional): lead executes DevData
```

---

## Idle Handling (T13)

Teammates go idle after every turn — this is **normal**.
- Idle does NOT mean done or unavailable
- Sending a message to an idle teammate wakes them up
- Do NOT treat idle as an error

---

## Graceful Shutdown (T11)

After phase completes:

```yaml
# For each teammate:
SendMessage:
  type: "shutdown_request"
  recipient: "{teammate-name}"
  content: "Phase complete, shutting down"

# Teammate responds:
SendMessage:
  type: "shutdown_response"
  request_id: "{from_request}"
  approve: true

# After all confirmations:
TeamDelete
```

---

## Decision Matrix

| Condition | Action |
|-----------|--------|
| economy_mode = true | NO teams, all sequential |
| Single entity (any layer) | NO teams, agent principal handles all |
| Multiple entities, Layer 2 | Teams: one teammate per entity (service + controller) |
| Multiple entities, Layer 3 | Teams: one teammate per entity (pages + i18n) |
| Layer 0, Layer 1, Layer 4 | NO teams (sequential by nature) |
| Analysis phase (step-01) | Teams: scan-backend + scan-frontend + scan-context |
