# /polish — Visual Refinement Loop

Tight screenshot-driven iteration loop for frontend polish. Takes screenshots at multiple viewports, analyzes them visually, makes targeted CSS/HTML fixes, re-screenshots to verify, and repeats until the UI looks right. You are both the reviewer and the fixer — no handoffs, no sub-agents, just direct visual iteration.

## When to Use

- After building any UI — polish it until it matches the design
- After a harness build that created frontend components
- When something "looks off" but you're not sure what
- Any time you want to tighten up spacing, alignment, typography, or color
- Standalone visual QA on any running frontend

## When NOT to Use

- Functional testing (clicking buttons, submitting forms) — use the harness browser round
- Creating a design system from scratch — use `/frontend-design`
- Building UI that doesn't exist yet — build it first, then polish

## Usage

```
/polish                                    # Polish current project's UI
/polish http://localhost:3000              # Specific URL
/polish http://localhost:8080/dashboard    # Specific page
/polish --pages /,/settings,/dashboard    # Multiple pages
/polish --max 8                           # Max iterations (default 5)
/polish --viewport desktop                # Single viewport only
```

## Parameters

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `[url]` | No | Auto-detect | Dev server URL |
| `--pages` | No | `/` | Comma-separated routes to check |
| `--max` | No | 5 | Max iteration rounds |
| `--viewport` | No | all | `desktop`, `tablet`, `mobile`, or `all` |
| `--design` | No | auto-detect | Path to DESIGN_SYSTEM.md |

---

## Protocol

### Step 0: Setup

**Find or start the dev server:**
- If URL provided, use it
- Else probe common ports: `curl -s -o /dev/null -w "%{http_code}" http://localhost:{3000,8080,5173,4200,8000}`
- Else look for start script (`npm run dev`, `python -m http.server`, etc.) and start it in background
- Wait for the server to respond before proceeding

**Load design ground truth (if available):**
- Check for `DESIGN_SYSTEM.md` in working directory
- If found, extract key tokens: color palette (hex values), font families, spacing scale, border-radius, shadows
- These are the reference for "correct" — without them, use general design principles and visual consistency

**Identify pages to check:**
- If `--pages` provided, use those
- Else default to `/` (expand later if issues are page-specific)

**Set viewport sizes:**

| Name | Width | Height | Represents |
|------|-------|--------|------------|
| Desktop | 1440 | 900 | Standard laptop/monitor |
| Tablet | 768 | 1024 | iPad portrait |
| Mobile | 375 | 812 | iPhone standard |

### Step 1: Screenshot Pass

For each page at each viewport:

1. **Resize:** `browser_resize` to viewport dimensions
2. **Navigate:** `browser_navigate` to the page URL
3. **Wait:** `browser_wait_for` — network idle or 2 seconds, whichever comes first
4. **Screenshot:** `browser_take_screenshot`
5. **Read:** Use the Read tool on the screenshot file to see it visually

These are your "before" snapshots for this round. You'll compare against them after fixing.

### Step 2: Analyze

Look at each screenshot. You're looking for five categories of issues:

**1. Layout & Spacing**
- Elements crammed together with no breathing room
- Inconsistent gaps between similar elements (cards with different margins, list items with uneven spacing)
- Content pushed against container edges (missing padding)
- Oversized empty areas that waste space
- Elements that don't align with their neighbors (ragged left edges, uneven grid)

**2. Typography & Readability**
- Text too small to read comfortably (below ~14px on mobile, ~13px on desktop)
- Line lengths too wide (over ~75 characters per line) or too narrow (under ~30)
- Inconsistent font sizes for same-level headings
- Poor contrast — light text on light background, or dark on dark
- Missing hierarchy — everything looks the same weight and size, nothing draws the eye

**3. Visual Coherence**
- Mismatched border-radius (some elements rounded, some sharp, no clear pattern)
- Inconsistent color usage (random one-off colors vs. a systematic palette)
- Shadow inconsistencies (some cards elevated, some flat, mixed within the same group)
- Orphaned elements that don't visually belong to any section or group

**4. Responsive Behavior**
- Horizontal scrollbar at any viewport
- Text overflow, truncation, or content spilling outside its container
- Desktop layout crammed into mobile without reflowing
- Touch targets too small on mobile (anything interactive should be at least 44px)
- Navigation that disappears, overlaps, or breaks on small screens

**5. Design System Compliance** (only if DESIGN_SYSTEM.md exists)
- Colors that don't match the defined palette
- Fonts that don't match the specified families
- Spacing that doesn't follow the defined scale
- Border-radius or shadow values that don't match tokens

For each issue found, note:
- What you see (the symptom)
- Where it is (which page, which viewport, which element)
- What you think the fix is

### Step 3: Prioritize and Fix

**Fix priority order — work top-down:**

