# glowup-ui

Adopt this skill: https://proskills.md/skills/other/avivgerz-hue-glowup-ui-skills-glowup-ui

Page: https://proskills.md/skills/other/avivgerz-hue-glowup-ui-skills-glowup-ui
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/glowup-ui/SKILL.md
size: 6556
sha: c8ae5fa96dc48b421b3321e71a2efbcfbce3c48a
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/SKILL.md

```text
---
name: glowup-ui
description: Build distinctive new web apps, transform existing frontends, refine interfaces, and implement purposeful UI motion or animation. Use when asked to create an app, redesign a frontend, improve responsive layouts, polish visuals, or implement UI interaction/motion. CREATE establishes composition and shared components on the first pass. TRANSFORM improves affected pages while preserving routes, content, data, APIs, behavior and branding. REFINE preserves identity and composition while repairing observed weaknesses. Especially useful for React, Vite, Next.js and Tailwind; adapt to the existing stack. Skip backend-only work.
license: MIT
compatibility: Agent Skills-compatible coding agents including Claude Code and Codex. Helpers use Node.js 20+ built-ins. Browser review uses an available browser or optional Playwright; never installs silently. No paid service required by the skill.
metadata:
  version: "0.1.2"
  homepage: "https://github.com/avivgerz-hue/glowup-ui"
---

# Glowup UI

Turn the user's task into a deliberate composition, then implement it. `<skill-dir>` means this folder. Follow the request and existing brand over any recipe.

## Select scope
- **CREATE:** empty project/new standalone product. Read [create-mode.md](references/create-mode.md). Establish the design in the first implementation.
- **TRANSFORM:** existing product, including new pages within it. Read [transform-mode.md](references/transform-mode.md). **Polish** keeps composition and identity. **Full redesign** may change layout, type hierarchy and shared visual components; it preserves brand, product and behavior. Do not interpret every redesign as tiny polish. Rebranding requires explicit intent.
- **REFINE** (polish): an already-designed interface or a local improvement. Use TRANSFORM's polish scope; preserve identity and composition, fix observed weaknesses.
- One element or bug: fix that scope using the existing system; skip scaffolding and broad audit.

## Execute
1. In at most four lines state the user task, scope, strongest existing feature and main weakness (or intended focal point for CREATE). No planning document.
2. Read the selected mode and [design-quality.md](references/design-quality.md). For CREATE or substantial TRANSFORM, use [design-decisions.md](references/design-decisions.md): infer TRANSFORM depth (polish/recompose/reframe), compare distinct product-specific compositions, then choose one. Skip exploration for REFINE or an already-chosen user direction. Inspect shell, theme, representative page and existing checks once. For a new system, `scripts/direction.mjs` supplies contrast-checked tokens and a product composition brief; scaffolding includes it. For an existing app lacking a clear hierarchy, use `scripts/composition.mjs --product "..." --mode redesign` without generating a replacement theme. Recipes are suggestions, not requirements. For UI motion or animation requests, also read [motion.md](references/motion.md) and implement the motion in the app; do not assume a video-generation asset is required.
3. Decide the page's focal region, supporting context, type roles and one useful signature treatment. Prioritize composition/navigation, typography, shared components and responsive states before decorative details. For full redesign, fix the shared causes across affected pages; three priorities can represent many changes, not a three-edit ceiling.
4. Implement in the app, not just a proposal. Check one representative screen, then propagate shared primitives and adapt every requested screen/state, including tabs/dialogs without separate routes. Preserve handlers, state, content, routes, APIs, auth, tests, assets and unrelated work. Use one global navigation system. No dependency or framework changes solely for styling.
5. Verify to scope using [verification.md](references/verification.md). For full work inspect actual desktop/phone screenshots and exercise the primary flow. Compare TRANSFORM with the original against its stated design priorities. Critique actual hierarchy, product specificity, navigation, consistency and phone composition separately from mechanical checks. Correct the biggest evidenced unmet priority or regression within two review rounds. Report incomplete implementation and unverified views explicitly.

## Design contract
Account for every requested screen/state as implemented, intentionally preserved with an observed reason, or incomplete. A full redesign is complete only when its identified hierarchy/composition weaknesses are addressed across affected pages, shared controls agree, and phone layouts and primary interactions work. Color/shadow-only edits do not satisfy a composition problem. Preserve already-strong sections; do not chase diff size or force novelty.

## Tools and effort
- `scripts/inspect.mjs [dir] [--scope redesign|refine]`: one orientation pass with routes, shared files and project checks; scope follows the request, not detected styling.
- `scripts/checkpoint.mjs save|check [dir]`: original-state fingerprints; save before edits, never reset to hide a failure. Warnings require review, not blind rollback of authorized design changes.
- `scripts/composition.mjs`: compact product/layout/type/phone decisions; explicit `--profile finance|commerce|productivity|portfolio|booking|chat|general` overrides keyword matching. Read-only, no network.
- `scripts/scaffold.mjs` / `scripts/direction.mjs`: CREATE foundation; keep an existing stack and brand. Do not scaffold inside an existing app.
- `scripts/screenshot.mjs`, `scripts/review.mjs`, `scripts/compare.mjs`: capture and group rendered issues. Add `--a11y` to run real DOM accessibility rules (ARIA, labels, ids, landmarks, target size) instead of relying on heuristics; critical/serious findings become blockers. Measurements are not aesthetic scores or proof of preserved behavior.
- `scripts/verify-flow.mjs`: optional browser outcome assertions when existing behavior tests do not cover an affected flow; see verification guidance.
- `scripts/palette.mjs`, `scripts/contrast.mjs`, `scripts/lint.mjs`: focused checks when relevant. Do not run every helper by habit.

Batch related reads; change shared components before repeating page edits. Small polish needs targeted checks, full redesign needs route/phone coverage. Reuse the browser and check results; no repeated analysis, mandatory planning files, decorative dependencies, invented content, silent commits or uploads. Never claim activation, visual improvement or testing without evidence.
```

## File: skills/glowup-ui/scripts/a11y.mjs
size: 11891
sha: 0efa03f6508e98723687dce551a2caba8a9ce250
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/a11y.mjs

```text
// Real accessibility rules, run inside the page. Same contract as measure.mjs: passed
// straight to page.evaluate, so it must be self-contained and must never read form values.
//
// Why this exists: everything else in the skill measures heuristics (does the button have an
// approximate name, is the contrast plausibly 4.5:1). Those heuristics cannot see ARIA misuse,
// duplicate ids, invalid roles, or a dialog that never traps focus. This implements the
// high-signal subset of the WCAG checks that a real audit reports most often, using only the
// DOM, with no dependency and no network access.
//
// It is not a replacement for a full engine or manual review, and it reports that limit.

export function auditAccessibility(options = {}) {
  const OPT = { maxViolations: 200, ...options };
  const findings = [];
  const push = (rule, impact, help, node, detail) => {
    if (findings.length >= OPT.maxViolations) return;
    findings.push({ rule, impact, help, node: String(node).slice(0, 120), detail: detail ? String(detail).slice(0, 200) : "" });
  };
  const text = (s) => String(s || "").replace(/\s+/g, " ").trim();
  const visible = (el) => {
    const s = getComputedStyle(el), r = el.getBoundingClientRect();
    return r.width > 1 && r.height > 1 && s.display !== "none" && s.visibility !== "hidden" && Number(s.opacity) !== 0 && !el.closest("[hidden], [inert]");
  };
  const describe = (el) => {
    if (!el) return "unknown";
    const tag = el.tagName.toLowerCase();
    const id = el.id ? `#${el.id}` : "";
    const cls = typeof el.className === "string" && el.className.trim() ? `.${el.className.trim().split(/\s+/)[0]}` : "";
    const label = el.getAttribute("aria-label") || el.getAttribute("name") || text(el.textContent).slice(0, 40);
    return `${tag}${id}${cls}${label ? ` "${label}"` : ""}`;
  };
  const accessibleName = (el) => {
    const labelledby = el.getAttribute("aria-labelledby");
    if (labelledby) {
      const joined = labelledby.split(/\s+/).map((id) => document.getElementById(id)?.textContent || "").join(" ");
      if (text(joined)) return text(joined);
    }
    const label = el.getAttribute("aria-label");
    if (text(label)) return text(label);
    if (el.labels && el.labels.length) return text([...el.labels].map((l) => l.textContent).join(" "));
    if (el.tagName === "IMG") return text(el.getAttribute("alt"));
    if (el.tagName === "INPUT" && ["button", "submit", "reset"].includes(el.type)) return text(el.value) || el.getAttribute("title") || "";
    return text(el.textContent) || text(el.getAttribute("title"));
  };
  const all = [...document.querySelectorAll("*")].filter((el) => !el.closest("script, style, template"));
  const shown = all.filter(visible);

  // 1. Images need an alternative (decorative images use alt="").
  for (const img of all.filter((el) => el.matches("img"))) {
    if (img.getAttribute("alt") === null) push("image-alt", "critical", "Images need an alt attribute (alt=\"\" when decorative)", describe(img));
    if (!img.complete || img.naturalWidth === 0) push("image-broken", "serious", "Image failed to load", describe(img), img.currentSrc || img.src);
  }

  // 2. Interactive elements need a name.
  // Form fields are handled once, by rule 3, so a single unlabelled checkbox cannot be
  // reported three times under two rules.
  const FIELD = "input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]), select, textarea";
  for (const el of shown) {
    if (el.matches(FIELD)) continue;
    if (!el.matches("button, a[href], [role=button], [role=link], [role=checkbox], [role=radio], [role=tab], [role=switch]")) continue;
    if (!accessibleName(el)) push("control-name", "critical", "Interactive controls need an accessible name", describe(el));
  }

  // 3. Form fields need a real label (a placeholder is not a label).
  for (const field of shown.filter((el) => el.matches(FIELD))) {
    // An associated but empty <label> names nothing, so require actual text.
    const labelText = text([...(field.labels || [])].map((l) => l.textContent).join(" "));
    const hasLabel = Boolean(labelText || text(field.getAttribute("aria-label")) || text(field.getAttribute("aria-labelledby")) || accessibleName(field));
    if (!hasLabel) push("field-label", "critical", "Form fields need a visible or programmatic label, not only a placeholder", describe(field), field.getAttribute("placeholder") ? `only placeholder "${field.getAttribute("placeholder")}"` : "");
  }

  // 4. ARIA roles must exist, and required attributes must be present.
  const VALID_ROLES = new Set("alert alertdialog application article banner button cell checkbox columnheader combobox complementary contentinfo definition dialog directory document feed figure form grid gridcell group heading img link list listbox listitem log main marquee math menu menubar menuitem menuitemcheckbox menuitemradio meter navigation none note option paragraph presentation progressbar radio radiogroup region row rowgroup rowheader scrollbar search searchbox separator slider spinbutton status switch tab table tablist tabpanel term textbox timer toolbar tooltip tree treegrid treeitem".split(" "));
  for (const el of all) {
    const roles = (el.getAttribute("role") || "").trim().toLowerCase().split(/\s+/).filter(Boolean);
    for (const role of roles) if (!VALID_ROLES.has(role)) push("aria-role-invalid", "serious", `"${role}" is not a valid ARIA role`, describe(el));
  }
  for (const el of all.filter((e) => ["checkbox", "switch", "radio"].includes(e.getAttribute("role")))) {
    if (!el.hasAttribute("aria-checked")) push("aria-required-attr", "serious", `role="${el.getAttribute("role")}" requires aria-checked`, describe(el));
  }
  for (const el of all.filter((e) => ["combobox", "listbox"].includes(e.getAttribute("role")))) {
    if (!el.hasAttribute("aria-expanded") && el.getAttribute("role") === "combobox") push("aria-required-attr", "serious", 'role="combobox" requires aria-expanded', describe(el));
  }

  // 5. aria-hidden must not hide focusable content from assistive technology.
  for (const el of all.filter((e) => e.getAttribute("aria-hidden") === "true")) {
    const focusable = el.querySelector('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
    if (focusable && visible(el)) push("aria-hidden-focus", "serious", "aria-hidden=\"true\" contains focusable content, which keyboard users can still reach", describe(el), describe(focusable));
  }

  // 6. Duplicate ids break label/aria references.
  const ids = new Map();
  for (const el of all) if (el.id) ids.set(el.id, (ids.get(el.id) || 0) + 1);
  for (const [id, n] of ids) if (n > 1) push("duplicate-id", "serious", `id "${id}" is used ${n} times; labels and aria-* references resolve to the first one`, `#${id}`);

  // 7. Headings must not skip levels.
  const headings = shown.filter((el) => /^H[1-6]$/.test(el.tagName)).map((el) => ({ level: Number(el.tagName[1]), el }));
  for (let i = 1; i < headings.length; i++) {
    if (headings[i].level - headings[i - 1].level > 1) push("heading-skip", "moderate", `Heading level jumps ${headings[i - 1].level} -> ${headings[i].level}`, describe(headings[i].el));
  }
  // No heading at all, or headings that never reach level 1, are both a missing page title.
  // Reporting only the zero-heading case missed the common "h2s but no h1" page.
  if (!headings.length) push("page-has-heading", "moderate", "Page has no headings", "document");
  else if (!headings.some((h) => h.level === 1)) push("page-has-heading", "moderate", "Page has no h1 heading", `${headings.length} heading(s), none at level 1`);
  if (headings.filter((h) => h.level === 1).length > 1) push("page-multiple-h1", "moderate", "More than one h1", `${headings.filter((h) => h.level === 1).length} h1 elements`);

  // 8. Landmarks.
  if (!document.querySelector('main, [role="main"]')) push("landmark-main", "moderate", "Page has no main landmark", "document");

  // 9. Scroll containers must be reachable by keyboard.
  for (const el of shown) {
    const s = getComputedStyle(el);
    if (!/auto|scroll/.test(s.overflowX + s.overflowY)) continue;
    if (el.scrollHeight <= el.clientHeight + 2 && el.scrollWidth <= el.clientWidth + 2) continue;
    const focusable = el.tabIndex >= 0 || el.querySelector('a[href], button, input, select, textarea, [tabindex="0"]');
    if (!focusable) push("scrollable-region-focusable", "serious", "A scrollable region has no keyboard access", describe(el));
  }

  // 10. Buttons with a type, so a form cannot submit by accident.
  for (const btn of shown.filter((el) => el.tagName === "BUTTON")) {
    if (!btn.hasAttribute("type") && btn.form) push("button-type", "minor", "A <button> inside a form should declare type=\"button\" unless it submits", describe(btn));
  }

  // 11. Focus visibility.
  //
  // This cannot be judged from the computed style of an unfocused element: browsers resolve
  // outline-style to "none" until :focus applies, so per-element testing flags every control on
  // the page. What is knowable statically is whether the page declares any focus styling at all.
  // A stylesheet with no :focus rule is the common "agent removed the outline" failure, so it
  // is reported once, at page level, instead of hundreds of per-element guesses.
  let focusRules = 0;
  const readRules = (rules) => {
    for (const rule of rules || []) {
      const text = rule.selectorText || rule.cssText || "";
      if (/:focus(-visible|-within)?\b/.test(text)) focusRules++;
      if (rule.cssRules) readRules(rule.cssRules);
    }
  };
  for (const sheet of document.styleSheets || []) {
    try { readRules(sheet.cssRules); } catch { /* cross-origin sheet: unreadable, not evidence */ }
  }
  for (const style of document.querySelectorAll("style")) {
    if (/:focus(-visible|-within)?\b/.test(style.textContent || "")) focusRules++;
  }
  const interactive = shown.filter((e) => e.matches("a[href], button, input, select, textarea, [tabindex]"));
  if (interactive.length && focusRules === 0) {
    push("focus-style-missing", "serious", "No :focus or :focus-visible rule found anywhere; keyboard users may get no visible focus", `${interactive.length} interactive elements`, "static check: add an explicit focus style and confirm with the keyboard");
  }

  // 12. Target size (WCAG 2.5.8 AA = 24px; the skill's design bar is 44px for touch).
  const small = shown.filter((el) => el.matches("button, a[href], [role=button], input[type=checkbox], input[type=radio]")).map((el) => {
    const r = el.getBoundingClientRect();
    return { el, w: Math.round(r.width), h: Math.round(r.height) };
  }).filter(({ el, w, h }) => !(el.tagName === "A" && getComputedStyle(el).display === "inline") && (w < 24 || h < 24));
  for (const { el, w, h } of small) push("target-size-min", "moderate", "Target is smaller than the 24px WCAG 2.5.8 minimum", describe(el), `${w}x${h}px`);

  // 13. Document language and title.
  if (!document.documentElement.lang) push("html-lang", "serious", "<html> has no lang attribute", "html");
  if (!text(document.title)) push("document-title", "serious", "Document has no title", "head");

  const byImpact = { critical: 0, serious: 0, moderate: 0, minor: 0 };
  for (const f of findings) byImpact[f.impact] = (byImpact[f.impact] || 0) + 1;
  return {
    version: 1,
    engine: "glowup-dom-rules",
    checked: shown.length,
    truncated: findings.length >= OPT.maxViolations,
    total: findings.length,
    byImpact,
    rules: [...new Set(findings.map((f) => f.rule))],
    findings,
    limitations: "DOM-only rules: no contrast-over-image, no screen reader, no keyboard trap, no live-region or focus-movement proof. focus-style-missing only detects a page with no :focus rules at all; it cannot judge whether a declared style is actually visible, so confirm focus with the keyboard.",
  };
}
```

## File: skills/glowup-ui/scripts/audit.mjs
size: 8376
sha: a3c8eed3a491a38414ad69222bc5da07d0030eb6
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/audit.mjs

```text
#!/usr/bin/env node
// Behavior and copy audit for redesigns. Compares the working tree with a git base (default HEAD):
//   - wiring that must survive a redesign: event handlers, ids, label links, roles, aria-*,
//     link targets, route paths, navigation and dialog calls
//   - user-visible copy that disappeared, and new copy that appeared (possible invented text)
//   - changes under tests/
// Read-only. Run from the project root:  node audit.mjs [--base HEAD] [--json]

import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

const SRC_DIRS = ["src", "app", "pages", "components", "lib"];
const CODE = /\.(jsx?|tsx?|vue|svelte|astro)$/;
const norm = (t) => t.replace(/\s+/g, " ").trim();

