# LLM Implement Command Instructions

## Goal
Generate HTML/CSS/JS (and assets) for a site using its Design.md while preserving uniqueness and quality gates.
Do not care accessibilty, but maximize visual appearance and artistic design. Do not care the consume of resources or token.

## Inputs
- Design.md for the site (aesthetics, layout, palette, motifs, prompts, uniqueness notes)
- Site directory: `sites/<domain-vX>/`

---

┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ CRITICAL: READ ALL RULES BEFORE ANY ACTION ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

## General Rules (Main Agent AND Subagents)

These rules apply to **BOTH the main agent AND all subagents**. Include these in every subagent prompt.

### G1. Script Execution
**ALWAYS run Python scripts with `uv run python3.12`:**

```bash
# CORRECT
uv run python3.12 tools/implement/run.py --batch 001
uv run python3.12 tools/implement/check-outputs.py sites/example.com-v1
uv run python3.12 tools/implement/generate.py sites/example.com-v1/DESIGN.md

# WRONG — DO NOT USE THESE FORMS
python3 tools/implement/run.py ...         # WRONG
python3.12 tools/implement/run.py ...      # WRONG
./tools/implement/run.py ...               # WRONG
```

**AVOID — Absolute paths add unnecessary directory prefix:**

```bash
# WRONG — Uses absolute path to script (symlink source)
uv run python3.12 /Volumes/Common/QJoon/llm/wdmaker/tools/implement/start.py domain.com --root /Volumes/Ephemeral/CMassM1

# WRONG — Uses absolute path to script AND arguments (repo path)
uv run python3.12 /Volumes/Ephemeral/CMassK1/tools/implement/check-outputs.py /Volumes/Ephemeral/CMassK1/sites/example.com-v1

# CORRECT — Uses relative paths for both script and arguments
uv run python3.12 tools/implement/start.py domain.com --root .
uv run python3.12 tools/implement/check-outputs.py sites/example.com-v1
```

Scripts are symlinked into the repo; always use relative `tools/...` and `sites/...` paths.

### G2. No Invented Commands
- **DO NOT create new bash commands or scripts**
- **DO NOT use ad-hoc shell commands** (cat/ls/find/grep/wc/for-loops)
- Use ONLY the provided assist scripts listed below

**AVOID — Ad-hoc inline Python:**

```bash
# WRONG — Inline Python to inspect files
uv run python3.12 -c "
import os
for f in os.listdir('sites/example.com-v1'):
    print(f)
"

# CORRECT — Use provided scripts
uv run python3.12 tools/implement/check-outputs.py sites/example.com-v1
tools/check/file-stats.sh sites/example.com-v1
```

**AVOID — Creating ad-hoc debug scripts in TMP:**

```bash
# WRONG — Creating and running debug scripts
uv run python3.12 /Volumes/Temp/WDMaker/CMassK1/debug_html.py
uv run python3.12 /Volumes/Temp/WDMaker/CMassK1/check_css.py

# CORRECT — Use provided scripts for inspection
tools/check/verify-site.sh sites/example.com-v1
tools/check/html-check.sh sites/example.com-v1
```

**AVOID — Using non-existent or invented scripts:**

```bash
# WRONG — tools/status.py does not exist
uv run python3.12 tools/status.py --root . | grep example.com

# CORRECT — Use provided status scripts
tools/check/status-report.sh
tools/implement/status.sh <BATCH_ID>
```

**AVOID — Piping to grep:**

```bash
# WRONG — Piping output to grep
tools/check/status-report.sh | grep example.com

# CORRECT — Use script options for filtering, or read full output
tools/implement/status.sh <BATCH_ID>
```

### G3. No HEREDOC Pattern
- **NEVER use HEREDOC** (`<<EOF`, `<<'EOF'`, etc.) for ad-hoc file writing
- Use **Write tool** or **Filesystem MCP server** when writing new files
- **Note:** HEREDOC in provided scripts (e.g., `tools/*.sh`) is fine — this rule prohibits ad-hoc LLM usage only

```bash
# WRONG — DO NOT USE HEREDOC for ad-hoc file creation
cat <<EOF > index.html
<!DOCTYPE html>
...
EOF

# CORRECT — Use Write tool or MCP
# (Use the Write tool in Claude Code to create files)
```

### G4. Temp Directory
- Use `${TMP}` from `.wdmaker/config.toml` for temporary files
- **NEVER use `/tmp`** — always use the configured temp directory

### G5. Directory Creation
- **Use provided scripts** for creating/preparing directories (e.g., `tools/prepare/batch.sh`)
- **NEVER use `mkdir`** directly — directories are scaffolded by workflow scripts
- **DO NOT create `.gitkeep`**, `.keep`, or similar placeholder files

