# Parallel Execution Protocol — APEX

> **Loaded by:** step-01 (analysis scan) and step-03 (parallel execution)
> **Condition:** NOT economy_mode
> **Purpose:** Reusable protocol for launching parallel Agent subagents.

---

## Agent Tool Usage

APEX uses the `Agent` tool from Claude Code to parallelize work. Agents are launched in a single message to run concurrently.

```yaml
Agent:
  subagent_type: "Explore" | "Snipper"   # See assignment table below
  model: "sonnet" | "opus"               # sonnet for scan, opus for dev
  prompt: "{detailed task prompt}"
```

### Model & Agent Assignment

| 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 (Layer 2/3) | Snipper | Opus | Fast code editing (Read, Edit, Write, Glob, Grep) |

---

## Task List Coordination

### Task Creation (by agent principal, BEFORE launching subagents)

Tasks MUST be created upfront for the full layer scope:

```
FOR EACH entity in layer:
  TaskCreate(
    subject: "Layer {N}: {Entity} {layer_type}",
    description: "{detailed scope: files, skills, MCP tools}",
    activeForm: "{Building/Creating} {Entity} {layer_type}"
  )
```

### Task Assignment (via prompt)

Include task ID and context in the Agent prompt:

```
"Your assigned task ID is {task_id}.
 Call TaskUpdate(taskId: '{task_id}', status: 'in_progress') before starting.
 Call TaskUpdate(taskId: '{task_id}', status: 'completed', metadata: { files_created: [...] }) when done."
```

### Task Monitoring (by agent principal)

```
1. Agent results are returned when each subagent completes
2. Agent principal updates TaskList after each result
3. All tasks completed → proceed to build gate
```

---

## Team Decomposition

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

Launch 2-3 `Explore` agents in parallel (single message):

```
Agent(subagent_type='Explore', model='sonnet',
  prompt='Scan backend for module {module_code}: entities, EF configs, services,
   DTOs, validators, controllers in Domain/ + Infrastructure/ + Application/ + Api/')

Agent(subagent_type='Explore', model='sonnet',
  prompt='Scan frontend for module {module_code}: pages, components, hooks,
   i18n files, route definitions in src/pages/ + src/components/ + src/locales/')

Agent(subagent_type='Explore', model='sonnet',
  prompt='Read context artifacts for module {module_code}: .ralph/prd-{module_code}.json,
   docs/business/**/feature.json → extract sections, entities, rules, permissions, ACs')
```

Agent principal aggregates all results after all agents complete.

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

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

```
Layer 2 (Backend) — if multiple entities:
  # AGENT BOUNDARY: Snipper agents do NOT have access to MCP tools.
  # Services, DTOs, controllers MUST be scaffolded by the principal agent via MCP.
  # Snipper agents handle ONLY: business logic, validators, code-gen wiring.

  # PHASE A — Sequential: MCP scaffolding (principal agent)
  For each entity:
    mcp__smartstack__scaffold_extension(type: "dto", name: "{Entity}", options: { navRoute: "..." })
    mcp__smartstack__scaffold_extension(type: "controller", name: "{Entity}", options: { navRoute: "..." })
    Verify NavRoute on generated controller (bash)

  # PHASE B — Parallel: post-scaffold adjustments (Snipper agents)
  Agent(subagent_type='Snipper', model='opus',
    prompt='Adjust Layer 2 backend for {Entity1}: service logic, validators, code-gen wiring.
            DO NOT regenerate controller/DTO — already created by MCP.')
  Agent(subagent_type='Snipper', model='opus',
    prompt='Adjust Layer 2 backend for {Entity2}: service logic, validators, code-gen wiring.
            DO NOT regenerate controller/DTO — already created by MCP.')
  # Launched in parallel in a single message

  # PHASE C — Sequential: DI registration (principal agent)
  # Register all services + validators in DependencyInjection.cs (single pass, no conflicts)

Layer 3 (Frontend) — if multiple entities:
  # ⛔ AGENT BOUNDARY: Snipper agents do NOT have access to Skill().
  # Pages (.tsx) MUST be generated by the principal agent via Skill("ui-components").
  # Snipper agents handle ONLY: API clients, routes, wiring, i18n — NOT pages.

  # PHASE A — Parallel: infrastructure (Snipper agents)
  Agent(subagent_type='Snipper', model='opus',
    prompt='Execute Layer 3 INFRASTRUCTURE for {Entity1}: API client, routes, wiring, i18n.
            DO NOT generate any .tsx page files — pages are handled by the principal agent.')
  Agent(subagent_type='Snipper', model='opus',
    prompt='Execute Layer 3 INFRASTRUCTURE for {Entity2}: API client, routes, wiring, i18n.
            DO NOT generate any .tsx page files — pages are handled by the principal agent.')
  # Launched in parallel in a single message

  # PHASE B — Sequential: pages (principal agent only)
  # After all Snipper agents complete, principal generates pages via Skill("ui-components").
  # See step-03-execute.md Layer 3 HARD RULE for full protocol.
```

Each agent has an **isolated scope**: handles one entity end-to-end within the layer.
**Exception:** Layer 3 pages are NOT delegated — see step-03 HARD RULE.

---

## Coordination

### Step-01: Agent principal aggregates scan results

```
1. Launch 2-3 Explore agents in parallel
2. Each returns findings when complete
3. Agent principal merges into unified analysis
```

### Step-03: Agent principal verifies between ALL 5 layers

```
1. Layer 0: agent principal executes (domain + infra + migration)
2. Build gate: dotnet build → MUST PASS
3. Layer 1: agent principal executes (seed data — sequential, no parallel agents)
4. Build gate: dotnet build → MUST PASS
5. Layer 2 Phase A: principal scaffolds ALL entities via MCP (dto + controller per entity)
5b. Layer 2 Phase B: launch Snipper agents for post-scaffold adjustments (parallel)
5c. Layer 2 Phase C: principal registers all DI in DependencyInjection.cs (single pass)
6. Build gate: dotnet build → MUST PASS
7. Backend tests inline (scaffold + run + fix max 3)
8. Layer 3 Phase A: launch Snipper agents for infra (api-client, routes, i18n) — NOT pages
9. Layer 3 Phase B: principal agent generates ALL pages via Skill("ui-components") — sequential
10. Compliance gate: 6 frontend checks → MUST PASS
10. Frontend tests inline (scaffold + run + fix max 3)
11. Layer 4 (optional): agent principal executes DevData
```

---

## Idle Handling

Agents launched via the Agent tool return their results when complete.
There is no idle state to manage — the agent principal simply waits for results.

---

## Decision Matrix

| Condition | Action |
|-----------|--------|
| economy_mode = true | NO parallel agents, all sequential |
| Single entity (any layer) | NO parallel agents, agent principal handles all |
| Multiple entities, Layer 2 | Phase A: principal scaffolds via MCP (sequential). Phase B: Snipper for business logic (parallel). Phase C: principal DI registration (sequential) |
| Multiple entities, Layer 3 | Parallel: Snipper agents for infra (api-client, routes, i18n) — pages by principal via Skill("ui-components") |
| Layer 0, Layer 1, Layer 4 | NO parallel agents (sequential by nature) |
| Analysis phase (step-01) | Parallel: 2-3 Explore agents (backend + frontend + context) |
