Skip to content

Clone any website into a pixel-accurate Next.js app with AI — Playwright-measured extraction (no eyeballing), spec-gated parallel builder agents, and scored pixel-diff QA at phone/tablet/desktop. Works with Claude Code, Cursor, Copilot + 9 more.

feat(specs): spec-scaffold.mjs generates mechanical spec sections from extraction JSON (T1)

Mahanaicoachd34f993c9e6d
diff --git a/.amazonq/cli-agents/clone-website.json b/.amazonq/cli-agents/clone-website.json
index 49404b9..8e76b9b 100644
--- a/.amazonq/cli-agents/clone-website.json
+++ b/.amazonq/cli-agents/clone-website.json
@@ -1,7 +1,7 @@
{
"name": "clone-website",
"description": "Reverse-engineer and clone a full multi-page website as a pixel-accurate Next.js replica",
- "prompt": "# Clone Website\n\nReverse-engineer and rebuild **the target URL (plus any extra instructions) provided by the user** as a pixel-accurate, multi-page Next.js clone.\n\nYou are a **foreman walking the job site**: scripts do the measuring, you do the judgment, specs are the contract, builder agents do the construction, and the pixel-diff score decides when you're done. Extraction and construction overlap — dispatch builders as soon as a section's spec passes lint, then keep extracting.\n\n## Resume Check (ALWAYS FIRST)\n\n```bash\nnode scripts/manifest.mjs status\n```\n\nIf a manifest exists, this is a **resumed run**: skip everything already done (`node scripts/manifest.mjs next` tells you where to continue). If not, this is a fresh run — start at Phase 0.\n\n## Scope Defaults\n\n- **Fidelity:** pixel-accurate — colors, spacing, typography, animations, interactions\n- **In scope:** every confirmed page, visual layout, component structure, interactions, responsive behavior (phone 390 / iPad 768 / PC 1440), real content and assets\n- **Out of scope:** real backend, auth, databases, forms that actually submit (mock them)\n- **Content goes in `src/data/*.ts`** — components take props; page files wire data to components. This keeps the clone restylable later (see `/restyle`).\n\nUser-provided instructions override these defaults.\n\n## Tooling\n\nThe scripts do the mechanical work — **use them instead of hand-measuring via browser MCP**:\n\n| Script | Purpose |\n|---|---|\n| **`node scripts/extract/page.mjs <url> [--no-site-files]`** | **THE WORKHORSE — one call, 3 page loads total.** Auto-detects sections, then produces `tokens.json` + `css.json` (skip on later pages with `--no-site-files`), `assets.json` + downloads to `public/`, `responsive.json` (all 3 viewports), a full computed-style walk per section (`sections/<name>.json`), and full-page **and** per-section screenshots at phone/iPad/PC. Accepts explicit `--selector \"css\" --name x` pairs to override detection. Everything is measured from the SAME page state, so numbers, walks and screenshots can never disagree |\n| `node scripts/extract/crawl.mjs <url> [--max 25]` | Discover pages (sitemap + nav links) → `docs/research/<host>/sitemap.json` |\n| `node scripts/extract/section.mjs <url> --selector \"css\" [--name x] --state scroll:600\\|click:sel\\|hover:sel [--viewport pc\\|ipad\\|phone]` | **State captures** (page.mjs covers the default state). Captures a second state and diffs them (element styles *and* `::before`/`::after`), waiting for the section's real transition duration. `--selector`/`--name` repeat — one page load for all |\n| `node scripts/extract/probe.mjs <url> --selector \"css\" [--selector \"css2\"] [--props a,b,c]` / `probe.mjs --route </r>` | Exact computed values for specific selectors at all 3 viewports, as a markdown table with a **varies** column — paste straight into a spec's Responsive section. **`--route` probes EVERY registered section of a page in one call (3 loads total, plus a `probe-<section>.json` per section) — never probe section-by-section** |\n| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |\n| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |\n| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |\n| `node scripts/lint-spec.mjs <spec.md\\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |\n| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |\n\nBrowser MCP (Chrome MCP, Playwright MCP — if available) is for **judgment work only**: watching how the page behaves while scrolling, exploring what's clickable, understanding an animation. Numbers always come from the scripts. If no browser MCP is available, the scripts alone are sufficient — use extra `screenshot.mjs` and `section.mjs --state` calls to observe behavior.\n\nThe scripts are plain Node CLIs — any coding agent can run them. Playwright's Chromium auto-installs on the first script run (or run `npm run setup` once). If your tool has no subagent/worktree support, skip the dispatch mechanics and build each section yourself, sequentially, from the same lint-passing specs — every quality gate still applies.\n\n## Guiding Principles\n\n1. **Completeness beats speed.** A builder that has to guess a color, font size, or padding value means extraction failed. Extract one more property rather than ship an incomplete spec.\n2. **Small tasks, perfect results.** One focused component per builder. Spec body over 150 lines = split the section (lint-spec enforces this).\n3. **Real content, real assets.** Actual text via the section walker, actual files via `assets.mjs`. Watch for **layered images** — a hero that looks like one image is often background + overlay + foreground; `assets.json` records sibling counts and z-index for exactly this reason.\n4. **Foundation first.** Tokens, fonts, types, icons, and shared chrome (header/footer) before any page section.\n5. **Extract how it looks AND how it behaves.** Every interactive element needs before/after states with exact values — `section.mjs --state` produces the diff mechanically.\n6. **Identify the interaction model before building.** Scroll-driven vs click-driven confusion is the most expensive mistake in cloning — a wrong call means a rewrite, not a CSS fix. Scroll first without clicking and watch; only then click. Record the model in the spec frontmatter.\n7. **Responsive is measured, never guessed — at all three widths.** Fill every spec's Responsive section from `responsive.json` + `probe.mjs`, with real numbers for phone AND iPad AND pc. Never write \"iPad: same as desktop\": most production sites step their root font-size at breakpoints, so *every* padding, margin, and font size changes even when the layout looks identical. A spec that only nails desktop produces a clone that scores ~98% at 1440px and ~91% at 390px. `lint-spec.mjs` rejects vague responsive sections.\n\n8. **The extraction JSON is ground truth; the spec is a summary of it.** If a builder finds the spec disagreeing with `sections/<name>.json` or `responsive.json`, the JSON wins — say so explicitly in every builder prompt and have the builder report the discrepancy so you can correct the spec.\n9. **Spec files are the contract.** No spec → no builder. lint-spec must pass → then dispatch.\n10. **The build must always compile.** Builders verify `npx tsc --noEmit`; you verify `npm run typecheck && npm run lint` after every merge. Full `npm run build` runs only at checkpoints (Phase 0, end of Phase 2, once mid-way through Phase 3, Phase 4, completion) — it takes 30–60s and running it per merge serializes otherwise-parallel builders.\n11. **The manifest is updated at every stage transition.** That's what makes the run resumable.\n\n## Phase 0 — Crawl & Scope\n\n1. Verify the base builds: `npm run build`.\n2. `node scripts/extract/crawl.mjs <url> --max 25`\n3. Show the user the discovered pages (route + source). **Ask which to clone** — recommend: start page + nav pages, skip legal/utility pages unless asked. Default cap ~10.\n4. Initialize state:\n ```bash\n node scripts/manifest.mjs init <url>\n node scripts/manifest.mjs add-page --url <url> --route / # per confirmed page\n ```\n\n## Phase 1 — Recon (one page.mjs call per page)\n\n1. **First page:** `node scripts/extract/page.mjs <start-url>` — produces tokens, css, assets+downloads, responsive signatures, per-section walks, and every screenshot in one shot (3 page loads).\n2. **Every other confirmed page:** `node scripts/extract/page.mjs <url> --no-site-files` (tokens/css are site-wide; everything else is per-page). Downloads dedupe across pages automatically — files already in `public/` are skipped.\n3. **Review the detected sections** in each run's stdout summary (name, selector, pc height, headline responsive change). Detection is a heuristic: if a \"section\" is really two, or two are really one, re-run with explicit `--selector \"css\" --name x` pairs. Section names become spec/component names — rename `section-3` style fallbacks to something meaningful via `--name`.\n4. **Interaction sweep** (judgment work — browser MCP if available): scroll each page slowly top to bottom. Does the header change? Do elements animate in? Auto-switching tabs? Scroll-snap? Smooth-scroll lib (`tokens.json` flags `.lenis`/Locomotive)? Then click every tab/pill/accordion and note what changes. Then hover. `css.json`'s `interactiveStates` lists every :hover/:focus rule the stylesheet defines — use it as the checklist of what to probe. Record findings in `docs/research/<host>/BEHAVIORS.md`.\n5. **Shared chrome detection:** compare screenshots across pages — header/nav/footer that repeat become SHARED components (`SiteHeader`, `SiteFooter`), extracted once from the page where they're most complete.\n\n**Per page — topology:** map every distinct section top to bottom with a working name, its selector, its interaction model (static / click-driven / scroll-driven / hover-driven / time-driven / mixed), and layer notes (sticky? overlay? z-index?). Save `docs/research/<host>/PAGE_TOPOLOGY.md`, then register each section:\n```bash\nnode scripts/manifest.mjs add-section --route / --name hero --selector \"section.hero\"\n```\n\n## Phase 2 — Foundation (sequential, you do it yourself)\n\n1. **Fonts** in `src/app/layout.tsx` via `next/font/google` or `next/font/local` (downloaded fonts are in `public/fonts/`) — families/weights from `tokens.json`\n2. **`globals.css`**: map the target's palette onto the shadcn `:root` token names; add custom properties for colors that don't map; add global keyframes, scroll-snap, smooth-scroll setup found in recon\n3. **TypeScript interfaces** in `src/types/` for the content structures you observed\n4. **Icons**: convert the deduplicated `inlineSvgs` from `assets.json` into named components in `src/components/icons.tsx` (named by function: `LogoIcon`, `ArrowRightIcon`…)\n5. **SEO**: favicons/OG from `public/seo/` wired into `layout.tsx` metadata\n6. Verify `npm run build`, then build **shared chrome** (header/footer) first — full spec → lint → builder cycle like any section, since every page depends on them.\n\n## Phase 3 — Per-Section Loop (extract → spec → lint → dispatch → merge)\n\nWork through `manifest.mjs next` until no sections remain. For each section:\n\n### 3a. Extract\n\n**The default state is already extracted** — Phase 1's page.mjs run wrote\n`sections/<name>.json`, `responsive.json`, and all screenshots.\n\n**First time you enter Phase 3 for a page, probe ALL its sections in ONE call** (3\npage loads total instead of 3 per section — never probe section-by-section):\n\n```bash\nnode scripts/extract/probe.mjs --route <r> # every registered section + probe-<section>.json each\n# add key children in the same call when a spec will need them:\nnode scripts/extract/probe.mjs --route <r> --selector \"<sel> h2\" --selector \"<sel> .card\"\n```\n\nSlice the per-section tables into each spec's Responsive section as you write it.\nPer section, only one thing remains:\n\n```bash\n# Per discovered behavior — one call per state (batch selectors sharing a trigger):\nnode scripts/extract/section.mjs <page-url> --selector \"<sel>\" --name <name>-hover --state hover:\".card\"\nnode scripts/extract/section.mjs <page-url> --selector \"<sel>\" --name <name>-scrolled --state scroll:600\n# per tab/pill state: --state click:\".tab-2\" etc. EVERY state, not just the default.\n```\nState captures wait for the section's actual transition duration, so a slow fade is\nrecorded at its end value, not mid-flight — check `settleMs` in the output if a diff\nlooks wrong. The `diff` array covers `::before`/`::after` too, which is where hover\noverlays usually live. Cross-check discovered behaviors against `css.json`'s\n`interactiveStates` — a :hover rule in the stylesheet with no captured state means\nthe extraction is not done.\n\nMark: `manifest.mjs set --route <r> --section <name> --stage extracted`\n\n### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`\n\n```markdown\n---\ncomponent: HeroSection\ntarget: src/components/HeroSection.tsx\npage: /\nscreenshot: docs/design-references/<host>/<name>-pc.png\ninteraction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed\nstates: default, hover, scrolled…\nassets: public/images/x.webp, icons:ArrowRightIcon\nresponsive: phone, ipad, pc\n---\n\n# <Component> Specification\n\n## DOM Structure\n<hierarchy from the section walker — what contains what>\n\n## Computed Styles\n<exact values from sections/<name>.json, per element. Never estimated.>\n\n## States & Behaviors\n<per behavior: Trigger / State A / State B / Transition — from the --state diffs.\n Include the implementation approach (CSS transition, IntersectionObserver, etc.)>\n\n## Per-State Content\n<for tabbed/stateful sections: full content per state. \"N/A — static\" otherwise>\n\n## Assets\n<local public/ paths + icon components used. Note layered compositions explicitly.>\n\n## Text Content\n<verbatim from the walker output — never paraphrased>\n\n## Responsive Behavior\n<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>\n```\n\n### 3c. Lint gate\n```bash\nnode scripts/lint-spec.mjs docs/research/components/<route-slug>/<name>.spec.md\n```\nFails → extract more. Passes → `manifest.mjs set … --stage specd` and dispatch.\n\n### 3d. Dispatch builder agent (worktree)\n\nEvery builder receives IN ITS PROMPT (never \"go read the file\"):\n- The **full spec file contents inline**\n- The screenshot paths (all 3 viewports)\n- Shared imports available: `cn()`, `icons.tsx` components, shadcn `ui/` primitives, types from `src/types/`\n- The target file path, and the data file to create in `src/data/` if the section has content collections\n- The rule: verify `npx tsc --noEmit` passes before finishing\n- **The ground-truth rule:** \"`docs/research/<host>/sections/<name>.json` and `responsive.json` are ground truth. If this spec contradicts them, follow the JSON and report the discrepancy.\" Builders reliably catch spec errors this way — treat their reports as corrections to make to the spec file.\n\nComplex section (3+ distinct sub-components) → one builder per sub-component + one for the wrapper, sub-components first. **Don't wait** — while builders run, extract the next section.\n\n### 3e. Merge\nAs builders finish: merge worktree → `npm run typecheck && npm run lint` → fix errors immediately → `manifest.mjs set … --stage merged`. tsc catches the cross-worktree breaks (imports, prop types) that per-merge builds used to catch, in a fraction of the time.\n\n**Once, after roughly half the page's sections are merged: run a full `npm run build` checkpoint.** It catches build-only failures (server/client component violations, route exports, metadata) while they're still cheap to bisect. Don't build after every merge.\n\n## Phase 4 — Page Assembly\n\nPer page: create `src/app/<route>/page.tsx` importing its section components with data from `src/data/`, plus page-level behaviors (scroll-snap, observers, smooth scroll). Shared chrome mounts in `layout.tsx` or a route group layout. Wire internal nav links to the cloned routes. `npm run build` must pass.\n\n## Phase 5 — Scored QA Loop\n\nStart the clone: `npm run dev` (background). Then **score the whole page's sections in ONE batched call** (one load per side per viewport instead of one per section):\n\n```bash\nnode scripts/diff.mjs --original <orig-page-url> --clone http://localhost:3000<route> --route <r> --viewport all\nnode scripts/manifest.mjs set --route <r> --section <name> --score pc=<match> # per section × viewport\n```\n\n**Fix iterations stay single-section** — the original-side shots captured by the sweep are cached, so a re-diff only re-renders the clone:\n\n```bash\nnode scripts/diff.mjs --original <orig-page-url> --clone http://localhost:3000<route> --selector \"<sel>\" --viewport all --name <name>\n```\n\n- **Pass = ≥95% on all three viewports** → `--stage qa_passed`\n- Below 95% → **read the band breakdown first**: it names the y-range where the mismatch lives, so you inspect that band of the diff image in `docs/research/qa/` instead of eyeballing the whole section. Then check the spec (wrong extraction → re-extract and fix; right spec, wrong build → fix component), re-diff\n- A large height mismatch reported by diff.mjs = missing content or wrong spacing — fix before pixel-tweaking\n- Max 3 fix iterations per section, then record the gap honestly and move on\n- **Text-heavy sections at phone width often plateau at 90–95%** when the target's font isn't available on Google Fonts (e.g. Source Sans Pro → Source Sans 3). Different metrics = different wrap points = unavoidable pixel drift. Confirm the layout matches, note the substitution, and accept it.\n- **A score that's high at pc but low at ipad/phone is always a responsive-spec problem**, not a styling bug. Re-run `probe.mjs` on the section and fill in the values the spec was missing.\n- Finally, test behaviors manually: scroll, click every tab, hover — screenshots can't verify motion; you must\n\nWhole-page diffs (`--selector` omitted) at all 3 viewports close out each page.\n\n## What NOT to Do\n\n- **Don't build click-tabs when the original is scroll-driven** (or vice versa). Scroll first, watch, then click. Wrong model = rewrite.\n- **Don't extract only the default state.** Every tab clicked, every hover captured, header at scroll 0 AND past the trigger.\n- **Don't miss layered/overlay images** — check `siblingImgs` and z-index hints in `assets.json`.\n- **Don't build HTML mockups of things that are actually `<video>`, Lottie, or canvas.** Check first.\n- **Don't approximate (\"looks like text-lg\").** Use the walker's exact computed values; use arbitrary values (`text-[17px]`) when Tailwind's scale doesn't match.\n- **Don't dispatch a builder without a lint-passing spec.** No exceptions — that's the whole quality model.\n- **Don't reference docs from builder prompts** — spec contents go inline.\n- **Don't skip the manifest updates.** An untracked run can't resume.\n- **Don't hardcode content in components.** Content → `src/data/`, components take props.\n- **Don't write \"same as desktop\" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.\n- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.\n- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.\n- **Don't declare done without QA scores.** \"Looks right\" is not a number.\n\n## Completion Report\n\n- Pages cloned (routes) · sections built · spec files written (must match section count)\n- Assets downloaded (from `assets.json` download log, including failures)\n- Final QA score table per section × viewport (from `manifest.mjs status`)\n- `npm run build` result\n- Known gaps and any section that couldn't reach 95%\n- Suggest next step: `/restyle` to rebrand the clone with your own identity",
+ "prompt": "# Clone Website\n\nReverse-engineer and rebuild **the target URL (plus any extra instructions) provided by the user** as a pixel-accurate, multi-page Next.js clone.\n\nYou are a **foreman walking the job site**: scripts do the measuring, you do the judgment, specs are the contract, builder agents do the construction, and the pixel-diff score decides when you're done. Extraction and construction overlap — dispatch builders as soon as a section's spec passes lint, then keep extracting.\n\n## Resume Check (ALWAYS FIRST)\n\n```bash\nnode scripts/manifest.mjs status\n```\n\nIf a manifest exists, this is a **resumed run**: skip everything already done (`node scripts/manifest.mjs next` tells you where to continue). If not, this is a fresh run — start at Phase 0.\n\n## Scope Defaults\n\n- **Fidelity:** pixel-accurate — colors, spacing, typography, animations, interactions\n- **In scope:** every confirmed page, visual layout, component structure, interactions, responsive behavior (phone 390 / iPad 768 / PC 1440), real content and assets\n- **Out of scope:** real backend, auth, databases, forms that actually submit (mock them)\n- **Content goes in `src/data/*.ts`** — components take props; page files wire data to components. This keeps the clone restylable later (see `/restyle`).\n\nUser-provided instructions override these defaults.\n\n## Tooling\n\nThe scripts do the mechanical work — **use them instead of hand-measuring via browser MCP**:\n\n| Script | Purpose |\n|---|---|\n| **`node scripts/extract/page.mjs <url> [--no-site-files]`** | **THE WORKHORSE — one call, 3 page loads total.** Auto-detects sections, then produces `tokens.json` + `css.json` (skip on later pages with `--no-site-files`), `assets.json` + downloads to `public/`, `responsive.json` (all 3 viewports), a full computed-style walk per section (`sections/<name>.json`), and full-page **and** per-section screenshots at phone/iPad/PC. Accepts explicit `--selector \"css\" --name x` pairs to override detection. Everything is measured from the SAME page state, so numbers, walks and screenshots can never disagree |\n| `node scripts/extract/crawl.mjs <url> [--max 25]` | Discover pages (sitemap + nav links) → `docs/research/<host>/sitemap.json` |\n| `node scripts/extract/section.mjs <url> --selector \"css\" [--name x] --state scroll:600\\|click:sel\\|hover:sel [--viewport pc\\|ipad\\|phone]` | **State captures** (page.mjs covers the default state). Captures a second state and diffs them (element styles *and* `::before`/`::after`), waiting for the section's real transition duration. `--selector`/`--name` repeat — one page load for all |\n| `node scripts/extract/probe.mjs <url> --selector \"css\" [--selector \"css2\"] [--props a,b,c]` / `probe.mjs --route </r>` | Exact computed values for specific selectors at all 3 viewports, as a markdown table with a **varies** column — paste straight into a spec's Responsive section. **`--route` probes EVERY registered section of a page in one call (3 loads total, plus a `probe-<section>.json` per section) — never probe section-by-section** |\n| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |\n| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |\n| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |\n| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |\n| `node scripts/lint-spec.mjs <spec.md\\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |\n| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |\n\nBrowser MCP (Chrome MCP, Playwright MCP — if available) is for **judgment work only**: watching how the page behaves while scrolling, exploring what's clickable, understanding an animation. Numbers always come from the scripts. If no browser MCP is available, the scripts alone are sufficient — use extra `screenshot.mjs` and `section.mjs --state` calls to observe behavior.\n\nThe scripts are plain Node CLIs — any coding agent can run them. Playwright's Chromium auto-installs on the first script run (or run `npm run setup` once). If your tool has no subagent/worktree support, skip the dispatch mechanics and build each section yourself, sequentially, from the same lint-passing specs — every quality gate still applies.\n\n## Guiding Principles\n\n1. **Completeness beats speed.** A builder that has to guess a color, font size, or padding value means extraction failed. Extract one more property rather than ship an incomplete spec.\n2. **Small tasks, perfect results.** One focused component per builder. Spec body over 150 lines = split the section (lint-spec enforces this).\n3. **Real content, real assets.** Actual text via the section walker, actual files via `assets.mjs`. Watch for **layered images** — a hero that looks like one image is often background + overlay + foreground; `assets.json` records sibling counts and z-index for exactly this reason.\n4. **Foundation first.** Tokens, fonts, types, icons, and shared chrome (header/footer) before any page section.\n5. **Extract how it looks AND how it behaves.** Every interactive element needs before/after states with exact values — `section.mjs --state` produces the diff mechanically.\n6. **Identify the interaction model before building.** Scroll-driven vs click-driven confusion is the most expensive mistake in cloning — a wrong call means a rewrite, not a CSS fix. Scroll first without clicking and watch; only then click. Record the model in the spec frontmatter.\n7. **Responsive is measured, never guessed — at all three widths.** Fill every spec's Responsive section from `responsive.json` + `probe.mjs`, with real numbers for phone AND iPad AND pc. Never write \"iPad: same as desktop\": most production sites step their root font-size at breakpoints, so *every* padding, margin, and font size changes even when the layout looks identical. A spec that only nails desktop produces a clone that scores ~98% at 1440px and ~91% at 390px. `lint-spec.mjs` rejects vague responsive sections.\n\n8. **The extraction JSON is ground truth; the spec is a summary of it.** If a builder finds the spec disagreeing with `sections/<name>.json` or `responsive.json`, the JSON wins — say so explicitly in every builder prompt and have the builder report the discrepancy so you can correct the spec.\n9. **Spec files are the contract.** No spec → no builder. lint-spec must pass → then dispatch.\n10. **The build must always compile.** Builders verify `npx tsc --noEmit`; you verify `npm run typecheck && npm run lint` after every merge. Full `npm run build` runs only at checkpoints (Phase 0, end of Phase 2, once mid-way through Phase 3, Phase 4, completion) — it takes 30–60s and running it per merge serializes otherwise-parallel builders.\n11. **The manifest is updated at every stage transition.** That's what makes the run resumable.\n\n## Phase 0 — Crawl & Scope\n\n1. Verify the base builds: `npm run build`.\n2. `node scripts/extract/crawl.mjs <url> --max 25`\n3. Show the user the discovered pages (route + source). **Ask which to clone** — recommend: start page + nav pages, skip legal/utility pages unless asked. Default cap ~10.\n4. Initialize state:\n ```bash\n node scripts/manifest.mjs init <url>\n node scripts/manifest.mjs add-page --url <url> --route / # per confirmed page\n ```\n\n## Phase 1 — Recon (one page.mjs call per page)\n\n1. **First page:** `node scripts/extract/page.mjs <start-url>` — produces tokens, css, assets+downloads, responsive signatures, per-section walks, and every screenshot in one shot (3 page loads).\n2. **Every other confirmed page:** `node scripts/extract/page.mjs <url> --no-site-files` (tokens/css are site-wide; everything else is per-page). Downloads dedupe across pages automatically — files already in `public/` are skipped.\n3. **Review the detected sections** in each run's stdout summary (name, selector, pc height, headline responsive change). Detection is a heuristic: if a \"section\" is really two, or two are really one, re-run with explicit `--selector \"css\" --name x` pairs. Section names become spec/component names — rename `section-3` style fallbacks to something meaningful via `--name`.\n4. **Interaction sweep** (judgment work — browser MCP if available): scroll each page slowly top to bottom. Does the header change? Do elements animate in? Auto-switching tabs? Scroll-snap? Smooth-scroll lib (`tokens.json` flags `.lenis`/Locomotive)? Then click every tab/pill/accordion and note what changes. Then hover. `css.json`'s `interactiveStates` lists every :hover/:focus rule the stylesheet defines — use it as the checklist of what to probe. Record findings in `docs/research/<host>/BEHAVIORS.md`.\n5. **Shared chrome detection:** compare screenshots across pages — header/nav/footer that repeat become SHARED components (`SiteHeader`, `SiteFooter`), extracted once from the page where they're most complete.\n\n**Per page — topology:** map every distinct section top to bottom with a working name, its selector, its interaction model (static / click-driven / scroll-driven / hover-driven / time-driven / mixed), and layer notes (sticky? overlay? z-index?). Save `docs/research/<host>/PAGE_TOPOLOGY.md`, then register each section:\n```bash\nnode scripts/manifest.mjs add-section --route / --name hero --selector \"section.hero\"\n```\n\n## Phase 2 — Foundation (sequential, you do it yourself)\n\n1. **Fonts** in `src/app/layout.tsx` via `next/font/google` or `next/font/local` (downloaded fonts are in `public/fonts/`) — families/weights from `tokens.json`\n2. **`globals.css`**: map the target's palette onto the shadcn `:root` token names; add custom properties for colors that don't map; add global keyframes, scroll-snap, smooth-scroll setup found in recon\n3. **TypeScript interfaces** in `src/types/` for the content structures you observed\n4. **Icons**: convert the deduplicated `inlineSvgs` from `assets.json` into named components in `src/components/icons.tsx` (named by function: `LogoIcon`, `ArrowRightIcon`…)\n5. **SEO**: favicons/OG from `public/seo/` wired into `layout.tsx` metadata\n6. Verify `npm run build`, then build **shared chrome** (header/footer) first — full spec → lint → builder cycle like any section, since every page depends on them.\n\n## Phase 3 — Per-Section Loop (extract → spec → lint → dispatch → merge)\n\nWork through `manifest.mjs next` until no sections remain. For each section:\n\n### 3a. Extract\n\n**The default state is already extracted** — Phase 1's page.mjs run wrote\n`sections/<name>.json`, `responsive.json`, and all screenshots.\n\n**First time you enter Phase 3 for a page, probe ALL its sections in ONE call** (3\npage loads total instead of 3 per section — never probe section-by-section):\n\n```bash\nnode scripts/extract/probe.mjs --route <r> # every registered section + probe-<section>.json each\n# add key children in the same call when a spec will need them:\nnode scripts/extract/probe.mjs --route <r> --selector \"<sel> h2\" --selector \"<sel> .card\"\n```\n\nSlice the per-section tables into each spec's Responsive section as you write it.\nPer section, only one thing remains:\n\n```bash\n# Per discovered behavior — one call per state (batch selectors sharing a trigger):\nnode scripts/extract/section.mjs <page-url> --selector \"<sel>\" --name <name>-hover --state hover:\".card\"\nnode scripts/extract/section.mjs <page-url> --selector \"<sel>\" --name <name>-scrolled --state scroll:600\n# per tab/pill state: --state click:\".tab-2\" etc. EVERY state, not just the default.\n```\nState captures wait for the section's actual transition duration, so a slow fade is\nrecorded at its end value, not mid-flight — check `settleMs` in the output if a diff\nlooks wrong. The `diff` array covers `::before`/`::after` too, which is where hover\noverlays usually live. Cross-check discovered behaviors against `css.json`'s\n`interactiveStates` — a :hover rule in the stylesheet with no captured state means\nthe extraction is not done.\n\nMark: `manifest.mjs set --route <r> --section <name> --stage extracted`\n\n### 3b. Write the spec — scaffold first, judgment second\n\n```bash\nnode scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route\n```\n\nThis generates `docs/research/components/<route-slug>/<name>.spec.md` with every\n**mechanical** section already filled from the extraction JSON — frontmatter, DOM\nStructure, Computed Styles, Assets, Text Content, Responsive Behavior — and any\ncaptured states listed as reference data. **Never transcribe values from the JSON\nby hand**: the scaffold is generated from the same files and can't mistype.\n\nYou fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:\n\n- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)\n- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference\n- `## Per-State Content` — full content per state for tabbed/stateful sections, or \"N/A — static\"\n- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas\n\nAn unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it\ncan never reach a builder. Correct a generated section only when it's wrong about\nthe page — don't restyle it.\n\n### 3c. Lint gate\n```bash\nnode scripts/lint-spec.mjs docs/research/components/<route-slug>/<name>.spec.md\n```\nFails → extract more. Passes → `manifest.mjs set … --stage specd` and dispatch.\n\n### 3d. Dispatch builder agent (worktree)\n\nEvery builder receives IN ITS PROMPT (never \"go read the file\"):\n- The **full spec file contents inline**\n- The screenshot paths (all 3 viewports)\n- Shared imports available: `cn()`, `icons.tsx` components, shadcn `ui/` primitives, types from `src/types/`\n- The target file path, and the data file to create in `src/data/` if the section has content collections\n- The rule: verify `npx tsc --noEmit` passes before finishing\n- **The ground-truth rule:** \"`docs/research/<host>/sections/<name>.json` and `responsive.json` are ground truth. If this spec contradicts them, follow the JSON and report the discrepancy.\" Builders reliably catch spec errors this way — treat their reports as corrections to make to the spec file.\n\nComplex section (3+ distinct sub-components) → one builder per sub-component + one for the wrapper, sub-components first. **Don't wait** — while builders run, extract the next section.\n\n### 3e. Merge\nAs builders finish: merge worktree → `npm run typecheck && npm run lint` → fix errors immediately → `manifest.mjs set … --stage merged`. tsc catches the cross-worktree breaks (imports, prop types) that per-merge builds used to catch, in a fraction of the time.\n\n**Once, after roughly half the page's sections are merged: run a full `npm run build` checkpoint.** It catches build-only failures (server/client component violations, route exports, metadata) while they're still cheap to bisect. Don't build after every merge.\n\n## Phase 4 — Page Assembly\n\nPer page: create `src/app/<route>/page.tsx` importing its section components with data from `src/data/`, plus page-level behaviors (scroll-snap, observers, smooth scroll). Shared chrome mounts in `layout.tsx` or a route group layout. Wire internal nav links to the cloned routes. `npm run build` must pass.\n\n## Phase 5 — Scored QA Loop\n\nStart the clone: `npm run dev` (background). Then **score the whole page's sections in ONE batched call** (one load per side per viewport instead of one per section):\n\n```bash\nnode scripts/diff.mjs --original <orig-page-url> --clone http://localhost:3000<route> --route <r> --viewport all\nnode scripts/manifest.mjs set --route <r> --section <name> --score pc=<match> # per section × viewport\n```\n\n**Fix iterations stay single-section** — the original-side shots captured by the sweep are cached, so a re-diff only re-renders the clone:\n\n```bash\nnode scripts/diff.mjs --original <orig-page-url> --clone http://localhost:3000<route> --selector \"<sel>\" --viewport all --name <name>\n```\n\n- **Pass = ≥95% on all three viewports** → `--stage qa_passed`\n- Below 95% → **read the band breakdown first**: it names the y-range where the mismatch lives, so you inspect that band of the diff image in `docs/research/qa/` instead of eyeballing the whole section. Then check the spec (wrong extraction → re-extract and fix; right spec, wrong build → fix component), re-diff\n- A large height mismatch reported by diff.mjs = missing content or wrong spacing — fix before pixel-tweaking\n- Max 3 fix iterations per section, then record the gap honestly and move on\n- **Text-heavy sections at phone width often plateau at 90–95%** when the target's font isn't available on Google Fonts (e.g. Source Sans Pro → Source Sans 3). Different metrics = different wrap points = unavoidable pixel drift. Confirm the layout matches, note the substitution, and accept it.\n- **A score that's high at pc but low at ipad/phone is always a responsive-spec problem**, not a styling bug. Re-run `probe.mjs` on the section and fill in the values the spec was missing.\n- Finally, test behaviors manually: scroll, click every tab, hover — screenshots can't verify motion; you must\n\nWhole-page diffs (`--selector` omitted) at all 3 viewports close out each page.\n\n## What NOT to Do\n\n- **Don't build click-tabs when the original is scroll-driven** (or vice versa). Scroll first, watch, then click. Wrong model = rewrite.\n- **Don't extract only the default state.** Every tab clicked, every hover captured, header at scroll 0 AND past the trigger.\n- **Don't miss layered/overlay images** — check `siblingImgs` and z-index hints in `assets.json`.\n- **Don't build HTML mockups of things that are actually `<video>`, Lottie, or canvas.** Check first.\n- **Don't approximate (\"looks like text-lg\").** Use the walker's exact computed values; use arbitrary values (`text-[17px]`) when Tailwind's scale doesn't match.\n- **Don't dispatch a builder without a lint-passing spec.** No exceptions — that's the whole quality model.\n- **Don't reference docs from builder prompts** — spec contents go inline.\n- **Don't skip the manifest updates.** An untracked run can't resume.\n- **Don't hardcode content in components.** Content → `src/data/`, components take props.\n- **Don't write \"same as desktop\" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.\n- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.\n- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).\n- **Don't declare done without QA scores.** \"Looks right\" is not a number.\n\n## Completion Report\n\n- Pages cloned (routes) · sections built · spec files written (must match section count)\n- Assets downloaded (from `assets.json` download log, including failures)\n- Final QA score table per section × viewport (from `manifest.mjs status`)\n- `npm run build` result\n- Known gaps and any section that couldn't reach 95%\n- Suggest next step: `/restyle` to rebrand the clone with your own identity",
"fileContext": [
"AGENTS.md",
"docs/research/**"
diff --git a/.augment/commands/clone-website.md b/.augment/commands/clone-website.md
index 13a9135..6ad197d 100644
--- a/.augment/commands/clone-website.md
+++ b/.augment/commands/clone-website.md
@@ -41,6 +41,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -132,44 +133,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -236,7 +221,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.claude/skills/clone-website/SKILL.md b/.claude/skills/clone-website/SKILL.md
index fbdaa84..8e02c9a 100644
--- a/.claude/skills/clone-website/SKILL.md
+++ b/.claude/skills/clone-website/SKILL.md
@@ -41,6 +41,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -132,44 +133,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -236,7 +221,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.codex/skills/clone-website/SKILL.md b/.codex/skills/clone-website/SKILL.md
index fbdaa84..8e02c9a 100644
--- a/.codex/skills/clone-website/SKILL.md
+++ b/.codex/skills/clone-website/SKILL.md
@@ -41,6 +41,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -132,44 +133,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -236,7 +221,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.continue/commands/clone-website.md b/.continue/commands/clone-website.md
index a6ee17c..c76590b 100644
--- a/.continue/commands/clone-website.md
+++ b/.continue/commands/clone-website.md
@@ -42,6 +42,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -133,44 +134,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -237,7 +222,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.cursor/commands/clone-website.md b/.cursor/commands/clone-website.md
index 1c54b02..367c70d 100644
--- a/.cursor/commands/clone-website.md
+++ b/.cursor/commands/clone-website.md
@@ -39,6 +39,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -130,44 +131,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -234,7 +219,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.gemini/commands/clone-website.toml b/.gemini/commands/clone-website.toml
index bdac1e7..d5bab78 100644
--- a/.gemini/commands/clone-website.toml
+++ b/.gemini/commands/clone-website.toml
@@ -41,6 +41,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -132,44 +133,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -236,7 +221,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.github/skills/clone-website/SKILL.md b/.github/skills/clone-website/SKILL.md
index fbdaa84..8e02c9a 100644
--- a/.github/skills/clone-website/SKILL.md
+++ b/.github/skills/clone-website/SKILL.md
@@ -41,6 +41,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -132,44 +133,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -236,7 +221,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.opencode/commands/clone-website.md b/.opencode/commands/clone-website.md
index 7e9e20c..107a844 100644
--- a/.opencode/commands/clone-website.md
+++ b/.opencode/commands/clone-website.md
@@ -40,6 +40,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -131,44 +132,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -235,7 +220,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/.windsurf/workflows/clone-website.md b/.windsurf/workflows/clone-website.md
index f050828..ee1d191 100644
--- a/.windsurf/workflows/clone-website.md
+++ b/.windsurf/workflows/clone-website.md
@@ -37,6 +37,7 @@ The scripts do the mechanical work — **use them instead of hand-measuring via
| `node scripts/extract/screenshot.mjs <url> [--selector css --name x ...]` | Extra screenshots at phone/iPad/PC (page.mjs already shot everything once). `--selector`/`--name` repeat — one call, 3 loads, N sections |
| `node scripts/extract/tokens.mjs` / `css.mjs` / `assets.mjs` / `responsive.mjs` | Single-purpose re-runs of one page.mjs output when something needs refreshing |
| `node scripts/diff.mjs --original <url> --clone <url> [--selector css] --viewport all [--threshold 95]` | Scored pixel diff, original vs clone. **`--viewport all` scores pc+ipad+phone in one call**, and the per-viewport **band breakdown names the y-range where the mismatch lives** — read it before guessing at causes. **Batched sweep: `--route </r>` (or repeated `--section name=css`) scores every section of a page from ONE load per side per viewport.** Original-side shots are cached 24h, so fix-iteration re-diffs only re-render the clone (`--fresh-original` to override) |
+| **`node scripts/spec-scaffold.mjs --route <r> --section <name>`** (or `--all`) | **Generates the mechanical spec sections** (frontmatter, DOM, computed styles, assets, text, responsive) straight from the extraction JSON into `docs/research/components/<route-slug>/<name>.spec.md`, leaving `<!-- AGENT: fill -->` blocks for the judgment parts. Never transcribe JSON values by hand |
| `node scripts/lint-spec.mjs <spec.md\|dir>` | Mechanical spec-completeness gate — must pass before ANY builder dispatch |
| `node scripts/manifest.mjs <cmd>` | Pipeline state: init / add-page / add-section / set / status / next |
@@ -128,44 +129,28 @@ the extraction is not done.
Mark: `manifest.mjs set --route <r> --section <name> --stage extracted`
-### 3b. Write the spec — `docs/research/components/<route-slug>/<name>.spec.md`
+### 3b. Write the spec — scaffold first, judgment second
-```markdown
----
-component: HeroSection
-target: src/components/HeroSection.tsx
-page: /
-screenshot: docs/design-references/<host>/<name>-pc.png
-interaction_model: static | click-driven | scroll-driven | hover-driven | time-driven | mixed
-states: default, hover, scrolled…
-assets: public/images/x.webp, icons:ArrowRightIcon
-responsive: phone, ipad, pc
----
-
-# <Component> Specification
-
-## DOM Structure
-<hierarchy from the section walker — what contains what>
-
-## Computed Styles
-<exact values from sections/<name>.json, per element. Never estimated.>
-
-## States & Behaviors
-<per behavior: Trigger / State A / State B / Transition — from the --state diffs.
- Include the implementation approach (CSS transition, IntersectionObserver, etc.)>
+```bash
+node scripts/spec-scaffold.mjs --route <r> --section <name> # or --all for the whole route
+```
-## Per-State Content
-<for tabbed/stateful sections: full content per state. "N/A — static" otherwise>
+This generates `docs/research/components/<route-slug>/<name>.spec.md` with every
+**mechanical** section already filled from the extraction JSON — frontmatter, DOM
+Structure, Computed Styles, Assets, Text Content, Responsive Behavior — and any
+captured states listed as reference data. **Never transcribe values from the JSON
+by hand**: the scaffold is generated from the same files and can't mistype.
-## Assets
-<local public/ paths + icon components used. Note layered compositions explicitly.>
+You fill ONLY the `<!-- AGENT: fill -->` blocks — the judgment calls:
-## Text Content
-<verbatim from the walker output — never paraphrased>
+- `interaction_model:` in the frontmatter (static | click-driven | scroll-driven | hover-driven | time-driven | mixed)
+- `## States & Behaviors` — per behavior: Trigger / State A / State B / Transition + the implementation approach (CSS transition, IntersectionObserver, …). The scaffold lists each captured state's trigger/settle/diff summary as reference
+- `## Per-State Content` — full content per state for tabbed/stateful sections, or "N/A — static"
+- `## Notes` — builder guidance: component split, `src/data/` shape, gotchas
-## Responsive Behavior
-<from responsive.json: real column counts and changes at 390 / 768 / 1440 + breakpoint>
-```
+An unfilled scaffold fails lint-spec on purpose (invalid interaction_model), so it
+can never reach a builder. Correct a generated section only when it's wrong about
+the page — don't restyle it.
### 3c. Lint gate
```bash
@@ -232,7 +217,7 @@ Whole-page diffs (`--selector` omitted) at all 3 viewports close out each page.
- **Don't hardcode content in components.** Content → `src/data/`, components take props.
- **Don't write "same as desktop" in a Responsive section.** Root font-size steps at breakpoints on most real sites, so every number changes. Run `probe.mjs` and write the real values for all three widths — lint-spec now rejects vague responsive sections.
- **Don't forget `::before` / `::after`.** They carry hero overlays, heading underline bars, and icon glyphs. `section.mjs` captures them under a `pseudo` key — if a spec has none and the screenshot shows decorations, extraction was incomplete.
-- **Don't trust the spec over the extraction JSON.** Specs are hand-written summaries and drift; `sections/*.json` is machine-measured.
+- **Don't trust the spec over the extraction JSON.** The judgment sections are hand-written and can drift; `sections/*.json` is machine-measured (and the mechanical spec sections are generated from it).
- **Don't declare done without QA scores.** "Looks right" is not a number.
## Completion Report
diff --git a/README.md b/README.md
index cde7efd..ae6a1c4 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,7 @@ Point it at a URL. `/clone-website` crawls the site, measures everything with sc
| Agent guesses CSS values from screenshots | `scripts/extract/section.mjs` — full `getComputedStyle()` DOM walk, exact values |
| Responsive behavior guessed from desktop | `scripts/extract/responsive.mjs` — measures real column counts at 390/768/1440px |
| "Looks close enough" QA | `scripts/diff.mjs` — pixel-diff score per section per viewport; 95% threshold to pass |
+| Agent mis-transcribes values into specs | `scripts/spec-scaffold.mjs` — mechanical spec sections generated straight from the extraction JSON |
| Incomplete specs slip through | `scripts/lint-spec.mjs` — mechanical completeness gate before any builder runs |
| Long runs die and restart from zero | `docs/research/manifest.json` — every section's stage tracked; runs resume where they stopped |
| Single-page only | `scripts/extract/crawl.mjs` — sitemap + nav discovery, shared header/footer extracted once |
@@ -67,6 +68,8 @@ node scripts/extract/page.mjs <url> # ONE-SHOT recon: tokens,
node scripts/extract/crawl.mjs <url> [--max 25] # discover pages
node scripts/extract/section.mjs <url> --selector "x" --state hover:".card" # hover/scroll/click state diffs
node scripts/extract/probe.mjs <url> --selector "x" # per-viewport value table for specs
+node scripts/spec-scaffold.mjs --route / --all # generate the mechanical spec sections from the
+ # extraction JSON; agent fills judgment blocks only
node scripts/extract/canvas.mjs <url> # capture <canvas> artwork as video/PNG
node scripts/extract/tokens.mjs / css.mjs / assets.mjs / responsive.mjs / screenshot.mjs # single-purpose re-runs
node scripts/diff.mjs --original <url> --clone <url> --viewport all # scored pixel diff, all 3 viewports in one
diff --git a/scripts/extract/walk-format.mjs b/scripts/extract/walk-format.mjs
new file mode 100644
index 0000000..a69de41
--- /dev/null
+++ b/scripts/extract/walk-format.mjs
@@ -0,0 +1,165 @@
+// Reading, resolving and iterating section-walk JSON — the single place that
+// understands both walk formats:
+//
+// legacy: { tree: { styles: {…}, children: […] } } (full blob per node)
+// compact-v1: { format: "compact-v1", styleTable: { s1: {…} },
+// tree: { style: "s1", children: […] } }
+//
+// In compact-v1 a node's `style` key points into the styleTable; the stored
+// object holds only (a) non-inherited props that survive the walker's SKIP
+// filter and (b) CSS-inherited props that DIFFER from the parent's value.
+// Resolution therefore is: inherited props fall back up the ancestor chain,
+// everything else is absent-means-default — exactly the semantics consumers
+// already assumed for legacy files.
+import { createHash } from "node:crypto";
+
+// CSS-inherited properties among the walker's PROPS list. Only these may be
+// pruned against the parent: a non-inherited prop that happens to equal the
+// parent's (say, both padding 16px) is a coincidence, and pruning it would
+// make "absent" ambiguous between "default" and "same as parent".
+export const INHERITED_PROPS = [
+ "fontSize", "fontWeight", "fontFamily", "lineHeight", "letterSpacing",
+ "color", "textAlign", "textTransform", "whiteSpace", "cursor", "visibility",
+];
+const INHERITED = new Set(INHERITED_PROPS);
+
+// Mirrors the walker's SKIP set (collectors.mjs) — used when compacting the
+// root node, where inherited props have no parent to diff against.
+export const SKIP_VALUES = new Set(["none", "normal", "auto", "0px", "rgba(0, 0, 0, 0)", "visible", "static", "initial", ""]);
+
+export function isCompact(doc) {
+ return doc?.format === "compact-v1";
+}
+
+// The raw style object stored on a node, whichever format.
+export function storedStyles(node, doc) {
+ if (!node) return {};
+ if (node.styles) return node.styles;
+ if (node.style && doc?.styleTable) return doc.styleTable[node.style] || {};
+ return {};
+}
+
+// Fully resolved styles for a node: its own stored props plus, for compact
+// files, inherited props filled in from the nearest ancestor that recorded
+// them. `ancestors` is root-first. Legacy nodes come back as-is.
+export function resolveStyles(node, ancestors, doc) {
+ const own = storedStyles(node, doc);
+ if (!isCompact(doc)) return { ...own };
+ const out = { ...own };
+ for (const prop of INHERITED_PROPS) {
+ if (prop in out) continue;
+ for (let i = ancestors.length - 1; i >= 0; i--) {
+ const v = storedStyles(ancestors[i], doc)[prop];
+ if (v !== undefined) {
+ out[prop] = v;
+ break;
+ }
+ }
+ }
+ return out;
+}
+
+// Depth-first iteration with everything a consumer needs to address or resolve
+// a node: `indexPath` ("0.2.1" = child indices from the root), `ancestors`
+// (root-first), and a short human label.
+export function* walkNodes(tree, { ancestors = [], indexPath = "" } = {}) {
+ if (!tree || tree.error) return;
+ yield { node: tree, indexPath: indexPath || "root", ancestors, label: nodeLabel(tree) };
+ const kids = tree.children || [];
+ for (let i = 0; i < kids.length; i++) {
+ yield* walkNodes(kids[i], {
+ ancestors: [...ancestors, tree],
+ indexPath: indexPath ? `${indexPath}.${i}` : String(i),
+ });
+ }
+}
+
+export function nodeLabel(node) {
+ const cls = (node.classes || "").split(" ").filter(Boolean).slice(0, 2).join(".");
+ return node.tag + (cls ? "." + cls : "");
+}
+
+// Look a node up by its "0.2.1" index path (as printed by resolve-walk.mjs).
+export function nodeAtPath(tree, path) {
+ if (!path || path === "root") return { node: tree, ancestors: [] };
+ const ancestors = [];
+ let cur = tree;
+ for (const part of String(path).split(".")) {
+ const i = Number(part);
+ if (!cur?.children?.[i]) return { node: null, ancestors };
+ ancestors.push(cur);
+ cur = cur.children[i];
+ }
+ return { node: cur, ancestors };
+}
+
+// ---------------------------------------------------------------------------
+// Compaction: legacy tree -> { tree, styleTable }
+//
+// Two passes of savings, measured on the plausible.io fixture run where 45 of
+// 63 nodes carried byte-identical style blobs:
+// 1. inherited-prop pruning — fontFamily/color/… stop repeating on every node
+// 2. style dictionary — the (now much smaller) per-node objects dedupe into
+// a shared table; nodes reference entries by key
+// ---------------------------------------------------------------------------
+
+export function compactWalk(tree) {
+ const table = new Map(); // styles-JSON -> key
+ const styleTable = {};
+
+ const keyFor = (styles) => {
+ const json = JSON.stringify(styles);
+ let key = table.get(json);
+ if (!key) {
+ key = `s${table.size + 1}`;
+ table.set(json, key);
+ styleTable[key] = styles;
+ }
+ return key;
+ };
+
+ const compactNode = (node, parentStyles) => {
+ if (!node || node.error) return node;
+ const src = node.styles || {};
+ const pruned = {};
+ for (const [prop, v] of Object.entries(src)) {
+ if (INHERITED.has(prop)) {
+ if (parentStyles) {
+ if (v !== parentStyles[prop]) pruned[prop] = v; // differs -> record
+ } else if (!SKIP_VALUES.has(v)) {
+ pruned[prop] = v; // root: keep non-default inherited values
+ }
+ } else {
+ pruned[prop] = v;
+ }
+ }
+ // Effective inherited values this node passes down (own overrides parent's)
+ const passDown = { ...(parentStyles || {}) };
+ for (const prop of INHERITED_PROPS) if (src[prop] !== undefined) passDown[prop] = src[prop];
+
+ const { styles: _drop, children, ...rest } = node;
+ const out = { ...rest };
+ if (Object.keys(pruned).length) out.style = keyFor(pruned);
+ if (children) out.children = children.map((c) => compactNode(c, passDown));
+ return out;
+ };
+
+ const compacted = compactNode(tree, null);
+ return { tree: compacted, styleTable };
+}
+
+// The subset of a styleTable a single tree actually references — per-section
+// files carry only their own entries.
+export function usedStyleTable(tree, styleTable) {
+ const used = {};
+ for (const { node } of walkNodes(tree)) {
+ if (node.style && styleTable[node.style]) used[node.style] = styleTable[node.style];
+ }
+ return used;
+}
+
+// Stable content hash of a node's identity (tag + classes) — used by the
+// structural differ to align children across two captures.
+export function nodeKey(node) {
+ return createHash("md5").update(`${node.tag}|${node.classes || ""}`).digest("hex").slice(0, 8);
+}
diff --git a/scripts/spec-scaffold.mjs b/scripts/spec-scaffold.mjs
new file mode 100644
index 0000000..eb1a0d0
--- /dev/null
+++ b/scripts/spec-scaffold.mjs
@@ -0,0 +1,395 @@
+#!/usr/bin/env node
+// Generate the MECHANICAL parts of a component spec straight from extraction
+// JSON — frontmatter skeleton, DOM Structure, Computed Styles, Assets, Text
+// Content, Responsive Behavior — leaving clearly marked <!-- AGENT: fill -->
+// blocks for the judgment sections (interaction_model, States & Behaviors,
+// Per-State Content, implementation notes).
+//
+// Specs used to be hand-transcribed from sections/<name>.json; agents
+// mis-transcribe, which is why the skill has the rule "if the spec disagrees
+// with the JSON, the JSON wins". This script kills the transcription step: the
+// mechanical sections are now generated from the same JSON they used to be
+// copied from, and the agent only writes the parts that need judgment.
+//
+// Usage:
+// node scripts/spec-scaffold.mjs --route / --section hero [--section pricing]
+// node scripts/spec-scaffold.mjs --route / --all # every section of the route
+// [--host plausible.io] host dir under research/ (from manifest when omitted)
+// [--research docs/research] research root (default docs/research)
+// [--out <research>/components]
+//
+// Reads: <research>/<host>/sections/<name>.json (walk — legacy or compact)
+// <research>/<host>/responsive.json, probe-<name>.json, assets.json
+// <research>/<host>/sections/<name>-*.json (state captures -> listed as states)
+// Writes: <out>/<route-slug>/<name>.spec.md
+//
+// The output passes lint-spec.mjs once the agent fills the marked blocks —
+// until then interaction_model is invalid on purpose, so an unfilled scaffold
+// can never be dispatched to a builder.
+import { readFileSync, readdirSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
+import { join, basename } from "node:path";
+import { hostOf, slugify, parseArgs, toList } from "./lib.mjs";
+import { walkNodes, resolveStyles, nodeLabel } from "./extract/walk-format.mjs";
+
+const args = parseArgs(process.argv.slice(2));
+const research = typeof args.research === "string" ? args.research : "docs/research";
+const outRoot = typeof args.out === "string" ? args.out : join(research, "components");
+const route = typeof args.route === "string" ? args.route : "/";
+const routeSlug = route === "/" ? "home" : slugify(route.replace(/^\//, ""));
+
+let host = typeof args.host === "string" ? args.host : null;
+let sections = toList(args.section).map(String);
+
+const manifestPath = join(research, "manifest.json");
+if (existsSync(manifestPath)) {
+ const m = JSON.parse(readFileSync(manifestPath, "utf8"));
+ if (!host && m.site) host = hostOf(m.site);
+ if (args.all) {
+ const p = m.pages.find((p) => p.route === route);
+ if (!p) {
+ console.error(`Route ${route} not in manifest. Routes: ${m.pages.map((p) => p.route).join(", ")}`);
+ process.exit(1);
+ }
+ sections = p.sections.map((s) => s.name);
+ }
+}
+if (!host) {
+ // fall back to the only host dir that has extraction output
+ const candidates = existsSync(research)
+ ? readdirSync(research).filter((d) => existsSync(join(research, d, "sections")))
+ : [];
+ if (candidates.length === 1) host = candidates[0];
+}
+if (!host || !sections.length) {
+ console.error("Usage: node scripts/spec-scaffold.mjs --route / --section hero [--section x ...] | --all [--host h] [--research dir] [--out dir]");
+ process.exit(1);
+}
+
+const hostDir = join(research, host);
+const sectionsDir = join(hostDir, "sections");
+const readJson = (p) => (existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : null);
+const responsive = readJson(join(hostDir, "responsive.json"));
+const assetsDoc = readJson(join(hostDir, "assets.json"));
+
+const trunc = (s, n) => (s && s.length > n ? s.slice(0, n - 1) + "…" : s || "");
+const AGENT = (hint) => `<!-- AGENT: fill — ${hint} -->`;
+// script/style nodes are in the walk (ground truth) but are noise in a spec
+const isNoise = (node) => ["script", "style", "noscript", "template"].includes(node.tag);
+
+// ── naming ──────────────────────────────────────────────────────────────────
+function componentName(name) {
+ if (/^(nav|header)$/.test(name)) return "SiteHeader";
+ if (name === "footer") return "SiteFooter";
+ const pascal = name.split(/[^a-z0-9]+/i).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
+ return pascal.endsWith("Section") ? pascal : pascal + "Section";
+}
+
+// ── DOM structure (collapsed wrapper chains, grouped sibling runs) ──────────
+const MAX_DOM_LINES = 18;
+function domStructure(tree) {
+ const lines = [];
+ let truncated = false;
+ const rec = (node, depth, countPrefix) => {
+ if (!node || node.error) return;
+ if (lines.length >= MAX_DOM_LINES) {
+ truncated = true;
+ return;
+ }
+ let label = nodeLabel(node);
+ let cur = node;
+ // a chain of lone wrappers is one line: div.container > div.mx-auto > …
+ while ((cur.children || []).length === 1 && !cur.text && !cur.img && label.length < 80) {
+ cur = cur.children[0];
+ label += " > " + nodeLabel(cur);
+ }
+ const text = cur.text ? ` — "${trunc(cur.text, 48)}"` : "";
+ const dims = cur.rect && depth <= 1 ? ` [${cur.rect.w}×${cur.rect.h}]` : "";
+ lines.push(`${" ".repeat(depth)}- ${countPrefix}${label}${dims}${text}`);
+ const kids = (cur.children || []).filter((k) => k && !k.error && !k.truncated && !isNoise(k));
+ const sig = (k) => `${k.tag}|${k.classes || ""}`;
+ let i = 0;
+ while (i < kids.length) {
+ let j = i + 1;
+ while (j < kids.length && sig(kids[j]) === sig(kids[i])) j++;
+ rec(kids[i], depth + 1, j - i >= 2 ? `×${j - i} ` : "");
+ i = j;
+ }
+ if (cur.truncatedChildren) lines.push(`${" ".repeat(depth + 1)}- … +${cur.truncatedChildren} more children (see JSON)`);
+ };
+ rec(tree, 0, "");
+ if (truncated) lines.push(`- … truncated — full tree in the section JSON (ground truth)`);
+ return lines;
+}
+
+// ── computed styles (selective + deduplicated) ──────────────────────────────
+const MAX_STYLE_LINES = 26;
+function summarizeStyles(s, hasText) {
+ const parts = [];
+ if (hasText && s.fontSize) {
+ let t = `${s.fontSize}/${s.fontWeight || "400"}/${s.lineHeight || "-"}`;
+ if (s.letterSpacing) t += ` ${s.letterSpacing}`;
+ if (s.color) t += ` ${s.color}`;
+ parts.push(t);
+ if (s.textAlign && !["start", "left"].includes(s.textAlign)) parts.push(s.textAlign);
+ if (s.textTransform) parts.push(s.textTransform);
+ }
+ if (s.backgroundColor) parts.push(`bg ${s.backgroundColor}`);
+ if (s.backgroundImage) parts.push(`bg-img ${trunc(s.backgroundImage, 42)}`);
+ if (s.borderRadius) parts.push(`radius ${s.borderRadius}`);
+ const bw = s.borderTopWidth || s.borderBottomWidth || s.borderLeftWidth || s.borderRightWidth;
+ if (bw && s.borderStyle && s.borderStyle !== "none") parts.push(`border ${bw} ${s.borderStyle} ${s.borderColor || ""}`.trim());
+ if (s.boxShadow) parts.push(`shadow ${trunc(s.boxShadow, 48)}`);
+ const pads = [s.paddingTop, s.paddingRight, s.paddingBottom, s.paddingLeft].map((v) => v || "0px");
+ if (pads.some((v) => v !== "0px")) parts.push(`pad ${pads.join(" ")}`);
+ const margins = [["mt", s.marginTop], ["mr", s.marginRight], ["mb", s.marginBottom], ["ml", s.marginLeft]].filter(([, v]) => v);
+ if (margins.length) parts.push(margins.map(([k, v]) => `${k} ${v}`).join(" "));
+ if (/flex/.test(s.display || "")) {
+ let f = `flex ${s.flexDirection || "row"}`;
+ if (s.gap) f += ` gap ${s.gap}`;
+ if (s.justifyContent) f += ` justify ${s.justifyContent}`;
+ if (s.alignItems) f += ` items ${s.alignItems}`;
+ parts.push(f);
+ } else if (/grid/.test(s.display || "")) {
+ parts.push(`grid cols [${trunc(s.gridTemplateColumns || "", 40)}]${s.gap ? ` gap ${s.gap}` : ""}`);
+ }
+ if (s.maxWidth) parts.push(`max-w ${s.maxWidth}`);
+ if (s.position && s.position !== "static") {
+ parts.push(`${s.position}${s.zIndex && s.zIndex !== "auto" ? ` z${s.zIndex}` : ""}${s.top ? ` top ${s.top}` : ""}${s.bottom ? ` bottom ${s.bottom}` : ""}`);
+ }
+ if (s.opacity && s.opacity !== "1") parts.push(`opacity ${s.opacity}`);
+ if (s.transform) parts.push(`transform ${trunc(s.transform, 36)}`);
+ return parts.join("; ");
+}
+
+function styleLines(doc, tree) {
+ const seen = new Map();
+ const entries = [];
+ for (const { node, ancestors } of walkNodes(tree)) {
+ if (node.isSvg || isNoise(node)) continue;
+ const styles = resolveStyles(node, ancestors, doc);
+ const hasText = !!node.text;
+ const visual = !!(styles.backgroundColor || styles.backgroundImage || styles.boxShadow || styles.borderRadius);
+ const layout = /(flex|grid)/.test(styles.display || "");
+ if (ancestors.length && !hasText && !visual && !layout && !node.img) continue;
+ const summary = summarizeStyles(styles, hasText);
+ if (!summary) continue;
+ const sig = `${node.tag}|${summary}`;
+ if (seen.has(sig)) {
+ seen.get(sig).count++;
+ continue;
+ }
+ const parent = ancestors[ancestors.length - 1];
+ const label = (parent ? nodeLabel(parent) + " > " : "") + nodeLabel(node) + (hasText ? ` ("${trunc(node.text, 22)}")` : "");
+ const entry = { label, summary, count: 1, size: node.rect ? ` [${node.rect.w}×${node.rect.h}]` : "" };
+ seen.set(sig, entry);
+ entries.push(entry);
+ }
+ const lines = entries.slice(0, MAX_STYLE_LINES).map(
+ (e) => `- **${e.label}**${e.count > 1 ? ` ×${e.count}` : ""}${e.size}: ${e.summary}`
+ );
+ if (entries.length > MAX_STYLE_LINES) {
+ lines.push(`- … +${entries.length - MAX_STYLE_LINES} more styled nodes — resolve any node with \`node scripts/resolve-walk.mjs\` (JSON is ground truth)`);
+ }
+ return lines;
+}
+
+// ── text content (verbatim) ─────────────────────────────────────────────────
+const MAX_TEXT_LINES = 36;
+function textLines(tree) {
+ const all = [];
+ for (const { node } of walkNodes(tree)) {
+ if (node.text && !isNoise(node)) all.push(`- ${node.tag}: "${node.text}"`);
+ }
+ // collapse exact consecutive repeats
+ const lines = [];
+ for (let i = 0; i < all.length; i++) {
+ let j = i + 1;
+ while (j < all.length && all[j] === all[i]) j++;
+ lines.push(j - i >= 2 ? `${all[i]} ×${j - i}` : all[i]);
+ i = j - 1;
+ }
+ if (lines.length > MAX_TEXT_LINES) {
+ const extra = lines.length - MAX_TEXT_LINES;
+ lines.length = MAX_TEXT_LINES;
+ lines.push(`- … +${extra} more text nodes — verbatim in the section JSON`);
+ }
+ return lines.length ? lines : ["None — no text nodes in this section."];
+}
+
+// ── assets ──────────────────────────────────────────────────────────────────
+function assetInfo(doc, tree) {
+ const localFor = (src) => assetsDoc?.downloads?.find((d) => d.remote === src)?.local || null;
+ const seen = new Set();
+ const lines = [];
+ const locals = [];
+ let svgCount = 0;
+ for (const { node, ancestors } of walkNodes(tree)) {
+ if (node.isSvg) svgCount++;
+ if (node.img?.src && !seen.has(node.img.src)) {
+ seen.add(node.img.src);
+ const local = localFor(node.img.src);
+ if (local) locals.push(local);
+ lines.push(`- img ${basename(new URL(node.img.src, "https://x/").pathname)} (${node.img.w}×${node.img.h})${node.img.alt ? ` alt "${trunc(node.img.alt, 40)}"` : ""} → ${local || "NOT DOWNLOADED — check assets.json"}`);
+ }
+ const bg = resolveStyles(node, ancestors, doc).backgroundImage;
+ const m = bg && bg.match(/url\(["']?([^"')]+)["']?\)/);
+ if (m && !m[1].startsWith("data:") && !seen.has(m[1])) {
+ seen.add(m[1]);
+ const local = localFor(m[1]);
+ if (local) locals.push(local);
+ lines.push(`- background-image ${basename(m[1])} on ${nodeLabel(node)} → ${local || "NOT DOWNLOADED"}`);
+ }
+ }
+ if (svgCount) lines.push(`- inline SVG ×${svgCount} — use/extend components in src/components/icons.tsx`);
+ if (!lines.length) lines.push("None — text and CSS only.");
+ const fmAssets = locals.length
+ ? locals.slice(0, 4).join(", ") + (locals.length > 4 ? ` +${locals.length - 4} more` : "")
+ : svgCount ? "icons only (icons.tsx)" : "none";
+ return { lines, fmAssets };
+}
+
+// ── state captures (mechanical reference for the agent's judgment block) ────
+function stateCaptures(name) {
+ const out = [];
+ if (!existsSync(sectionsDir)) return out;
+ for (const f of readdirSync(sectionsDir)) {
+ if (!f.startsWith(name + "-") || !f.endsWith(".json")) continue;
+ const doc = readJson(join(sectionsDir, f));
+ if (!doc?.trigger) continue;
+ const byProp = {};
+ for (const d of doc.diff || []) byProp[d.prop] = (byProp[d.prop] || 0) + 1;
+ const top = Object.entries(byProp).sort((a, b) => b[1] - a[1]).slice(0, 5).map(([p]) => p);
+ out.push({
+ suffix: f.slice(name.length + 1, -5),
+ file: f,
+ trigger: doc.trigger,
+ settleMs: doc.settleMs,
+ changes: (doc.diff || []).length,
+ added: (doc.added || []).length,
+ removed: (doc.removed || []).length,
+ topProps: top,
+ });
+ }
+ return out;
+}
+
+// ── responsive behavior ─────────────────────────────────────────────────────
+function responsiveLines(name, selector) {
+ const entry = responsive?.sections?.find((s) => s.name === name) || responsive?.sections?.find((s) => s.selector === selector);
+ const probe = readJson(join(hostDir, `probe-${slugify(name)}.json`));
+ const probeFor = (vp) => {
+ const bySel = probe?.results?.[vp];
+ if (!bySel) return null;
+ return bySel[selector] || Object.values(bySel)[0] || null;
+ };
+ const lines = [];
+ for (const [vp, px] of [["phone", 390], ["ipad", 768], ["pc", 1440]]) {
+ const sig = entry?.[vp];
+ const pr = probeFor(vp);
+ if (!sig && !pr) continue;
+ const parts = [];
+ if (sig) {
+ parts.push(`section ${sig.width}×${sig.height}px`);
+ if (sig.paddingX && sig.paddingX !== "0px / 0px") parts.push(`pad-x ${sig.paddingX}`);
+ if (sig.headingFontSize) parts.push(`heading ${sig.headingFontSize}`);
+ if (sig.fontSize) parts.push(`body ${sig.fontSize}`);
+ const cols = sig.innerLayout?.realColumns;
+ if (cols) parts.push(`${cols} col${cols > 1 ? "s" : ""} (${sig.innerLayout.itemCount} items, gap ${sig.innerLayout.gap})`);
+ if (sig.hiddenChildren) parts.push(`${sig.hiddenChildren} hidden children`);
+ }
+ if (pr) {
+ const p = [];
+ if (pr.paddingTop && pr.paddingTop !== "0px") p.push(`pt ${pr.paddingTop}`);
+ if (pr.paddingBottom && pr.paddingBottom !== "0px") p.push(`pb ${pr.paddingBottom}`);
+ if (pr.marginTop && pr.marginTop !== "0px") p.push(`mt ${pr.marginTop}`);
+ if (pr.maxWidth && pr.maxWidth !== "none") p.push(`max-w ${pr.maxWidth}`);
+ if (pr.lineHeight) p.push(`lh ${pr.lineHeight}`);
+ if (pr.gridTemplateColumns && pr.gridTemplateColumns !== "none") p.push(`grid [${trunc(pr.gridTemplateColumns, 36)}]`);
+ if (p.length) parts.push(p.join(", "));
+ }
+ lines.push(`- ${vp} ${px}: ${parts.join("; ")}`);
+ }
+ if (!lines.length) {
+ return [AGENT(`no responsive.json entry for "${name}" — run probe.mjs --route ${route} and fill measured values for phone/ipad/pc`)];
+ }
+ for (const c of entry?.summary?.changes || []) lines.push(`- change: ${c}`);
+ if (entry?.summary?.ipadBehavior) lines.push(`- ${entry.summary.ipadBehavior}`);
+ lines.push(`- exact per-property values: probe-${slugify(name)}.json + responsive.json (ground truth)`);
+ return lines;
+}
+
+// ── main ────────────────────────────────────────────────────────────────────
+let failed = 0;
+for (const name of sections) {
+ const doc = readJson(join(sectionsDir, `${name}.json`));
+ if (!doc) {
+ console.error(`✗ ${name}: no ${join(sectionsDir, `${name}.json`)} — extract it first (page.mjs)`);
+ failed++;
+ continue;
+ }
+ if (!doc.tree) {
+ console.error(`✗ ${name}: ${name}.json is a state capture, not a section walk — scaffold the base section`);
+ failed++;
+ continue;
+ }
+ const tree = doc.tree;
+ const captures = stateCaptures(name);
+ const comp = componentName(name);
+ const { lines: assetLines, fmAssets } = assetInfo(doc, tree);
+ const statesFm = ["default", ...captures.map((c) => c.suffix)].join(", ");
+
+ const captureLines = captures.length
+ ? captures.map((c) =>
+ `- state "${c.suffix}" (${c.file}): trigger \`${c.trigger}\`, settle ${c.settleMs}ms — ${c.changes} props changed` +
+ (c.added || c.removed ? `, +${c.added}/-${c.removed} nodes` : "") +
+ (c.topProps.length ? ` (top: ${c.topProps.join(", ")})` : "")
+ )
+ : [`- No state captures on disk. Cross-check css.json interactiveStates — a :hover/:focus rule for this section with no capture means extraction is not done.`];
+
+ const md = `---
+component: ${comp}
+target: src/components/${comp}.tsx
+page: ${route}
+screenshot: docs/design-references/${host}/${name}-pc.png
+interaction_model: ${AGENT("one of: static | click-driven | scroll-driven | hover-driven | time-driven | mixed")}
+states: ${statesFm}
+assets: ${fmAssets}
+responsive: phone, ipad, pc
+---
+
+# ${comp} Specification
+
+## DOM Structure
+${domStructure(tree).join("\n")}
+
+## Computed Styles
+${styleLines(doc, tree).join("\n")}
+
+## States & Behaviors
+${AGENT("per behavior: Trigger / State A / State B / Transition + implementation approach (CSS transition, IntersectionObserver, …). Mechanical capture data below is reference, not a substitute.")}
+${captureLines.join("\n")}
+
+## Per-State Content
+${AGENT('full content per state for tabbed/stateful sections; write "N/A — static" if the section has one state')}
+
+## Assets
+${assetLines.join("\n")}
+
+## Text Content
+${textLines(tree).join("\n")}
+
+## Responsive Behavior
+${responsiveLines(name, doc.selector).join("\n")}
+
+## Notes
+${AGENT("implementation notes for the builder: component split, data file shape for src/data/, gotchas. Delete this section if nothing to add.")}
+`;
+
+ const outDir = join(outRoot, routeSlug);
+ mkdirSync(outDir, { recursive: true });
+ const outPath = join(outDir, `${name}.spec.md`);
+ writeFileSync(outPath, md);
+ const bodyLines = md.split("\n").length;
+ console.log(`✓ ${outPath} (${bodyLines} lines, ${captures.length} captured state(s)) — fill the <!-- AGENT: fill --> blocks, then lint`);
+}
+process.exit(failed ? 1 : 0);