### G6. Preserve Reports
- **DO NOT delete** generated reports (implementation reports, batch reports, logs)
- Reports in `.smbatcher/batches/`, `.smbatcher/runs/`, `${TMP}/` are historical records

---

## Claude Code Specific Rules

These rules are specific to Claude Code orchestration.

### C1. Model Restriction
- **DO NOT use Sonnet model** for implementation tasks
- Use Opus for implementation work (higher quality, better code generation)

### C2. Subagent Assignment — ONE SITE PER SUBAGENT
- Each subagent implements **EXACTLY ONE site**, then terminates
- **NEVER assign 2+ sites** to a single subagent
- Context exhaustion is UNRECOVERABLE — this is not optional
```
CORRECT:   10 subagents × 1 site each = 10 sites
INCORRECT: 10 subagents × 8 sites each = 80 sites ← WILL FAIL
```

### C3. Subagent Execution Mode
- **ALWAYS launch subagents in synchronous mode**, NOT background mode
- Wait for each subagent to complete before proceeding
- Do NOT use `run_in_background: true` for implementation subagents

### C4. Status Code Updates via Scripts
**NEVER modify REGISTRY.md or batch files directly. Use scripts for all status transitions.**

| Role | Status | Script | When |
|------|--------|--------|------|
| Main | O | `tools/implement/lock.sh <BATCH>` | Before starting implementation |
| Subagent | i | `uv run python3.12 tools/implement/start.py <domain>` | Before starting implementation work |
| Subagent | I | `uv run python3.12 tools/implement/complete.py <domain>` | After implementation validated |
| Main | Q | `uv run python3.12 tools/implement/finish.py --batch <BATCH>` | After all subagents complete |

**Flow:**
```
Main agent: O (open for implement via lock.sh)
     ↓
Subagent: i (implement started) → [write code] → I (implement complete)
     ↓
Main agent: Q (done via finish.py)
```

---

## Assist Scripts Reference

### `tools/implement/start.py`
**Purpose:** Mark a single site as implement-in-progress (i) in REGISTRY. Called by subagent at START of implementation.

```bash
uv run python3.12 tools/implement/start.py example.com --root .
```

**Actions:**
- Acquires REGISTRY.lock
- Updates domain status: O → i
- Records timestamp

**Options:**
- `<domain>` — Domain to mark (required)
- `--root <path>` — Repository root (default: .)

---

### `tools/implement/complete.py`
**Purpose:** Mark a single site as implement-complete (I) in REGISTRY. Called by subagent at END of implementation.

```bash
uv run python3.12 tools/implement/complete.py example.com --root .
```

**Actions:**
- Validates required files exist (index.html, styles.css, script.js)
- Runs check-outputs.py validation (unless --skip-validation)
- Acquires REGISTRY.lock
- Updates domain status: i → I
- Records timestamp

**Options:**
- `<domain>` — Domain to mark (required)
- `--root <path>` — Repository root (default: .)
- `--skip-validation` — Skip implementation validation

---

### `tools/implement/finish.py`
**Purpose:** Mark all implemented sites (I) in a batch as done (Q). Called by main agent after all subagents complete.

```bash
uv run python3.12 tools/implement/finish.py --batch 001 --root .
```

**Actions:**
- Acquires REGISTRY.lock
- Transitions all I-status sites in batch to Q
- Records timestamp

**Options:**
- `--batch <ID>` — Batch ID (required)
- `--root <path>` — Repository root (default: .)

---

### `tools/implement/lock.sh`
**Purpose:** Lock batch and transition status D→O for implementation.

```bash
tools/implement/lock.sh <BATCH_ID>
```

**Actions:**
- Acquires exclusive lock on REGISTRY.lock
- Transitions all batch sites from D (Designed) to O (Open for implement)
- Creates `batch-<ID>-implement.md` tracker if not exists
- Records locked domains in tracker

**Options:**
- `<BATCH_ID>` — Required. The batch ID (e.g., 001)

**Exit codes:**
- 0 = Success (locked D→O or batch already open/in progress)
- 1 = Batch not found or no D/O/i domains to lock
- 2 = Registry not found

---

### `tools/implement/run.sh`
**Purpose:** Wrapper script that runs `run.py` with correct environment.

```bash
tools/implement/run.sh --batch <BATCH_ID> --concurrency <N>
```

**Actions:**
- Sets WDMAKER_ROOT environment variable
- Delegates to `tools/run-python.sh` with `run.py`
- Passes all arguments through