const WIRING = [
  /\bon[A-Z][A-Za-z]+=\{[^}]*\}?/g,
  /\b(?:on[a-z]+|on:[\w-]+(?:\|[\w-]+)*)=\{[^}]*\}/g,
  /@[\w:-]+(?:\.[\w-]+)*=(?:"[^"]*"|'[^']*')/g,
  /\bv-(?:model|on:[\w-]+)(?::[\w-]+)?(?:\.[\w-]+)*=(?:"[^"]*"|'[^']*')/g,
  /\b(?:bind|use):[\w-]+(?:=\{[^}]*\})?/g,
  /:[\w-]+=(?:"[^"]*"|'[^']*')/g,
  /\b(?:id|htmlFor|for|role|name|type|action|method|data-testid)=(?:"[^"]+"|'[^']+')/g,
  /\baria-(?!hidden)[a-z-]+=(?:"[^"]*"|'[^']*'|\{[^}]*\})/g,
  /\b(?:to|href)=(?:"[^"]+"|'[^']+'|\{`[^`]+`\}|\{"[^"]+"\})/g,
  /\bpath(?:=|:\s*)["'`][^"'`]*["'`]/g,
  /\b(?:navigate|alert|confirm|prompt)\([^)]*\)/g,
  /\bnoValidate\b/g,
];

function git(args, cwd) {
  const r = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
  return r.status === 0 ? r.stdout : null;
}

function listBase(cwd, base) {
  const out = git(["ls-tree", "-r", "--name-only", base], cwd);
  return (out || "").split("\n").filter((f) => CODE.test(f) && SRC_DIRS.some((d) => f === d || f.startsWith(`${d}/`)));
}

function listNow(cwd) {
  const out = [];
  const walk = (dir) => {
    for (const e of fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }) : []) {
      if (e.name === "node_modules" || e.name.startsWith(".")) continue;
      const p = path.join(dir, e.name);
      if (e.isDirectory()) walk(p); else if (CODE.test(e.name)) out.push(path.relative(cwd, p).split(path.sep).join("/"));
    }
  };
  for (const d of SRC_DIRS) walk(path.join(cwd, d));
  return out;
}

export function wiringTokens(text) {
  return new Set(wiringOccurrences(text));
}

export function wiringOccurrences(text) {
  const found = [];
  for (const re of WIRING) for (const m of text.matchAll(re)) found.push(norm(m[0]).split(" className=")[0]);
  return found;
}

const ATTRS = /\b(?:title|placeholder|aria-label|alt|label|value)="([^"{}]{3,})"/g;
// Any other string prop that reads like a sentence (3+ words), e.g. description="Welcome back...".
const PROSE_PROP = /\b(?!(?:className|class|style|viewBox|points|transform|d|fill|stroke|href|to|id|htmlFor)=)[a-zA-Z-]+="([^"{}]*\s[^"{}]*\s[^"{}]*)"/g;
const LOOKS_LIKE_CODE = /^[),;:}\]]|[(\[{=]\s*$|=>|\bfunction\b|\breturn\b|:\s*\($|\/\/|;\s*(?:const|let|var|if)\b/;

export function copyStrings(text) {
  const found = new Set();
  const add = (s) => { const t = norm(s); if (t.length >= 3 && /[A-Za-z]{3}/.test(t) && !LOOKS_LIKE_CODE.test(t)) found.add(t); };
  for (const m of text.matchAll(/>([^<>{}]*[A-Za-z][^<>{}]*)</g)) add(m[1]);
  for (const m of text.matchAll(/\{\s*["'`]([^"'`{}$]{3,})["'`]\s*\}/g)) add(m[1]);
  for (const m of text.matchAll(ATTRS)) add(m[1]);
  for (const m of text.matchAll(PROSE_PROP)) add(m[1]);
  return found;
}

// Visual richness that must not shrink in a redesign: illustrations, images, icons, avatars, charts, progress, badges.
const VISUALS = { brandmarks: /<(?:Logo\w*|Wordmark)\b/g, illustrations: /<svg\b|<Illustration\b|<ArtTile\b/g, images: /<img\b|<Image\b/g, icons: /<[A-Z][A-Za-z]*Icon\b|<Icon\b|lucide-react|react-icons/g, avatars: /<Avatar\w*\b/g, charts: /<(?:\w*Chart|Sparkline|Donut|BarList|canvas)\b|recharts/g, progress: /<Progress\w*\b|role="progressbar"|<progress\b/g, badges: /<Badge\b|<Chip\b|<Tag\b|rounded-full[^"']*\b(?:px|bg)-/g };
export function countVisuals(text) { const out = {}; for (const [k, re] of Object.entries(VISUALS)) out[k] = (text.match(re) || []).length; return out; }

function collect(files, read) {
  const wiring = new Set(), copy = new Set(), visuals = Object.fromEntries(Object.keys(VISUALS).map((k) => [k, 0]));
  for (const f of files) {
    const text = read(f);
    if (text == null) continue;
    for (const [k, n] of Object.entries(countVisuals(text))) visuals[k] += n;
    for (const t of wiringTokens(text)) wiring.add(t);
    for (const s of copyStrings(text)) copy.add(s);
  }
  return { wiring, copy, visuals };
}

export function audit(cwd = process.cwd(), base = "HEAD") {
  if (git(["rev-parse", "--verify", base], cwd) === null) throw new Error(`Not a git repository, or unknown base "${base}". Run this from the project root.`);
  const baseFiles = listBase(cwd, base);
  const nowFiles = listNow(cwd);
  const before = collect(baseFiles, (f) => git(["show", `${base}:${f}`], cwd));
  const after = collect(nowFiles, (f) => fs.readFileSync(path.join(cwd, f), "utf8"));
  const lostWiring = [...before.wiring].filter((t) => !after.wiring.has(t));
  const lostCopy = [...before.copy].filter((t) => !after.copy.has(t));
  const newCopy = [...after.copy].filter((t) => !before.copy.has(t) && !/^(Skip to|Open|Close|Toggle|Menu|Main|Primary|Navigation)\b/i.test(t));
  const shrunk = Object.entries(before.visuals).filter(([k, n]) => n >= 3 && after.visuals[k] < n * 0.65).map(([k, n]) => ({ kind: k, before: n, after: after.visuals[k] }));
  const testsChanged = (git(["status", "--porcelain", "--", "tests", "test", "__tests__"], cwd) || "").split("\n").filter(Boolean);
  return {
    base, filesCompared: { before: baseFiles.length, now: nowFiles.length },
    wiring: { before: before.wiring.size, preserved: before.wiring.size - lostWiring.length, lost: lostWiring },
    copy: { lost: lostCopy, added: newCopy },
    visuals: { before: before.visuals, after: after.visuals, shrunk },
    testsChanged,
  };
}

export function report(r) {
  const out = [`Behavior audit vs ${r.base} (${r.filesCompared.now} source files now, ${r.filesCompared.before} at base)`];
  const show = (list, n = 8) => list.slice(0, n).map((s) => `    - ${s.length > 110 ? s.slice(0, 107) + "..." : s}`).concat(list.length > n ? [`    ...and ${list.length - n} more`] : []);
  if (r.wiring.lost.length === 0) out.push(`✓ Wiring: all ${r.wiring.before} handlers, ids, roles, aria attributes, link targets, and routes are preserved`);
  else { out.push(`✗ Wiring: ${r.wiring.lost.length} of ${r.wiring.before} items from the original are missing. Restore them, or confirm each was intentionally replaced:`, ...show(r.wiring.lost)); }
  if (r.copy.lost.length === 0) out.push("✓ Copy: no original text was lost");
  else out.push(`! Copy: ${r.copy.lost.length} original strings no longer appear. Restore any that were not moved or restyled:`, ...show(r.copy.lost));
  if (r.copy.added.length === 0) out.push("✓ Copy: no new text was added");
  else out.push(`! Copy: ${r.copy.added.length} new strings. Keep labels for icons and screen readers; remove invented taglines, claims, or filler:`, ...show(r.copy.added));
  if (r.visuals.shrunk.length === 0) out.push("✓ Richness: no kind of visual element (illustrations, images, icons, avatars, charts, progress, badges) shrank noticeably");
  else out.push("! Richness: these visual elements shrank. Make sure the redesign is not a downgrade; restore what made the original better:", ...r.visuals.shrunk.map((v) => `    - ${v.kind}: ${v.before} -> ${v.after}`));
  out.push(r.testsChanged.length === 0 ? "✓ Tests: untouched" : `✗ Tests: changed (${r.testsChanged.length}). A redesign should not edit tests:\n${show(r.testsChanged).join("\n")}`);
  return out.join("\n");
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({ options: { base: { type: "string", default: "HEAD" }, json: { type: "boolean", default: false } } });
  try {
    const r = audit(process.cwd(), values.base);
    console.log(values.json ? JSON.stringify(r, null, 2) : report(r));
    process.exit(r.wiring.lost.length || r.testsChanged.length ? 1 : 0);
  } catch (error) {
    console.error(error.message);
    process.exit(64);
  }
}
```

## File: skills/glowup-ui/scripts/checkpoint.mjs
size: 12616
sha: 79de1123c0c141b954839bb28893651ac8834ed4
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/checkpoint.mjs

```text
#!/usr/bin/env node
// Local, dependency-free preservation checks. Never restores files or executes project code.
// node checkpoint.mjs save|check [project] [--file .glowup/checkpoint.json] [--json]
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { parseArgs } from "node:util";
import { fileURLToPath } from "node:url";
import { wiringOccurrences, copyStrings, countVisuals } from "./audit.mjs";
import { detectLook } from "./look.mjs";

const SKIP = new Set(["node_modules", ".git", ".glowup", ".next", ".nuxt", ".svelte-kit", ".claude", ".agents", ".opencode", ".glowup-ui", "dist", "build", "coverage", ".cache", "vendor"]);
const SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|html|css|scss|sass|less)$/i;
const ASSET = /\.(?:svg|png|jpe?g|webp|avif|gif|ico|woff2?|ttf|otf)$/i;
const TEST = /(?:^|\/)(?:tests?|__tests__|e2e|cypress|playwright)(?:\/|\.)|\.(?:test|spec)\.[^.]+$/i;
const CONFIG = /(?:^|\/)(?:package\.json|.*lock.*|[^/]*config\.[^/]+|tsconfig[^/]*\.json|\.env[^/]*|\.npmrc|\.yarnrc[^/]*|[^/]*routes?\.[^/]+)$/i;
const BRAND = /(?:^|\/)[^/]*(?:logo|wordmark|brandmark)[^/]*$/i;
const hash = (data) => createHash("sha256").update(data).digest("hex");
const normalize = (s) => s.replace(/\s+/g, " ").trim();
const chromeCount = (text) => (text.match(/<header\b|<(?:AppHeader|SiteHeader|GlobalHeader|TopBar|Navbar)\b/g) || []).length;

function files(root, dir = root, out = []) {
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (SKIP.has(entry.name)) continue;
    const full = path.join(dir, entry.name);
    // Do not follow symlinks; record their target without reading external content.
    if (entry.isDirectory()) files(root, full, out);
    else out.push(path.relative(root, full).split(path.sep).join("/"));
  }
  return out.sort();
}

function identity(text) {
  // Freeze existing palette and typography declarations, including repeated dark-mode tokens.
  const tokens = [...text.matchAll(/(?:--[\w-]*(?:color|brand|primary|accent|ink|canvas|surface|font)[\w-]*|font-family|color-scheme)\s*:\s*([^;{}]+)/gi)]
    .map((m) => normalize(m[0]));
  // Brand components can live alongside ordinary icons, rather than in Logo.jsx.
  // Conservative source slices: changes require review, including legitimate refactors.
  for (const m of text.matchAll(/(?:^|\n)(?:export\s+)?(?:default\s+)?(?:function|const|let)\s+\w*(?:Logo|Wordmark|Brandmark)\w*\b[\s\S]*?(?=\n(?:export\s+)?(?:default\s+)?(?:function|const|let)\s|$(?![\s\S]))/gi)) tokens.push(`brand-component:${hash(normalize(m[0]))}`);
  return tokens.sort();
}

function dirtyFiles(root) {
  const r = spawnSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], { cwd: root, encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024 * 1024 });
  if (r.status !== 0) {
    if (r.status === 128 && /not a git repository/i.test(r.stderr || "")) return [];
    if (r.error?.code === "ENOENT" && !process.env.GIT_DIR && !process.env.GIT_WORK_TREE) {
      let metadata = false;
      for (let dir = root; ; dir = path.dirname(dir)) {
        const gitPath = path.join(dir, ".git"), stat = fs.lstatSync(gitPath, { throwIfNoEntry: false });
        if (stat && (!stat.isDirectory() || ["HEAD", "config", "objects"].some((f) => fs.existsSync(path.join(gitPath, f))))) metadata = true;
        if (path.dirname(dir) === dir) break;
      }
      if (!metadata) return []; // Git is optional for a positively non-Git project.
    }
    throw new Error("Cannot inspect existing Git changes safely. Resolve Git access/status before saving or checking a checkpoint.");
  }
  const entries = r.stdout.split("\0");
  const out = [];
  for (let i = 0; i < entries.length; i++) {
    const entry = entries[i];
    if (!entry) continue;
    out.push(entry.slice(3));
    if (/[RC]/.test(entry.slice(0, 2))) i++;
  }
  return out;
}

export function snapshot(root) {
  root = fs.realpathSync(root);
  const dirty = new Set(dirtyFiles(root));
  const records = {};
  for (const name of files(root)) {
    const full = path.join(root, name);
    const stat = fs.lstatSync(full);
    const nonVisualCode = /\.[cm]?[jt]s$/.test(name) && !/<[A-Za-z][\w.-]*(?:\s|>|\/)/.test(fs.lstatSync(full).isFile() ? fs.readFileSync(full, "utf8") : "");
    const fixed = TEST.test(name) || CONFIG.test(name) || ASSET.test(name) || BRAND.test(name) || nonVisualCode;
    const frozen = fixed || dirty.has(name);
    if (stat.isSymbolicLink()) {
      records[name] = { hash: hash(fs.readlinkSync(full)), frozen: true, symlink: true };
      continue;
    }
    if (!stat.isFile() || (!frozen && !SOURCE.test(name))) continue;
    const bytes = fs.readFileSync(full);
    const record = { hash: hash(bytes), frozen, fixed };
    // Do not store environment/config/asset contents in the checkpoint.
    if (SOURCE.test(name) && !frozen) {
      const text = bytes.toString("utf8");
      record.wiring = wiringOccurrences(text);
      record.copy = [...copyStrings(text)];
      record.visuals = countVisuals(text);
      record.identity = identity(text);
      record.chrome = chromeCount(text);
    }
    records[name] = record;
  }
  if (!Object.keys(records).length) throw new Error("No application files found; choose the application root.");
  return { version: 1, root, createdAt: new Date().toISOString(), look: detectLook(root), records };
}

export function compareCheckpoint(before, after) {
  if (before.version !== 1 || after.version !== 1 || before.root !== after.root) throw new Error("Checkpoint belongs to another project or unsupported version.");
  const failures = [], warnings = [], relocated = [];
  const changed = [];
  const count = (records, key) => {
    const counts = new Map();
    for (const record of Object.values(records)) for (const token of record[key] || []) counts.set(token, (counts.get(token) || 0) + 1);
    return counts;
  };
  // Count per-file occurrences so a control still present on another page cannot hide its removal.
  for (const key of ["wiring", "copy"]) {
    const prev = count(before.records, key), now = count(after.records, key);
    for (const [token, n] of prev) if ((now.get(token) || 0) < n) failures.push({ kind: key, detail: token, before: n, after: now.get(token) || 0 });
    // Moving a handler or a sentence to a different file keeps the totals intact, so the
    // aggregate check above cannot see it. Separate-file relocation is usually extraction or
    // a component move, so it needs review rather than a silent pass.
    for (const [token, n] of prev) {
      const still = now.get(token) || 0;
      if (still < n) continue; // already reported as a loss above
      if (still > n) continue;  // duplicated, not relocated
      const from = [], to = [];
      for (const [name, record] of Object.entries(before.records)) if ((record[key] || []).includes(token)) from.push(name);
      for (const [name, record] of Object.entries(after.records)) if ((record[key] || []).includes(token)) to.push(name);
      const left = from.filter((name) => !to.includes(name));
      if (!left.length) continue; // still where it was; nothing to report
      // Extracting a control into a new component is a legitimate restructuring: the markup
      // still exists in a new file, so nothing can be lost. Say it moved, and leave the verdict alone.
      const sourceIntact = left.every((name) => name in after.records);
      const landedInNew = to.some((name) => !(name in before.records));
      relocated.push({ kind: `relocated-${key}`, detail: token, from: left.join(", "), to: to.join(", "), moved: sourceIntact && landedInNew });
    }
  }
  const originalCopy = count(before.records, "copy");
  for (const token of count(after.records, "copy").keys()) {
    if (!originalCopy.has(token)) warnings.push({ kind: "new-copy", detail: token });
  }
  for (const [name, prev] of Object.entries(before.records)) {
    const now = after.records[name];
    if (now?.hash === prev.hash) continue;
    changed.push(name);
    if (prev.frozen) failures.push({ kind: "protected-file", file: name, detail: now ? "changed" : "removed" });
    if (prev.identity?.length && JSON.stringify(prev.identity) !== JSON.stringify(now?.identity || [])) failures.push({ kind: "identity", file: name, detail: "Existing palette or typography declarations changed; review before accepting." });
    for (const [kind, n] of Object.entries(prev.visuals || {})) {
      if ((now?.visuals?.[kind] || 0) < n) warnings.push({ kind: "visual-loss", file: name, detail: kind, before: n, after: now?.visuals?.[kind] || 0 });
    }
  }
  for (const name of Object.keys(after.records)) if (!(name in before.records)) {
    changed.push(name);
    if (after.records[name].frozen) failures.push({ kind: "protected-file", file: name, detail: "added" });
  }
  if (before.look.shell && before.look.shell !== after.look.shell) warnings.push({ kind: "shell", detail: `${before.look.shell} -> ${after.look.shell || "unknown"}` });
  if (before.look.scheme !== after.look.scheme) warnings.push({ kind: "scheme", detail: `${before.look.scheme} -> ${after.look.scheme}` });
  const headers = (records) => Object.values(records).reduce((n, record) => n + (record.chrome || 0), 0);
  if (headers(after.records) > headers(before.records)) warnings.push({ kind: "added-chrome", detail: "Additional global header markup detected; verify that navigation, avatar, and notifications are not duplicated." });
  return { ok: !failures.length && !warnings.length, changed, failures, warnings, relocated, limitation: "Source heuristics, not a proof of behavior or visual quality. Review false positives; do not weaken checks to pass. Run original tests and compare every affected route in a browser." };
}