1. **Broken layout** — overflow, overlapping elements, invisible content, horizontal scroll
2. **Spacing** — too tight, too loose, inconsistent gaps
3. **Typography** — readability, hierarchy, contrast
4. **Color & visual** — palette compliance, shadows, borders, coherence
5. **Responsive** — mobile/tablet breakpoints, touch targets
6. **Micro-polish** — hover states, transitions, subtle alignment

**Fix discipline:**

- **3-5 fixes per round.** Don't try to fix everything at once. CSS changes interact — a margin fix can cascade through the layout. Small batches let you verify each change.
- **Edit directly.** Open the CSS/HTML/JS files and make the changes. Prefer CSS changes over structural HTML changes — they're lower risk and easier to revert.
- **Follow existing patterns.** If the project uses CSS custom properties (`var(--spacing-md)`), use those. If it uses utility classes (Tailwind, etc.), use those. Don't introduce a new pattern.
- **Think across viewports.** Before making a change, consider how it affects all three viewports. A `padding: 40px` that looks great on desktop might crush mobile. Use responsive units or media queries when needed.
- **If DESIGN_SYSTEM.md exists, move toward it.** Every fix should bring the UI closer to the spec, not further away.

### Step 4: Verify

After applying fixes:

1. **Re-screenshot** every page × viewport that could be affected by your changes
2. **Read** each new screenshot
3. **For each fix, confirm:**
   - The issue is resolved — the spacing looks right, the text is readable, etc.
   - No new issues were introduced — check the surrounding area, not just the fixed element
   - Other viewports weren't broken — a desktop fix shouldn't wreck mobile

**If a fix caused a regression:** Revert it immediately. Note why it regressed — you may need a different approach (media query, different CSS property, structural change).

### Step 5: Log the Round

Print a concise summary:

```
Round {N}: {found} issues found, {fixed} fixed
- [FIXED] Sidebar padding 4px → 16px (styles/layout.css:42)
- [FIXED] Card gap inconsistency — unified to 24px (styles/components.css:118)
- [REGRESSION] Header font-size change broke mobile nav — reverted
- [DEFERRED] Grid needs restructuring for tablet — requires HTML changes
```

### Step 6: Loop or Exit

**Continue** if issues remain AND round count < max iterations.

**Exit** if ANY of these:
- **Convergence:** Two consecutive rounds find zero new issues. The UI is clean.
- **Max rounds:** Hit the iteration cap (default 5). Report remaining issues.
- **Structural only:** All remaining issues require architectural changes (HTML restructuring, component refactoring) that are beyond CSS polish. Report them as recommendations.

### Step 7: Summary

When done, print:

```
## /polish Complete

**URL:** {url}
**Pages:** {page list}
**Rounds:** {N}
**Issues found:** {total across all rounds}
**Issues fixed:** {total}
**Issues deferred:** {total}
**Exit:** convergence | max-rounds | structural-only

### Fixes Applied
| Round | File | Change |
|-------|------|--------|
| 1 | styles/main.css | Added 16px padding to .card containers |
| 1 | components/Nav.jsx | Increased mobile nav height to 48px |
| 2 | styles/main.css | Fixed heading hierarchy (h2 24px → 20px) |

### Remaining Issues (if any)
- {description} — requires {what kind of change}
```

---

## Design Principles

1. **Screenshot is ground truth.** Code review misses visual bugs. A screenshot shows exactly what the user sees. Always look at the actual screenshot — don't assume a CSS change looks right because the code is correct.

2. **Small batches, fast cycles.** 3-5 fixes per round, then re-screenshot. This catches regressions early and keeps each round's scope manageable. A 20-fix batch where fix #3 broke something means 17 wasted fixes.

3. **Move toward the spec, not toward taste.** If DESIGN_SYSTEM.md exists, compliance with it is the goal — not subjective "this would look better if..." changes. Without a spec, use consistency as the guide: make similar elements look similar.

4. **Don't over-polish.** Convergence means "no issues found," not "perfect." Diminishing returns are real. If the UI is clean and consistent, stop. Don't spend round 5 debating whether 14px or 15px line-height is better.

5. **Responsive is not optional.** Every fix must be verified at all active viewports. A desktop-only fix that breaks mobile is a net negative. When in doubt, use responsive CSS (clamp, min/max, media queries).

6. **Regressions are information.** A fix that breaks something else reveals a coupling you didn't know about. Note it — it may indicate a structural issue that belongs in the "deferred" list rather than a CSS fix.

---

## Natural Pairing

```
/frontend-design  →  Build phases  →  /polish
(create design)      (implement)      (refine until it matches)
```

Or standalone after any UI change:

```
edit some CSS  →  /polish  →  looks right
```

Or after a harness build:

```
/harness BUILD_SPEC.md --debug  →  /polish
(functional correctness)           (visual correctness)
```