---

### `tools/implement/run.py`
**Purpose:** Queue manager for implementation workflow. Does NOT generate site code.

```bash
uv run python3.12 tools/implement/run.py --batch <BATCH_ID> --concurrency <N>
```

**Actions:**
- Calls `lock.sh` to acquire batch
- Collects domains from registry for the batch
- Transitions status: O → i (in-progress) → I (implemented) → Q (queued/complete)
- Runs `generate.py`, `validate.py`, `check-outputs.py` for each site
- Handles retries and cleanup on failure
- Logs to `.smbatcher/runs/implement-<timestamp>.log`

**Options:**
- `--batch <ID>` — Batch ID or 'auto' (default: auto → 001)
- `--concurrency <N>` — Worker count (default: 4)
- `--dry-run` — Simulate without writing
- `--root <path>` — Override repository root
- `--max-retries <N>` — Retries per site on failure (default: 1)

**Important:** The actual HTML/CSS/JS code must be authored by the LLM coding tool. This script only orchestrates the queue and validation.

---

### `tools/implement/generate.py`
**Purpose:** Prepare assets directory for site implementation.

```bash
uv run python3.12 tools/implement/generate.py <DESIGN.md>
```

**Actions:**
- Creates `assets/` directory if not exists
- Does NOT generate placeholder HTML/CSS/JS (LLM must author)

**Options:**
- `<DESIGN.md>` — Path to the design file (e.g., sites/example.com-v1/DESIGN.md)

---

### `tools/implement/check-outputs.py`
**Purpose:** Validate HTML/CSS/JS presence for a site directory.

```bash
uv run python3.12 tools/implement/check-outputs.py <site-dir>
```

**Checks:**
- index.html exists
- styles.css exists
- script.js exists

**Output:**
- "ok" if all required files present
- "missing: <list>" if any files missing

**Exit codes:**
- 0 = All files present
- 1 = Missing required files

---

### `tools/implement/status.sh`
**Purpose:** Show registry entries for a specific batch.

```bash
tools/implement/status.sh <BATCH_ID>
```

**Output:**
- Registry lines matching the batch ID
- "No entries for batch <ID>" if none found

---

### `tools/shared/validate.py`
**Purpose:** Shared HTML/asset validation checks using BeautifulSoup.

```bash
uv run python3.12 tools/shared/validate.py <index.html>
```

**Functions:**
- `validate_html(file_path)` — Check for `<html>` root element, return errors list
- `ensure_assets(asset_dir)` — Verify assets directory exists

**Usage:**
- Called by `run.py` during implementation validation
- Returns list of error strings; empty list means valid

---

### `tools/check/verify-site.sh`
**Purpose:** Comprehensive site verification — runs all checks in sequence.

```bash
tools/check/verify-site.sh <site-dir>
tools/check/verify-site.sh sites/example.com-v1
```

**Actions:**
1. Checks required files exist (index.html, styles.css, script.js)
2. Runs HTML structure check via `html-check.sh`
3. Runs JavaScript syntax check via `js-syntax.sh`
4. Shows file statistics via `file-stats.sh`
5. Checks for DESIGN.md presence

**Exit codes:**
- 0 = All checks passed
- 1 = One or more checks failed

---

### `tools/check/html-check.sh`
**Purpose:** Check HTML structure for required elements.

```bash
tools/check/html-check.sh <site-dir>
tools/check/html-check.sh sites/example.com-v1
```

**Checks:**
- DOCTYPE declaration
- `<html>`, `<head>`, `<body>` tags
- `<title>` tag
- Viewport meta tag
- CSS link or inline styles
- JavaScript reference
- Closing `</html>` tag

**Exit codes:**
- 0 = HTML structure valid
- 1 = Structural issues found

---

### `tools/check/js-syntax.sh`
**Purpose:** Check JavaScript syntax using Node.js.

```bash
tools/check/js-syntax.sh <site-dir>
tools/check/js-syntax.sh sites/example.com-v1
```

**Actions:**
- Finds all .js files in site directory (maxdepth 2)
- Runs `node -c` on each file to check syntax
- Reports pass/fail for each file

**Exit codes:**
- 0 = All JavaScript files valid
- 1 = Syntax errors found

---

### `tools/check/file-stats.sh`
**Purpose:** Show file statistics for a site directory.

```bash
tools/check/file-stats.sh <site-dir>
tools/check/file-stats.sh sites/example.com-v1
```

**Output:**
- Line counts and file sizes for HTML, CSS, JS files
- Total lines and KB