export function check(root, baseline) {
  const after = snapshot(root);
  // A file that was initially dirty remains protected even if an agent committed it.
  // Conversely, our own UI edits must not become protected merely because they are now dirty.
  for (const [name, record] of Object.entries(after.records)) {
    if (!baseline.records[name]?.frozen && record.frozen && !record.fixed && !record.symlink && SOURCE.test(name)) {
      const text = fs.readFileSync(path.join(root, name), "utf8");
      Object.assign(record, { frozen: false, wiring: wiringOccurrences(text), copy: [...copyStrings(text)], visuals: countVisuals(text), identity: identity(text), chrome: chromeCount(text) });
    }
    if (!(name in baseline.records) && !record.fixed && !record.symlink) record.frozen = false;
  }
  return compareCheckpoint(baseline, after);
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  try {
    const { values, positionals } = parseArgs({ allowPositionals: true, options: { file: { type: "string", default: ".glowup/checkpoint.json" }, json: { type: "boolean", default: false } } });
    const [command, project = "."] = positionals;
    const root = fs.realpathSync(project), file = path.resolve(root, values.file);
    if (command === "save") {
      const baseline = snapshot(root);
      fs.mkdirSync(path.dirname(file), { recursive: true });
      // Never overwrite the evidence from before editing.
      fs.writeFileSync(file, JSON.stringify(baseline, null, 2) + "\n", { flag: "wx", mode: 0o600 });
      console.log(`Saved ${Object.keys(baseline.records).length} file fingerprints to ${file}. Keep this original checkpoint until review is complete.`);
    } else if (command === "check") {
      const result = check(root, JSON.parse(fs.readFileSync(file, "utf8")));
      const movedLines = (result.relocated || []).filter((r) => !r.moved).map((r) => `- moved (review): ${r.kind}: ${r.detail}  [${r.from} -> ${r.to}]`);
      const extractedLines = (result.relocated || []).filter((r) => r.moved).map((r) => `- extracted (ok): ${r.kind}: ${r.detail}  [${r.from} -> ${r.to}]`);
      console.log(values.json ? JSON.stringify(result, null, 2) : `${result.ok ? "PASS" : "REVIEW REQUIRED"}: ${result.changed.length} changed files, ${result.failures.length} preservation failures, ${result.warnings.length} visual warnings\n${[...result.failures, ...result.warnings].map((f) => `- ${f.kind}: ${f.file || ""} ${f.detail}`).join("\n")}${movedLines.length || extractedLines.length ? `\n${[...movedLines, ...extractedLines].join("\n")}` : ""}\n${result.limitation}`);
      process.exitCode = result.ok ? 0 : 1;
    } else throw new Error("Usage: checkpoint.mjs save|check [project] [--file path] [--json]");
  } catch (error) { console.error(error.message); process.exitCode = 64; }
}
```

## File: skills/glowup-ui/scripts/compare.mjs
size: 5211
sha: b98e04dc37695ad45d5f160a66a49376dcce320d
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/compare.mjs

```text
#!/usr/bin/env node
// Build a local side-by-side before/after page from screenshot manifests.
// Usage: node compare.mjs [--out .glowup/screenshots] [--before before] [--after after]

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

export function escapeHtml(value) {
  return String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
}

function readManifest(dir) {
  const file = path.join(dir, "manifest.json");
  if (!fs.existsSync(file)) return null;
  return JSON.parse(fs.readFileSync(file, "utf8"));
}

export function pairShots(before, after) {
  const key = (s) => `${s.viewport}::${s.route}`;
  const map = new Map();
  for (const s of before?.shots || []) map.set(key(s), { route: s.route, viewport: s.viewport, before: s, after: null });
  for (const s of after?.shots || []) {
    const entry = map.get(key(s)) || { route: s.route, viewport: s.viewport, before: null, after: null };
    entry.after = s;
    map.set(key(s), entry);
  }
  return [...map.values()];
}

function cell(shot, labelDir) {
  if (!shot) return `<div class="missing">Not captured</div>`;
  const badges = [];
  if (shot.status !== "ok") badges.push(`<span class="badge warn">${escapeHtml(shot.status)}</span>`);
  if (shot.overflowX) badges.push(`<span class="badge warn">horizontal overflow</span>`);
  const img = shot.file
    ? `<a href="${escapeHtml(`${labelDir}/${shot.file}`)}"><img loading="lazy" src="${escapeHtml(`${labelDir}/${shot.file}`)}" alt="${escapeHtml(`${shot.route} (${shot.viewport})`)}"></a>`
    : `<div class="missing">${escapeHtml(shot.error || "No image")}</div>`;
  return `${badges.join(" ")}${img}`;
}

