# Clone Website

> Reverse-engineer and clone one or more websites in one shot. Extracts assets, CSS, content and behaviors section by section using Playwriter (the user's own Chrome browser) and dispatches parallel builder agents as it goes. Use whenever the user wants to clone, replicate, rebuild, reverse-engineer or copy any website. Also triggers on "make a copy of this site", "rebuild this page", "pixel-perfect clone". Provide one or more target URLs as arguments. Windows / PowerShell environment.

- Skill: `rodrigonask/clone-website` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add rodrigonask/clone-website`
- Raw SKILL.md: https://api.skillmd.com/api/skills/rodrigonask/clone-website/raw
- Safety review: pending (external: skill-scanner WARNING, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Web & Frontend
- Author: rodrigonask (https://skillmd.com/u/rodrigonask)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/rodrigonask/clone-website

---


# Clone Website (Playwriter + PowerShell Edition)

You are about to reverse-engineer and rebuild **$ARGUMENTS** as pixel-perfect clones.

**Environment assumption:** Windows 11, PowerShell, Playwriter against the user's real Chrome browser. Every shell snippet in this skill is PowerShell. Do not translate to bash. If you find yourself reaching for `export`, `$(...)`, or `<<'EOF'`, stop: those are bash. Use `$env:NAME = ...`, `(command)`, and `@'...'@` here-strings instead. (On macOS or Linux, translate the shell snippets to bash. The browser-side JavaScript is identical.)

When multiple URLs are provided, process them independently and in parallel where possible, while keeping each site's extraction artifacts isolated in dedicated folders (for example, `docs/research/<hostname>/`).

This is not a two-phase process (inspect, then build). You are a **foreman walking the job site**: as you inspect each section of the page, you write a detailed specification to a file, then hand that file to a specialist builder agent with everything they need. Extraction and construction happen in parallel, but extraction is meticulous and produces auditable artifacts.

## Scope Defaults

The target is whatever page `$ARGUMENTS` resolves to. Clone exactly what is visible at that URL. Unless the user specifies otherwise, use these defaults:

- **Fidelity level:** Pixel-perfect. Exact match in colors, spacing, typography, animations.
- **In scope:** Visual layout and styling, component structure and interactions, responsive design, mock data for demo purposes.
- **Out of scope:** Real backend / database, authentication, real-time features, SEO optimization, accessibility audit.
- **Customization:** None. Pure emulation.
- **Link handling:** A clone is almost always a **homepage-only preview**, so root-relative links to pages you did not build will 404. By default, rewrite every navigational link to an **absolute URL on the original domain**: `href="/x"` becomes `href="https://<original-host>/x"`, including `/#anchor` links, the logo's `href="/"`, and `href="#"` placeholders (which become the original homepage). Catch hrefs in **both** JSX attributes AND data arrays (`href: '/x'`), and do NOT rewrite non-href strings that merely start with `/` (for example a `'/ mo'` price suffix). Only keep links page-local when explicitly building the full multi-page site. (Buttons like "Watch demo" are not links. Leave them, or ask whether to wire them to the original.)

If the user provides additional instructions (specific fidelity level, customizations, extra context), honor those over the defaults.

## Pre-Flight

1. **Playwriter is required.** This skill drives the user's real Chrome browser via the Playwriter CLI. NOT Playwright, NOT a headless browser, NOT Chrome MCP. Verify with `playwriter --version`. If missing, instruct the user to install: `npm install -g playwriter@latest`.

2. **Create a Playwriter session and capture the ID.** Each `playwriter` call needs `-s <ID>` to share state across calls:

   ```powershell
   playwriter session new
   # Output is a single integer (e.g., 1). Note it. You will use it as <SID> for every subsequent call.
   ```

   **Shell state does NOT persist between tool calls.** Setting `$env:CLONE_SID = ...` in one PowerShell call will NOT survive into the next. Either capture the integer and substitute it literally into every subsequent command (recommended), or chain everything in a single PowerShell call when feasible.

   In the rest of this skill, `<SID>` is a placeholder. Replace it with the integer Playwriter returned.

3. **Chrome must be running with the target tab enabled for Playwriter.** If you get "extension is not connected" or "no browser tabs have Playwriter enabled":
   - Ask the user to open Chrome and click the Playwriter extension icon on the target tab, OR
   - Launch Chrome with auto-accept flags:

     ```powershell
     Start-Process chrome.exe -ArgumentList '--profile-directory=Default --allowlisted-extension-id=jfeammnjpkecdekppnclgkkffahnhfhe --auto-accept-this-tab-capture'
     ```

4. **Parse `$ARGUMENTS`** as one or more URLs. Normalize and validate each URL; if any are invalid, ask the user to correct them before proceeding. For each valid URL, verify it loads (substitute `<SID>` and `URL_HERE`):

   ```powershell
   playwriter -s <SID> -e 'state.page = await context.newPage(); await state.page.goto("URL_HERE", { waitUntil: "networkidle" }); await state.page.title()'
   ```

5. **Verify the base project builds:** `npm run build`. The default expected scaffold is:
   - **Framework:** Vite + React + TypeScript strict (versions drift; trust the scaffold's `package.json` over this list)
   - **UI:** shadcn/ui + Tailwind CSS v4 (OKLCH design tokens) + Framer Motion
   - **Routing:** React Router
   - **Hosting:** Cloudflare Pages (`npm run build` produces `dist/`; deploy via `npx wrangler pages deploy dist --project-name <name> --branch main`. The `--branch main` is NOT optional, see Deploy safety. Always `npx wrangler`; wrangler is not a local dep.)
   - **Dev server port:** 5173 (Vite default)

   **Expected file layout for this skill:**
   - `index.html`: root HTML, `<link>` font tags, favicons, meta
   - `src/main.tsx`: React entry; imports `./index.css`
   - `src/App.tsx`: router root
   - `src/index.css`: Tailwind v4 entry. Imports `tailwindcss`, `shadcn/tailwind.css`, font packages, and defines OKLCH design tokens inside `:root { ... }` and `.dark { ... }` blocks.
   - `src/pages/Home.tsx`: the cloned page goes here (or `src/App.tsx` if no routing)
   - `src/components/`: section components and `icons.tsx`
   - `src/types/`: content interfaces
   - `public/`: downloaded images, videos, favicons (in `public/seo/`)

   If no scaffold is present, scaffold one matching the above before continuing (`npm create vite@latest`, then add Tailwind v4 and shadcn). If the user has explicitly directed a different stack (Next.js, Astro, plain Vite, etc.), honor that and adapt the file paths in this skill accordingly.

6. **Create the output directories** if they do not exist: `docs/research/`, `docs/research/components/`, `docs/design-references/`, `scripts/`. PowerShell:

   ```powershell
   'docs/research', 'docs/research/components', 'docs/design-references', 'scripts' | ForEach-Object { New-Item -ItemType Directory -Force -Path $_ | Out-Null }
   ```

   For multiple clones, also prepare per-site folders like `docs/research/<hostname>/` and `docs/design-references/<hostname>/`.

7. **When working with multiple sites** in one command, optionally confirm whether to run them in parallel (recommended, if resources allow) or sequentially to avoid overload. Each parallel site should get its OWN Playwriter session (`playwriter session new`) so their `state.page` references do not collide. Track each site's `<SID>` separately.

8. **Access gate: ask for everything up front, in ONE message.** Every credential the run will eventually need gets requested or verified NOW, before Phase 1, in a single message, not discovered mid-run when it stops the world. Missing items do NOT block the start: record each one in `docs/RUNSHEET.md` as `BLOCKER-AHEAD: <credential> blocks <step>` and keep going until that step is actually reached.

   For a plain clone the list is short:
   - **Playwriter**: already verified in item 1; note it here only if it failed and the user deferred fixing it.
   - **Cloudflare** (only if the user asked to deploy): `npx wrangler whoami` succeeds; if multiple accounts, `CLOUDFLARE_ACCOUNT_ID` is set; target Pages project name checked against `pages project list` (free vs. intended-existing).
   - **Meta Pixel ID + Conversions API token** (only if the user asked for tracking, see the optional add-on at the end): ask at kickoff, not launch week.
   - **Git remote / backup**: optional but ask once. Without a remote, the whole deliverable exists on one disk.

   Rule: **ask once, list everything, accept partial answers, log the gaps.** When a later step hits a `BLOCKER-AHEAD`, that is a planned pause with a named owner, not a surprise stall.

## Execution Contract: survive compaction, finish every step (MANDATORY)

A full run outlives several context compactions. Anything that lives only in the conversation, including your plan, WILL be summarized away mid-run. Two stores survive: **the task list** (lives outside the context window and is re-injected after compaction) and **files on disk** (survive compaction AND session death once committed). Use both, from minute one:

1. **Before any extraction work, create the run's tasks** with `TaskCreate`: one task per phase or step you intend to execute, IN ORDER, including the opt-in ones the user authorized (deploy, tracking add-on). Put the *verification criterion* in the task description, not just the step name. For example: "Phase 5: Visual QA, side-by-side vs original at 1440 and 390, all interactions tested". A post-compaction you then knows what "done" means, not just what the step was called. Mark `in_progress` when starting a step, `completed` only when its verification passed. Never batch-complete at the end.

2. **Write `docs/RUNSHEET.md` in the deliverable repo at the same moment**: the durable twin of the task list. One checkbox per step with an **evidence** line you fill as you go (commit hash, deployed URL, screenshot path). Commit it with each phase's commit. This is the source of truth when the task list and your memory disagree. Write excusable unchecked lines so a reader can parse them: `skipped: <why>`, `BLOCKER-AHEAD: <credential> blocks <step> (owner: <who>)`, `pending`, `deferred`, `n/a`. A naked unchecked box is an unfinished run.

3. **After ANY compaction: re-read `docs/RUNSHEET.md` and the task list BEFORE resuming work.** The summary you wake up with is lossy. It routinely drops "not yet done" items and optional-but-authorized steps (real incident: the final step of a multi-day run was silently skipped across two compactions and nobody noticed until the user asked days later). The runsheet is what you promised; the summary is what you remember. Trust the runsheet.

4. **The completion report REQUIRES the filled runsheet.** Do not report the run done while any box is unchecked. Either finish the step or list it explicitly as "skipped because <user said so / blocked on X>".

5. **Scope the tasks at authorization time, not discovery time.** When the user's phrasing opts into everything ("go all the way", "everything", "and deploy it"), enumerate ALL downstream steps as tasks immediately. A step that was never written down is a step that compaction will erase.

## Guiding Principles

These are the truths that separate a successful clone from a "close enough" mess. Internalize them. They should inform every decision you make.

### 1. Completeness Beats Speed

Every builder agent must receive **everything** it needs to do its job perfectly: screenshot, exact CSS values, downloaded assets with local paths, real text content, component structure. If a builder has to guess anything (a color, a font size, a padding value) you have failed at extraction. Take the extra minute to extract one more property rather than shipping an incomplete brief.

### 2. Small Tasks, Perfect Results

When an agent gets "build the entire features section," it glosses over details. It approximates spacing, guesses font sizes, and produces something "close enough" but clearly wrong. When it gets a single focused component with exact CSS values, it nails it every time.

Look at each section and judge its complexity. A simple banner with a heading and a button? One agent. A complex section with 3 different card variants, each with unique hover states and internal layouts? One agent per card variant plus one for the section wrapper. When in doubt, make it smaller.

**Complexity budget rule:** If a builder prompt exceeds ~150 lines of spec content, the section is too complex for one agent. Break it into smaller pieces. This is a mechanical check. Do not override it with "but it's all related."

### 3. Real Content, Real Assets

Extract the actual text, images, videos, and SVGs from the live site. This is a clone, not a mockup. Use `element.textContent`, download every `<img>` and `<video>`, extract inline `<svg>` elements as React components. The only time you generate content is when something is clearly server-generated and unique per session.

**Layered assets matter.** A section that looks like one image is often multiple layers: a background watercolor or gradient, a foreground UI mockup PNG, an overlay icon. Inspect each container's full DOM tree and enumerate ALL `<img>` elements and background images within it, including absolutely-positioned overlays. Missing an overlay image makes the clone look empty even if the background is correct.

### 4. Foundation First

Nothing can be built until the foundation exists: global CSS with the target site's design tokens (colors, fonts, spacing), TypeScript types for the content structures, and global assets (fonts, favicons). This is sequential and non-negotiable. Everything after this can be parallel.

### 5. Extract How It Looks AND How It Behaves

A website is not a screenshot. It is a living thing. Elements move, change, appear, and disappear in response to scrolling, hovering, clicking, resizing, and time. If you only extract the static CSS of each element, your clone will look right in a screenshot but feel dead when someone actually uses it.

For every element, extract its **appearance** (exact computed CSS via `getComputedStyle()`) AND its **behavior** (what changes, what triggers the change, and how the transition happens). Not "it looks like 16px": extract the actual computed value. Not "the nav changes on scroll": document the exact trigger (scroll position, IntersectionObserver threshold, viewport intersection), the before and after states (both sets of CSS values), and the transition (duration, easing, CSS transition vs. JS-driven vs. CSS `animation-timeline`).

Examples of behaviors to watch for. These are illustrative, not exhaustive. The page may do things not on this list, and you must catch those too:
- A navbar that shrinks, changes background, or gains a shadow after scrolling past a threshold
- Elements that animate into view when they enter the viewport (fade-up, slide-in, stagger delays)
- Sections that snap into place on scroll (`scroll-snap-type`)
- Parallax layers that move at different rates than the scroll
- Hover states that animate (not just change: the transition duration and easing matter)
- Dropdowns, modals, accordions with enter/exit animations
- Scroll-driven progress indicators or opacity transitions
- Auto-playing carousels or cycling content
- Dark-to-light (or any theme) transitions between page sections
- **Tabbed or pill content that cycles**: buttons that switch visible card sets with transitions
- **Scroll-driven tab or accordion switching**: sidebars where the active item auto-changes as content scrolls past (IntersectionObserver, NOT click handlers)
- **Smooth scroll libraries** (Lenis, Locomotive Scroll): check for `.lenis` class or scroll container wrappers

### 6. Identify the Interaction Model Before Building

This is the single most expensive mistake in cloning: building a click-based UI when the original is scroll-driven, or vice versa. Before writing any builder prompt for an interactive section, you must definitively answer: **Is this section driven by clicks, scrolls, hovers, time, or some combination?**

How to determine this:
1. **Do not click first.** Scroll through the section slowly via Playwriter and observe if things change on their own as you scroll.
2. If they do, it is scroll-driven. Extract the mechanism: `IntersectionObserver`, `scroll-snap`, `position: sticky`, `animation-timeline`, or JS scroll listeners.
3. If nothing changes on scroll, THEN click or hover to test for click- or hover-driven interactivity.
4. Document the interaction model explicitly in the component spec: "INTERACTION MODEL: scroll-driven with IntersectionObserver" or "INTERACTION MODEL: click-to-switch with opacity transition."

A section with a sticky sidebar and scrolling content panels is fundamentally different from a tabbed interface where clicking switches content. Getting this wrong means a complete rewrite, not a CSS tweak.

### 7. Extract Every State, Not Just the Default

Many components have multiple visual states: a tab bar shows different cards per tab, a header looks different at scroll position 0 vs 100, a card has hover effects. You must extract ALL states, not just whatever is visible on page load.

For tabbed or stateful content:
- Click each tab or button via Playwriter (`state.page.click(selector)`)
- Extract the content, images, and card data for EACH state
- Record which content belongs to which state
- Note the transition animation between states (opacity, slide, fade, etc.)

For scroll-dependent elements:
- Capture computed styles at scroll position 0 (initial state)
- Scroll past the trigger threshold (`state.page.evaluate(() => window.scrollTo(0, 200))`) and capture computed styles again (scrolled state)
- Diff the two to identify exactly which CSS properties change
- Record the transition CSS (duration, easing, properties)
- Record the exact trigger threshold (scroll position in px, or viewport intersection ratio)

### 8. Spec Files Are the Source of Truth

Every component gets a specification file in `docs/research/components/` BEFORE any builder is dispatched. This file is the contract between your extraction work and the builder agent. The builder receives the spec file contents inline in its prompt. The file also persists as an auditable artifact that the user (or you) can review if something looks wrong.

The spec file is not optional. It is not a nice-to-have. If you dispatch a builder without first writing a spec file, you are shipping incomplete instructions based on whatever you can remember from a Playwriter session, and the builder will guess to fill gaps.

### 9. Build Must Always Compile

Every builder agent must verify `npx tsc --noEmit` passes before finishing. After merging worktrees, you verify `npm run build` passes. A broken build is never acceptable, even temporarily.

## Playwriter Mechanics Cheatsheet (PowerShell)

Every Playwriter command needs `-s <SID>` (substitute the integer returned by `playwriter session new`). The `state` object on the JS side persists across calls within the same session. Store the page there so you do not lose it.

**Critical PowerShell quoting rules:**
- For single-line JS: use **single quotes** around the `-e` argument. Do not worry about `$` inside; PowerShell does not expand inside `'...'`.
- For multi-line JS: use a **single-quoted here-string** `@'...'@`. The closing `'@` **MUST be at column 0** (no leading whitespace) on its own line, or PowerShell throws a parse error.
- Never use `@"..."@` (double-quoted here-string) for JS. `$` characters inside would get interpolated.

**Navigate and persist the page:**
```powershell
playwriter -s <SID> -e 'state.page = await context.newPage(); await state.page.goto("https://example.com", { waitUntil: "networkidle" })'
```

**Take a full-page screenshot:**
```powershell
playwriter -s <SID> -e 'await state.page.screenshot({ path: "docs/design-references/desktop-full.png", fullPage: true })'
```

**Change viewport:**
```powershell
playwriter -s <SID> -e 'await state.page.setViewportSize({ width: 1440, height: 900 })'
playwriter -s <SID> -e 'await state.page.setViewportSize({ width: 390, height: 844 })'
```

**Scroll programmatically:**
```powershell
playwriter -s <SID> -e 'await state.page.evaluate(() => window.scrollTo({ top: 0, behavior: "instant" }))'
playwriter -s <SID> -e 'await state.page.evaluate(() => window.scrollTo({ top: 1000, behavior: "instant" }))'
```

**Click, hover:**
```powershell
playwriter -s <SID> -e 'await state.page.click("button.tab-pricing")'
playwriter -s <SID> -e 'await state.page.hover(".card-feature")'
```

**Run a non-trivial JS extraction (single-quoted here-string):**
```powershell
playwriter -s <SID> -e @'
const data = await state.page.evaluate(() => {
  // any browser-context JS here
  return { fonts: [...new Set([...document.querySelectorAll('*')].slice(0, 200).map(el => getComputedStyle(el).fontFamily))] };
});
console.log(JSON.stringify(data, null, 2));
'@
```

**Write extraction output to a file for later use:**
```powershell
playwriter -s <SID> -e @'
const data = await state.page.evaluate(() => { /* ... */ });
require('node:fs').writeFileSync('docs/research/assets.json', JSON.stringify(data, null, 2));
console.log('Wrote', Object.keys(data).length, 'keys');
'@
```

**Session reset if browser connection goes stale:**
```powershell
playwriter session reset <SID>
```

**List active sessions** (when in doubt which `<SID>` to use):
```powershell
playwriter session list
```

## Field Notes (incident-born)

Hard-won gotchas from real clones. Read before starting; they save hours.

**If you drive Playwriter via the `mcp__playwriter__execute` MCP tool instead of the CLI** (cleaner; avoids PowerShell's native-arg quote-stripping that mangles `goto("https://…")` into a syntax error):
- Scope: `{page, state, context}` are in scope. **Only `state.*` persists between calls.** Local `const`/`let` are gone next call. Store results on `state`, then read them back with a *bare trailing expression* (`JSON.stringify(state.x)`). Multi-statement snippets often return nothing; a single trailing expression returns its value.
- **No `//` line comments.** The tool wraps your code on one line inside `(async()=>{…})()`, so `//` comments out the closing braces and you get "Unexpected end of input". Use `/* */` or none.
- **`require('node:fs')` is sandboxed** to the relay's working directory. Absolute paths into a deeper project subdir throw `EPERM: access outside allowed directories`, but **relative paths resolved under that root WORK**. `page.screenshot({path})` / `locator.screenshot({path})` are **NOT** sandboxed; they write anywhere. Exploit this: serialize each section's cleaned HTML to disk via relative `fs` writes and screenshots to absolute paths, so extraction never bloats your context.

**Downloading assets from a Next.js / SPA target:**
- Direct subdirectory static URLs (`/problems/tabs.png`) frequently return the **SPA HTML shell** (identical ~4KB files for every "image") instead of the asset: a routing catch-all. Tell: every PNG is the same byte size and starts with `<!DOCTYPE html>`. Root-level assets (logos, og-image, favicon) usually DO resolve directly.
- Get the real raster via the optimizer: `https://<host>/_next/image?url=%2Fpath%2Ffile.png&w=1200&q=75` with a browser `User-Agent` + `Accept: image/webp`. **`q` must be allowed** (default 75; `q=90` gives HTTP 400). Returns WebP. SVGs are not served by the optimizer: fetch root-level ones directly; sub-path SVGs may just be broken on the original (check `naturalWidth===0`).

**When the target is itself Tailwind/shadcn (very common):** the DOM class names ARE the spec. Extract the site's `:root`/`@theme` CSS custom properties (often shadcn token names: `--background`, `--primary`, `--sidebar`, customs) for an exact palette, then serialize each section's **cleaned outerHTML** (de-proxy `_next/image` srcs to local `/public` paths, strip `data-*`, **absolutize root-relative `href`s to the original domain** per Scope Defaults, keep inline SVGs in place) to disk and hand builders that markup: near 1:1 JSX conversion, no hand-measuring. (Remember data-array hrefs render via `href={x.href}` and will not show up in an `href="` grep. Check both.) **Extract the real heading-font utility** (on one clone it was a custom `font-display` mapped to Instrument Serif, NOT `font-serif`); if you do not define that exact utility token in your `@theme`, every heading silently falls back to the body font.

**Builders without worktrees:** git worktrees do not carry `node_modules` (gitignored), so per-worktree `tsc` fails. For a JS project it is simpler and faster to dispatch parallel builders that each create ONE disjoint component file in the shared dir (shared `node_modules`), forbid them from running `npm/tsc/vite` (concurrent runs see each other's half-written files), and run ONE authoritative `npm run build` yourself after they return. Disjoint files = zero merge conflicts. Worked first try for 13 components.

**Phase 5 QA with the dev server running:** Vite's HMR websocket never goes network-idle, which makes `mcp__playwriter__execute` calls with trailing `evaluate`/return hang or time out, but the `screenshot({path})` inside them still lands on disk first. So: keep each QA call to a single screenshot op and `Read` the file from disk (ignore the timeout). Avoid `waitUntil:"networkidle"` on the clone; use `domcontentloaded` + a fixed wait. **Full-page screenshots of very tall mobile pages** can fail with "Unable to capture screenshot" (exceeds capture limits). Capture viewport crops at scroll positions instead, or reset the connection.

**Playwriter bakes its own UI into screenshots.** Because it drives the user's real Chrome, its injected elements are part of the page: the ghost cursor (`#__playwriter_ghost_cursor__`) and a floating toolbar (an unnamed `position:fixed` div at z-index 2147483647, direct child of `<html>`) appear in every capture, plus any third-party extension nodes. Fine for your own QA reads; NOT fine for screenshots that ship in a deliverable. Before deliverable captures, inject once per navigation:
```js
await page.addStyleTag({ content: '#__playwriter_ghost_cursor__, html > div { display:none !important } html, body { scrollbar-width:none !important } ::-webkit-scrollbar { display:none !important }' })
```
(`html > div` is safe. React mounts in `#root` under `<body>`; only injected overlays live as direct `<html>` children.)

**Do not screenshot with `animations: "disabled"` on pages using enter animations (framer-motion Reveal etc.).** It freezes animations at their INITIAL state, opacity ~0, so sections render as washed-out ghosts. Correct pattern for deliverable captures: let animations run, wait 2 to 3 s after `networkidle`, then screenshot. Reserve `animations: "disabled"` for pages with *infinite* animations (counters, pulsing dots) that never settle, and eyeball the result.

## Phase 1: Reconnaissance

Navigate to the target URL with Playwriter (using the snippet above to assign `state.page`).

### Screenshots
- Take **full-page screenshots** at desktop (1440px) and mobile (390px) viewports
- Save to `docs/design-references/` with descriptive names
- These are your master reference. Builders will receive section-specific crops later.

```powershell
# Desktop
playwriter -s <SID> -e 'await state.page.setViewportSize({ width: 1440, height: 900 }); await state.page.screenshot({ path: "docs/design-references/desktop-full.png", fullPage: true })'

# Mobile
playwriter -s <SID> -e 'await state.page.setViewportSize({ width: 390, height: 844 }); await state.page.screenshot({ path: "docs/design-references/mobile-full.png", fullPage: true })'
```

### Global Extraction
Extract these from the page before doing anything else:

**Fonts**: Inspect `<link>` tags for Google Fonts or self-hosted fonts. Check computed `font-family` on key elements (headings, body, code, labels). Document every family, weight, and style actually used. Install via `@fontsource-variable/<name>` packages and import them at the top of `src/index.css`, or add `<link>` tags to `index.html` for Google Fonts CDN delivery.

**Colors**: Extract the site's color palette from computed styles across the page. Update `src/index.css`: add the target's actual colors as OKLCH tokens inside the `:root { ... }` and `.dark { ... }` blocks. Map them to shadcn's token names (`--background`, `--foreground`, `--primary`, `--muted`, etc.) where they fit. Add custom `--<name>` properties for colors that do not map to shadcn tokens. Prefer OKLCH (e.g., `oklch(0.48 0.24 300)`) over hex; convert hex to OKLCH if needed.

**Favicons & Meta**: Download the TARGET site's favicons, apple-touch-icons, OG image, and webmanifest to `public/seo/`, and update `<link rel="icon">`, `<meta>`, and `<title>` in `index.html`. **ALWAYS also ship a real `/favicon.ico` at the `public/` root and link it FIRST** (`<link rel="icon" href="/favicon.ico" sizes="any">` + `<link rel="shortcut icon" href="/favicon.ico">`, then the PNG `<link>`s). This is non-negotiable and incident-born ("you are inheriting the logo of the wrong company"): browsers **hard-request `/favicon.ico` before parsing HTML**, and PNG-only `<link>`s do NOT satisfy that request. When it 404s, Chrome silently shows whatever favicon it cached for that origin, **and every clone reuses the same `localhost:xxxx` and `*.pages.dev` origins, so the tab shows a PREVIOUS project's logo.** How to get the real `.ico`: most WordPress/CMS sites serve their site-icon at `/favicon.ico` (often `200 image/png`), so fetch that; otherwise wrap the 32x32 PNG in a minimal ICO (6-byte ICONDIR `00 00 01 00 01 00` + 16-byte dir entry + the PNG bytes; browsers accept PNG-in-ICO). Confirm the icon is genuinely the cloned brand (open the PNG and look), and verify post-deploy with `fetch('/favicon.ico')` returning 200 + real byte count.

**Global UI patterns**: Identify any site-wide CSS or JS: custom scrollbar hiding, scroll-snap on the page container, global keyframe animations, backdrop filters, gradients used as overlays, **smooth scroll libraries** (Lenis, Locomotive Scroll: check for `.lenis`, `.locomotive-scroll`, or custom scroll container classes). Add these to `src/index.css` and note any libraries that need to be installed.

### Mandatory Interaction Sweep

This is a dedicated pass AFTER screenshots and BEFORE anything else. Its purpose is to discover every behavior on the page, many of which are invisible in a static screenshot.

**Scroll sweep:** Scroll the page slowly from top to bottom via Playwriter. At each section, pause and observe:
- Does the header change appearance? Record the scroll position where it triggers.
- Do elements animate into view? Record which ones and the animation type.
- Does a sidebar or tab indicator auto-switch as you scroll? Record the mechanism.
- Are there scroll-snap points? Record which containers.
- Is there a smooth scroll library active? Check for non-native scroll behavior.

A useful one-shot scroll sweep that captures header CSS at intervals:

```powershell
playwriter -s <SID> -e @'
const samples = [];
for (const y of [0, 100, 300, 600, 1200, 2400]) {
  await state.page.evaluate((y) => window.scrollTo({ top: y, behavior: 'instant' }), y);
  await new Promise(r => setTimeout(r, 400));
  const headerCss = await state.page.evaluate(() => {
    const header = document.querySelector('header, nav, [role="banner"]');
    if (!header) return null;
    const cs = getComputedStyle(header);
    return { backgroundColor: cs.backgroundColor, boxShadow: cs.boxShadow, height: cs.height, backdropFilter: cs.backdropFilter, transform: cs.transform };
  });
  samples.push({ scrollY: y, headerCss });
}
console.log(JSON.stringify(samples, null, 2));
'@
```

**Click sweep:** Click every element that looks interactive:
- Every button, tab, pill, link, card
- Record what happens: does content change? Does a modal open? Does a dropdown appear?
- For tabs and pills: click EACH ONE and record the content that appears for each state

**Hover sweep:** Hover over every element that might have hover states:
- Buttons, cards, links, images, nav items
- Record what changes: color, scale, shadow, underline, opacity

**Responsive sweep:** Test at 3 viewport widths via Playwriter:
- Desktop: 1440px
- Tablet: 768px
- Mobile: 390px
- At each width, note which sections change layout (columns to stack, sidebar disappears, etc.) and at approximately which breakpoint the change occurs.

Save all findings to `docs/research/BEHAVIORS.md`. This is your behavior bible. Reference it when writing every component spec.

### Page Topology
Map out every distinct section of the page from top to bottom. Give each a working name. Document:
- Their visual order
- Which are fixed or sticky overlays vs. flow content
- The overall page layout (scroll container, column structure, z-index layers)
- Dependencies between sections (e.g., a floating nav that overlays everything)
- **The interaction model** of each section (static, click-driven, scroll-driven, time-driven)

Save this as `docs/research/PAGE_TOPOLOGY.md`. It becomes your assembly blueprint.

## Phase 2: Foundation Build

This is sequential. Do it yourself (not delegated to an agent) since it touches many files:

1. **Wire up fonts**: install `@fontsource-variable/<name>` packages (or add `<link>` tags to `index.html`) and import them at the top of `src/index.css`. Match every family, weight, and style observed on the target.
2. **Update `src/index.css`** with the target's OKLCH color tokens (in `:root` and `.dark` blocks), spacing values, keyframe animations, utility classes, and any **global scroll behaviors** (Lenis, smooth scroll CSS, scroll-snap on body)
3. **Create TypeScript interfaces** in `src/types/` for the content structures you have observed
4. **Extract SVG icons**: find all inline `<svg>` elements on the page, deduplicate them, and save as named React components in `src/components/icons.tsx`. Name them by visual function (e.g., `SearchIcon`, `ArrowRightIcon`, `LogoIcon`).
5. **Download global assets**: write and run a Node.js script (`scripts/download-assets.mjs`) that downloads all images, videos, and other binary assets from the page to `public/`. Preserve meaningful directory structure.
6. Verify: `npm run build` passes

### Asset Discovery Script (run via Playwriter)

```powershell
playwriter -s <SID> -e @'
const inventory = await state.page.evaluate(() => ({
  images: [...document.querySelectorAll('img')].map(img => ({
    src: img.src || img.currentSrc,
    alt: img.alt,
    width: img.naturalWidth,
    height: img.naturalHeight,
    parentClasses: img.parentElement?.className,
    siblings: img.parentElement ? [...img.parentElement.querySelectorAll('img')].length : 0,
    position: getComputedStyle(img).position,
    zIndex: getComputedStyle(img).zIndex
  })),
  videos: [...document.querySelectorAll('video')].map(v => ({
    src: v.src || v.querySelector('source')?.src,
    poster: v.poster,
    autoplay: v.autoplay,
    loop: v.loop,
    muted: v.muted
  })),
  backgroundImages: [...document.querySelectorAll('*')].filter(el => {
    const bg = getComputedStyle(el).backgroundImage;
    return bg && bg !== 'none';
  }).map(el => ({
    url: getComputedStyle(el).backgroundImage,
    element: el.tagName + '.' + (el.className?.toString().split(' ')[0] || '')
  })),
  svgCount: document.querySelectorAll('svg').length,
  fonts: [...new Set([...document.querySelectorAll('*')].slice(0, 200).map(el => getComputedStyle(el).fontFamily))],
  favicons: [...document.querySelectorAll('link[rel*="icon"]')].map(l => ({ href: l.href, sizes: l.sizes?.toString() }))
}));
require('node:fs').writeFileSync('docs/research/asset-inventory.json', JSON.stringify(inventory, null, 2));
console.log('Inventory:', inventory.images.length, 'images,', inventory.videos.length, 'videos,', inventory.backgroundImages.length, 'bg-images,', inventory.svgCount, 'svgs');
'@
```

Then write a download script that fetches everything to `public/`. Use batched parallel downloads (4 at a time) with proper error handling.

## Phase 3: Component Specification & Dispatch

This is the core loop. For each section in your page topology (top to bottom), you do THREE things: **extract**, **write the spec file**, then **dispatch builders**.

### Step 1: Extract

For each section, use Playwriter to extract everything:

1. **Screenshot** the section in isolation. Scroll the section into view, then screenshot the viewport (or a clipped region). Save to `docs/design-references/`.

   ```powershell
   playwriter -s <SID> -e 'await state.page.locator("section.hero").scrollIntoViewIfNeeded(); await state.page.screenshot({ path: "docs/design-references/hero.png", clip: await state.page.locator("section.hero").boundingBox() })'
   ```

2. **Extract CSS** for every element in the section. Use the extraction script below. Do not hand-measure individual properties. Run it once per component container and capture the full output (substitute `SELECTOR_HERE`):

   ```powershell
   playwriter -s <SID> -e @'
   const tree = await state.page.evaluate((selector) => {
     const el = document.querySelector(selector);
     if (!el) return { error: 'Element not found: ' + selector };
     const props = [
       'fontSize','fontWeight','fontFamily','lineHeight','letterSpacing','color',
       'textTransform','textDecoration','backgroundColor','background',
       'padding','paddingTop','paddingRight','paddingBottom','paddingLeft',
       'margin','marginTop','marginRight','marginBottom','marginLeft',
       'width','height','maxWidth','minWidth','maxHeight','minHeight',
       'display','flexDirection','justifyContent','alignItems','gap',
       'gridTemplateColumns','gridTemplateRows',
       'borderRadius','border','borderTop','borderBottom','borderLeft','borderRight',
       'boxShadow','overflow','overflowX','overflowY',
       'position','top','right','bottom','left','zIndex',
       'opacity','transform','transition','cursor',
       'objectFit','objectPosition','mixBlendMode','filter','backdropFilter',
       'whiteSpace','textOverflow','WebkitLineClamp'
     ];
     const extractStyles = (element) => {
       const cs = getComputedStyle(element);
       const styles = {};
       props.forEach(p => { const v = cs[p]; if (v && v !== 'none' && v !== 'normal' && v !== 'auto' && v !== '0px' && v !== 'rgba(0, 0, 0, 0)') styles[p] = v; });
       return styles;
     };
     const walk = (element, depth) => {
       if (depth > 4) return null;
       const children = [...element.children];
       return {
         tag: element.tagName.toLowerCase(),
         classes: element.className?.toString().split(' ').slice(0, 5).join(' '),
         text: element.childNodes.length === 1 && element.childNodes[0].nodeType === 3 ? element.textContent.trim().slice(0, 200) : null,
         styles: extractStyles(element),
         images: element.tagName === 'IMG' ? { src: element.src, alt: element.alt, naturalWidth: element.naturalWidth, naturalHeight: element.naturalHeight } : null,
         childCount: children.length,
         children: children.slice(0, 20).map(c => walk(c, depth + 1)).filter(Boolean)
       };
     };
     return walk(el, 0);
   }, 'SELECTOR_HERE');
   require('node:fs').writeFileSync('docs/research/components/SELECTOR_HERE.json', JSON.stringify(tree, null, 2));
   console.log('Extracted', JSON.stringify(tree).length, 'bytes');
   '@
   ```

3. **Extract multi-state styles**: for any element with multiple states (scroll-triggered, hover, active tab), capture BOTH states by triggering the state change between extractions:

   ```powershell
   # State A: capture
   playwriter -s <SID> -e 'await state.page.evaluate(() => window.scrollTo(0, 0))'
   # ... run extraction script, save as state-a.json

   # Trigger transition (choose one)
   playwriter -s <SID> -e 'await state.page.evaluate(() => window.scrollTo(0, 500))'
   # OR: playwriter -s <SID> -e 'await state.page.click("button.tab-pricing")'
   # OR: playwriter -s <SID> -e 'await state.page.hover(".card-feature")'

   # Wait for CSS transitions to finish before re-extracting
   playwriter -s <SID> -e 'await new Promise(r => setTimeout(r, 600))'

   # State B: capture
   # ... run extraction script, save as state-b.json
   ```

   Record the diff explicitly: "Property X changes from VALUE_A to VALUE_B, triggered by TRIGGER, with transition: TRANSITION_CSS."

4. **Extract real 

…(truncated)