**Example:**
```
HTML:
  index.html           150 lines    5.2 KB

CSS:
  styles.css           200 lines    4.1 KB

JavaScript:
  script.js            100 lines    3.0 KB
---
TOTAL: 450 lines, 12.3 KB
```

---

### `tools/check/design-compliance.sh`
**Purpose:** Check implementation compliance against DESIGN.md specifications.

```bash
tools/check/design-compliance.sh <site-dir>
tools/check/design-compliance.sh sites/example.com-v1
```

**Checks:**
1. **Color Palette** — Verifies hex colors from DESIGN.md appear in CSS
2. **Typography** — Checks specified fonts are used
3. **CSS Animations** — Counts @keyframes and transitions
4. **Performance Patterns** — Checks for will-change, transforms, requestAnimationFrame, etc.
5. **JavaScript Features** — Counts classes, functions, event listeners
6. **Accessibility** — ARIA attributes, focus styles, keyboard handling
7. **External Dependencies** — External scripts, images, fonts

**Output:**
- Pass/Warn/Fail counts per category
- Summary: FULL COMPLIANCE, PARTIAL COMPLIANCE, or COMPLIANCE ISSUES FOUND

**Exit codes:**
- 0 = No failures (may have warnings)
- 1 = Compliance issues found

---

## Prohibited vs Alternatives

| ❌ Prohibited | ✅ Use Instead |
|--------------|----------------|
| `cat/less/head/tail` file inspection | `uv run python3.12 tools/implement/check-outputs.py <site-dir>` or `tools/implement/status.sh <BATCH>` |
| `ls/find/wc/globs` directory listing | `uv run python3.12 tools/design/check-dirs.py --batch-id <ID> --root .` or `tools/check/file-stats.sh <site-dir>` |
| `grep "pattern"` searching | `tools/implement/status.sh <BATCH>` |
| `for f in *.html; do` loops | `uv run python3.12 tools/implement/run.py --batch <ID>` (handles queue) |
| `mkdir -p` directory creation | `uv run python3.12 tools/implement/generate.py <DESIGN.md>` or `tools/prepare/batch.sh` |
| `python3 script.py` | `uv run python3.12 tools/.../<script>.py` |
| `cat <<EOF` HEREDOC | Write tool or Filesystem MCP |
| Creating new scripts | Use existing assist scripts only |
| Manual HTML validation | `tools/check/html-check.sh <site-dir>` or `tools/check/verify-site.sh <site-dir>` |
| Manual JS validation | `tools/check/js-syntax.sh <site-dir>` |
| Manual compliance check | `tools/check/design-compliance.sh <site-dir>` |

---

## Required Outputs
- `index.html` matching Design.md layout and tone
- `styles.css` implementing palette/typography/motifs
- `script.js` for interactions; ensure no console errors
- `assets/` for required media/SVGs
- No placeholders: deliver complete, production-ready files (LLM coding tools own the final content).

---

## Steps for LLM

> **Note:** General Rules (G1-G4) and Claude Code Rules (C1-C5) apply to ALL steps below.

### Step 1: Pick Batch (Main Agent)
Execute: Read REGISTRY
  Tool: Read
  Path: .smbatcher/REGISTRY.md
  Background:
  - If batch number is not provided by user, check `.smbatcher/REGISTRY.md` and choose batches with sites not at `Q`. you can select multiple batches.

### Step 2: Acquire Lock and Open Batch (Main Agent)
Execute: 
  Tool: Bash
  Command: `tools/implement/lock.sh "$BATCH"`
  Background:
  - Handles D→O transition, lock + rollback on contention.

### Step 3: Launch Subagents (Main Agent)
Launch ~10 Opus subagents to implement sites in parallel. Assign only ONE site to each subagent. When launch a subagent, provide Subagent Launch Template to the subagent

**CRITICAL — PARALLEL LAUNCH:**
To execute subagents in parallel, you MUST send a **SINGLE message** containing **MULTIPLE Task tool calls**.

Example for 10 sites in batch:
```
ONE message with 10 Task tool calls:
  Task #1: prompt="Implement ONLY site1.com...", subagent_type="general-purpose"
  Task #2: prompt="Implement ONLY site2.com...", subagent_type="general-purpose"
  Task #3: prompt="Implement ONLY site3.com...", subagent_type="general-purpose"
  ...
  Task #10: prompt="Implement ONLY site10.com...", subagent_type="general-purpose"
```

**DO NOT** launch only one subagent at total, wait for it, then launch the next. Launch only one subagent is sequential, not parallel.
**DO** include all Task tool calls in the same response message.

### Step 4: Implement Site (Subagent — Per Site LLM Work)