export function renderCompare(before, after, { beforeLabel = "before", afterLabel = "after" } = {}) {
  const pairs = pairShots(before, after);
  const rows = pairs.map((p) => `
    <section>
      <h2><code>${escapeHtml(p.route)}</code> <span class="vp">${escapeHtml(p.viewport)}</span></h2>
      <div class="pair ${p.viewport === "mobile" ? "narrow" : ""}">
        <figure><figcaption>Before</figcaption>${cell(p.before, beforeLabel)}</figure>
        <figure><figcaption>After</figcaption>${cell(p.after, afterLabel)}</figure>
      </div>
    </section>`).join("\n");
  return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Glowup UI — before / after</title>
<style>
  :root { color-scheme: light dark; --bg: #f7f7f8; --fg: #18181b; --muted: #71717a; --card: #fff; --line: #e4e4e7; }
  @media (prefers-color-scheme: dark) { :root { --bg: #0f0f12; --fg: #f4f4f5; --muted: #a1a1aa; --card: #18181b; --line: #27272a; } }
  * { box-sizing: border-box; }
  body { margin: 0; font: 15px/1.5 system-ui, -apple-system, Segoe UI, sans-serif; background: var(--bg); color: var(--fg); }
  header, main { max-width: 1400px; margin: 0 auto; padding: 24px 16px; }
  h1 { margin: 0 0 4px; font-size: 24px; letter-spacing: -0.02em; }
  header p { margin: 0; color: var(--muted); }
  section { background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 16px; margin-bottom: 24px; }
  h2 { font-size: 15px; margin: 0 0 12px; } .vp { color: var(--muted); font-weight: 400; }
  .pair { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
  .pair.narrow { max-width: 860px; }
  @media (max-width: 700px) { .pair { grid-template-columns: 1fr; } }
  figure { margin: 0; min-width: 0; } figcaption { font-size: 12px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin-bottom: 6px; }
  img { width: 100%; height: auto; display: block; border: 1px solid var(--line); border-radius: 8px; }
  .missing { padding: 32px; text-align: center; color: var(--muted); border: 1px dashed var(--line); border-radius: 8px; }
  .badge { display: inline-block; font-size: 12px; padding: 2px 8px; border-radius: 999px; margin-bottom: 6px; }
  .warn { background: #fef3c7; color: #92400e; }
</style>
</head>
<body>
<header>
  <h1>Before / after</h1>
  <p>Before: ${escapeHtml(before?.capturedAt || "not captured")} · After: ${escapeHtml(after?.capturedAt || "not captured")} · ${pairs.length} comparisons</p>
</header>
<main>
${rows || "<p>No screenshots found.</p>"}
</main>
</body>
</html>
`;
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      out: { type: "string", default: ".glowup/screenshots" },
      before: { type: "string", default: "before" },
      after: { type: "string", default: "after" },
    },
  });
  const before = readManifest(path.join(values.out, values.before));
  const after = readManifest(path.join(values.out, values.after));
  if (!before && !after) {
    console.error(`No manifests found in ${values.out}/${values.before} or ${values.out}/${values.after}. Run screenshot.mjs first.`);
    process.exit(66);
  }
  const file = path.join(values.out, "compare.html");
  fs.writeFileSync(file, renderCompare(before, after, { beforeLabel: values.before, afterLabel: values.after }));
  console.log(`Wrote ${file}`);
}
```

## File: skills/glowup-ui/scripts/composition.mjs
size: 10490
sha: a8ca83a9dcec41b2182e8acbb38e93429c3647b8
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/composition.mjs

```text
#!/usr/bin/env node
// Original, bounded product recipes. Read-only; no dependency or network access.
import { parseArgs } from 'node:util';
import { fileURLToPath } from 'node:url';

export const RECIPES = {
  chat: {
    terms: ['chat','chatbot','conversation','messaging','assistant'],
    goal: 'Read the conversation, compose without losing context, and find earlier work.',
    composition: 'Give the transcript the dominant region with a readable text measure. Keep history in one navigation region and composer in its own layout row. History is a searchable collection; settings is a grouped form, not another transcript.',
    type: 'Use a readable body family, comfortable message leading and restrained author labels. Differentiate senders with alignment or surface before reducing text contrast; metadata must stay readable in both themes.',
    responsive: 'Use a flexible transcript row (min-height: 0) with keyboard-reachable scrolling; composer occupies real space, not an overlay. Collapse secondary history on phone. Check short viewport, multiline draft and long history, including focus near the composer.',
    signature: 'Let message rhythm and one consistent active-state treatment establish identity; avoid decorating each message as a dashboard card.',
    acceptance: ['Last message and composer never cover each other', 'New, streaming, stopped and failed replies preserve draft and focus behavior', 'History and settings retain their controls in light and dark themes']
  },
  finance: {
    terms: ['finance','banking','invoice','ledger','accounting','budget','transaction'],
    goal: 'Understand position, compare changes, then inspect a transaction.',
    composition: 'Lead with balance plus period/comparison; follow with a trend and a full-width transaction table. Keep filters adjacent to the table; avoid equal-weight KPI cards.',
    type: 'Use the existing readable sans for controls, tabular numerals for values, right-aligned amounts and aligned decimal precision. Separate balance, section title and metadata into three visibly different roles.',
    responsive: 'Keep amount and transaction identity visible; contain remaining columns in a named keyboard-scrollable region. Do not discard financial fields.',
    signature: 'Use restrained ledger rules and a single emphasized comparison; reserve status color for meaning.',
    acceptance: ['Balance includes currency and period', 'Amounts align for comparison', 'Status is readable without color']
  },
  commerce: {
    terms: ['commerce','store','shop','product','checkout','cart','catalog'],
    goal: 'Compare products, choose a variant, and understand the total before purchase.',
    composition: 'Give product imagery a consistent aspect ratio and generous area; group name, price and choice. Detail uses media beside selection; cart exposes totals and checkout together.',
    type: 'Use expressive display type only for collection titles; keep price, variant and controls in a legible body family. Give price and availability different emphasis.',
    responsive: 'Stack media before selection; keep variant, total and purchase action reachable without overlapping content. Preserve cart state between routes.',
    signature: 'Repeat one image crop and caption treatment; let merchandise provide the color rather than competing decorative gradients.',
    acceptance: ['Prices and variants remain visible', 'Image proportions are consistent', 'Checkout total is clear before submit']
  },
  productivity: {
    terms: ['productivity','task','project','issue','helpdesk','ticket','workspace','dashboard'],
    goal: 'Locate work, understand its state, and perform the next action quickly.',
    composition: 'Use one navigation system, a compact page heading and a toolbar over the work list. Put detail in a clear secondary region; use a dashboard only when it answers a real overview question.',
    type: 'Prefer one legible sans; distinguish title, row identity and metadata by size/weight before color. Use compact row spacing with comfortable control hit areas.',
    responsive: 'Move secondary navigation into a labelled menu; keep search and the primary action visible. Let long names wrap rather than removing context.',
    signature: 'Use a consistent status rail or grouped list rhythm instead of a card around every field.',
    acceptance: ['Current location is visible', 'Search and primary action work on phone', 'Shared list and detail controls use the same treatment']
  },
  portfolio: {
    terms: ['portfolio','photography','artist','creative','studio','gallery'],
    goal: 'Understand the creator and inspect the work without decorative interference.',
    composition: 'Choose one deliberate editorial grid: a dominant project followed by contrasting smaller work. Use project detail for process and evidence; avoid identical tiles for every section.',
    type: 'Pair an expressive display face with a quiet readable body only if branding permits. Use fluid display sizes, tight heading leading and prose constrained to roughly 60 characters.',
    responsive: 'Keep reading and project order intentional when the grid stacks; constrain display type with clamp and wrap long titles.',
    signature: 'Use a distinctive caption alignment or typographic scale; preserve artwork proportions and never invent client claims.',
    acceptance: ['Work dominates decoration', 'Project hierarchy survives stacking', 'Long headings fit without clipping']
  },
  booking: {
    terms: ['booking','reservation','appointment','spa','hotel','clinic','schedule'],
    goal: 'Choose a service and time with confidence, then verify the reservation.',
    composition: 'Make selection the main column and keep a concise summary beside it. Group service, date and time in their real workflow order; confirmation repeats the actual chosen details.',
    type: 'Use a calm readable body with clearly stronger step headings. Keep date, time, duration and price legible; an optional display face belongs to service headings, not form labels.',
    responsive: 'Stack summary near submission, preserve selected values and show selected/unavailable time slots with text or icons as well as color.',
    signature: 'Use a restrained step rhythm and summary divider to reassure; do not add a second global header or decorative steps that change the flow.',
    acceptance: ['Selected slot is obvious', 'Summary matches actual values', 'Validation and confirmation remain usable by keyboard']
  },
  general: {
    terms: [], goal: 'Make the main user task immediately understandable.',
    composition: 'Choose a dominant content region, put its action nearby, and group supporting context beneath or beside it. Use one shared shell and vary composition by page purpose.',
    type: 'Start with the existing family; use three roles: page title, body/control and supporting metadata. Keep body near 16px, prose leading near 1.5 and text lines roughly 45–75 characters.',
    responsive: 'Stack by task priority; keep actions reachable, wrap text and contain wide data locally.',
    signature: 'Repeat one content-supported treatment across pages instead of adding unrelated decoration.',
    acceptance: ['Primary action is identifiable', 'Shared controls are consistent', 'Phone layout preserves content and actions']
  }
};

export function composition(product, { profile, mode = 'create' } = {}) {
  if (!['create','redesign','polish','refine'].includes(mode)) throw new Error('mode must be create, redesign, refine or polish');
  if (profile && !Object.hasOwn(RECIPES, profile)) throw new Error('Unknown profile');
  const words = String(product).toLowerCase().split(/[^a-z]+/);
  // A word that names a surface ("dashboard", "app") says how the product is packaged, not what
  // it is for. Counting it like a domain noun made "finance dashboard" tie with "helpdesk
  // dashboard" and fall back to the generic recipe, so surface words break ties instead of
  // creating them.
  const SURFACE = new Set(['dashboard','app','apps','workspace','panel','admin','tool','platform','portal','site','website','web','dashboard']);
  const candidates = Object.entries(RECIPES).filter(([id]) => id !== 'general').map(([id,r]) => {
    const matched = r.terms.filter(term => words.includes(term) || words.includes(term+'s'));
    return { id, matches: matched, domain: matched.filter(term => !SURFACE.has(term)) };
  }).sort((a,b) => b.domain.length - a.domain.length || b.matches.length - a.matches.length);
  const winner = candidates[0];
  // Two genuinely different domains ("finance booking") stay ambiguous on purpose: guessing one
  // would silently miscompose the product. A surface word only never decides on its own, and it
  // no longer drags a single real domain into that ambiguity.
  const rival = candidates[1];
  const ambiguous = winner.domain.length > 0 && rival.domain.length === winner.domain.length;
  const id = profile || (winner.matches.length && !ambiguous ? winner.id : 'general');
  const { terms, ...recipe } = RECIPES[id];
  return { profile: id, selection: profile ? 'explicit' : id === 'general' ? 'fallback; specify --profile if useful' : 'keyword heuristic; verify product fit', matched: candidates.filter(c=>c.matches.length), mode,
    scope: ['polish','refine'].includes(mode) ? 'Keep identity and composition; repair observed local weaknesses.' : mode === 'redesign' ? 'Improve composition, hierarchy and shared components across affected pages. Preserve brand and all behavior; adapt existing tokens before adding new ones.' : 'Choose the composition and shared visual system before implementing pages.', ...recipe };
}
export function formatComposition(plan) {
  return [`COMPOSITION: ${plan.profile} (${plan.selection})`, `Task: ${plan.goal}`, `Scope: ${plan.scope}`, `Layout: ${plan.composition}`, `Type: ${plan.type}`, `Phone: ${plan.responsive}`, `Signature: ${plan.signature}`, `Verify: ${plan.acceptance.join('; ')}.`].join('\n');
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  try {
    const { values } = parseArgs({options:{product:{type:'string'},profile:{type:'string'},mode:{type:'string',default:'create'},json:{type:'boolean'}}});
    if (!values.product?.trim()) throw new Error('--product is required');
    const plan = composition(values.product, values);
    console.log(values.json ? JSON.stringify(plan,null,2) : formatComposition(plan));
  } catch (error) { console.error(error.message); process.exitCode=64; }
}
```

## File: skills/glowup-ui/scripts/contrast.mjs
size: 1620
sha: cc3cf1011fab2616e81c54ecf4bf01c7d45f0368
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/contrast.mjs

```text
#!/usr/bin/env node
// WCAG 2.x contrast ratio between two hex colors.
// Usage: node contrast.mjs "#6b7280" "#ffffff"

import { fileURLToPath } from "node:url";

export function parseHex(input) {
  const hex = String(input).trim().replace(/^#/, "");
  if (!/^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex)) {
    throw new Error(`Not a hex color: ${input} (use #rgb or #rrggbb)`);
  }
  const full = hex.length === 3 ? [...hex].map((c) => c + c).join("") : hex;
  return [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16));
}

function channel(value) {
  const c = value / 255;
  return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
}

export function luminance(rgb) {
  const [r, g, b] = rgb.map(channel);
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

export function contrastRatio(a, b) {
  const la = luminance(parseHex(a));
  const lb = luminance(parseHex(b));
  const [hi, lo] = la > lb ? [la, lb] : [lb, la];
  return (hi + 0.05) / (lo + 0.05);
}

export function grade(ratio) {
  return {
    ratio: Math.round(ratio * 100) / 100,
    aaText: ratio >= 4.5,
    aaLargeText: ratio >= 3,
    aaUi: ratio >= 3,
    aaaText: ratio >= 7,
  };
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const [fg, bg] = process.argv.slice(2);
  if (!fg || !bg) {
    console.error('Usage: node contrast.mjs "<foreground hex>" "<background hex>"');
    process.exit(64);
  }
  try {
    const result = grade(contrastRatio(fg, bg));
    console.log(JSON.stringify({ foreground: fg, background: bg, ...result }, null, 2));
  } catch (error) {
    console.error(error.message);
    process.exit(64);
  }
}
```

## File: skills/glowup-ui/scripts/design-brief.mjs
size: 6752
sha: 20c6fb48dacf1764e1ebe1f072f2b2d81d0b8286
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/design-brief.mjs

```text
#!/usr/bin/env node
// Original composition alternatives, not themes or a quality oracle. No writes/network.
import { parseArgs } from 'node:util';
import { fileURLToPath } from 'node:url';
import { composition } from './composition.mjs';

const alternatives = {
 finance: [
  ['position','Position and movement','Balance and its period change lead; trend occupies the wide region, with commitments beside it and activity below.','Large tabular amount, clear period labels, quiet row typography; use the existing brand accent for the selected comparison.','Phone: balance → change → commitments → activity; keep transfer/add reachable in the shared shell.','Best for checking financial position; weak if users mainly reconcile many entries.'],
  ['ledger','Activity-led ledger','A grouped transaction journal dominates; running balance and filters sit above it. Account context becomes a narrow supporting rail rather than equal summary cards.','Aligned amounts and strong date/group rhythm; existing type family gains a clear row/metadata distinction.','Phone: transaction identity and amount remain paired; filters expand in place, secondary account context follows the journal.','Best for frequent reconciliation; less glanceable for long-term planning.'],
  ['commitments','Commitments and runway','Upcoming obligations and budget allocation form the main reading path; current balance is context. Show what remains after commitments using existing, truthful data only.','Emphasize due dates and remaining amounts; status uses text as well as color, with no fabricated forecast.','Phone: next commitment → available balance → allocation → activity; preserve every destination and edit state.','Best for planning; reject if the app has no obligation/allocation data.']
 ],
 booking: [
  ['selection','Selection with reassurance','Service/date/time choices lead a clear sequence; an accurate reservation summary supports selection rather than competing with it.','Readable step headings, prominent available times, quieter policy copy; reuse brand type and service assets.','Phone: choices first, summary near confirmation; keep selected values visible when returning to earlier steps.','Best for repeat booking; weaker for users who need to understand unfamiliar services.'],
  ['service','Service-led guide','Lead with existing service detail and comparison: duration, purpose and price. Booking becomes the decisive secondary region after understanding the offer.','Use service names as expressive headings and actual imagery only when available; controls remain calm and legible.','Phone: service evidence → selection → dates → summary; no decorative hero hiding the booking action.','Best for first visits; avoid lengthy storytelling when users already know their service.'],
  ['availability','Availability-led schedule','Available days and slots dominate; selecting a slot reveals service constraints and the confirmation summary alongside the schedule.','Strong day/time hierarchy, restrained unavailable states and explicit selected labels; identity comes from the schedule rhythm.','Phone: day chooser → slots → selected details; offer readable lists instead of compressing a desktop calendar.','Best when timing drives the choice; reject if the real app cannot support this selection order.']
 ]
};

export function designBrief(product, { profile, mode = 'transform', depth = mode === 'refine' ? 'polish' : 'recompose' } = {}) {
 if (!String(product).trim()) throw new Error('Specify the actual product and user task');
 if (!['create','transform','refine'].includes(mode) || !['polish','recompose','reframe'].includes(depth)) throw new Error('Use create|transform|refine and polish|recompose|reframe');
 if (mode === 'refine' && depth !== 'polish') throw new Error('REFINE requires polish depth');
 const recipe=composition(product,{profile,mode:mode==='create'?'create':depth==='polish'?'refine':'redesign'});
 const options=mode==='refine'||(mode==='transform'&&depth==='polish')?[]:(alternatives[recipe.profile] || [
  ['task','Task-led composition',recipe.composition,recipe.type,recipe.responsive,'Prefer when the main action matters more than exploring a collection.'],
  ['collection','Collection-led composition',`Make the existing collection/work itself dominant; ${recipe.goal} Move overview context into a supporting region.`,recipe.type,'Phone: retain collection identity, scan order and reachable actions; relocate supporting context rather than deleting it.','Prefer when comparing/locating existing items is the real job; reject if no meaningful collection exists.'],
  ['sequence','Decision-led sequence',`Group the existing content by the decisions needed to ${recipe.goal.toLowerCase()} Give each decision its own region rather than repeating one card grid.`,recipe.type,'Phone: preserve decision order and current selections; keep summaries adjacent to the decision they explain.','Prefer when a genuine sequence exists; do not invent steps, routes or data to fit it.']
 ]).map(([id,name,layout,type,phone,tradeoff])=>({id,name,layout,type,phone,tradeoff}));
 return { product, profile:recipe.profile, selection:recipe.selection, mode, depth, options,
  constraints:'Preserve brand, routes, content, data, APIs, handlers, auth and working flows. Reframe changes presentation/IA, not product capabilities. User constraints win.',
  choose:options.length?'Compare two or three real options against actual content/constraints; choose one or adapt/reject all with a reason. Record the dominant region, shell, type roles and phone order. Do not build multiple prototypes or combine every option.':'Use the current identity/composition; skip alternative exploration and fix the requested local weakness.',
  coverage:'For major work, map each requested screen/state to its job, lead region, supporting context and shared primitives. Implement and inspect every requested state, including tabs/dialogs at one URL; preserve observed strengths with reasons.',
  acceptance:recipe.acceptance };
}
export function formatBrief(b) {
 return [`${b.mode.toUpperCase()} / ${b.depth}: ${b.product}`,`Profile: ${b.profile} (${b.selection})`,b.constraints,...b.options.map(o=>`${o.id} — ${o.name}\nLayout: ${o.layout}\nType: ${o.type}\n${o.phone}\nTradeoff: ${o.tradeoff}`),b.choose,b.coverage].join('\n');
}
if(process.argv[1]===fileURLToPath(import.meta.url)) {
 try {const {values}=parseArgs({options:{product:{type:'string'},profile:{type:'string'},mode:{type:'string',default:'transform'},depth:{type:'string'},json:{type:'boolean'}}});const b=designBrief(values.product||'',values);console.log(values.json?JSON.stringify(b,null,2):formatBrief(b));}
 catch(e){console.error(e.message);process.exitCode=64;}
}
```

## File: skills/glowup-ui/scripts/direction.mjs
size: 17681
sha: 9117094b8115dbe72348be9626d8c0297312300f
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/direction.mjs

```text
#!/usr/bin/env node
// Pick a visual direction for a product and emit a ready-to-paste design system.
//
//   node direction.mjs --product "personal finance dashboard for freelancers" --surface app
//   node direction.mjs --product "..." --surface commerce --out src/theme.css
//   node direction.mjs --product "..." --direction luxe --brand "#7a1f3d" --keep-fonts
//
// Why a script: asked to invent a look, a model drifts to the category default (Inter, slate,
// indigo, a sidebar and four KPI cards). Scoring a curated set of directions against the product,
// breaking ties with a hash of the product text, gives a committed, distinct, internally consistent
// starting point in one call. The agent may override it with --direction.

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
import { spawnSync } from "node:child_process";
import { DIRECTIONS, SURFACES, GENERIC_KEYWORDS } from "./directions.mjs";
import { buildPalette, hexToOklch } from "./palette.mjs";
import { detectLook } from "./look.mjs";
import { composition, formatComposition } from "./composition.mjs";

export function hashString(text) {
  let h = 2166136261;
  for (const ch of text) { h ^= ch.codePointAt(0); h = Math.imul(h, 16777619); }
  return h >>> 0;
}

const words = (text) => new Set(String(text).toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2));
// The look agents default to for any app. Only chosen when asked for by id, never dealt automatically.
const NEVER_AUTO = new Set(["saas-mist"]);
// When an app has no domain signal at all, deal from directions that are calm and work for any tool.
const NEUTRAL_POOLS = {
  app: ["control-room", "clinical-calm", "civic-clear", "ledger", "soft-pastel", "instrument"],
  service: ["clinical-calm", "civic-clear", "luxe", "field-notes", "soft-pastel"],
  commerce: ["storefront", "paper-goods", "field-notes", "luxe"],
  marketing: ["soft-pastel", "field-notes", "poster", "civic-clear", "night-signal"],
  editorial: ["ledger", "field-notes", "paper-goods", "luxe"],
};

const HUES = { red: [345, 30], orange: [30, 70], amber: [70, 100], yellow: [70, 110], green: [110, 170], teal: [170, 205], cyan: [195, 225], blue: [225, 265], indigo: [265, 290], iris: [265, 290], purple: [290, 330], violet: [290, 330], pink: [330, 360] };
const inRange = (h, [a, b]) => (a <= b ? h >= a && h < b : h >= a || h < b);
const hueOf = (hex) => { try { return hexToOklch(hex).h || 0; } catch { return 0; } };

/**
 * Directions to leave behind when redesigning: --current "light, blue, sidebar" drops directions with the same scheme and
 * accent hue family as the existing look (a redesign should not land on a recolored version of what it replaces).
 */
export function leaveBehind(current = "") {
  const w = words(current);
  const scheme = w.has("dark") ? "dark" : w.has("light") || w.has("white") ? "light" : null;
  const hues = Object.entries(HUES).filter(([name]) => w.has(name)).map(([, range]) => range);
  return (d) => hues.length > 0 && (!scheme || d.palette.scheme === scheme) && hues.some((r) => inRange(hueOf(d.palette.primary), r));
}

// invoice ~ invoicing, booking ~ bookings, recipe ~ recipes: words that share their first 6 letters (or one is a prefix of the other, 5+ letters).
const sameStem = (a, b) => (a.length >= 5 && b.length >= 5 && (a.startsWith(b) || b.startsWith(a))) || (a.length >= 6 && b.length >= 6 && a.slice(0, 6) === b.slice(0, 6));

/** Score every direction against the product text and surface, best first. */
export function rankDirections(product, surface, { exclude = () => false } = {}) {
  const w = words(product);
  const ranked = DIRECTIONS.map((d) => {
    const matched = d.keywords.filter((k) => w.has(k) || [...w].some((x) => sameStem(k, x)));
    const hits = matched.length;
    const evidence = matched.reduce((n, k) => n + (GENERIC_KEYWORDS.has(k) ? 1 : 3), 0);
    const surfaceFit = d.surfaces.includes(surface) ? 1 : -100;
    // Specific domain words weigh most; the generic productivity look must earn its place.
    const score = evidence + surfaceFit;
    return { direction: d, hits, score };
  }).filter((r) => r.score > -50 && !exclude(r.direction));
  const seed = hashString(`${surface}:${product}`);
  // Deterministic jitter: near-equal candidates are ordered by the product hash, so different
  // products land on different directions while the same product always gets the same one.
  return ranked
    .map((r, i) => ({ ...r, tie: hashString(`${r.direction.id}:${seed}`) % 1000 / 1000 }))
    .sort((a, b) => b.score - a.score || b.tie - a.tie);
}

export function pickDirection(product, surface, forcedId, { current = "", avoid = [] } = {}) {
  const left = leaveBehind(current);
  const ranked = rankDirections(product, surface, { exclude: (d) => !forcedId && (left(d) || avoid.includes(d.id)) });
  if (forcedId) {
    const found = DIRECTIONS.find((d) => d.id === forcedId);
    if (!found) throw new Error(`Unknown direction "${forcedId}". Known: ${DIRECTIONS.map((d) => d.id).join(", ")}`);
    return { chosen: found, runnersUp: ranked.filter((r) => r.direction.id !== forcedId).slice(0, 2).map((r) => r.direction), forced: true, evidence: null };
  }
  const auto = ranked.filter((r) => !NEVER_AUTO.has(r.direction.id));
  const top = auto[0].score;
  // Candidates within 1 point of the best are all reasonable; the hash picks among them.
  let pool = auto.filter((r) => r.score >= top - 1).slice(0, 3);
  // No domain evidence (best score is only the surface fit): deal from the surface's neutral pool.
  if (top <= 1 && NEUTRAL_POOLS[surface]) {
    const neutral = auto.filter((r) => NEUTRAL_POOLS[surface].includes(r.direction.id));
    if (neutral.length) pool = neutral;
  }
  const pick = pool[hashString(`${surface}:${product}`) % pool.length];
  const chosen = pick.direction;
  return { chosen, runnersUp: ranked.filter((r) => r.direction.id !== chosen.id).slice(0, 2).map((r) => r.direction), forced: false, evidence: pick.hits ? Math.max(0, pick.score - 1) : 0 };
}

const FALLBACK = { sans: 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif', serif: 'ui-serif, Georgia, "Times New Roman", serif', mono: 'ui-monospace, "SF Mono", Menlo, Consolas, monospace' };
const stack = (f) => `"${f.family}", ${FALLBACK[f.kind]}`;

export function designSystem(direction, { brand, keepFonts = false } = {}) {
  const p = direction.palette;
  const palette = buildPalette({ primary: brand || p.primary, accent: p.accent, neutralTint: p.tint, neutralHue: p.neutralHue, scheme: p.scheme });
  const r = palette.roles;
  const fonts = direction.fonts;
  const packages = keepFonts ? [] : [...new Set(Object.values(fonts).map((f) => f.pkg))];
  const acc = palette.scales.accent;
  const roles = {
    canvas: r.canvas, surface: r.surface, raised: r.raised, sunken: r.sunken, line: r.border, "line-strong": r["border-strong"],
    ink: r.text, muted: r.muted,
    primary: r.primary, "primary-hover": r["primary-hover"], "primary-soft": r["primary-soft"], "primary-ink": r["primary-ink"], "on-primary": r["on-primary"],
    "primary-text": r["primary-text"] || r.primary,
    accent: acc[p.scheme === "dark" ? 400 : 600], "accent-soft": acc[p.scheme === "dark" ? 900 : 100], "accent-ink": acc[p.scheme === "dark" ? 200 : 800],
    ok: r.success, "ok-soft": r["success-soft"], "ok-ink": r["success-ink"],
    warn: r.warning, "warn-soft": r["warning-soft"], "warn-ink": r["warning-ink"],
    bad: r.danger, "bad-soft": r["danger-soft"], "bad-ink": r["danger-ink"],
    info: r.info, "info-soft": r["info-soft"], "info-ink": r["info-ink"],
    focus: r.focus,
  };
  return { palette, roles, packages, fonts, keepFonts };
}

function shadows(direction, roles) {
  const dark = direction.palette.scheme === "dark";
  const ink = dark ? "0 0 0" : "20 18 14";
  switch (direction.surface) {
    case "hardshadow": return { card: `4px 4px 0 0 ${roles.ink}`, pop: `6px 6px 0 0 ${roles.ink}` };
    case "ruled": case "hairline": return { card: "none", pop: `0 8px 24px -8px rgb(${ink} / 0.18)` };
    case "tonal": return { card: "none", pop: `0 12px 32px -10px rgb(${ink} / ${dark ? 0.6 : 0.2})` };
    case "paper": return { card: `0 1px 0 rgb(${ink} / 0.06), 0 6px 14px -8px rgb(${ink} / 0.14)`, pop: `0 14px 30px -12px rgb(${ink} / 0.25)` };
    case "tinted": case "soft": return { card: `0 1px 2px rgb(${ink} / 0.05), 0 8px 24px -12px rgb(${ink} / 0.12)`, pop: `0 16px 40px -14px rgb(${ink} / 0.22)` };
    default: return { card: `0 1px 2px rgb(${ink} / 0.06)`, pop: `0 10px 30px -10px rgb(${ink} / 0.2)` };
  }
}

/** Tailwind v4 theme file: font imports, @theme tokens, and base styles. */
export function themeCss(direction, system, { plain = false } = {}) {
  const { roles, fonts, packages } = system;
  const sh = shadows(direction, roles);
  const tabular = direction.numerals === "mono" ? "var(--font-mono)" : "var(--font-sans)";
  const lines = [];
  if (!plain) lines.push('@import "tailwindcss";');
  for (const pkg of packages) lines.push(`@import "${pkg}";`);
  lines.push("", `/* Direction: ${direction.name} (${direction.id}). ${direction.summary} */`, plain ? ":root {" : "@theme {");
  // keepFonts: the project already has its own typefaces, so the theme must not name fonts that are not installed.
  if (!system.keepFonts) {
    lines.push(`  --font-sans: ${stack(fonts.body)};`, `  --font-display: ${stack(fonts.display)};`);
    lines.push(`  --font-mono: ${stack(fonts.mono || { kind: "mono", family: "ui-monospace" })};`);
  }
  const hard = direction.surface === "hardshadow";
  for (const [name, hex] of Object.entries(roles)) lines.push(`  --color-${name}: ${hard && (name === "line" || name === "line-strong") ? roles.ink : hex};`);
  if (hard) lines.push("  --card-border: 2px;");
  lines.push(`  --radius-control: ${direction.shape.control};`, `  --radius-card: ${direction.shape.card};`, `  --radius-sheet: ${direction.shape.sheet};`, `  --radius-pill: ${direction.shape.pill};`);
  lines.push(`  --shadow-card: ${sh.card};`, `  --shadow-pop: ${sh.pop};`, "}", "");
  lines.push("@layer base {", "  html { color-scheme: " + direction.palette.scheme + "; }");
  lines.push(`  body { background: var(--color-canvas); color: var(--color-ink); ${system.keepFonts ? "" : "font-family: var(--font-sans); "}font-size: 16px; line-height: 1.55; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }`);
  lines.push(`  h1, h2, h3, h4 { ${system.keepFonts ? "" : "font-family: var(--font-display); "}font-weight: ${direction.heading.weight}; letter-spacing: ${direction.heading.tracking}; line-height: 1.12; text-wrap: balance; }`);
  lines.push(`  .num, table, [data-numeric] { font-variant-numeric: tabular-nums;${system.keepFonts ? "" : ` font-family: ${tabular};`} }`);
  lines.push("  :focus-visible { outline: 2px solid var(--color-focus); outline-offset: 2px; }");
  lines.push("  ::selection { background: var(--color-primary-soft); color: var(--color-primary-ink); }");
  lines.push("  @media (prefers-reduced-motion: reduce) { *, ::before, ::after { animation-duration: .01ms !important; transition-duration: .01ms !important; scroll-behavior: auto !important; } }", "}", "");
  return lines.join("\n");
}

function brief(direction, runnersUp, system, forced, surface, product, extra = {}) {
  const f = direction.fonts;
  const failing = system.palette.checks.filter((c) => !c.pass).length;
  const out = [];
  out.push(`DIRECTION: ${direction.name} (${direction.id})${forced ? " [chosen by you]" : ""}`);
  out.push(`For: ${product} · surface: ${surface} = ${SURFACES[surface]}`);
  if (extra.leaving) out.push(`Leaving behind: ${extra.leaving} (the new look must not be a recolor of it)`);
  if (!forced && extra.evidence === 0) out.push("Match: weak. No domain words in the product text matched an allowed direction, so this one came from a neutral pool. If you know the product's personality (playful, formal, premium, technical), pick with --direction <id> from --list.");
  else if (!forced && extra.evidence >= 3) out.push("Match: strong.");
  out.push(direction.summary, "");
  out.push(`Fonts: display ${f.display.family}; body ${f.body.family}${f.mono ? `; mono ${f.mono.family}` : ""}.`);
  out.push(system.packages.length ? `Install once (or pass --install): npm i ${system.packages.join(" ")}` : "Fonts: keep the project's existing fonts.");
  out.push(`Palette (${direction.palette.scheme}): canvas ${system.roles.canvas}, ink ${system.roles.ink}, primary ${system.roles.primary} (text on it: ${system.roles["on-primary"]}), accent ${system.roles.accent}. Contrast checks failing: ${failing}.`);
  out.push(`Shape: controls ${direction.shape.control}, cards ${direction.shape.card}, sheets ${direction.shape.sheet}. Surfaces: ${direction.surface}. Density: ${direction.density}. Headings weight ${direction.heading.weight}, tracking ${direction.heading.tracking}. Numerals: ${direction.numerals}.`);
  out.push(`Shell: ${direction.shells[surface] || Object.values(direction.shells)[0]}`);
  out.push("Optional signature treatment (reuse where it supports the content): " + direction.motif.join("; ") + ".");
  out.push("Signature moves:"); for (const m of direction.moves) out.push(`  - ${m}`);
  out.push("Avoid: " + direction.avoid.join("; ") + ".", "");
  out.push(`Runners-up if this feels wrong for the product: ${runnersUp.map((d) => `${d.id} (${d.name})`).join(", ")}. Re-run with --direction <id>.`);
  out.push("", formatComposition(composition(product)));
  return out.join("\n");
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values: v } = parseArgs({ options: {
    product: { type: "string" }, surface: { type: "string", default: "app" }, direction: { type: "string" },
    brand: { type: "string" }, current: { type: "string" }, avoid: { type: "string" }, "keep-fonts": { type: "boolean", default: false }, out: { type: "string" },
    install: { type: "boolean", default: false }, mode: { type: "string" },
    format: { type: "string", default: "brief" }, plain: { type: "boolean", default: false }, list: { type: "boolean", default: false },
  } });
  if (v.list) { for (const d of DIRECTIONS) console.log(`${d.id.padEnd(14)} ${d.name.padEnd(24)} ${d.surfaces.join("/")}  ${d.summary}`); process.exit(0); }
  if (!v.product) { console.error('Usage: node direction.mjs --product "what it is and who it is for" --surface app|marketing|commerce|editorial|service [--mode create|refine|replace] [--out NEW-FILE.css] [--install] [--direction id] [--current "light, blue"] [--avoid id,id] [--brand "#hex"] [--keep-fonts] [--list]'); process.exit(64); }
  if (!SURFACES[v.surface]) { console.error(`Unknown surface "${v.surface}". Use: ${Object.keys(SURFACES).join(", ")}`); process.exit(64); }
  try {
    if (v.mode && !["create", "refine", "replace"].includes(v.mode)) throw new Error("--mode must be create, refine, or replace");
    const detected = detectLook(process.cwd());
    const existing = detected.files > 0;
    const look = v.current === "auto" || existing ? detected : null;
    // Existing applications default to preservation even when detection finds no brand.
    // A style fingerprint cannot grant permission to replace someone's application.
    const mode = v.mode || (existing ? "refine" : "create");
    if (mode === "refine") {
      const result = { mode, look, packages: [], writes: [], instruction: "Keep the existing palette, fonts, logo, shell, and dependencies. Fix evidenced usability, hierarchy, responsive, and accessibility weaknesses with local edits. No generated theme or font installation." };
      if (v.format === "json") console.log(JSON.stringify(result, null, 2));
      else console.log(`REFINE MODE: preserve the existing application.\n${result.instruction}\n${v.out ? `Left ${v.out} untouched; no suggestion file generated.` : ""}`);
      process.exit(0);
    }
    if (mode === "create" && existing) throw new Error("Application source already exists. Use REFINE, or --mode replace only for an explicitly requested new visual direction.");
    const leaving = look ? look.current : v.current;
    const brand = v.brand;
    const keepFonts = v["keep-fonts"];
    const { chosen, runnersUp, forced, evidence } = pickDirection(v.product, v.surface, v.direction, { current: leaving, avoid: (v.avoid || "").split(",").filter(Boolean) });
    const system = designSystem(chosen, { brand, keepFonts });
    const css = themeCss(chosen, system, { plain: v.plain });
    const outPath = v.out;
    if (v.out && fs.existsSync(v.out)) throw new Error(`Refusing to overwrite ${v.out}.`);
    if (outPath) { fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true }); fs.writeFileSync(outPath, css); }
    if (v.install && system.packages.length) {
      const r = spawnSync("npm", ["install", "--no-audit", "--no-fund", "--loglevel=error", ...system.packages], { stdio: ["ignore", "ignore", "inherit"] });
      if (r.status !== 0) throw new Error(`Font install failed. Run: npm i ${system.packages.join(" ")}`);
    }
    if (v.format === "css") console.log(css);
    else if (v.format === "json") console.log(JSON.stringify({ composition: composition(v.product), direction: chosen.id, roles: system.roles, packages: system.packages, runnersUp: runnersUp.map((d) => d.id) }, null, 2));
    else console.log(brief(chosen, runnersUp, system, forced, v.surface, v.product, { leaving, evidence }) + (outPath ? `\n\nWrote new design tokens to ${outPath}. Merge into an existing app without replacing its CSS entry.` : ""));
  } catch (error) {
    console.error(error.message);
    process.exit(64);
  }
}
```

## File: skills/glowup-ui/scripts/directions.mjs
size: 25057
sha: b9f626756107499bcd572c53b692b64cd5ba2eff
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/directions.mjs

```text
// Curated visual directions. Each one is a complete, internally consistent starting point:
// fonts, palette seeds, shape, surfaces, density, shells, and signature moves.
// direction.mjs picks one for a product; the agent may override it.
//
// fonts[].pkg are @fontsource-variable packages (self-hosted, no CDN). kind sets the fallback stack.

export const DIRECTIONS = [
  {
    id: "ledger", name: "Editorial ledger",
    summary: "Printed-page seriousness: serif display, ruled lines, paper neutrals, one ink color.",
    surfaces: ["app", "editorial", "service"],
    keywords: ["finance", "budget", "invoice", "accounting", "bank", "report", "ledger", "tax", "legal", "newsletter", "magazine", "journal", "publishing", "research", "archive", "studio", "agency", "portfolio", "notes"],
    fonts: { display: { family: "Newsreader Variable", pkg: "@fontsource-variable/newsreader", kind: "serif" }, body: { family: "Instrument Sans Variable", pkg: "@fontsource-variable/instrument-sans", kind: "sans" } },
    palette: { primary: "#1f3a5f", accent: "#b4541a", neutralHue: 85, tint: 0.018, scheme: "light" },
    heading: { weight: 500, tracking: "-0.02em" }, numerals: "display",
    shape: { control: "3px", card: "4px", sheet: "6px", pill: "999px" }, surface: "ruled", density: "comfortable",
    shells: { app: "Slim top bar with section tabs under a wordmark; content up to 1280px in two-column layouts (headline figure and chart left, ruled ledger or list right)", editorial: "Single column with a running header and folios", service: "Centered wordmark over a quiet nav row" },
    motif: ["column rules and double rules under table heads", "folio numbers and small-caps section labels", "key figures set large in the display serif"],
    moves: ["White 'sheets' on a paper-toned canvas, separated by hairline rules instead of shadows", "Headline numbers in the serif, labels in tracked small caps", "Charts drawn as ink lines on faint ruled paper, never filled gradients"],
    avoid: ["card grids with shadows", "gradient buttons", "sidebar + four KPI cards"],
  },
  {
    id: "instrument", name: "Precision instrument",
    summary: "Dark, exact, and luminous: monospace numerals, one signal color, dense tonal layers.",
    surfaces: ["app"],
    keywords: ["observability", "monitoring", "devops", "infrastructure", "logs", "metrics", "analytics", "trading", "crypto", "terminal", "developer", "api", "deploy", "pipeline", "security", "telemetry", "incident", "uptime"],
    fonts: { display: { family: "Geist Variable", pkg: "@fontsource-variable/geist", kind: "sans" }, body: { family: "Geist Variable", pkg: "@fontsource-variable/geist", kind: "sans" }, mono: { family: "JetBrains Mono Variable", pkg: "@fontsource-variable/jetbrains-mono", kind: "mono" } },
    palette: { primary: "#f5a524", accent: "#38bdf8", neutralHue: 255, tint: 0.012, scheme: "dark" },
    heading: { weight: 600, tracking: "-0.015em" }, numerals: "mono",
    shape: { control: "6px", card: "8px", sheet: "10px", pill: "999px" }, surface: "tonal", density: "compact",
    shells: { app: "Icon rail plus a collapsible panel, a command bar on top, and full-width dense content" },
    motif: ["status LEDs and hairline crosshair ticks", "faint dot grid behind empty areas", "sparkline and bar glyphs inside table cells"],
    moves: ["IDs, timestamps, and numbers in the monospace; labels in the sans", "Luminous status dots with text labels, never color alone", "Sticky table headers, 36px rows, and keyboard-hint chips"],
    avoid: ["pastel fills", "large rounded cards", "decorative gradients"],
  },
  {
    id: "poster", name: "Poster bold",
    summary: "Loud, confident, high-contrast: oversized type, flat color fields, thick rules, hard shadows.",
    surfaces: ["marketing", "editorial", "commerce", "service"],
    keywords: ["creative", "studio", "festival", "event", "music", "band", "gallery", "launch", "agency", "art", "poster", "community", "conference", "merch", "zine", "podcast", "brand", "design"],
    fonts: { display: { family: "Bricolage Grotesque Variable", pkg: "@fontsource-variable/bricolage-grotesque", kind: "sans" }, body: { family: "DM Sans Variable", pkg: "@fontsource-variable/dm-sans", kind: "sans" } },
    palette: { primary: "#e5332a", accent: "#ffcf33", neutralHue: 80, tint: 0.012, scheme: "light" },
    heading: { weight: 800, tracking: "-0.035em" }, numerals: "display",
    shape: { control: "0px", card: "0px", sheet: "0px", pill: "999px" }, surface: "hardshadow", density: "airy",
    shells: { marketing: "Oversized wordmark bar with a marquee strip; sections as full-bleed color fields", commerce: "Sticky slim bar, huge category type, tiles with thick ink borders", app: "Top bar with oversized active tab, content in bordered panels" },
    motif: ["2px ink borders with 4px hard offset shadows", "sticker badges rotated 2–4 degrees", "marquee strips and oversized numerals"],
    moves: ["Headlines at 72–120px with tight tracking", "Alternate full-bleed color fields (cream, red, yellow, ink) between sections", "Buttons are rectangular with a hard shadow that presses in on active"],
    avoid: ["soft shadows", "rounded-xl everywhere", "timid gray text on color"],
  },
  {
    id: "soft-pastel", name: "Soft and friendly",
    summary: "Warm, rounded, encouraging: tinted panels, pill controls, gentle color, kind microcopy space.",
    surfaces: ["app", "marketing", "service"],
    keywords: ["habit", "wellness", "mindful", "meditation", "family", "parent", "school", "education", "learning", "community", "pet", "recipe", "journal", "baby", "tutor", "yoga", "fitness", "mood", "planner", "todo", "tasks", "roadmap", "team", "project"],
    fonts: { display: { family: "Figtree Variable", pkg: "@fontsource-variable/figtree", kind: "sans" }, body: { family: "Figtree Variable", pkg: "@fontsource-variable/figtree", kind: "sans" } },
    palette: { primary: "#e8664a", accent: "#6fae9a", neutralHue: 60, tint: 0.02, scheme: "light" },
    heading: { weight: 700, tracking: "-0.02em" }, numerals: "display",
    shape: { control: "14px", card: "22px", sheet: "28px", pill: "999px" }, surface: "tinted", density: "airy",
    shells: { app: "Top bar with pill nav on desktop and a floating bottom tab bar on mobile", marketing: "Rounded top bar, big friendly hero with a shape collage", service: "Soft pill nav with a prominent rounded call-to-action" },
    motif: ["blob and circle shapes behind headings", "icon bubbles in tinted circles", "progress shown as rounded rings and chunky bars"],
    moves: ["Tinted panels (sage, peach, butter) instead of white cards with borders", "Pill buttons and inputs, with generous 48px targets", "Empty states with a friendly shape illustration and a warm sentence"],
    avoid: ["sharp corners", "dense tables", "cold gray palettes"],
  },
  {
    id: "clinical-calm", name: "Calm clinical",
    summary: "Clear, quiet, trustworthy: cool whites, one steady blue, large targets, status-led color.",
    surfaces: ["app", "service", "marketing"],
    keywords: ["clinic", "health", "medical", "patient", "doctor", "dental", "care", "therapy", "pharmacy", "hospital", "appointment", "booking", "schedule", "wellbeing", "physio", "vet", "helpdesk", "support", "customers", "inbox", "hr", "recruiting", "people", "payroll"],
    fonts: { display: { family: "Hanken Grotesk Variable", pkg: "@fontsource-variable/hanken-grotesk", kind: "sans" }, body: { family: "Hanken Grotesk Variable", pkg: "@fontsource-variable/hanken-grotesk", kind: "sans" } },
    palette: { primary: "#1d6fa5", accent: "#e0664f", neutralHue: 225, tint: 0.008, scheme: "light" },
    heading: { weight: 650, tracking: "-0.015em" }, numerals: "display",
    shape: { control: "10px", card: "14px", sheet: "18px", pill: "999px" }, surface: "soft", density: "comfortable",
    shells: { app: "Top bar with a day or section switcher; one clear primary action per screen", service: "Simple top bar with a persistent 'Book' button and a phone number", marketing: "Calm hero with a trust strip and a clear booking path" },
    motif: ["a gentle pulse line used sparingly in empty states", "soft-edged status chips with an icon", "large readable times and names"],
    moves: ["16–18px body text and 48px minimum targets", "Status always shown as icon + word + color", "Coral used only for urgent and destructive states"],
    avoid: ["dark mode by default", "tiny gray metadata", "decorative motion"],
  },
  {
    id: "luxe", name: "Refined luxury",
    summary: "Quiet, spacious, expensive: fine serif display, hairlines, bone and ink, a touch of brass.",
    surfaces: ["marketing", "commerce", "service", "editorial"],
    keywords: ["spa", "hotel", "resort", "jewelry", "fashion", "boutique", "salon", "perfume", "fine", "dining", "restaurant", "wine", "villa", "wellness", "retreat", "premium", "couture", "interior", "architecture", "wedding"],
    fonts: { display: { family: "Cormorant Garamond Variable", pkg: "@fontsource-variable/cormorant-garamond", kind: "serif" }, body: { family: "Hanken Grotesk Variable", pkg: "@fontsource-variable/hanken-grotesk", kind: "sans" } },
    palette: { primary: "#1b1a17", accent: "#9a7b4f", neutralHue: 80, tint: 0.016, scheme: "light" },
    heading: { weight: 500, tracking: "-0.01em" }, numerals: "display",
    shape: { control: "0px", card: "0px", sheet: "0px", pill: "999px" }, surface: "hairline", density: "airy",
    shells: { marketing: "Centered wordmark with split navigation either side; transparent over a full-bleed hero", service: "Centered wordmark, small tracked-caps nav, and an outlined 'Reserve' button", commerce: "Centered wordmark, minimal nav, and a thin announcement line" },
    motif: ["fine 1px rules and arch-shaped image masks", "italic accent words inside serif headlines", "small tracked uppercase labels"],
    moves: ["Hero headline at 64–96px in the serif with generous leading", "Imagery as tall arch or portrait frames with color-field art when no photos exist", "Buttons are outlined or underlined; the filled one is rare"],
    avoid: ["bright saturated accents", "rounded pills", "dense grids", "drop shadows"],
  },
  {
    id: "storefront", name: "Modern storefront",
    summary: "Product-led retail: crisp white, black buttons, one sale signal, big tiles and clear prices.",
    surfaces: ["commerce"],
    keywords: ["shop", "store", "retail", "products", "cart", "checkout", "listings", "property", "homes", "fashion", "apparel", "sneakers", "electronics", "gadgets", "furniture", "beauty", "skincare", "marketplace", "catalog"],
    fonts: { display: { family: "Manrope Variable", pkg: "@fontsource-variable/manrope", kind: "sans" }, body: { family: "Manrope Variable", pkg: "@fontsource-variable/manrope", kind: "sans" } },
    palette: { primary: "#16161a", accent: "#ff4f5a", neutralHue: 270, tint: 0.004, scheme: "light" },
    heading: { weight: 800, tracking: "-0.03em" }, numerals: "display",
    shape: { control: "10px", card: "14px", sheet: "20px", pill: "999px" }, surface: "flat", density: "comfortable",
    shells: { commerce: "Announcement strip, a bar with search in the middle, and a cart link with a count; mega-menu on desktop and a drawer on mobile" },
    motif: ["product tiles with a distinct color field per product", "price tags and corner badges", "sticky buy box on product pages"],
    moves: ["Large product tiles in a 4-up (desktop) and 2-up (mobile) grid, price directly under the name", "Black primary buttons with a single red signal for sale and low-stock states", "Product pages: gallery left, sticky buy box right, a details accordion below"],
    avoid: ["long marketing hero text", "gray image placeholders", "pastel accents"],
  },
  {
    id: "paper-goods", name: "Paper goods",
    summary: "Tactile and crafted: cream stock, forest ink, terracotta stamps, serif headings, stitched borders.",
    surfaces: ["commerce", "marketing", "editorial", "service"],
    keywords: ["stationery", "paper", "notebook", "books", "bookstore", "pens", "desk", "coffee", "cafe", "bakery", "recipe", "recipes", "cooking", "blog", "ceramics", "craft", "artisan", "handmade", "candle", "plants", "gift", "print", "letterpress"],
    fonts: { display: { family: "Literata Variable", pkg: "@fontsource-variable/literata", kind: "serif" }, body: { family: "Work Sans Variable", pkg: "@fontsource-variable/work-sans", kind: "sans" } },
    palette: { primary: "#2f5d50", accent: "#c8553d", neutralHue: 95, tint: 0.026, scheme: "light" },
    heading: { weight: 600, tracking: "-0.015em" }, numerals: "display",
    shape: { control: "6px", card: "8px", sheet: "12px", pill: "999px" }, surface: "paper", density: "comfortable",
    shells: { commerce: "Centered wordmark over a nav row, cart on the right; a thin dashed rule under the bar", marketing: "Wordmark left, nav center, a stamped 'Shop' button", app: "Top bar with a stamped wordmark and tab nav" },
    motif: ["dashed 'stitched' borders and perforation edges", "round stamp badges (new, handmade, limited)", "hand-drawn squiggle underlines in SVG"],
    moves: ["Cream canvas with subtle paper grain made from a CSS gradient", "Product tiles with a colored card-stock field, a simple SVG object, and a stamp", "Serif headings with a terracotta underline squiggle on one word"],
    avoid: ["pure white backgrounds", "glossy gradients", "generic sans-only palettes"],
  },
  {
    id: "saas-mist", name: "Modern productivity",
    summary: "Crisp and efficient: cool neutral layers, one tuned iris accent, tight type, command-bar feel.",
    surfaces: ["app"],
    keywords: ["saas", "productivity", "workspace", "dashboard"],
    fonts: { display: { family: "Onest Variable", pkg: "@fontsource-variable/onest", kind: "sans" }, body: { family: "Onest Variable", pkg: "@fontsource-variable/onest", kind: "sans" } },
    palette: { primary: "#5b5bd6", accent: "#12a594", neutralHue: 270, tint: 0.006, scheme: "light" },
    heading: { weight: 650, tracking: "-0.02em" }, numerals: "tabular",
    shape: { control: "8px", card: "12px", sheet: "16px", pill: "999px" }, surface: "tonal", density: "comfortable",
    shells: { app: "Grouped sidebar with section labels, a search/command bar on top, and a content header with tabs" },
    motif: ["keyboard-hint chips", "tonal layers instead of heavy borders", "inline progress and avatar stacks"],
    moves: ["Three tonal levels: canvas, panel, raised, with 1px borders at low contrast", "Tabular figures everywhere; the lead metric gets a sparkline, not a gradient card", "Table rows with hover actions and a quick-filter bar above"],
    avoid: ["purple-to-blue gradients", "four identical KPI cards", "oversized decorative hero"],
  },
  {
    id: "control-room", name: "Data-dense control room",
    summary: "Utilitarian and fast: neutral steel, petrol and amber, ruled tables, status first.",
    surfaces: ["app"],
    keywords: ["logistics", "fleet", "warehouse", "inventory", "dispatch", "operations", "ops", "erp", "orders", "queue", "supply", "factory", "shipping", "scheduling", "maintenance", "boats", "vehicles", "manufacturing", "crm", "sales", "leads", "deals", "admin", "backoffice", "fulfillment"],
    fonts: { display: { family: "IBM Plex Sans Variable", pkg: "@fontsource-variable/ibm-plex-sans", kind: "sans" }, body: { family: "IBM Plex Sans Variable", pkg: "@fontsource-variable/ibm-plex-sans", kind: "sans" }, mono: { family: "JetBrains Mono Variable", pkg: "@fontsource-variable/jetbrains-mono", kind: "mono" } },
    palette: { primary: "#0b6e99", accent: "#f08c00", neutralHue: 230, tint: 0.01, scheme: "light" },
    heading: { weight: 600, tracking: "-0.01em" }, numerals: "mono",
    shape: { control: "4px", card: "6px", sheet: "8px", pill: "999px" }, surface: "ruled", density: "compact",
    shells: { app: "Left navigation with icons and labels, a thin top filter bar, and a persistent status strip" },
    motif: ["status dots with labels and counts", "priority flags and age badges", "row-density toggle"],
    moves: ["Tables lead every page: sticky header, 40px rows, right-aligned tabular numbers, mono IDs", "Color is reserved for status and the primary action", "A summary strip of counts doubles as quick filters"],
    avoid: ["big hero headings", "airy padding", "decorative illustrations"],
  },
  {
    id: "field-notes", name: "Field notes",
    summary: "Grounded and organic: moss and ochre on warm stone, humanist serif, topographic detail.",
    surfaces: ["marketing", "commerce", "service", "app"],
    keywords: ["outdoor", "hiking", "camping", "farm", "garden", "organic", "food", "travel", "tours", "sailing", "boat", "surf", "nature", "sustainable", "eco", "fishing", "adventure", "school", "lessons", "marina"],
    fonts: { display: { family: "Lora Variable", pkg: "@fontsource-variable/lora", kind: "serif" }, body: { family: "Work Sans Variable", pkg: "@fontsource-variable/work-sans", kind: "sans" } },
    palette: { primary: "#3f6b3a", accent: "#d98e2b", neutralHue: 105, tint: 0.022, scheme: "light" },
    heading: { weight: 600, tracking: "-0.015em" }, numerals: "display",
    shape: { control: "10px", card: "14px", sheet: "20px", pill: "999px" }, surface: "tonal", density: "comfortable",
    shells: { app: "Top bar with a wordmark and a weather or status chip; tabbed sections", marketing: "Wordmark left, nav right, hero with a contour-line backdrop", service: "Friendly top bar with a booking button", commerce: "Top bar with a category row" },
    motif: ["topographic contour lines as background texture", "compass and tick marks on dividers", "stamp-style badges and handwritten-feel labels in the serif italic"],
    moves: ["Warm stone canvas with moss panels and ochre highlights", "Contour-line SVG behind hero and empty states", "Conditions, dates, and levels shown as small gauge or tide-style graphics"],
    avoid: ["neon colors", "cold grays", "tech-startup gradients"],
  },
  {
    id: "neo-brutal", name: "Neo-brutal",
    summary: "Raw and playful: black outlines, hard shadows, acid highlights, mono accents.",
    surfaces: ["app", "marketing"],
    keywords: ["indie", "hackathon", "maker", "playful", "game", "zine", "newsletter", "builders", "hacker", "zines"],
    fonts: { display: { family: "Space Grotesk Variable", pkg: "@fontsource-variable/space-grotesk", kind: "sans" }, body: { family: "Space Grotesk Variable", pkg: "@fontsource-variable/space-grotesk", kind: "sans" }, mono: { family: "JetBrains Mono Variable", pkg: "@fontsource-variable/jetbrains-mono", kind: "mono" } },
    palette: { primary: "#111111", accent: "#c6ff3d", neutralHue: 90, tint: 0.01, scheme: "light" },
    heading: { weight: 700, tracking: "-0.03em" }, numerals: "mono",
    shape: { control: "0px", card: "0px", sheet: "0px", pill: "999px" }, surface: "hardshadow", density: "comfortable",
    shells: { app: "Bordered top bar with chunky tabs", marketing: "Bordered bar and a bold sticker-style hero" },
    motif: ["2px black outlines and 3px hard shadows", "acid-lime highlighter marks behind words", "mono labels and ASCII-style dividers"],
    moves: ["Every panel has a black border and a hard offset shadow", "Highlighter-lime behind the one word that matters", "Buttons depress by translating into their shadow"],
    avoid: ["subtle shadows", "gradients", "serious finance or health contexts"],
  },
  {
    id: "night-signal", name: "Night signal",
    summary: "Cinematic dark: deep ink canvas, one hot signal, big numerals, poster tiles.",
    surfaces: ["app", "marketing", "commerce"],
    keywords: ["music", "streaming", "media", "video", "podcast", "gaming", "esports", "nightlife", "radio", "film", "cinema", "concert", "tickets", "playlist", "creator", "live"],
    fonts: { display: { family: "Sora Variable", pkg: "@fontsource-variable/sora", kind: "sans" }, body: { family: "Hanken Grotesk Variable", pkg: "@fontsource-variable/hanken-grotesk", kind: "sans" } },
    palette: { primary: "#ff3d71", accent: "#3dd6ff", neutralHue: 275, tint: 0.012, scheme: "dark" },
    heading: { weight: 700, tracking: "-0.03em" }, numerals: "display",
    shape: { control: "12px", card: "18px", sheet: "24px", pill: "999px" }, surface: "tonal", density: "comfortable",
    shells: { app: "Slim left rail with a prominent now-playing or status bar at the bottom", marketing: "Transparent bar over a full-bleed dark hero", commerce: "Dark top bar with poster tiles" },
    motif: ["waveform and equalizer bars", "poster-style tiles with a gradient field per item", "glow only on the active element"],
    moves: ["Near-black canvas with two elevated layers", "One hot signal color for the current item and primary action", "Big numerals and uppercase micro-labels"],
    avoid: ["light backgrounds", "many accent colors", "thin low-contrast text"],
  },
  {
    id: "civic-clear", name: "Civic clarity",
    summary: "Plain-spoken and accessible: strong contrast, large readable type, civic blue and gold.",
    surfaces: ["app", "marketing", "service", "editorial"],
    keywords: ["government", "civic", "airline", "flight", "flights", "transit", "railway", "airport", "nonprofit", "charity", "donate", "city", "council", "library", "university", "school", "public", "forms", "benefits", "permit", "election", "community", "foundation", "church"],
    fonts: { display: { family: "Source Serif 4 Variable", pkg: "@fontsource-variable/source-serif-4", kind: "serif" }, body: { family: "Libre Franklin Variable", pkg: "@fontsource-variable/libre-franklin", kind: "sans" } },
    palette: { primary: "#1d4e89", accent: "#f2a900", neutralHue: 235, tint: 0.006, scheme: "light" },
    heading: { weight: 700, tracking: "-0.01em" }, numerals: "display",
    shape: { control: "4px", card: "6px", sheet: "8px", pill: "999px" }, surface: "ruled", density: "comfortable",
    shells: { app: "Top bar with plain section names and a skip link; breadcrumbs on inner pages", marketing: "Utility strip, clear nav, and a hero stating the one task", service: "Top bar with the main task as a button" },
    motif: ["thick top rule in civic blue", "numbered steps", "high-visibility focus rings"],
    moves: ["18px body, 1.6 line height, and 2px focus outlines", "Task-first homepage: the main action is the first thing after the heading", "Forms in one column with visible labels and inline help"],
    avoid: ["low-contrast gray text", "trendy gradients", "icon-only controls"],
  },
  {
    id: "pop-play", name: "Pop and play",
    summary: "Bright, bouncy, sticker-like: multiple saturated hues, chunky type, rounded everything.",
    surfaces: ["app", "marketing", "commerce"],
    keywords: ["kids", "children", "games", "game", "quiz", "learning", "toy", "party", "fun", "social", "stickers", "snacks", "candy", "learn", "language", "trivia", "rewards", "challenge"],
    fonts: { display: { family: "Unbounded Variable", pkg: "@fontsource-variable/unbounded", kind: "sans" }, body: { family: "Figtree Variable", pkg: "@fontsource-variable/figtree", kind: "sans" } },
    palette: { primary: "#ff4d6d", accent: "#00b8a0", neutralHue: 300, tint: 0.012, scheme: "light" },
    heading: { weight: 700, tracking: "-0.02em" }, numerals: "display",
    shape: { control: "16px", card: "24px", sheet: "32px", pill: "999px" }, surface: "hardshadow", density: "airy",
    shells: { app: "Chunky top bar with colorful tabs; a bottom bar on mobile", marketing: "Playful bar with a bouncing mascot shape", commerce: "Rounded bar with sticker-style category chips" },
    motif: ["sticker badges and speech bubbles", "wavy dividers", "rotating accent colors per section"],
    moves: ["Four accent hues, each assigned to a section or category", "Chunky 3px outlines with a solid offset shadow", "Large rounded buttons with a bounce on press"],
    avoid: ["muted neutrals only", "tiny text", "serious corporate tone"],
  },
];

export const SURFACES = {
  app: "an app you work in: dashboards, tools, admin, settings. Scanability and consistency come first.",
  marketing: "a site that persuades: landing pages, products, campaigns. Composition and voice come first.",
  commerce: "a store: browsing, product pages, cart, checkout. Product presentation and trust come first.",
  editorial: "reading and publishing: articles, docs, reports. Typography and rhythm come first.",
  service: "a local-service site with booking: spas, clinics, studios, restaurants. Clarity and a short path to booking come first.",
};

// Words that describe the *kind* of product (a store, a dashboard) rather than its domain.
// They count for less than domain words (stationery, spa, observability) when matching.
export const GENERIC_KEYWORDS = new Set(["shop", "store", "retail", "products", "cart", "checkout", "catalog", "marketplace", "dashboard", "team", "workspace", "saas", "admin", "project", "tasks", "booking", "appointment", "schedule", "community", "studio", "notes", "report", "tools", "dev", "side", "open", "source", "forms", "public", "brand", "design", "creative", "live", "learn", "fun", "social", "inbox"]);
```

## File: skills/glowup-ui/scripts/discover.mjs
size: 16902
sha: 32bcada1979915837917533f220e6f16e8cde008
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/discover.mjs

```text
#!/usr/bin/env node
// Summarize a web project's UI-relevant structure as JSON.
// Read-only: it never writes files, runs project code, or reads .env files.
// Usage: node discover.mjs [project-dir]

import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const IGNORE_DIRS = new Set([
  "node_modules", ".git", ".next", ".nuxt", ".svelte-kit", ".astro", ".output",
  ".agents", ".claude", ".opencode", ".glowup-ui",
  "dist", "build", "out", "coverage", ".turbo", ".vercel", ".glowup", ".cache",
]);
const CODE_EXT = /\.(jsx?|tsx?|mjs|cjs|vue|svelte|astro|mdx?)$/;
const STYLE_EXT = /\.(css|scss|sass|less|pcss)$/;
const MAX_FILES = 20000;
const LOCAL_IMPORT = /^(\.|@\/|~\/|#\/|\$lib\/|src\/)/;
const ASSET_IMPORT = /\.(css|scss|sass|less|svg|png|jpe?g|gif|webp|avif|json|md)$/;

function readJson(file) {
  try {
    return JSON.parse(fs.readFileSync(file, "utf8"));
  } catch {
    return null;
  }
}

function readText(file, limit = 200_000) {
  try {
    const text = fs.readFileSync(file, "utf8");
    return text.length > limit ? text.slice(0, limit) : text;
  } catch {
    return "";
  }
}

function exists(root, ...parts) {
  return fs.existsSync(path.join(root, ...parts));
}

export function walk(root, dir = root, files = []) {
  let entries;
  try {
    entries = fs.readdirSync(dir, { withFileTypes: true });
  } catch {
    return files;
  }
  for (const entry of entries) {
    if (files.length >= MAX_FILES) break;
    if (entry.name.startsWith(".env")) continue;
    const full = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      if (!IGNORE_DIRS.has(entry.name)) walk(root, full, files);
    } else if (entry.isFile()) {
      files.push(path.relative(root, full).split(path.sep).join("/"));
    }
  }
  return files;
}

function majorVersion(range) {
  const match = String(range || "").match(/(\d+)/);
  return match ? Number(match[1]) : null;
}

function detectPackageManager(root) {
  if (exists(root, "pnpm-lock.yaml")) return "pnpm";
  if (exists(root, "yarn.lock")) return "yarn";
  if (exists(root, "bun.lockb") || exists(root, "bun.lock")) return "bun";
  if (exists(root, "package-lock.json")) return "npm";
  return exists(root, "package.json") ? "npm" : null;
}

function detectFramework(root, deps, files) {
  const has = (name) => Boolean(deps[name]);
  const appDir = ["app", "src/app"].find((d) => files.some((f) => f.startsWith(`${d}/`) && /\/page\.(jsx?|tsx?|mdx)$/.test(`/${f}`)));
  const pagesDir = ["pages", "src/pages"].find((d) => files.some((f) => f.startsWith(`${d}/`) && CODE_EXT.test(f)));
  if (has("next")) {
    return { name: "next", version: deps.next, router: appDir ? (pagesDir ? "app+pages" : "app") : "pages", appDir: appDir || null, pagesDir: pagesDir || null };
  }
  if (has("nuxt")) return { name: "nuxt", version: deps.nuxt, router: "file" };
  if (has("@sveltejs/kit")) return { name: "sveltekit", version: deps["@sveltejs/kit"], router: "file" };
  if (has("astro")) return { name: "astro", version: deps.astro, router: "file" };
  if (has("@remix-run/react") || has("@react-router/dev")) {
    return { name: has("@react-router/dev") ? "react-router-framework" : "remix", version: deps["@react-router/dev"] || deps["@remix-run/react"], router: "file" };
  }
  const bundler = has("vite") ? "vite" : has("react-scripts") ? "cra" : has("webpack") ? "webpack" : null;
  if (has("react")) {
    const router = has("react-router-dom") || has("react-router") ? "react-router" : has("@tanstack/react-router") ? "tanstack-router" : has("wouter") ? "wouter" : "none";
    return { name: "react", version: deps.react, bundler, router };
  }
  if (has("vue")) return { name: "vue", version: deps.vue, bundler, router: has("vue-router") ? "vue-router" : "none" };
  if (has("svelte")) return { name: "svelte", version: deps.svelte, bundler, router: "none" };
  if (files.some((f) => f.endsWith(".html"))) return { name: "static-html", router: "file" };
  return { name: "unknown" };
}

function nextAppRoute(file, appDir) {
  const rel = file.slice(appDir.length + 1).replace(/(^|\/)page\.(jsx?|tsx?|mdx)$/, "");
  const segments = rel.split("/").filter(Boolean);
  if (segments.some((s) => s.startsWith("_") || s.startsWith("@"))) return null;
  const visible = segments.filter((s) => !/^\(.*\)$/.test(s));
  return "/" + visible.join("/");
}

function filePageRoute(file, baseDir, pattern) {
  let rel = file.slice(baseDir.length + 1).replace(pattern, "");
  rel = rel.replace(/(^|\/)index$/, "");
  const segments = rel.split("/").filter(Boolean).filter((s) => !/^\(.*\)$/.test(s));
  if (segments.some((s) => s.startsWith("_"))) return null;
  return "/" + segments.join("/");
}

function extractRouterPaths(root, files) {
  const routes = new Set();
  const candidates = files.filter((f) => /\.(jsx?|tsx?)$/.test(f) && !/\.(test|spec)\./.test(f));
  for (const file of candidates) {
    const text = readText(path.join(root, file));
    const routeLike = /react-router|@tanstack\/react-router|wouter|<Route\b|\belement\s*:|\bComponent\s*:|(^|\/)routes?\.[jt]sx?$/;
    if (!routeLike.test(text) && !routeLike.test(file)) continue;
    const patterns = [/\bpath\s*:\s*["'`]([^"'`]*)["'`]/g, /\bpath\s*=\s*\{?\s*["'`]([^"'`]*)["'`]/g];
    for (const re of patterns) {
      for (const match of text.matchAll(re)) {
        const value = match[1].trim();
        if (value === "*" || value === "") continue;
        routes.add(value.startsWith("/") ? value : `/${value}`);
      }
    }
  }
  return [...routes];
}

export function detectRoutes(root, framework, files) {
  let routes = [];
  if (framework.name === "next") {
    if (framework.appDir) {
      routes.push(...files.filter((f) => f.startsWith(`${framework.appDir}/`) && /(^|\/)page\.(jsx?|tsx?|mdx)$/.test(f)).map((f) => nextAppRoute(f, framework.appDir)));
    }
    if (framework.pagesDir) {
      const dir = framework.pagesDir;
      routes.push(...files
        .filter((f) => f.startsWith(`${dir}/`) && /\.(jsx?|tsx?|mdx)$/.test(f) && !f.startsWith(`${dir}/api/`))
        .map((f) => filePageRoute(f, dir, /\.(jsx?|tsx?|mdx)$/)));
    }
  } else if (framework.name === "sveltekit") {
    routes = files.filter((f) => /^src\/routes\/(.*\/)?\+page\.svelte$/.test(f)).map((f) => filePageRoute(f, "src/routes", /\/?\+page\.svelte$/));
  } else if (framework.name === "nuxt") {
    const dir = files.some((f) => f.startsWith("app/pages/")) ? "app/pages" : "pages";
    routes = files.filter((f) => f.startsWith(`${dir}/`) && f.endsWith(".vue")).map((f) => filePageRoute(f, dir, /\.vue$/));
  } else if (framework.name === "astro") {
    routes = files.filter((f) => /^src\/pages\/.*\.(astro|mdx?|html)$/.test(f)).map((f) => filePageRoute(f, "src/pages", /\.(astro|mdx?|html)$/));
  } else if (framework.name === "remix" || framework.name === "react-router-framework") {
    routes = files
      .filter((f) => /^app\/routes\/[^/]+\.(jsx?|tsx?)$/.test(f))
      .map((f) => {
        const name = f.replace(/^app\/routes\//, "").replace(/\.(jsx?|tsx?)$/, "");
        if (name.startsWith("_") && !name.includes(".")) return null;
        const segs = name.split(".").filter((s) => s !== "_index" && !s.startsWith("_")).map((s) => s.replace(/^\$(.+)/, ":$1"));
        return "/" + segs.join("/");
      });
  } else if (["react", "vue"].includes(framework.name)) {
    routes = extractRouterPaths(root, files);
    if (routes.length === 0) routes = ["/"];
  } else if (framework.name === "static-html") {
    routes = files.filter((f) => f.endsWith(".html")).map((f) => "/" + f.replace(/(^|\/)index\.html$/, ""));
  }
  const unique = [...new Set(routes.filter((r) => r !== null).map((r) => r.replace(/\/+$/, "") || "/"))].sort();
  return unique.map((route) => ({ path: route, dynamic: /\[|:|\$/.test(route), type: classifyRoute(route) }));
}

/** Guess a route's page type from its path, so large apps can design one composition per type. */
export function classifyRoute(route) {
  const p = route.toLowerCase();
  const last = p.split("/").filter(Boolean).pop() || "";
  if (/(^|\/)(login|log-in|signin|sign-in|signup|sign-up|register|auth|forgot|reset|verify|logout|invite|onboarding)(\/|$)/.test(p)) return "auth";
  if (/(^|\/)(404|500|not-found|error)(\/|$)/.test(p) || p === "*") return "error";
  if (/(^|\/)(settings|account|profile|preferences|billing|security|notifications|admin\/config)(\/|$)/.test(p)) return "settings";
  if (/(^|\/)(pricing|about|features|blog|contact|terms|privacy|legal|landing|changelog|careers)(\/|$)/.test(p)) return "marketing";
  if (p === "/" || /(^|\/)(dashboard|overview|home|analytics|reports?|insights)(\/|$)/.test(p)) return "dashboard";
  if (/^(\[.*\]|:.+|\$.+)$/.test(last)) return "detail";
  if (/(^|\/)(new|create|edit)(\/|$)/.test(p)) return "form";
  return "collection";
}

// Not visual: modules under these folders, or named like hooks, are skipped in the ranking.
const NON_VISUAL_SEGMENT = /^(hooks?|types?|stores?|state|utils?|lib|helpers?|api|server|trpc|services?|constants?|config|schemas?|models?|data|i18n|locales?|context|providers?|actions?)$/;

/** True when a module id looks like UI (a component or UI folder), not types, hooks, or data. */
export function isVisualModule(id) {
  const segments = id.split("/").filter(Boolean);
  const last = segments[segments.length - 1] || "";
  if (/^use[A-Z]/.test(last) || /\.(types?|d|schema|store|utils?)$/.test(last)) return false;
  if (/(Repository|Provider|Store|Service|Context|Client|Schema|Router|Handler|Helper|Utils?|Types?|Config)$/.test(last)) return false;
  if (segments.some((s) => NON_VISUAL_SEGMENT.test(s))) return false;
  return /^[A-Z]/.test(last) || segments.some((s) => /^(components?|ui|primitives|design-system|layouts?|shell)$/i.test(s));
}

/**
 * Rank UI modules by how many files import them: the highest-leverage components to restyle first.
 * Counts relative/aliased imports and imports from monorepo workspace packages (for example "@acme/ui/button").
 */
export function componentUsage(root, files, limit = 25, workspacePackages = []) {
  const counts = new Map();
  const isWorkspace = (spec) => workspacePackages.some((name) => spec === name || spec.startsWith(`${name}/`));
  const codeFiles = files.filter((f) => /\.(jsx?|tsx?|mjs|vue|svelte|astro)$/.test(f) && !/\.(test|spec|stories|e2e)\./.test(f) && !/(^|\/)(tests?|__tests__|__mocks__|e2e|playwright|cypress|fixtures|test-utils|mocks)\//.test(f));
  for (const file of codeFiles.slice(0, 8000)) {
    const text = readText(path.join(root, file));
    const seen = new Set();
    for (const m of text.matchAll(/(?:import|export)\s+(?:[\w*{}\s,]+\s+from\s+)?["']([^"']+)["']/g)) {
      const spec = m[1];
      if (!(LOCAL_IMPORT.test(spec) || isWorkspace(spec)) || ASSET_IMPORT.test(spec)) continue;
      let id = spec.startsWith(".") ? path.posix.normalize(path.posix.join(path.posix.dirname(file), spec)) : spec;
      id = id.replace(/\.(jsx?|tsx?|mjs|vue|svelte)$/, "").replace(/\/index$/, "");
      if (seen.has(id) || !isVisualModule(id)) continue;
      seen.add(id);
      counts.set(id, (counts.get(id) || 0) + 1);
    }
  }
  return [...counts.entries()]
    .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
    .slice(0, limit)
    .map(([module, importedBy]) => ({ module, importedBy }));
}

function detectStyling(root, deps, files) {
  const has = (name) => Boolean(deps[name]);
  const cssFiles = files.filter((f) => STYLE_EXT.test(f));
  const twConfig = files.find((f) => /^tailwind\.config\.(js|cjs|mjs|ts)$/.test(f)) || null;
  const v4Import = cssFiles.find((f) => /@import\s+["']tailwindcss["']/.test(readText(path.join(root, f), 20_000)));
  let tailwind = null;
  if (has("tailwindcss") || twConfig || v4Import) {
    const major = majorVersion(deps.tailwindcss) ?? (v4Import && !twConfig ? 4 : 3);
    tailwind = { version: deps.tailwindcss || null, major, config: twConfig, cssEntry: v4Import || null };
  }
  const libs = ["styled-components", "@emotion/react", "@mui/material", "@chakra-ui/react", "@mantine/core", "antd", "@radix-ui/react-slot", "@headlessui/react", "react-aria-components", "class-variance-authority", "clsx", "classnames", "tailwind-merge", "sass", "bootstrap", "@vanilla-extract/css"];
  const tokenFiles = [];
  for (const f of cssFiles) {
    const text = readText(path.join(root, f), 100_000);
    const vars = text.match(/--[a-zA-Z0-9-_]+\s*:/g) || [];
    if (vars.length > 0 || /@theme\b/.test(text)) {
      tokenFiles.push({ file: f, customProperties: vars.length, tailwindTheme: /@theme\b/.test(text) });
    }
  }
  return {
    tailwind,
    cssModules: cssFiles.filter((f) => /\.module\.(css|scss|sass|less)$/.test(f)).length,
    stylesheets: cssFiles.slice(0, 50),
    libraries: libs.filter(has),
    shadcn: exists(root, "components.json"),
    tokenFiles,
  };
}

function detectFonts(root, deps, files) {
  const fonts = new Set();
  for (const name of Object.keys(deps)) {
    if (name.startsWith("@fontsource")) fonts.add(name);
  }
  const html = files.filter((f) => f.endsWith(".html")).slice(0, 10);
  for (const f of html) {
    for (const m of readText(path.join(root, f)).matchAll(/fonts\.googleapis\.com\/css2?\?family=([^"'&]+)/g)) {
      fonts.add(`google:${decodeURIComponent(m[1]).replace(/\+/g, " ")}`);
    }
  }
  const code = files.filter((f) => /\.(jsx?|tsx?)$/.test(f) && /(layout|_app|font)/i.test(f)).slice(0, 30);
  for (const f of code) {
    const text = readText(path.join(root, f));
    for (const m of text.matchAll(/import\s*\{([^}]+)\}\s*from\s*["']next\/font\/google["']/g)) {
      m[1].split(",").map((s) => s.trim()).filter(Boolean).forEach((n) => fonts.add(`next/font:${n}`));
    }
    if (/next\/font\/local/.test(text)) fonts.add("next/font:local");
  }
  return [...fonts];
}

export function discover(rootInput = ".") {
  const root = path.resolve(rootInput);
  const pkg = readJson(path.join(root, "package.json")) || {};
  const deps = { ...(pkg.peerDependencies || {}), ...(pkg.devDependencies || {}), ...(pkg.dependencies || {}) };
  const files = walk(root);
  const framework = detectFramework(root, deps, files);
  const scripts = pkg.scripts || {};
  const pick = (...names) => names.filter((n) => scripts[n]).map((n) => ({ name: n, command: scripts[n] }));
  const componentDirs = [...new Set(files
    .map((f) => f.match(/^(.*?\/?(components|ui)\/)/)?.[1])
    .filter(Boolean)
    .map((d) => d.replace(/\/$/, "")))].slice(0, 20);
  const specialStates = files.filter((f) => /(^|\/)(loading|error|not-found|global-error|404|500|\+error)\.(jsx?|tsx?|svelte|vue|astro)$/.test(f));
  const routes = detectRoutes(root, framework, files);
  const pageTypes = {};
  for (const r of routes) (pageTypes[r.type] ||= []).push(r.path);
  const componentFiles = files.filter((f) => /(^|\/)(components|ui)\//.test(f) && /\.(jsx|tsx|vue|svelte|astro)$/.test(f) && !/\.(test|spec|stories)\./.test(f)).length;
  const large = routes.length >= 30 || componentFiles >= 100;

  return {
    root,
    name: pkg.name || path.basename(root),
    packageManager: detectPackageManager(root),
    framework,
    typescript: Boolean(deps.typescript) || files.some((f) => f === "tsconfig.json"),
    scale: {
      routes: routes.length,
      componentFiles,
      size: large ? "large" : routes.length >= 10 || componentFiles >= 30 ? "medium" : "small",
      advice: large ? "Work by route group; fix shared primitives first and inspect every affected route. Keep already-good pages unchanged." : "Fix evidenced weaknesses in the requested scope. Reuse shared components; inspect affected routes without rewriting every page.",
    },
    routes,
    pageTypes,
    componentUsage: componentUsage(root, files, 25, Object.entries(deps).filter(([, v]) => /^(workspace:|file:|link:|\*$)/.test(String(v))).map(([k]) => k)),
    styling: detectStyling(root, deps, files),
    fonts: detectFonts(root, deps, files),
    componentDirs,
    specialStateFiles: specialStates,
    scripts: {
      dev: pick("dev", "start", "serve"),
      build: pick("build"),
      preview: pick("preview"),
      lint: pick("lint", "lint:check"),
      typecheck: pick("typecheck", "type-check", "tsc", "check-types", "check"),
      test: pick("test", "test:unit", "test:ci"),
    },
    browserTooling: {
      playwrightDependency: Boolean(deps.playwright || deps["@playwright/test"]),
    },
    notes: [
      "Routes are detected statically; confirm them against the router code.",
      "Dynamic routes need a real ID from seed or mock data before they can be captured.",
    ],
    fileCount: files.length,
    truncated: files.length >= MAX_FILES,
  };
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const target = process.argv[2] || ".";
  if (!fs.existsSync(target)) {
    console.error(`Directory not found: ${target}`);
    process.exit(66);
  }
  console.log(JSON.stringify(discover(target), null, 2));
}
```

## File: skills/glowup-ui/scripts/inspect.mjs
size: 5126
sha: 866f5506ba3789e4d3bc68edd3de413ce35e8ac6
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/inspect.mjs

```text
#!/usr/bin/env node
// One read-only orientation call. Does not run application code or read .env values.
import path from "node:path";
import fs from "node:fs";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
import { discover } from "./discover.mjs";
import { detectLook } from "./look.mjs";

export function inspect(root = ".", { scope = "auto" } = {}) {
  if (!["auto", "redesign", "refine", "polish"].includes(scope)) throw new Error("Scope must be auto, redesign, refine or polish; inspect is for existing apps.");
  root = fs.realpathSync(root);
  if (!fs.statSync(root).isDirectory()) throw new Error("Choose an application directory");
  const d = discover(root), look = detectLook(root);
  const command = (name) => `${d.packageManager || "npm"} run ${name}`;
  const checks = Object.fromEntries(["build", "test", "typecheck", "lint"].map((kind) => [kind, (d.scripts[kind] || []).map((s) => command(s.name))]));
  // Only resolve aliases declared in local JSON configs. Never guess a custom
  // alias or suggest a file outside the inspected application.
  let options = {};
  for (const config of ["tsconfig.json", "jsconfig.json"]) {
    try {
      const file = fs.realpathSync(path.join(root, config));
      if (!file.startsWith(root + path.sep)) continue;
      options = JSON.parse(fs.readFileSync(file, "utf8")).compilerOptions || {};
      break;
    } catch {}
  }
  const resolve = (name) => {
    const bases = [name];
    for (const [alias, targets] of Object.entries(options.paths || {})) {
      if (!Array.isArray(targets)) continue;
      const parts = alias.split("*");
      if (parts.length > 2) continue;
      const match = parts.length === 1 ? name === alias : name.startsWith(parts[0]) && name.endsWith(parts[1]) && name.length >= parts[0].length + parts[1].length;
      if (!match) continue;
      const middle = parts.length === 1 ? "" : name.slice(parts[0].length, name.length - parts[1].length);
      for (const target of targets) if (typeof target === "string") bases.push(path.resolve(root, typeof options.baseUrl === "string" ? options.baseUrl : ".", target.replace("*", middle)));
    }
    for (const base of bases) for (const candidate of [base, ...[".jsx", ".tsx", ".js", ".ts", ".mjs", ".vue", ".svelte", ".astro"].flatMap(ext => [base + ext, path.join(base, "index" + ext)])]) {
      const full = path.resolve(root, candidate);
      if (!full.startsWith(root + path.sep)) continue;
      try {
        const physical = fs.realpathSync(full);
        if (physical.startsWith(root + path.sep) && fs.statSync(full).isFile()) return path.relative(root, full).split(path.sep).join("/");
      } catch {}
    }
  };
  const shells = [...d.componentUsage.filter((c) => /layout|shell|header|navbar/i.test(c.module)).map((c) => c.module), "src/App", "src/app/layout", "app/layout", "src/components/Layout"].map(resolve).filter(Boolean).slice(0, 4);
  return {
    root: d.root, product: d.name, mode: scope === "redesign" ? "TRANSFORM (full redesign; preserve product and behavior)" : ["refine", "polish"].includes(scope) ? "REFINE (preserve identity and composition)" : "Select TRANSFORM or REFINE from the user request; existing files do not determine redesign scope", framework: d.framework, packageManager: d.packageManager,
    identity: { scheme: look.scheme, accent: look.accent, brand: look.brand, fonts: d.fonts, shell: look.shell, designedSignals: look.designSignals, ...(look.partial ? { partial: true, unreadable: look.unreadable } : {}) },
    scale: d.scale, routes: d.routes, checks,
    readFirst: [...new Set([...(d.styling.tokenFiles || []).map((t) => t.file), ...shells, ...d.componentUsage.slice(0, 6).map((c) => resolve(c.module)).filter(Boolean)])],
    sharedComponents: d.componentUsage.slice(0, 8),
    next: ["Save a checkpoint before editing; baseline the app's own tests/build.", "Capture the requested routes at desktop/mobile; include real dynamic IDs and existing states.", "Use review.mjs findings and the request to choose up to three priorities, not a limit on edits. Full redesign may span composition and shared components; REFINE stays local.", "Make one representative route better before applying a shared change; compare the same captures after."],
    truncated: d.truncated, limitations: [
      ...d.notes,
      ...(look.partial ? [`identity fingerprint is partial: ${look.unreadable.length} unreadable path(s) skipped (${look.unreadable.map((u) => `${u.dir}: ${u.code}`).join(", ")}); inspect them by hand before concluding the app has no identity`] : []),
      "readFirst resolves local files and aliases from plain JSON tsconfig/jsconfig only; inherited/JSONC/bundler/workspace aliases need manual inspection.",
    ],
  };
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  try {
    const { values, positionals } = parseArgs({ allowPositionals: true, options: { scope: { type: "string", default: "auto" } } });
    console.log(JSON.stringify(inspect(positionals[0] || ".", { scope: values.scope }), null, 2));
  }
  catch (error) { console.error(error.message); process.exitCode = 64; }
}
```

## File: skills/glowup-ui/scripts/lint.mjs
size: 9302
sha: 35f57179de02df783935683267880634d0cc1389
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/lint.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/lint.mjs

## File: skills/glowup-ui/scripts/look.mjs
size: 8731
sha: 17a95b384731ccb5d27efa1783a1dadc6f8307aa
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/look.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/look.mjs

## File: skills/glowup-ui/scripts/measure.mjs
size: 8910
sha: f55bb1ab905c1ebcfb0df4819114735496b49531
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/measure.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/measure.mjs

## File: skills/glowup-ui/scripts/palette.mjs
size: 11448
sha: 0bf597cb9a4def2fc7e45fa14e1cd47d1408636f
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/palette.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/palette.mjs

## File: skills/glowup-ui/scripts/review.mjs
size: 10743
sha: 9ad4fa7117d68660bb7650385bc028526934ec24
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/review.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/review.mjs

## File: skills/glowup-ui/scripts/scaffold.mjs
size: 11542
sha: 95c6c9e8209c46d709e3353384ca5425eb736138
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/scaffold.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/scaffold.mjs

## File: skills/glowup-ui/scripts/screenshot.mjs
size: 15191
sha: 025f6477a49afe173455ce27cb3d647929c4f121
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/screenshot.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/screenshot.mjs

## File: skills/glowup-ui/scripts/verify-flow.mjs
size: 6313
sha: 3042e77cae4bd2b9da2e71a5bb5c2718a1f9329b
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/verify-flow.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/scripts/verify-flow.mjs

## File: skills/glowup-ui/references/behavior-checks.md
size: 4202
sha: a3ee88a46024285a9e034a9877a0c00de92a04f3
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/behavior-checks.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/behavior-checks.md

## File: skills/glowup-ui/references/create-mode.md
size: 6477
sha: 075c471c077ff63e3acce5944973e62a8f1e6a8c
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/create-mode.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/create-mode.md

## File: skills/glowup-ui/references/design-decisions.md
size: 5903
sha: 4db4f0ea1c75d6c6ad569a98ebf3504e170752e5
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/design-decisions.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/design-decisions.md

## File: skills/glowup-ui/references/design-quality.md
size: 4572
sha: 4da7d478bfca2040f156aa816f8f13a8006ed897
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/design-quality.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/design-quality.md

## File: skills/glowup-ui/references/motion.md
size: 4094
sha: 7852e7ae2256e1af7929435fab82787b6b6592f7
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/motion.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/motion.md

## File: skills/glowup-ui/references/transform-mode.md
size: 6005
sha: c7e988de275be155d91d2f953105eae5420ca82c
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/transform-mode.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/transform-mode.md

## File: skills/glowup-ui/references/verification.md
size: 8238
sha: 0b8fdb7f54dee43428d41eab5562c6345a91b9c0
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/verification.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/references/verification.md

## File: skills/glowup-ui/assets/starter/project/gitignore.tpl
size: 32
sha: 4a02c38a0eb3a96026a60125653f8f36a1a9d37d
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/gitignore.tpl

```text
node_modules
dist
.glowup
*.log
```

## File: skills/glowup-ui/assets/starter/project/index.html.tpl
size: 293
sha: 8afce96e963211312ff7a72fcfe0a1b0d9a5d2e5
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/index.html.tpl

```text
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>__NAME__</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
```

## File: skills/glowup-ui/assets/starter/project/package-lock.json.tpl
size: 132085
sha: 54ed39fd75e99ceae6809e8bcbf50f987461acd6
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/package-lock.json.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/package-lock.json.tpl

## File: skills/glowup-ui/assets/starter/project/package.json.tpl
size: 647
sha: 65e14b41f2ca6e8ad632e6ff2e5158e3e7414bc4
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/package.json.tpl

```text
{
  "name": "__NAME__",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "vitest run"
  },
  "dependencies": {
    "react": "^19.1.0",
    "react-dom": "^19.1.0",
    "react-router-dom": "^7.6.0"
  },
  "devDependencies": {
    "@tailwindcss/vite": "^4.1.0",
    "@testing-library/jest-dom": "^6.6.0",
    "@testing-library/react": "^16.3.0",
    "@testing-library/user-event": "^14.6.0",
    "@vitejs/plugin-react": "^5.0.0",
    "jsdom": "^26.1.0",
    "tailwindcss": "^4.1.0",
    "vite": "^7.0.0",
    "vitest": "4.1.12"
  }
}
```

## File: skills/glowup-ui/assets/starter/project/src/index.css.tpl
size: 131
sha: 68deb7020e2e5a6d234b82aff5dd10f1841860f5
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/src/index.css.tpl

```text
/* Replaced by: node <skill-dir>/scripts/direction.mjs --product "..." --surface app --out src/index.css */
@import "tailwindcss";
```

## File: skills/glowup-ui/assets/starter/project/src/main.jsx.tpl
size: 346
sha: f2be76ae3f8b03b7be61ed03435f209907732fe4
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/src/main.jsx.tpl

```text
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import { AppRoutes } from "./routes.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <BrowserRouter>
      <AppRoutes />
    </BrowserRouter>
  </StrictMode>,
);
```

## File: skills/glowup-ui/assets/starter/project/src/routes.jsx.tpl
size: 603
sha: 05e5793c6d4f2e95cb62a6d4d7fb2bdb0b98df85
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/src/routes.jsx.tpl

```text
import { Route, Routes } from "react-router-dom";
// import { SidebarShell } from "./shells/SidebarShell.jsx";   // app products
// import { TopBarShell } from "./shells/TopBarShell.jsx";     // marketing, store, booking
import { PageHeader } from "./ui/index.js";

// Replace this skeleton: one <Route> per page, wrapped in the shell the direction calls for.
function Home() {
  return <main className="mx-auto max-w-6xl px-4 py-8 sm:px-6"><PageHeader title="__NAME__" /></main>;
}

export function AppRoutes() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
    </Routes>
  );
}
```

## File: skills/glowup-ui/assets/starter/project/tests/setup.js.tpl
size: 614
sha: 0939b6787d3ae8aa28a8fe25fbbbe6da0560b6b7
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/tests/setup.js.tpl

```text
import "@testing-library/jest-dom/vitest";
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";

afterEach(() => cleanup());

// jsdom has no <dialog> methods or matchMedia.
if (typeof HTMLDialogElement !== "undefined") {
  HTMLDialogElement.prototype.showModal ??= function () { this.setAttribute("open", ""); };
  HTMLDialogElement.prototype.close ??= function () { this.removeAttribute("open"); this.dispatchEvent(new Event("close")); };
}
window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
```

## File: skills/glowup-ui/assets/starter/project/tests/smoke.test.jsx.tpl
size: 334
sha: 9a9b912cf8afde51579f83dda386be228de525ba
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/tests/smoke.test.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/tests/smoke.test.jsx.tpl

## File: skills/glowup-ui/assets/starter/project/vite.config.js.tpl
size: 300
sha: 1deea43b7ba06a0d3145f4b8f1e82457a04a1290
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/vite.config.js.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/project/vite.config.js.tpl

## File: skills/glowup-ui/assets/starter/shells/SidebarShell.jsx.tpl
size: 2466
sha: 53b7d2293626087f136c5f28410f6c39256e580c
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/shells/SidebarShell.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/shells/SidebarShell.jsx.tpl

## File: skills/glowup-ui/assets/starter/shells/TopBarShell.jsx.tpl
size: 2325
sha: 53401717f901c8f32a4822c53b3c0250d10b5126
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/shells/TopBarShell.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/shells/TopBarShell.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/ArtTile.jsx.tpl
size: 2563
sha: 9ff2b004c87e251655ae57d4f7966cc9e0e6f813
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/ArtTile.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/ArtTile.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Avatar.jsx.tpl
size: 1383
sha: 63a62a85477f2352b7a4f98823a2215a99f9704a
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Avatar.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Avatar.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Badge.jsx.tpl
size: 798
sha: 11dd55c945e4afaf7dfb0e6bbcd67741c954de07
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Badge.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Badge.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Button.jsx.tpl
size: 1642
sha: e17b0c5da21ec0c202ae0d9bc80d1b4d425ecaa7
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Button.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Button.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Card.jsx.tpl
size: 732
sha: 096c5d4e256d0ff2f91488890c4e24dc6840f7a8
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Card.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Card.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Charts.jsx.tpl
size: 6758
sha: 5e1e4878b506ae534e818f3a11c82c022d550075
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Charts.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Charts.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Choice.jsx.tpl
size: 2435
sha: e2159d3e2ca6224d30331cb865735aa72d24cc1e
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Choice.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Choice.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/cn.js.tpl
size: 361
sha: a096936602a00706fae064dca6f73a9d929dacf1
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/cn.js.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/cn.js.tpl

## File: skills/glowup-ui/assets/starter/ui/Dialog.jsx.tpl
size: 2809
sha: a07feb8a58f9a1753d4793d95b58168b9f6f227c
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Dialog.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Dialog.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Field.jsx.tpl
size: 2953
sha: cbc47cd72781180fb722b6fe8cd697dedbee4619
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Field.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Field.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Icon.jsx.tpl
size: 5183
sha: 0ad3fbe992bf431a448a796712495184d67c1e75
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Icon.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Icon.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Illustrations.jsx.tpl
size: 5781
sha: edd08208d87f9cabb8285ae653279eea3ebd5a55
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Illustrations.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Illustrations.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/index.js.tpl
size: 1099
sha: 8a3409d94ab9d91905c00900e18109a0977fe5ca
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/index.js.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/index.js.tpl

## File: skills/glowup-ui/assets/starter/ui/Layouts.jsx.tpl
size: 9232
sha: 7835b35c8254a4c4f3916a02643f9daf703719c0
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Layouts.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Layouts.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Motifs.jsx.tpl
size: 4328
sha: 4d99457799f1c5f001a2dcc3233c5dc2e67be25a
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Motifs.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Motifs.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/PageHeader.jsx.tpl
size: 742
sha: 4ced1fa43a390923627bd322ac3bc0866971d0f8
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/PageHeader.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/PageHeader.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Progress.jsx.tpl
size: 1846
sha: 926c419b00c5b877e433d2512de01ab248e1f459
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Progress.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Progress.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/States.jsx.tpl
size: 1984
sha: 7462c8868254333f4bfd480f10ddd8243897cd95
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/States.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/States.jsx.tpl

## File: skills/glowup-ui/assets/starter/ui/Table.jsx.tpl
size: 1276
sha: 3476e6c7ab5f4b835888fb4205e25db6d96ad184
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Table.jsx.tpl

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/assets/starter/ui/Table.jsx.tpl

## File: skills/glowup-ui/agents/openai.yaml
size: 568
sha: 4377da2eee479035eff256e9713bdb9830757974
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/agents/openai.yaml

Content is not inlined in the catalog. Read the upstream file: https://github.com/avivgerz-hue/glowup-ui/blob/main/skills/glowup-ui/agents/openai.yaml

## File: README.md
upstream: https://github.com/avivgerz-hue/glowup-ui/blob/main/README.md

````text
<picture>
  <source media="(max-width: 600px)" srcset="assets/brand/hero-mobile.svg">
  <img src="assets/brand/hero.svg" alt="Glowup UI — Your app works. Now make it look incredible." width="1280">
</picture>

# Glowup UI — frontend design skill for existing apps

**UI redesign with preservation checks.** Glowup UI is an MIT-licensed Agent Skill for AI coding agents. It focuses on improving composition, typography, navigation and shared components in existing web apps while retaining routes, content, data and behavior. It also supports new apps (**CREATE**) and focused polish (**REFINE**).

Use it with Claude Code, Codex, OpenCode or GitHub Copilot through one canonical skill. Installation is tested; native activation and a comparative design-quality advantage remain unverified. [Compatibility and evidence →](docs/compatibility.md)

[![CI](https://github.com/avivgerz-hue/glowup-ui/actions/workflows/ci.yml/badge.svg)](https://github.com/avivgerz-hue/glowup-ui/actions/workflows/ci.yml) · [v0.1.2 · Public Preview](https://github.com/avivgerz-hue/glowup-ui/releases/tag/v0.1.2) · [MIT](LICENSE)

**Skill source:** [published v0.1.2 skill](https://github.com/avivgerz-hue/glowup-ui/blob/v0.1.2/skills/glowup-ui/SKILL.md) · [development instructions](skills/glowup-ui/SKILL.md). These links identify the canonical Agent Skill maintained in this repository; the tagged source matches the pinned installation commands below.

**v0.1.2 (published):** [engineering fixes and verification limits](docs/release/NOTES-v0.1.2.md). It adds an opt-in DOM accessibility audit (`screenshot.mjs --a11y`, 18 rules whose critical/serious findings become REFINE blockers) and corrects several defects it found in the skill itself — including a palette contrast check that never compared a filled action against its own page. The commands below use the published v0.1.2 tag, which was installed, hash-compared and removed from a clean directory after publication.

## Try it in your app

From your project, with Node 20+ and Git:

```bash
npx --yes --package=git+https://github.com/avivgerz-hue/glowup-ui.git#v0.1.2 glowup-ui install --agent codex --scope project
```

This installs `.agents/skills/glowup-ui/SKILL.md` in that project. End the old agent session and start a new trusted Codex conversation in the same app root; then ask:

```text
$glowup-ui Transform this app across all pages. Improve composition, navigation,
 typography and shared components. Preserve routes, content, APIs and behavior.
 Inspect matching desktop and mobile screenshots before and after.
```

Claude Code: replace `codex` with `claude`, then invoke `/glowup-ui`. OpenCode uses `--agent opencode`; VS Code Copilot uses `--agent copilot`. Their loading conventions vary: follow the [host-specific first-use steps](docs/installation.md#confirm-installation-then-load-the-skill), rather than assuming the Codex prompt works everywhere. The command runs our installer from the tagged GitHub source; **no npm publication is implied**. [Other agents, updates, safe uninstall and troubleshooting →](docs/installation.md)

### Or use the standard skills CLI

With Node **22.20+** and Git, from your app's root (project scope; telemetry disabled):

```bash
DISABLE_TELEMETRY=1 DO_NOT_TRACK=1 npx --yes skills@1.7.4 add 'avivgerz-hue/glowup-ui#v0.1.2' --skill glowup-ui -a codex --copy
```

Both the CLI and skill release are pinned. For Claude Code, use `-a claude-code`. The standard CLI can replace existing copies; review them first and use one installer per destination. Our installer above supports Node 20+ and recoverable backups. Installation is not native activation proof. [Removal, compatibility and skills.sh indexing →](docs/installation.md#optional-standard-installer)

Skill listed but not used? [Confirm full instruction loading, inspect candidate copies, and uninstall safely →](docs/installation.md#confirm-installation-then-load-the-skill). Discovery and the agent saying “I used Glowup” are not activation proof.

For a first trial, choose a disposable copy or a clean branch of your app. Start with one page using REFINE, or explicitly request TRANSFORM for a full redesign. Save the original views, verify that the agent read the instructions and selected reference, then inspect the actual result and run the app's checks. [Short independent testing guide →](docs/INDEPENDENT-TESTING.md) · [Reproducible two-session redesign challenge →](docs/REDESIGN-CHALLENGE.md)

## Inspect the examples

**Real renders. Fictional data. Maintainer examples, not controlled agent benchmarks.**

![Before and after: the same Plotline dashboard, plain output on the left and an editorial redesign on the right](assets/marketing/hero-desktop.png)

Fresh Chromium captures of the bundled source, composited side by side. Routes, copy, data and
behaviour are unchanged; each version passes its original 12 behavior tests.
[Source, exact provenance and reproduction](docs/examples.md).

<details><summary>Compare the phone layouts · 390 × 844</summary>

![Phone layouts: original, transformed, and a CREATE example, all at 390px wide](assets/marketing/hero-phone.png)

</details>

### CREATE · start with a point of view

![Margin finance workspace: one dominant balance and trend, quieter monthly context and aligned activity](assets/examples/create-desktop.png)

**Margin**, a maintainer-directed CREATE example with search, category filtering, a validated transaction dialog and local preferences. [Phone view](assets/examples/create-mobile.png) · [Run the app and inspect its brief](demo/create-ledger/README.md). It demonstrates a finance-specific composition, not a bank connection or a measured model-quality gain.

### Choose the right scope

| Mode | Ask for | Preserve |
|---|---|---|
| **CREATE** | A new application with a coherent layout and shared components from the first pass | The brief, content and chosen stack |
| **TRANSFORM** | A substantial redesign across the existing app | Routes, data, APIs, behavior and brand constraints |
| **REFINE** | Fix observed weaknesses in an already-designed interface | Its identity and composition |

REFINE is the preservation-focused scope of TRANSFORM, not a second competing design system. [See the restrained example](docs/examples.md#refine--retain-the-identity): a larger logout target and keyboard-accessible chart, with the palette, type and original tests unchanged.

```text
/glowup-ui Create an event-planning app with Dashboard, Events and Guests.
Include search, RSVP validation and responsive layouts.
```

```text
$glowup-ui Refine the settings and project views. Keep the existing palette,
typography and layout. Fix evidenced spacing, focus and phone usability issues.
```

## How it works

The agent reads one concise workflow, inspects the project, chooses a product-appropriate composition, implements shared primitives, and checks real desktop/phone views. Optional Node helpers provide design recipes, contrast-checked directions, a small starter, starting-state checkpoints and rendered issue reports. Detailed references load only when relevant.

An existing app keeps its framework and working logic. The agent is instructed to preserve routes, handlers, data, content and tests. Checkpoints, original tests and browser review help detect regressions; they do not guarantee every change is safe or aesthetically better. Review the diff.

## Coding-agent support

| Agent | Installer selection | Explicit request | Evidence |
|---|---|---|---|
| Claude Code | `--agent claude` | `/glowup-ui` | Installer tested |
| OpenAI Codex | `--agent codex` | `$glowup-ui` | Installer tested |
| OpenCode, Gemini CLI, Copilot, VS Code, Pi, Vibe, Goose, Roo | [Selections and paths](docs/compatibility.md) | Host-specific | Installer tested; runtime varies |

One canonical skill, no separate prompt forks. **Installation and discovery are not proof of full instruction loading.** Current authenticated native activation and a controlled design-quality advan
````
