# Team Orchestration — Multi-Module Parallel Execution

> **Loaded by:** step-00 when multi-module detected (PRD_COUNT > 1)
> **Purpose:** Parallelize independent modules via Agent Teams.
> **Rule:** Single module = NO team. Only create team for 2+ modules.

---

## 1. Layer Detection

Read dependency graph from master feature.json:

```javascript
const master = readJSON(MASTER_FEATURE);
const layers = master.metadata?.workflow?.dependencyGraph?.layers
            || master.dependencyGraph?.layers;

// Example layers:
// [
//   { layer: 0, modules: ["employees"], reason: "foundation" },
//   { layer: 1, modules: ["timetracking", "leavemanagement"], reason: "depends on employees" },
//   { layer: 2, modules: ["reporting"], reason: "depends on all" }
// ]

// Fallback: if no layers, treat all modules as sequential (layer 0, 1, 2...)
if (!layers) {
  const modules = queue.modules.map((m, i) => ({
    layer: i, modules: [m.code], reason: "sequential"
  }));
}
```

---

## 2. Team Setup

```javascript
// Create team
TeamCreate({ team_name: `ralph-${appName}` });

// Store team context
const teamContext = {
  teamName: `ralph-${appName}`,
  layers: layers,
  currentLayer: 0,
  teammates: {}  // name → agentId mapping (populated after spawn)
};
```

---

## 3. Teammate Spawn — Per Layer

For each layer, spawn teammates IN PARALLEL (single message, multiple Task calls):

```javascript
for (const layer of layers) {
  // Wait for previous layer to complete (except layer 0)
  if (layer.layer > 0) {
    // WAIT: check for MODULE_COMPLETE messages from all previous layer teammates
    // Messages are automatically delivered via SendMessage
  }

  // Spawn all modules in this layer in parallel
  for (const moduleCode of layer.modules) {
    const prdFile = `.ralph/prd-${moduleCode}.json`;
    const prdContent = readJSON(prdFile);

    Task({
      subagent_type: "general-purpose",
      team_name: `ralph-${appName}`,
      name: `mod-${moduleCode}`,
      mode: "bypassPermissions",
      prompt: TEAMMATE_PROMPT(moduleCode, prdContent),
      description: `Module ${moduleCode}`
    });
  }
}
```

---

## 4. Teammate Prompt Template

Each teammate receives a self-contained prompt that delegates to `/apex`:

```
You are a Ralph Loop module worker for module "${moduleCode}".

## Your Mission
Execute ALL tasks in the PRD by delegating to /apex.
You are an ORCHESTRATOR — you NEVER generate code directly.

## PRD File
${prdFile}

## Execution
1. INVOKE `/apex -d ${prdFile}`
   → Apex handles all layers: domain → infrastructure → migration → seed data → application → api → frontend → tests
   → Apex runs POST-CHECKs, MCP validation, build verification, and commits per layer
   → Apex updates task statuses in the PRD file directly
2. After apex returns, re-read ${prdFile} to check task statuses
3. If tasks remain pending/failed, re-invoke `/apex -d ${prdFile}`

## Communication Protocol
- After apex completes and build passes:
  SendMessage({ type: "message", recipient: "team-lead", content: "LAYER_READY:${moduleCode}", summary: "${moduleCode} foundation ready" })
- When ALL tasks complete:
  SendMessage({ type: "message", recipient: "team-lead", content: "MODULE_COMPLETE:${moduleCode}", summary: "${moduleCode} complete" })
- On blocking error:
  SendMessage({ type: "message", recipient: "team-lead", content: "ERROR:${moduleCode}:{error}", summary: "${moduleCode} blocked" })

## Project Context
- Project path: ${projectPath}
- Branch: ${branch}
- Application: ${appName}
- Context: ${contextCode}
```

---

## 5. Team Lead Wait Logic

After spawning a layer, the team lead waits for completion:

```javascript
// Track expected messages
const expectedMessages = layer.modules.length;
let receivedComplete = 0;
let receivedReady = 0;
let errors = [];

// Messages arrive automatically via SendMessage
// When a teammate sends "MODULE_COMPLETE:xxx", increment counter
// When a teammate sends "ERROR:xxx:yyy", record error

// For LAYER_READY: wait until all layer 0 modules signal before spawning layer 1
// For MODULE_COMPLETE: wait until all layer N modules complete before spawning layer N+1

// If error received:
//   - Log to progress.txt
//   - Decide: retry module or mark as partial
```

---

## 6. Cross-Module Verification

After all layers complete, team lead runs:

```bash
# Full solution build
dotnet build --no-restore

# Full test suite
dotnet test --no-build

# MCP validation
mcp__smartstack__validate_conventions checks=["all"]
```

---

## 7. Cleanup

After all modules done and report generated:

```javascript
// Shutdown all teammates
for (const [name, _] of Object.entries(teamContext.teammates)) {
  SendMessage({ type: "shutdown_request", recipient: name, content: "All modules complete" });
}

// Wait for shutdown confirmations, then:
TeamDelete();
```

---

## Decision Matrix

| Condition | Action |
|-----------|--------|
| 1 module | NO team, classic compact loop |
| 2+ modules, no dependency graph | Sequential layers (one at a time) |
| 2+ modules, with layers | Parallel within each layer |
| Teammate error | Log, try to continue other modules |
| All modules done | Cross-module verify → step-05 → TeamDelete |