Execute #1: Mark implement start
  Tool: Bash
  Command: `uv run python3.12 tools/implement/start.py <domain> --root .`

Execute #2: Read design
  Tool: Bash
  Command: `uv run python3.12 tools/design/read-design.py sites/<domain-vX>/DESIGN.md`
  Background:
  - Extract layout/palette/motifs/interaction directives

Build a site (files)
After Execution #1~#2, Build a site
Write these files via Write tool:
- `sites/<domain-vX>/index.html`
- `sites/<domain-vX>/styles.css`
- `sites/<domain-vX>/script.js`
- `sites/<domain-vX>/assets/<filename>` (if needed)

- Build `index.html` → `styles.css` → `script.js`
- Keep IDs/classes consistent
- Add required assets to `assets/` such as SVG, etc.
- Avoid console errors
- Follow uniqueness notes (avoid overused motifs)

Execute #3: Validate Basic file presence check
  Tool: Bash
  Command: `uv run python3.12 tools/implement/check-outputs.py sites/<domain-vX>`

Execute #4: Validate Comprehensive verification (HTML, JS syntax, file stats)
  Tool: Bash
  Command: `tools/check/verify-site.sh sites/<domain-vX>`

Execute #5: Validate Design compliance check (colors, fonts, patterns)
  Tool: Bash
  Command: `tools/check/design-compliance.sh sites/<domain-vX>`

Execute #6: Mark implement complete
  Tool: Bash
  Command: `uv run python3.12 tools/implement/complete.py <domain> --root .`


### Step 5: Finalize Batch (Main Agent)
After all subagents complete:
Execute:
  Tool: Bash
  Command: `uv run python3.12 tools/implement/finish.py --batch "$BATCH" --root .`
  Background:
  - This transitions all I-status sites to Q (done).

---

## Subagent Launch Template

When launching subagents for parallel implementation.
**IMPORTANT:**
- Launch in **synchronous mode** (C3), assign **ONE site only** (C2)
- **Subagents MUST use Opus model** — set `model: "opus"` parameter when launching. NEVER use Sonnet.

```
Implement ONLY the site <domain>. Do NOT implement any other sites.

- NEVER TRY to create file(ex: DESIGN.md) via cat/HEREDOC pattern. Use Only Write tool or Filesystem MCP.
- NEVER DELETE file which you created.
- DO NOT report result

## Step 0: Read instructions
Execute:
  Tool: Read
  Path: tools/implement/IMPLEMENT_COMMAND.md
Motivation: LLMs skipped reading instructions and invented ad-hoc commands.

## Step 1: Mark implement start
Execute:
  Tool: Bash
  Command: uv run python3.12 tools/implement/start.py <domain> --root .

## Step 2: Read the design
Execute:
  Tool: Bash
  Command: uv run python3.12 tools/design/read-design.py sites/<domain-vX>/DESIGN.md

## Step 3: Get creative implementation ideas
Execute:
  Tool: Skill
  Skill: frontend-design
  Background: Ensures high-quality, distinctive implementations.

## Step 4: Write index.html
Execute:
  Tool: Write
  Path: sites/<domain-vX>/index.html
  Background: 
  - Keep IDs/classes consistent
  - Add required assets to `assets/` such as SVG, etc.
  - Avoid console errors
  - Follow uniqueness notes (avoid overused motifs)

## Step 5: Write styles.css
Execute:
  Tool: Write
  Path: sites/<domain-vX>/styles.css
  Background: 
  - Keep IDs/classes consistent
  - Add required assets to `assets/` such as SVG, etc.
  - Avoid console errors
  - Follow uniqueness notes (avoid overused motifs)

## Step 6: Write script.js
Execute:
  Tool: Write
  Path: sites/<domain-vX>/script.js
  Background: 
  - Keep IDs/classes consistent
  - Add required assets to `assets/` such as SVG, etc.
  - Avoid console errors
  - Follow uniqueness notes (avoid overused motifs)

## Step 7: Check outputs exist
Execute:
  Tool: Bash
  Command: uv run python3.12 tools/implement/check-outputs.py sites/<domain-vX>

## Step 8: Verify site structure
Execute:
  Tool: Bash
  Command: tools/check/verify-site.sh sites/<domain-vX>

## Step 9: Check design compliance
Execute:
  Tool: Bash
  Command: tools/check/design-compliance.sh sites/<domain-vX>

## Step 10: Mark implement complete
Execute:
  Tool: Bash
  Command: uv run python3.12 tools/implement/complete.py <domain> --root .
```

---

## Output Format
Save files under the site directory; keep relative paths consistent and runnable with no external network calls.
