# Implement Phase - Main Orchestrator (Haiku)

## Role
You are the **orchestrator** for the implementation phase. You coordinate the workflow, lock batches, launch Opus subagents, and finalize results. 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. Launch Opus subagents (one per domain)                  │
│  4. Wait for subagents to complete                          │
│  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. Parallel Launch
- Launch up to 10 subagents in ONE message with multiple Task calls
- Wait for wave completion before launching next wave

### R6. Foreground Mode
- Do NOT use `run_in_background: true`
- Subagents run in foreground (synchronous)

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

### R8. Persistent Task Tracking
- After getting domains (Step 2), create a persistent task for EACH domain using TaskCreate.
- Task subject: "Implement: <domain>"
- Task activeForm: "Implementing <domain>"
- Mark tasks `in_progress` before launching each subagent (Step 3).
- Mark tasks `completed` after each subagent finishes successfully.
- If context is compacted, run TaskList FIRST to recover progress before proceeding.

---

## 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.1: Create Persistent Tasks

For each domain in the batch, create a persistent task:
- Tool: TaskCreate
- subject: "Implement: <domain>"
- description: "Implement phase for <domain> in batch <BATCH_ID>"
- activeForm: "Implementing <domain>"

These tasks survive context compaction. If the session is compacted,
run TaskList first to see which domains are already completed.

### 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: Launch Opus Subagents

For each domain in batch, launch ONE Opus subagent.

**Before launching:** Call `TaskUpdate` to mark each domain's task `in_progress`.
**After each subagent returns:** Call `TaskUpdate` to mark its task `completed`.

**Launch Template:**
```
Task tool parameters:
  - subagent_type: "general-purpose"
  - model: "opus"
  - 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.
```

**Parallel Launch:**
- Include ALL Task calls in ONE message (up to N=10 max, default N=4)
- If batch > N sites, launch in waves

Example prompt for each site:
```
Read tools/implement/SIMPLEMENT.md and follow its instructions exactly.

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

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

### Step 4: Wait for Completion

All subagents must complete before proceeding.
Each subagent will update status to I when done.

### Step 5: Finalize Batch

After ALL subagents complete:
```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

---

## Recovery After Context Compaction

If context was compacted mid-batch:
1. Run TaskList to see all persistent tasks and their statuses.
2. Identify tasks still `pending` or `in_progress`.
3. For `in_progress` tasks, check actual file status:
   - `tools/shared/list-sites.sh --batch <ID> --status "O,i,I"`
4. Re-launch subagents only for domains that are NOT in status I.
5. Mark already-completed domains' tasks as `completed`.
