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"becomeshref="https://<original-host>/x", including/#anchorlinks, the logo'shref="/", andhref="#"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
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.Create a Playwriter session and capture the ID. Each
playwritercall needs-s <ID>to share state across calls: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.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:
Start-Process chrome.exe -ArgumentList '--profile-directory=Default --allowlisted-extension-id=jfeammnjpkecdekppnclgkkffahnhfhe --auto-accept-this-tab-capture'
Parse
$ARGUMENTSas 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>andURL_HERE):playwriter -s <SID> -e 'state.page = await context.newPage(); await state.page.goto("URL_HERE", { waitUntil: "networkidle" }); await state.page.title()'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.jsonover this list) - UI: shadcn/ui + Tailwind CSS v4 (OKLCH design tokens) + Framer Motion
- Routing: React Router
- Hosting: Cloudflare Pages (
npm run buildproducesdist/; deploy vianpx wrangler pages deploy dist --project-name <name> --branch main. The--branch mainis NOT optional, see Deploy safety. Alwaysnpx 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, metasrc/main.tsx: React entry; imports./index.csssrc/App.tsx: router rootsrc/index.css: Tailwind v4 entry. Importstailwindcss,shadcn/tailwind.css, font packages, and defines OKLCH design tokens inside:root { ... }and.dark { ... }blocks.src/pages/Home.tsx: the cloned page goes here (orsrc/App.tsxif no routing)src/components/: section components andicons.tsxsrc/types/: content interfacespublic/: downloaded images, videos, favicons (inpublic/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.- Framework: Vite + React + TypeScript strict (versions drift; trust the scaffold's
Create the output directories if they do not exist:
docs/research/,docs/research/components/,docs/design-references/,scripts/. 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>/anddocs/design-references/<hostname>/.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 theirstate.pagereferences do not collide. Track each site's<SID>separately.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.mdasBLOCKER-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 whoamisucceeds; if multiple accounts,CLOUDFLARE_ACCOUNT_IDis set; target Pages project name checked againstpages 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:
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. Markin_progresswhen starting a step,completedonly when its verification passed. Never batch-complete at the end.Write
docs/RUNSHEET.mdin 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.After ANY compaction: re-read
docs/RUNSHEET.mdand 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.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>".
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
.lenisclass 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:
- Do not click first. Scroll through the section slowly via Playwriter and observe if things change on their own as you scroll.
- If they do, it is scroll-driven. Extract the mechanism:
IntersectionObserver,scroll-snap,position: sticky,animation-timeline, or JS scroll listeners. - If nothing changes on scroll, THEN click or hover to test for click- or hover-driven interactivity.
- 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
-eargument. 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:
playwriter -s <SID> -e 'state.page = await context.newPage(); await state.page.goto("https://example.com", { waitUntil: "networkidle" })'
Take a full-page screenshot:
playwriter -s <SID> -e 'await state.page.screenshot({ path: "docs/design-references/desktop-full.png", fullPage: true })'
Change viewport:
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:
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:
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):
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:
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:
playwriter session reset <SID>
List active sessions (when in doubt which <SID> to use):
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. Onlystate.*persists between calls. Localconst/letare gone next call. Store results onstate, 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 throwEPERM: 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 relativefswrites 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=75with a browserUser-Agent+Accept: image/webp.qmust be allowed (default 75;q=90gives 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 (checknaturalWidth===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 hrefs 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:
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.
# 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:
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:
- Wire up fonts: install
@fontsource-variable/<name>packages (or add<link>tags toindex.html) and import them at the top ofsrc/index.css. Match every family, weight, and style observed on the target. - Update
src/index.csswith the target's OKLCH color tokens (in:rootand.darkblocks), spacing values, keyframe animations, utility classes, and any global scroll behaviors (Lenis, smooth scroll CSS, scroll-snap on body) - Create TypeScript interfaces in
src/types/for the content structures you have observed - Extract SVG icons: find all inline
<svg>elements on the page, deduplicate them, and save as named React components insrc/components/icons.tsx. Name them by visual function (e.g.,SearchIcon,ArrowRightIcon,LogoIcon). - 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 topublic/. Preserve meaningful directory structure. - Verify:
npm run buildpasses
Asset Discovery Script (run via Playwriter)
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:
Screenshot the section in isolation. Scroll the section into view, then screenshot the viewport (or a clipped region). Save to
docs/design-references/.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() })'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):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'); '@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:
# 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.jsonRecord the diff explicitly: "Property X changes from VALUE_A to VALUE_B, triggered by TRIGGER, with transition: TRANSITION_CSS."
**Extract real
…(truncated)