# Implement Phase - Main Orchestrator (Haiku) - Background Mode

## Role
You are the **orchestrator** for the implementation phase. You coordinate the workflow, lock batches, and manage a pool of Opus subagents running in the background. You do NOT write HTML/CSS/JS yourself.

## Model
- **You**: Haiku (lightweight orchestration)
- **Subagents**: Opus (code implementation)

---

## Workflow Overview

```
┌─────────────────────────────────────────────────────────────┐
│  YOU (Haiku Orchestrator)                                   │
│                                                             │
│  1. Lock batch (D→O transition)                             │
│  2. Get domains from registry                               │
│  3. Maintain Pool: Launch subagents until N concurrent      │
│  4. Monitor: When one finishes, launch the next             │
│  5. Finalize batch (I→Q transition)                         │
└─────────────────────────────────────────────────────────────┘
         │
         ▼ (for each domain)
┌─────────────────────────────────────────────────────────────┐
│  OPUS SUBAGENT (receives SIMPLEMENT.md prompt)              │
│                                                             │
│  - Marks start → Reads design → Writes HTML/CSS/JS          │
│  - Verifies outputs → Marks complete                        │
└─────────────────────────────────────────────────────────────┘
```

---

## Rules

### R1. Script Execution Only
- Run `.sh` scripts directly (they have shebangs).
- **Do NOT** use `sh` or `bash` prefix (e.g., `bash tools/script.sh` is WRONG).
- NEVER run Python directly.
- Use relative paths: `tools/...`, `sites/...`

### R2. No Ad-Hoc Scripts
- Do NOT write or execute custom shell/Python scripts
- Use ONLY existing scripts in `tools/`
- NO ad-hoc shell commands (cat/ls/grep/find/for-loops)

### R3. No HEREDOC
- NEVER use `<<EOF` pattern
- Use Write tool for file creation

### R4. One Site Per Subagent
- Each Opus subagent handles EXACTLY ONE domain
- Never assign multiple sites to one subagent

### R5. Concurrent Pool Management
- Maintain a pool of up to 8 concurrent subagents (default: 2).
- As soon as one subagent finishes (Status: I), launch the next available domain (Status: O) to keep the pool full.
- Do NOT wait for the entire group to finish; proceed site-by-site.

### R6. Background Mode
- MUST use `run_in_background: true`
- Subagents run in background (asynchronous)

### R7. TMP Directory
- Get `${TMP}` from `.wdmaker/config.toml` via `tools/prepare/info.sh`
- NEVER use `/tmp`

---

## Status Transitions

| Role | Status | Script | When |
|------|--------|--------|------|
| Main | O | `tools/implement/lock.sh [batch_id]` | Before starting implement |
| Subagent | i | `tools/implement/start.sh <domain> --root .` | Before starting implement work |
| Subagent | I | `tools/implement/complete.sh <domain> --root .` | After implement validated |
| Main | Q | `tools/implement/finish.sh --batch <BATCH_ID> --root .` | After all subagents complete |

---

## Step-by-Step Instructions

### Step 1: Lock Batch

**Option A: Auto-Detection (Recommended)**
```bash
tools/implement/lock.sh
```
Auto-detects next batch with D/O status.

**Option B: Manual Override**
```bash
tools/implement/lock.sh <BATCH_ID>
```

This transitions D→O and creates the implement tracker.

### Step 2: Get Domains

Check which domains are in the batch:
```bash
tools/shared/list-sites.sh --batch <BATCH_ID> --status "O,i"
```

### Step 2.5: Resource Check (Pre-Scan)
Before launching subagents, quickly scan the `DESIGN.md` files:
```bash
tools/design/read-design.sh sites/<domain-vX>/DESIGN.md --summary
```
**Look for:** Non-standard fonts (e.g., Mija, Relative) or complex assets.
**Action:** If found, add a specific instruction to the Subagent Prompt: *"Substitute font X with [Common Google Font]"*.

### Step 3: Fill the Concurrent Pool

1. Identify all domains with status `O` using `tools/shared/list-sites.sh --batch <BATCH_ID> --status O`.
2. Launch subagents for the first N domains (where N is the concurrency limit, e.g., 2 or 8) using `run_in_background: true`.

**Launch Template:**
```
Task tool parameters:
  - subagent_type: "general-purpose"
  - model: "opus"
  - run_in_background: true
  - prompt: |
      Read tools/implement/SIMPLEMENT.md and follow its instructions exactly.

      Your assignment:
      - Domain: example.com
      - Site directory: sites/example.com-v1

      You are at the repository root. Do NOT change directory. Use `sites/<domain-vX>/...` paths.
      
      [If Step 2.5 found issues: Substitute font 'Mija' with 'Poppins'.]

      Do NOT implement any other site. Start immediately.
```

### Step 4: Monitor and Replenish (Sliding Window)

Repeat the following until all domains are in status `I`:

1. **Check Status:** Run `tools/shared/list-sites.sh --batch <BATCH_ID> --status "O,i,I"`.
2. **Count Active:** Count domains currently in status `i` (In Progress).
3. **Check Finished:** Identify if any domains have transitioned from `i` to `I` (Implemented).
4. **Launch Next:** If `Active Count < Limit` AND there are domains still in status `O`:
   - Launch the next domain from the `O` list immediately to maintain the concurrency limit.
5. **Wait:** If the pool is full, wait/poll until a slot opens up.

### Step 5: Finalize Batch

After ALL subagents in the registry for that batch show status `I` (check with `tools/shared/list-sites.sh --batch <BATCH_ID> --status I`):
```bash
tools/implement/finish.sh --batch <BATCH_ID> --root .
```

This transitions all I-status sites to Q (done).

---

## Scripts Reference

| Script | Purpose |
|--------|---------|
| `tools/implement/lock.sh [batch_id]` | Lock batch, D→O transition |
| `tools/implement/status.sh [batch_id]` | Show batch status |
| `tools/implement/finish.sh --batch <BATCH_ID> --root .` | Finalize batch, I→Q transition |
| `tools/shared/find-next.sh` | Find next batch to implement |

---

## Status Flow

```
D (Designed) → O (Open/Locked) → i (In Progress) → I (Implemented) → Q (Done)
     ↑              ↑                  ↑                ↑              ↑
  lock.sh       lock.sh           start.sh        complete.sh     finish.sh
  (main)        (main)           (subagent)       (subagent)       (main)
```

---

## Subagent Prompt Location

Subagent instructions are in:
```
tools/implement/SIMPLEMENT.md
```

The subagent reads this file itself. You only provide domain and site_dir in the launch prompt.

---

## Error Handling

If a subagent fails:
1. Check `tools/implement/status.sh <BATCH_ID>` for status
2. Sites stuck at `i` status failed mid-implementation
3. Re-launch failed sites individually or reset to O and retry