diff --git a/.github/hooks/impeccable.json b/.github/hooks/impeccable.json
new file mode 100644
index 0000000..0e93780
--- /dev/null
+++ b/.github/hooks/impeccable.json
@@ -0,0 +1,13 @@
+{
+ "version": 1,
+ "hooks": {
+ "postToolUse": [
+ {
+ "type": "command",
+ "matcher": "edit|create|apply_patch",
+ "bash": "node \"$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/hook.mjs\"",
+ "timeoutSec": 5
+ }
+ ]
+ }
+}
diff --git a/.github/skills/impeccable/SKILL.md b/.github/skills/impeccable/SKILL.md
new file mode 100644
index 0000000..34c7658
--- /dev/null
+++ b/.github/skills/impeccable/SKILL.md
@@ -0,0 +1,167 @@
+---
+name: impeccable
+description: Use when the user wants to design, redesign, shape, critique, audit, polish, clarify, distill, harden, optimize, adapt, animate, colorize, extract, or otherwise improve a frontend interface. Covers websites, landing pages, dashboards, product UI, app shells, components, forms, settings, onboarding, and empty states. Handles UX review, visual hierarchy, information architecture, cognitive load, accessibility, performance, responsive behavior, theming, anti-patterns, typography, fonts, spacing, layout, alignment, color, motion, micro-interactions, UX copy, error states, edge cases, i18n, and reusable design systems or tokens. Also use for bland designs that need to become bolder or more delightful, loud designs that should become quieter, live browser iteration on UI elements, or ambitious visual effects that should feel technically extraordinary. Not for backend-only or non-UI tasks.
+version: 3.9.1
+user-invocable: true
+argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · init|document|extract|live] [target]"
+license: Apache 2.0
+---
+
+Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
+
+## Setup
+
+You MUST do these steps before proceeding:
+
+1. Run `node .github/skills/impeccable/scripts/context.mjs` once per session; if the runtime shows this skill's loaded base directory, run `node /scripts/context.mjs` instead. Keep cwd/workdir at the user's project, not the skill directory. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and append `--target ` to the same command. If you've already seen its output in this conversation, do not re-run it. The script either prints the project's PRODUCT.md (and DESIGN.md when present) as a markdown block, or tells you it's missing. Follow whatever it prints. **If it reports `NO_PRODUCT_MD`:** divert into `reference/init.md` first when the user invoked `init`, `teach`, `craft`, or `shape`, or when their wording clearly maps to one of those from-scratch build flows (for example: "build/create/make a landing page", "design a new app", or "shape a feature"). Captured product context is the point of those flows. For any other command, a scoped evaluate / refine / enhance / fix / iterate request against existing code, do **not** divert into init. The existing code is the context: proceed with the requested command, infer the register from the surface in focus (step 4), and offer `/impeccable init` once as a suggestion the user can take later. A missing PRODUCT.md must never block a scoped request. If the output ends with an `UPDATE_AVAILABLE` directive, follow it (ask the user once about updating, then continue). It never blocks the current task.
+2. If the user invoked a sub-command (`craft`, `shape`, `audit`, `polish`, ...), you MUST read the command's reference next: **`reference/.md`, or the native variant from the Commands table** (e.g. `reference/audit.native.md`) **when the project platform is native** (`ios` / `android` / `adaptive`, per the `context.mjs` directive). One file, not both. Non-optional. The reference defines the command's flow; without it you will skip steps the user expects.
+3. Familiarize yourself with any existing design system, conventions, and components in the code. Read at least one project file (CSS / tokens / theme / a representative component or page). **Required even when you've loaded a sub-command reference in step 2.** Don't reinvent the wheel; use what's there when it works, branch out when the UX wins.
+4. Read the matching register reference. **This is non-optional; skipping it produces generic output.** If the project is marketing, a landing page, a campaign, long-form content, or a portfolio (design IS the product), read `reference/brand.md`. If it is app UI, admin, a dashboard, or a tool (design SERVES the product), read `reference/product.md`. Pick by first match: (1) task cue ("landing page" vs "dashboard"); (2) surface in focus (the page, file, or route being worked on); (3) `register` field in PRODUCT.md.
+5. **If PRODUCT.md's `## Platform` is `ios` or `android`**, also read `reference/.md` (HIG / Material 3 conventions). `adaptive` (cross-platform, ships both) reads both files. `web`, absent, or unrecognized: nothing extra to read. `context.mjs` prints the directive when one applies.
+6. **If the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .github/skills/impeccable/scripts/palette.mjs` to receive a brand seed color and composition guidance. This is the anchor for your primary brand color. Compose the rest of the palette (bg, surface, ink, accent, muted) around it per the script's instructions. Use OKLCH throughout. **Skip this step only if step 3 found committed brand colors in existing tokens; in that case identity-preservation wins.**
+
+## Design guidance
+
+Produce ready-to-ship, production-grade code, not prototypes or starting points. Take no shortcuts unless the user asks for them (when in doubt, ask). Don't stop until arriving at a complete implementation (beautiful, responsive, fast, precise, bug-free, on brand). You take attention to detail seriously: every page, section or component crafted is battle tested using the tools available to you (browser screenshotting, computer use, etc). the model is capable of extraordinary work. Don't hold back.
+
+### General rules
+
+#### Color
+
+- **Verify contrast.** Body text must hit ≥4.5:1 against its background; large text (≥18px or bold ≥14px) needs ≥3:1. Placeholder text needs the same 4.5:1, not the muted-gray default. The most common failure: muted gray body text on a tinted near-white. If the contrast is even close, bump the body color toward the ink end of the ramp; light gray "for elegance" is the single biggest reason AI designs feel hard to read.
+- Gray text on a colored background looks washed out. Use a darker shade of the background's own hue, or a transparency of the text color.
+
+#### Typography
+
+- Cap body line length at 65–75ch.
+- Don't pair fonts that are similar but not identical (two geometric sans-serifs, two humanist sans-serifs). Pair on a contrast axis (serif + sans, geometric + humanist) or use one family in multiple weights.
+- Hero / display heading ceiling: clamp() max ≤ 6rem (~96px). Above that the page is shouting, not designing.
+- Display heading letter-spacing floor: ≥ -0.04em. Anything tighter and letters touch; cramped, not "designed".
+- Use `text-wrap: balance` on h1–h3 for even line lengths; `text-wrap: pretty` on long prose to reduce orphans.
+
+#### Layout
+
+- Vary spacing for rhythm.
+- Cards are the lazy answer. Use them only when they're truly the best affordance. Nested cards are always wrong.
+- Flexbox for 1D, Grid for 2D. Don't default to Grid when `flex-wrap` would be simpler.
+- For responsive grids without breakpoints: `repeat(auto-fit, minmax(280px, 1fr))`.
+- Build a semantic z-index scale (dropdown → sticky → modal-backdrop → modal → toast → tooltip). Never arbitrary values like 999 or 9999.
+
+#### Motion
+- Motion should be intentional, and not be an afterthought. consider it as part of the build.
+- Don't animate CSS layout properties unless truly needed.
+- Ease out with exponential curves (ease-out-quart / quint / expo). No bounce, no elastic.
+- Use libraries for more advanced motion needs (e.g. motion, gsap, anime.js, lenis etc)
+- Reduced motion is not optional. Every animation needs a `@media (prefers-reduced-motion: reduce)` alternative: typically a crossfade or instant transition.
+- Staggering the items within one list is legitimate. The tell is the uniform reflex (one identical entrance applied to every section), not motion itself; each reveal should fit what it reveals. Suppressing the reflex is never a reason to ship a page with no motion at all.
+- Reveal animations must enhance an already-visible default. Don't gate content visibility on a class-triggered transition; transitions pause on hidden tabs and headless renderers, so the reveal never fires and the section ships blank.
+- Premium motion materials are not just transform/opacity. Blur, backdrop-filter, clip-path, mask, and shadow/glow are part of the palette when they materially improve the effect and stay smooth.
+
+#### Interaction
+
+- Dropdowns rendered with `position: absolute` inside an `overflow: hidden` or `overflow: auto` container will be clipped. Use the native `` / popover API, `position: fixed`, or a portal to escape the stacking context.
+
+### New projects only (when no prior work exists)
+
+#### Color & Theme
+
+- Use OKLCH.
+- **The cream / sand / beige body bg is the saturated AI default of 2026.** The whole warm-neutral band (OKLCH L 0.84-0.97, C < 0.06, hue 40-100) reads as cream/sand/paper/parchment regardless of what you call it. Token names like `--paper`, `--cream`, `--sand`, `--bone`, `--flour`, `--linen`, `--parchment`, `--wheat`, `--biscuit`, `--ivory` are tells in themselves. If the brief is "warm, traditional, family-coastal-Italian" or "magazine-warm" or "editorial-restraint", DO NOT translate that into a near-white warm-tinted bg; that's the AI move. Pick: (a) a saturated brand color as the body (terracotta, oxblood, deep ochre, near-black), (b) a true off-white at chroma 0 (or chroma toward the brand's own hue, not toward warmth-by-default), or (c) a darker mid-tone tinted neutral that's clearly the brand's own. "Warmth" in the brand is carried by accent + typography + imagery, not by body bg.
+- Tinted neutrals: add 0.005–0.015 chroma toward the brand's hue. Don't default-tint toward warm or cool "because the brand feels that way"; that's the cross-project monoculture move.
+- When picking a theme: Dark vs. light is never a default. Not dark "because tools look cool dark." Not light "to be safe.".Before choosing, write one sentence of physical scene: who uses this, where, under what ambient light, in what mood. If the sentence doesn't force the answer, it's not concrete enough. Add detail until it does.
+- Pick a **color strategy** before picking colors. Four steps on the commitment axis:
+ - **Restrained**: tinted neutrals + one accent ≤10%. Product default; brand minimalism.
+ - **Committed**: one saturated color carries 30–60% of the surface. Brand default for identity-driven pages.
+ - **Full palette**: 3–4 named roles, each used deliberately. Brand campaigns; product data viz.
+ - **Drenched**: the surface IS the color. Brand heroes, campaign pages.
+
+### Absolute bans
+
+Match-and-refuse. If you're about to write any of these, rewrite the element with different structure.
+
+- **Side-stripe borders.** `border-left` or `border-right` greater than 1px as a colored accent on cards, list items, callouts, or alerts. Never intentional. Rewrite with full borders, background tints, leading numbers/icons, or nothing.
+- **Gradient text.** `background-clip: text` combined with a gradient background. Decorative, never meaningful. Use a single solid color. Emphasis via weight or size.
+- **Glassmorphism as default.** Blurs and glass cards used decoratively. Rare and purposeful, or nothing.
+- **The hero-metric template.** Big number, small label, supporting stats, gradient accent. SaaS cliché.
+- **Identical card grids.** Same-sized cards with icon + heading + text, repeated endlessly.
+- **Tiny uppercase tracked eyebrow above every section.** The 2023-era kicker (small all-caps text with wide tracking, "ABOUT" "PROCESS" "PRICING" above each heading) is now the saturated AI scaffold; it appears on 55-95% of generations regardless of brief, which is the definition of a tell. One named kicker as a deliberate brand system is voice; an eyebrow on every section is AI grammar. Choose a different cadence.
+- **Numbered section markers as default scaffolding (01 / 02 / 03).** Putting `01 · About / 02 · Process / 03 · Pricing` above every section is the eyebrow trope one tier deeper: reach for it because "landing pages do this" and you're scaffolding by reflex. Numbers earn their place when the section actually IS a sequence (a real 3-step process, an ordered flow, a typed timeline) and the order carries information the reader needs. One deliberate numbered sequence on one page is voice; numbered eyebrows on every section across the site is AI grammar.
+- **Text that overflows its container.** Long heading words plus large clamp scales plus narrow grids cause headline overflow on tablet/mobile. Test the heading copy at every breakpoint; if it overflows, reduce the clamp max or rewrite the copy. The viewport is part of the design.
+
+### The AI slop test
+
+If someone could look at this interface and say "AI made that" without doubt, it's failed. Cross-register failures are the absolute bans above. Register-specific failures live in each reference.
+
+**Category-reflex check.** Run at two altitudes; the second one catches what the first one misses.
+
+- **First-order:** if someone could guess the theme + palette from the category alone, it's the first training-data reflex. Rework the scene sentence and color strategy until the answer isn't obvious from the domain.
+- **Second-order:** if someone could guess the aesthetic family from category-plus-anti-references ("AI workflow tool that's not SaaS-cream → editorial-typographic", "fintech that's not navy-and-gold → terminal-native dark mode"), it's the trap one tier deeper. The first reflex was avoided; the second wasn't. Rework until both answers are not obvious. The brand register's [reflex-reject aesthetic lanes](reference/brand.md) list catches the currently-saturated families.
+
+## Commands
+
+| Command | Category | Description | Reference |
+|---|---|---|---|
+| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) |
+| `shape [feature]` | Build | Plan UX/UI before writing code | [reference/shape.md](reference/shape.md) |
+| `init` | Build | Set up project context: PRODUCT.md, DESIGN.md, live config, next steps | [reference/init.md](reference/init.md) |
+| `document` | Build | Generate DESIGN.md from existing project code | [reference/document.md](reference/document.md) |
+| `extract [target]` | Build | Pull reusable tokens and components into design system | [reference/extract.md](reference/extract.md) |
+| `critique [target]` | Evaluate | UX design review with heuristic scoring | [reference/critique.md](reference/critique.md) |
+| `audit [target]` | Evaluate | Technical quality checks (a11y, perf, responsive) | [reference/audit.md](reference/audit.md) · native: [reference/audit.native.md](reference/audit.native.md) |
+| `polish [target]` | Refine | Final quality pass before shipping | [reference/polish.md](reference/polish.md) |
+| `bolder [target]` | Refine | Amplify safe or bland designs | [reference/bolder.md](reference/bolder.md) |
+| `quieter [target]` | Refine | Tone down aggressive or overstimulating designs | [reference/quieter.md](reference/quieter.md) |
+| `distill [target]` | Refine | Strip to essence, remove complexity | [reference/distill.md](reference/distill.md) |
+| `harden [target]` | Refine | Production-ready: errors, i18n, edge cases | [reference/harden.md](reference/harden.md) |
+| `onboard [target]` | Refine | Design first-run flows, empty states, activation | [reference/onboard.md](reference/onboard.md) |
+| `animate [target]` | Enhance | Add purposeful animations and motion | [reference/animate.md](reference/animate.md) |
+| `colorize [target]` | Enhance | Add strategic color to monochromatic UIs | [reference/colorize.md](reference/colorize.md) |
+| `typeset [target]` | Enhance | Improve typography hierarchy and fonts | [reference/typeset.md](reference/typeset.md) |
+| `layout [target]` | Enhance | Fix spacing, rhythm, and visual hierarchy | [reference/layout.md](reference/layout.md) |
+| `delight [target]` | Enhance | Add personality and memorable touches | [reference/delight.md](reference/delight.md) |
+| `overdrive [target]` | Enhance | Push past conventional limits | [reference/overdrive.md](reference/overdrive.md) |
+| `clarify [target]` | Fix | Improve UX copy, labels, and error messages | [reference/clarify.md](reference/clarify.md) |
+| `adapt [target]` | Fix | Adapt for different devices and screen sizes | [reference/adapt.md](reference/adapt.md) · native: [reference/adapt.native.md](reference/adapt.native.md) |
+| `optimize [target]` | Fix | Diagnose and fix UI performance | [reference/optimize.md](reference/optimize.md) |
+| `live` | Iterate | Visual variant mode: pick elements in the browser, generate alternatives | [reference/live.md](reference/live.md) |
+
+Plus three management commands: `pin `, `unpin `, and `hooks `, detailed below.
+
+### Routing rules
+
+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` the project has no captured context yet, so lead the menu with `/impeccable init` as the top recommendation (one line on why) and still show the rest below; don't silently jump into init. Otherwise run `node .github/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**
+
+ Reason over the signals; there is no score to obey:
+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).
+ - `critique.latest` is `null` → the project has never been critiqued; for a set-up project with a real surface, offering `/impeccable critique ` is a strong default.
+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.
+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.
+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`. **`live` and the bundled `detect.mjs` are web-only.** If `setup.platform` is `ios`, `android`, or `adaptive`, don't lead with either; the browser overlay and the HTML rule engine don't apply to native app code.
+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.
+
+ **If `scan.targets` is non-empty and `setup.platform` is not `ios`/`android`/`adaptive`, run `node .github/skills/impeccable/scripts/detect.mjs --json ` once** (the bundled detector over local files: no network, no npx; it reads HTML/CSS, so skip it for native projects). `scan.via` tells you what they are: `git-changes` (the markup/style files in your dirty tree, the most relevant set), `source-dir` (e.g. `src`, `app`), `html`, or `root`. Fold the hits into your picks: many quality / contrast hits → `audit` or `polish`; a specific slop family → the matching command (gradient text or eyebrows → `quieter` / `typeset`, flat or gray palette → `colorize`, and so on). It's a real, current signal that beats guessing. If detect errors or the tree is large and slow, skip it and recommend the user run `audit` themselves; never block the suggestion on it.
+
+ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.
+2. **First word matches a command** (table above OR `pin` / `unpin` / `hooks`): load its reference file (on native platforms, the table's native variant; Setup step 2's one-file rule) and follow its instructions. Everything after the command name is the target.
+3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference (same native-variant rule) and proceed as if invoked. If two commands could fit, ask once which.
+4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.
+
+Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `/impeccable`.
+
+If the first word is `craft` or `shape`, or routing rule 3 clearly maps the user's intent to either command, setup still runs first, but the matching reference ([reference/craft.md](reference/craft.md) or [reference/shape.md](reference/shape.md)) owns the rest of the flow. Both are from-scratch build flows: if setup invokes `init` as a blocker, finish init, refresh context, then resume the original command and target.
+
+`teach` is a deprecated alias for `init`: if the user types it, load [reference/init.md](reference/init.md) and proceed as if they ran `init`.
+
+## Pin / Unpin
+
+**Pin** creates a standalone shortcut so `/` invokes `/impeccable ` directly. **Unpin** removes it. The script writes to every harness directory present in the project.
+
+```bash
+node .github/skills/impeccable/scripts/pin.mjs
+```
+
+Valid `` is any command from the table above. Report the script's result concisely. Confirm the new shortcut on success, relay stderr verbatim on error.
+
+## Hooks
+
+`/impeccable hooks ` manages the design detector hook for this project. The hook auto-runs the detector after direct UI file edits and surfaces findings as system reminders. Full flow is in [reference/hooks.md](reference/hooks.md); load it when the user invokes `/impeccable hooks` with any argument.
\ No newline at end of file
diff --git a/.github/skills/impeccable/reference/adapt.md b/.github/skills/impeccable/reference/adapt.md
new file mode 100644
index 0000000..7f76bbb
--- /dev/null
+++ b/.github/skills/impeccable/reference/adapt.md
@@ -0,0 +1,312 @@
+> **Additional context needed**: target platforms/devices and usage contexts.
+
+Adapt an existing design to a different context: another screen size, device, platform, or use case. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context.
+
+**Web only** (mobile web included). Native platforms (`ios` / `android` / `adaptive`) route to [adapt.native.md](adapt.native.md) instead; if the project is native, switch to it now.
+
+---
+
+## Assess Adaptation Challenge
+
+Understand what needs adaptation and why:
+
+1. **Identify the source context**:
+ - What was it designed for originally? (Desktop web? Mobile app?)
+ - What assumptions were made? (Large screen? Mouse input? Fast connection?)
+ - What works well in current context?
+
+2. **Understand target context**:
+ - **Device**: Mobile, tablet, desktop, TV, watch, print?
+ - **Input method**: Touch, mouse, keyboard, voice, gamepad?
+ - **Screen constraints**: Size, resolution, orientation?
+ - **Connection**: Fast wifi, slow 3G, offline?
+ - **Usage context**: On-the-go vs desk, quick glance vs focused reading?
+ - **User expectations**: What do users expect on this platform?
+
+3. **Identify adaptation challenges**:
+ - What won't fit? (Content, navigation, features)
+ - What won't work? (Hover states on touch, tiny touch targets)
+ - What's inappropriate? (Desktop patterns on mobile, mobile patterns on desktop)
+
+**CRITICAL**: Adaptation is rethinking the experience for the new context, not scaling pixels.
+
+## Plan Adaptation Strategy
+
+Create context-appropriate strategy:
+
+### Mobile Adaptation (Desktop → Mobile)
+
+**Layout Strategy**:
+- Single column instead of multi-column
+- Vertical stacking instead of side-by-side
+- Full-width components instead of fixed widths
+- Bottom navigation instead of top/side navigation
+
+**Interaction Strategy**:
+- Touch targets 44x44px minimum (not hover-dependent)
+- Swipe gestures where appropriate (lists, carousels)
+- Bottom sheets instead of dropdowns
+- Thumbs-first design (controls within thumb reach)
+- Larger tap areas with more spacing
+
+**Content Strategy**:
+- Progressive disclosure (don't show everything at once)
+- Prioritize primary content (secondary content in tabs/accordions)
+- Shorter text (more concise)
+- Larger text (16px minimum)
+
+**Navigation Strategy**:
+- Hamburger menu or bottom navigation
+- Reduce navigation complexity
+- Sticky headers for context
+- Back button in navigation flow
+
+### Tablet Adaptation (Hybrid Approach)
+
+**Layout Strategy**:
+- Two-column layouts (not single or three-column)
+- Side panels for secondary content
+- Master-detail views (list + detail)
+- Adaptive based on orientation (portrait vs landscape)
+
+**Interaction Strategy**:
+- Support both touch and pointer
+- Touch targets 44x44px but allow denser layouts than phone
+- Side navigation drawers
+- Multi-column forms where appropriate
+
+### Desktop Adaptation (Mobile → Desktop)
+
+**Layout Strategy**:
+- Multi-column layouts (use horizontal space)
+- Side navigation always visible
+- Multiple information panels simultaneously
+- Fixed widths with max-width constraints (don't stretch to 4K)
+
+**Interaction Strategy**:
+- Hover states for additional information
+- Keyboard shortcuts
+- Right-click context menus
+- Drag and drop where helpful
+- Multi-select with Shift/Cmd
+
+**Content Strategy**:
+- Show more information upfront (less progressive disclosure)
+- Data tables with many columns
+- Richer visualizations
+- More detailed descriptions
+
+### Print Adaptation (Screen → Print)
+
+**Layout Strategy**:
+- Page breaks at logical points
+- Remove navigation, footer, interactive elements
+- Black and white (or limited color)
+- Proper margins for binding
+
+**Content Strategy**:
+- Expand shortened content (show full URLs, hidden sections)
+- Add page numbers, headers, footers
+- Include metadata (print date, page title)
+- Convert charts to print-friendly versions
+
+### Email Adaptation (Web → Email)
+
+**Layout Strategy**:
+- Narrow width (600px max)
+- Single column only
+- Inline CSS (no external stylesheets)
+- Table-based layouts (for email client compatibility)
+
+**Interaction Strategy**:
+- Large, obvious CTAs (buttons not text links)
+- No hover states (not reliable)
+- Deep links to web app for complex interactions
+
+## Implement Adaptations
+
+Apply changes systematically:
+
+### Responsive Breakpoints
+
+Choose appropriate breakpoints:
+- Mobile: 320px-767px
+- Tablet: 768px-1023px
+- Desktop: 1024px+
+- Or content-driven breakpoints (where design breaks)
+
+### Layout Adaptation Techniques
+
+- **CSS Grid/Flexbox**: Reflow layouts automatically
+- **Container Queries**: Adapt based on container, not viewport
+- **`clamp()`**: Fluid sizing between min and max
+- **Media queries**: Different styles for different contexts
+- **Display properties**: Show/hide elements per context
+
+### Touch Adaptation
+
+- Increase touch target sizes (44x44px minimum)
+- Add more spacing between interactive elements
+- Remove hover-dependent interactions
+- Add touch feedback (ripples, highlights)
+- Consider thumb zones (easier to reach bottom than top)
+
+### Content Adaptation
+
+- Use `display: none` sparingly (still downloads)
+- Progressive enhancement (core content first, enhancements on larger screens)
+- Lazy loading for off-screen content
+- Responsive images (`srcset`, `picture` element)
+
+### Navigation Adaptation
+
+- Transform complex nav to hamburger/drawer on mobile
+- Bottom nav bar for mobile apps
+- Persistent side navigation on desktop
+- Breadcrumbs on smaller screens for context
+
+**IMPORTANT**: Test on real devices. Device emulation in DevTools is helpful but not perfect.
+
+**NEVER**:
+- Hide core functionality on mobile (if it matters, make it work)
+- Assume desktop = powerful device (consider accessibility, older machines)
+- Use different information architecture across contexts (confusing)
+- Break user expectations for platform (mobile users expect mobile patterns)
+- Forget landscape orientation on mobile/tablet
+- Use generic breakpoints blindly (use content-driven breakpoints)
+- Ignore touch on desktop (many desktop devices have touch)
+
+## Verify Adaptations
+
+Test thoroughly across contexts:
+
+- **Real devices**: Test on actual phones, tablets, desktops
+- **Different orientations**: Portrait and landscape
+- **Different browsers**: Safari, Chrome, Firefox, Edge
+- **Different OS**: iOS, Android, Windows, macOS
+- **Different input methods**: Touch, mouse, keyboard
+- **Edge cases**: Very small screens (320px), very large screens (4K)
+- **Slow connections**: Test on throttled network
+
+When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
+
+---
+
+## Reference Material
+
+The sections below were previously `responsive-design.md` and live inline now so the adapt flow has its deep responsive reference in one place.
+
+### Responsive Design
+
+#### Mobile-First: Write It Right
+
+Start with base styles for mobile, use `min-width` queries to layer complexity. Desktop-first (`max-width`) means mobile loads unnecessary styles first.
+
+#### Breakpoints: Content-Driven
+
+Don't chase device sizes; let content tell you where to break. Start narrow, stretch until design breaks, add breakpoint there. Three breakpoints usually suffice (640, 768, 1024px). Use `clamp()` for fluid values without breakpoints.
+
+#### Detect Input Method, Not Just Screen Size
+
+**Screen size doesn't tell you input method.** A laptop with touchscreen, a tablet with keyboard. Use pointer and hover queries:
+
+```css
+/* Fine pointer (mouse, trackpad) */
+@media (pointer: fine) {
+ .button { padding: 8px 16px; }
+}
+
+/* Coarse pointer (touch, stylus) */
+@media (pointer: coarse) {
+ .button { padding: 12px 20px; } /* Larger touch target */
+}
+
+/* Device supports hover */
+@media (hover: hover) {
+ .card:hover { transform: translateY(-2px); }
+}
+
+/* Device doesn't support hover (touch) */
+@media (hover: none) {
+ .card { /* No hover state - use active instead */ }
+}
+```
+
+**Critical**: Don't rely on hover for functionality. Touch users can't hover.
+
+#### Safe Areas: Handle the Notch
+
+Modern phones have notches, rounded corners, and home indicators. Use `env()`:
+
+```css
+body {
+ padding-top: env(safe-area-inset-top);
+ padding-bottom: env(safe-area-inset-bottom);
+ padding-left: env(safe-area-inset-left);
+ padding-right: env(safe-area-inset-right);
+}
+
+/* With fallback */
+.footer {
+ padding-bottom: max(1rem, env(safe-area-inset-bottom));
+}
+```
+
+**Enable viewport-fit** in your meta tag:
+```html
+
+```
+
+#### Responsive Images: Get It Right
+
+##### srcset with Width Descriptors
+
+```html
+
+```
+
+**How it works**:
+- `srcset` lists available images with their actual widths (`w` descriptors)
+- `sizes` tells the browser how wide the image will display
+- Browser picks the best file based on viewport width AND device pixel ratio
+
+##### Picture Element for Art Direction
+
+When you need different crops/compositions (not just resolutions):
+
+```html
+
+
+
+
+
+```
+
+#### Layout Adaptation Patterns
+
+**Navigation**: Three stages: hamburger + drawer on mobile, horizontal compact on tablet, full with labels on desktop. **Tables**: Transform to cards on mobile using `display: block` and `data-label` attributes. **Progressive disclosure**: Use `/` for content that can collapse on mobile.
+
+#### Testing: Don't Trust DevTools Alone
+
+DevTools device emulation is useful for layout but misses:
+
+- Actual touch interactions
+- Real CPU/memory constraints
+- Network latency patterns
+- Font rendering differences
+- Browser chrome/keyboard appearances
+
+**Test on at least**: One real iPhone, one real Android, a tablet if relevant. Cheap Android phones reveal performance issues you'll never see on simulators.
+
+---
+
+**Avoid**: Desktop-first design. Device detection instead of feature detection. Separate mobile/desktop codebases. Ignoring tablet and landscape. Assuming all mobile devices are powerful.
diff --git a/.github/skills/impeccable/reference/adapt.native.md b/.github/skills/impeccable/reference/adapt.native.md
new file mode 100644
index 0000000..f1ccd65
--- /dev/null
+++ b/.github/skills/impeccable/reference/adapt.native.md
@@ -0,0 +1,58 @@
+> **Additional context needed**: target platforms/devices and usage contexts.
+
+Adapt an existing **native** design (`ios` / `android` / `adaptive`) to a different context: another device class, orientation, platform, or origin. The trap is treating adaptation as scaling. The job is rethinking the experience for the new context, inside the platform conventions of [ios.md](ios.md) / [android.md](android.md); read the target platform's reference before planning if Setup hasn't already.
+
+## Assess Adaptation Challenge
+
+1. **Source context**: what was it designed for, and what assumptions did it make? (Phone-only? Portrait-only? One platform's idioms? A website?)
+2. **Target context**: which device class (phone, tablet, foldable), orientation, platform, and usage posture (one-handed on the go vs two-handed at rest)?
+3. **What breaks**: navigation that doesn't fit the target, layouts that stretch instead of restructure, gestures or controls that don't exist there?
+
+## Adaptation Strategies
+
+### Phone → Tablet (iPad / large screens)
+
+- **Restructure, don't stretch.** A scaled-up phone UI on a tablet is the failure mode. Use size classes (iOS) / window size classes (Android) to switch structure.
+- **Navigation changes shape**: tab bar stays or becomes a sidebar on iPad; Android navigation bar becomes a rail or drawer on expanded width.
+- **Use the width**: split view / master-detail (list + detail side by side), multi-column grids, popovers where phones used sheets.
+- **Multitasking is a size, not an edge case**: iPad Split View and Android multi-window can hand you a phone-width window on a tablet; size-class-driven layout handles both for free.
+
+### Orientation & foldables
+
+- Landscape restructures (side-by-side panes, repositioned controls); never clip or letterbox. Lock orientation only when the task truly demands it.
+- Foldables (Android): react to posture and hinge via window size classes; test folded, unfolded, and tabletop.
+
+### Platform → platform (iOS ↔ Android)
+
+Translate idioms; never transplant them:
+
+| iOS | Android |
+|---|---|
+| Tab bar | Navigation bar / rail / drawer |
+| Edge-swipe back, back chevron | Predictive Back gesture / button |
+| Switch, segmented control, system pickers | Material switch, chips, Material pickers |
+| Action sheet | Bottom sheet / Material dialog |
+| SF Symbols, SF Pro, Dynamic Type | Material Symbols, Roboto, sp scaling |
+| Semantic system colors, materials | Material color roles, tonal elevation |
+| System push/sheet transitions | Container transform, shared-axis, fade-through |
+
+Rebuild navigation and controls in the target's vocabulary; carry over the brand's expressive layer (palette intent, type accent, motion personality) through the target's theming system.
+
+### Web → native (porting a website or web app)
+
+Reconform, don't reflow. Replace web navigation with the platform's model, HTML-shaped controls with platform controls, hover affordances with touch-first ones, and px-based type with Dynamic Type / sp. Then treat the result to the full platform reference; the slop test there is the acceptance bar.
+
+## Implement & Verify
+
+- Drive structure from **size classes / window size classes**, never from device-model checks.
+- Respect safe areas and window insets in every new configuration (notch, hinge, status bar, keyboard).
+- Test on simulators for breadth, then real hardware for truth: at least one phone and one tablet per shipped platform, both orientations, split-screen where supported.
+
+When the adaptation feels native to each context, hand off to `/impeccable polish` for the final pass.
+
+**NEVER**:
+- Ship a stretched phone layout on a tablet
+- Port one platform's controls or navigation onto the other
+- Hide core functionality on smaller devices (if it matters, make it work)
+- Lock orientation to dodge a layout bug
+- Trust simulators alone (posture, gestures, and performance need hardware)
diff --git a/.github/skills/impeccable/reference/android.md b/.github/skills/impeccable/reference/android.md
new file mode 100644
index 0000000..3575c31
--- /dev/null
+++ b/.github/skills/impeccable/reference/android.md
@@ -0,0 +1,40 @@
+# Android platform
+
+For native Android apps: Jetpack Compose, Android Views, React Native, Expo, Flutter shipping to Android hardware.
+
+On native, register narrows. Material Design 3 governs structure, navigation, and interaction whatever the register; brand expresses through Material's theming (color roles, type scale, shape, motion). A Material-everywhere cross-platform app that also ships to iPhone still owes iOS its OS guarantees on that hardware: safe-area insets, Reduce Motion, edge-swipe back.
+
+## The Android slop test
+
+Would a fluent Android user trust this app, or trip on off-spec components? The most common tell is an iOS app wearing Android's skin: a bottom-only navigation copied from iPhone, a back arrow that ignores the system Back gesture, Cupertino-shaped switches and dialogs. Material 3 is the rulebook; follow its components and theme the brand through it.
+
+## Layout & structure
+
+- **Material navigation, matched to size.** Navigation bar (bottom, 3–5 destinations) on compact width; navigation rail or drawer on expanded width. Never ship a phone bottom-bar untouched on a tablet.
+- **System Back always works.** Honor the predictive Back gesture and Back button; never trap the user or hijack the gesture.
+- **Edge-to-edge with window insets.** Apply the status bar, navigation bar, display cutout, and IME insets so content never hides behind system bars or the keyboard.
+- **Top app bar for screen context**; pair with a FAB when the screen has a single primary action.
+
+## Touch targets
+
+- **48×48 dp minimum** for every touch target, with at least 8 dp between them.
+
+## Typography
+
+- **Material type scale.** Display, Headline, Title, Body, Label roles (large/medium/small each). Map text to roles; never hand-pick sizes per screen.
+- **Roboto is the system face**; theme a brand face in through the type scale, keeping body, labels, and controls legible and consistent.
+- **sp units, never fixed px**, so type follows the system font-size setting.
+
+## Color & theming
+
+- **Material color roles** (primary, on-primary, surface, surface-variant, secondary-container, outline, error). Role tokens resolve light/dark and contrast variants automatically; raw hex breaks there.
+- **Dynamic Color (Material You)** where it fits: derive the scheme from the user's wallpaper on Android 12+, with a static fallback.
+- **Dark theme is a first-class scheme.** Design and test it; never a quick invert.
+- **Tonal elevation.** Convey elevation through the standard surface tonal levels (plus shadow where appropriate); no arbitrary drop shadows.
+
+## Components & motion
+
+- **Material components.** Buttons (filled / tonal / outlined / text), FAB, switches, chips, snackbars, bottom sheets, Material dialogs, navigation bar/rail/drawer. Never port iOS controls or invent equivalents.
+- **One FAB, one primary action.** Never stack FABs or spend one on a secondary task.
+- **Snackbars for transient feedback** (actionable when useful, never a toast for that); dialogs only for decisions that must interrupt.
+- **Material motion patterns.** Container transform, shared-axis, fade-through, with standard easing and durations; honor the system Remove animations setting with a crossfade or instant cut.
diff --git a/.github/skills/impeccable/reference/animate.md b/.github/skills/impeccable/reference/animate.md
new file mode 100644
index 0000000..390b8fb
--- /dev/null
+++ b/.github/skills/impeccable/reference/animate.md
@@ -0,0 +1,203 @@
+> **Additional context needed**: performance constraints.
+
+Add motion that conveys state, gives feedback, and clarifies hierarchy. Cut motion that exists only for decoration. Animation fatigue is a real cost; spend the budget on the moments that need it.
+
+---
+
+## Register
+
+Brand: motion is part of the voice; one well-rehearsed entrance beats scattered micro-interactions. The saturated AI default is fade-and-rise reveals on every scrolled section; that's a tell, not a choreography. Reserve scroll-triggered motion for moments that earn it.
+
+Product: 150–250 ms on most transitions. Motion conveys state: feedback, reveal, loading, transitions between views. No page-load choreography; users are in a task and won't wait for it.
+
+Native (`ios` / `android` / `adaptive`): implementation follows the Motion section of [ios.md](ios.md) / [android.md](android.md) (read it first if Setup hasn't already): system transitions and OS Reduce Motion, never the web tooling below.
+
+---
+
+## Assess Animation Opportunities
+
+Analyze where motion would improve the experience:
+
+1. **Identify static areas**:
+ - **Missing feedback**: Actions without visual acknowledgment (button clicks, form submission, etc.)
+ - **Jarring transitions**: Instant state changes that feel abrupt (show/hide, page loads, route changes)
+ - **Unclear relationships**: Spatial or hierarchical relationships that aren't obvious
+ - **Lack of delight**: Functional but joyless interactions
+ - **Missed guidance**: Opportunities to direct attention or explain behavior
+
+2. **Understand the context**:
+ - What's the personality? (Playful vs serious, energetic vs calm)
+ - What's the performance budget? (Mobile-first? Complex page?)
+ - Who's the audience? (Motion-sensitive users? Power users who want speed?)
+ - What matters most? (One hero animation vs many micro-interactions?)
+
+If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
+
+**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them.
+
+## Plan Animation Strategy
+
+Create a purposeful animation plan:
+
+- **Hero moment**: What's the ONE signature animation? (Page load? Hero section? Key interaction?)
+- **Feedback layer**: Which interactions need acknowledgment?
+- **Transition layer**: Which state changes need smoothing?
+- **Delight layer**: Where can we surprise and delight?
+
+**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments.
+
+## Implement Animations
+
+Add motion systematically across these categories:
+
+### Entrance Animations
+- **Hero section**: Dramatic entrance for primary content (scale, parallax, or creative effects)
+- **Modal/drawer entry**: Smooth slide + fade, backdrop fade, focus management
+- **List rhythm**: Sibling stagger is legitimate for cards-in-a-grid or list-items-appearing. Whole-section fade-on-scroll is not a list and is not legitimate. Cap total stagger time: 10 items at 50ms each = 500ms total. For more items, reduce per-item delay or cap the staggered count.
+
+ Use CSS custom properties for clean stagger: `animation-delay: calc(var(--i, 0) * 50ms)` with `style="--i: 0"`, `style="--i: 1"`, etc. on each item.
+
+### Micro-interactions
+- **Button feedback**:
+ - Hover: Subtle scale (1.02-1.05), color shift, shadow increase
+ - Click: Quick scale down then up (0.95 → 1), ripple effect
+ - Loading: Spinner or pulse state
+- **Form interactions**:
+ - Input focus: Border color transition, slight scale or glow
+ - Validation: Shake on error, check mark on success, smooth color transitions
+- **Toggle switches**: Smooth slide + color transition (200-300ms)
+- **Checkboxes/radio**: Check mark animation, ripple effect
+- **Like/favorite**: Scale + rotation, particle effects, color transition
+
+### State Transitions
+- **Show/hide**: Fade + slide (not instant), appropriate timing (200-300ms)
+- **Expand/collapse**: Height transition with overflow handling, icon rotation
+- **Loading states**: Skeleton screen fades, spinner animations, progress bars
+- **Success/error**: Color transitions, icon animations, gentle scale pulse
+- **Enable/disable**: Opacity transitions, cursor changes
+
+### Navigation & Flow
+- **Page transitions**: Crossfade between routes, shared element transitions
+- **Tab switching**: Slide indicator, content fade/slide
+- **Carousel/slider**: Smooth transforms, snap points, momentum
+- **Scroll effects**: Parallax layers, sticky headers with state changes, scroll progress indicators
+
+### Feedback & Guidance
+- **Hover hints**: Tooltip fade-ins, cursor changes, element highlights
+- **Drag & drop**: Lift effect (shadow + scale), drop zone highlights, smooth repositioning
+- **Copy/paste**: Brief highlight flash on paste, "copied" confirmation
+- **Focus flow**: Highlight path through form or workflow
+
+### Delight Moments
+- **Empty states**: Subtle floating animations on illustrations
+- **Completed actions**: Confetti, check mark flourish, success celebrations
+- **Easter eggs**: Hidden interactions for discovery
+- **Contextual animation**: Weather effects, time-of-day themes, seasonal touches
+
+## Technical Implementation
+
+Use appropriate techniques for each animation:
+
+### Timing & Easing
+
+**Duration: the 100/300/500 rule.** Timing matters more than easing for "feels right":
+
+| Duration | Use Case | Examples |
+|----------|----------|----------|
+| **100–150ms** | Instant feedback | Button press, toggle, color change |
+| **200–300ms** | State changes | Menu open, tooltip, hover state |
+| **300–500ms** | Layout changes | Accordion, modal, drawer |
+| **500–800ms** | Entrance animations | Page load, hero reveal |
+
+**Easing curves (use these, not CSS defaults):**
+```css
+/* Recommended: natural deceleration */
+--ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); /* Smooth */
+--ease-out-quint: cubic-bezier(0.22, 1, 0.36, 1); /* Slightly snappier */
+--ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1); /* Confident, decisive */
+
+/* AVOID: feel dated and tacky */
+/* bounce: cubic-bezier(0.34, 1.56, 0.64, 1); */
+/* elastic: cubic-bezier(0.68, -0.6, 0.32, 1.6); */
+```
+
+**Exit animations are faster than entrances.** Use ~75% of enter duration.
+
+### CSS Animations
+```css
+/* Prefer for simple, declarative animations */
+- transitions for state changes
+- @keyframes for complex sequences
+- transform and opacity for reliable movement
+- blur, filters, masks, clip paths, shadows, and color shifts for premium atmospheric effects when verified smooth
+```
+
+### JavaScript Animation
+```javascript
+/* Use for complex, interactive animations */
+- Web Animations API for programmatic control
+- Framer Motion for React
+- GSAP for complex sequences
+```
+
+### Motion Materials
+
+Transform and opacity are reliable defaults, not the whole palette. Premium interfaces often need atmospheric properties. Match material to effect:
+
+- **Transform / opacity**: movement, press feedback, simple reveals, list choreography
+- **Blur / filter / backdrop-filter**: focus pulls, depth, glass or lens effects, softened entrances
+- **Clip-path / masks**: wipes, reveals, editorial cropping, product-like transitions
+- **Shadow / glow / color filters**: energy, affordance, focus, warmth, active state
+- **Grid-template-rows or FLIP-style transforms**: expanding and reflowing layout without animating `height` directly
+
+The hard rule isn't "transform and opacity only." It's: avoid animating layout-driving properties casually (`width`, `height`, `top`, `left`, margins), keep expensive effects bounded to small or isolated areas, and verify smoothness in-browser on target viewports.
+
+### Performance
+- **Layout safety**: Avoid casual animation of layout-driving properties (`width`, `height`, `top`, `left`, margins)
+- **will-change**: Add sparingly for known expensive animations only (e.g. on `:hover` or an `.animating` class), never preemptively across the whole page
+- **Scroll triggers**: Use Intersection Observer instead of scroll event listeners; unobserve after the animation fires once
+- **Bound expensive effects**: Keep blur/filter/shadow areas small or isolated, use `contain` where appropriate
+- **Monitor FPS**: Ensure 60fps on target devices
+
+### Perceived Performance
+
+Nobody cares how fast your site *is*, only how fast it feels. The 80ms threshold: anything under ~80ms feels instant because our brains buffer sensory input for that long to synchronize perception. Target this for micro-interactions.
+
+- **Preemptive start**: Begin transitions immediately while loading (iOS app zoom, skeleton UI). Users perceive work happening.
+- **Early completion**: Show content progressively, don't wait for everything (progressive images, streaming HTML, skeleton fade-ins).
+- **Optimistic UI**: Update the interface immediately, handle failures gracefully. Use for low-stakes actions (likes, follows). Avoid for payments or destructive operations.
+- **Easing affects perceived duration**: Ease-in (accelerating toward completion) makes tasks feel shorter because the peak-end effect weights final moments heavily. Ease-out feels satisfying for entrances.
+- **Caution**: Too-fast responses can decrease perceived value for complex operations (search, analysis). Sometimes a brief delay signals "real work" is happening.
+
+### Accessibility
+```css
+@media (prefers-reduced-motion: reduce) {
+ * {
+ animation-duration: 0.01ms !important;
+ animation-iteration-count: 1 !important;
+ transition-duration: 0.01ms !important;
+ }
+}
+```
+
+**NEVER**:
+- Use bounce or elastic easing curves; they feel dated and draw attention to the animation itself
+- Animate layout properties casually (`width`, `height`, `top`, `left`, margins) when transform, FLIP, or grid-based techniques would work
+- Use durations over 500ms for feedback (it feels laggy)
+- Animate without purpose (every animation needs a reason)
+- Ignore `prefers-reduced-motion` (this is an accessibility violation)
+- Animate everything (animation fatigue makes interfaces feel exhausting)
+- Block interaction during animations unless intentional
+
+## Verify Quality
+
+Test animations thoroughly:
+
+- **Smooth at 60fps**: No jank on target devices
+- **Feels natural**: Easing curves feel organic, not robotic
+- **Appropriate timing**: Not too fast (jarring) or too slow (laggy)
+- **Reduced motion works**: Animations disabled or simplified appropriately
+- **Doesn't block**: Users can interact during/after animations
+- **Adds value**: Makes interface clearer or more delightful
+
+When the motion clarifies state instead of decorating it, hand off to `/impeccable polish` for the final pass.
diff --git a/.github/skills/impeccable/reference/audit.md b/.github/skills/impeccable/reference/audit.md
new file mode 100644
index 0000000..72815af
--- /dev/null
+++ b/.github/skills/impeccable/reference/audit.md
@@ -0,0 +1,135 @@
+Run systematic **technical** quality checks and generate a comprehensive report. Don't fix issues; document them for other commands to address.
+
+This is a code-level audit, not a design critique. Check what's measurable and verifiable in the implementation.
+
+**Web only.** Native platforms (`ios` / `android` / `adaptive`) route to [audit.native.md](audit.native.md) instead; if the project is native, switch to it now.
+
+## Diagnostic Scan
+
+Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
+
+### 1. Accessibility (A11y)
+
+**Check for**:
+- **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA)
+- **Missing ARIA**: Interactive elements without proper roles, labels, or states
+- **Keyboard navigation**: Missing focus indicators, illogical tab order, keyboard traps
+- **Semantic HTML**: Improper heading hierarchy, missing landmarks, divs instead of buttons
+- **Alt text**: Missing or poor image descriptions
+- **Form issues**: Inputs without labels, poor error messaging, missing required indicators
+
+**Score 0-4**: 0=Inaccessible (fails WCAG A), 1=Major gaps (few ARIA labels, no keyboard nav), 2=Partial (some a11y effort, significant gaps), 3=Good (WCAG AA mostly met, minor gaps), 4=Excellent (WCAG AA fully met, approaches AAA)
+
+### 2. Performance
+
+**Check for**:
+- **Layout thrashing**: Reading/writing layout properties in loops
+- **Expensive animations**: Casual layout-property animation, unbounded blur/filter/shadow effects, or effects that visibly drop frames
+- **Missing optimization**: Images without lazy loading, unoptimized assets, missing will-change
+- **Bundle size**: Unnecessary imports, unused dependencies
+- **Render performance**: Unnecessary re-renders, missing memoization
+
+**Score 0-4**: 0=Severe issues (layout thrash, unoptimized everything), 1=Major problems (no lazy loading, expensive animations), 2=Partial (some optimization, gaps remain), 3=Good (mostly optimized, minor improvements possible), 4=Excellent (fast, lean, well-optimized)
+
+### 3. Theming
+
+**Check for**:
+- **Hard-coded colors**: Colors not using design tokens
+- **Broken dark mode**: Missing dark mode variants, poor contrast in dark theme
+- **Inconsistent tokens**: Using wrong tokens, mixing token types
+- **Theme switching issues**: Values that don't update on theme change
+
+**Score 0-4**: 0=No theming (hard-coded everything), 1=Minimal tokens (mostly hard-coded), 2=Partial (tokens exist but inconsistently used), 3=Good (tokens used, minor hard-coded values), 4=Excellent (full token system, dark mode works perfectly)
+
+### 4. Responsive Design
+
+**Check for**:
+- **Fixed widths**: Hard-coded widths that break on mobile
+- **Touch targets**: Interactive elements < 44x44px
+- **Horizontal scroll**: Content overflow on narrow viewports
+- **Text scaling**: Layouts that break when text size increases
+- **Missing breakpoints**: No mobile/tablet variants
+
+**Score 0-4**: 0=Desktop-only (breaks on mobile), 1=Major issues (some breakpoints, many failures), 2=Partial (works on mobile, rough edges), 3=Good (responsive, minor touch target or overflow issues), 4=Excellent (fluid, all viewports, proper touch targets)
+
+### 5. Anti-Patterns (CRITICAL)
+
+Check against ALL the **DON'T** guidelines from the parent impeccable skill (already loaded in this context). Look for AI slop tells (AI color palette, gradient text, glassmorphism, hero metrics, card grids, generic fonts) and general design anti-patterns (gray on color, nested cards, bounce easing, redundant copy).
+
+**Score 0-4**: 0=AI slop gallery (5+ tells), 1=Heavy AI aesthetic (3-4 tells), 2=Some tells (1-2 noticeable), 3=Mostly clean (subtle issues only), 4=No AI tells (distinctive, intentional design)
+
+## Generate Report
+
+### Audit Health Score
+
+| # | Dimension | Score | Key Finding |
+|---|-----------|-------|-------------|
+| 1 | Accessibility | ? | [most critical a11y issue or "--"] |
+| 2 | Performance | ? | |
+| 3 | Responsive Design | ? | |
+| 4 | Theming | ? | |
+| 5 | Anti-Patterns | ? | |
+| **Total** | | **??/20** | **[Rating band]** |
+
+**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
+
+### Anti-Patterns Verdict
+**Start here.** Pass/fail: Does this look AI-generated? List specific tells. Be brutally honest.
+
+### Executive Summary
+- Audit Health Score: **??/20** ([rating band])
+- Total issues found (count by severity: P0/P1/P2/P3)
+- Top 3-5 critical issues
+- Recommended next steps
+
+### Detailed Findings by Severity
+
+Tag every issue with **P0-P3 severity**:
+- **P0 Blocking**: Prevents task completion. Fix immediately
+- **P1 Major**: Significant difficulty or WCAG AA violation. Fix before release
+- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
+- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
+
+For each issue, document:
+- **[P?] Issue name**
+- **Location**: Component, file, line
+- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern
+- **Impact**: How it affects users
+- **WCAG/Standard**: Which standard it violates (if applicable)
+- **Recommendation**: How to fix it
+- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
+
+### Patterns & Systemic Issues
+
+Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
+- "Hard-coded colors appear in 15+ components, should use design tokens"
+- "Touch targets consistently too small (<44px) throughout mobile experience"
+
+### Positive Findings
+
+Note what's working well: good practices to maintain and replicate.
+
+## Recommended Actions
+
+List recommended commands in priority order (P0 first, then P1, then P2):
+
+1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
+2. **[P?] `/command-name`**: Brief description (specific context)
+
+**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
+
+After presenting the summary, tell the user:
+
+> You can ask me to run these one at a time, all at once, or in any order you prefer.
+>
+> Re-run `/impeccable audit` after fixes to see your score improve.
+
+**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
+
+**NEVER**:
+- Report issues without explaining impact (why does this matter?)
+- Provide generic recommendations (be specific and actionable)
+- Skip positive findings (celebrate what works)
+- Forget to prioritize (everything can't be P0)
+- Report false positives without verification
+
diff --git a/.github/skills/impeccable/reference/audit.native.md b/.github/skills/impeccable/reference/audit.native.md
new file mode 100644
index 0000000..737d50e
--- /dev/null
+++ b/.github/skills/impeccable/reference/audit.native.md
@@ -0,0 +1,139 @@
+Run systematic **technical** quality checks on a native app (`ios` / `android` / `adaptive`) and generate a comprehensive report. Don't fix issues; document them for other commands to address.
+
+This is a code-level audit, not a design critique. Audit from source (SwiftUI / UIKit / Compose / React Native / Flutter); no browser tooling or `detect.mjs` applies. Score against the platform reference(s): [ios.md](ios.md) / [android.md](android.md), both for `adaptive`. Read them before scoring if Setup hasn't already. The report skeleton mirrors [audit.md](audit.md); keep the two in sync when changing it.
+
+## Diagnostic Scan
+
+Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the criteria below.
+
+### 1. Accessibility (VoiceOver / TalkBack)
+
+**Check for**:
+- **Missing labels**: interactive elements without accessibility labels, traits/roles, or state announcements
+- **Reading and focus order**: illogical traversal, unreachable controls, focus lost on navigation
+- **Text scaling**: fixed point sizes defeating Dynamic Type (iOS) or px instead of sp (Android); layouts that clip or overlap at large sizes
+- **Touch targets**: below 44 pt (iOS) / 48 dp (Android), or crammed without spacing
+- **Reduce Motion ignored**: parallax and large slides with no crossfade alternative
+- **Contrast**: text failing contrast in either appearance, light or dark
+
+**Score 0-4**: 0=Screen reader unusable, 1=Major gaps (unlabeled controls, no scaling), 2=Partial (labels exist, order or scaling breaks), 3=Good (minor gaps), 4=Excellent (labeled, ordered, scales cleanly, Reduce Motion honored)
+
+### 2. Performance
+
+**Check for**:
+- **Slow startup**: heavy work on launch before first frame
+- **Unvirtualized lists**: long content without FlatList / LazyColumn / List recycling
+- **Main-thread jank**: synchronous work in scroll or gesture paths, dropped frames on 60/120 Hz
+- **Wasted rendering**: unnecessary re-renders (React Native) or recompositions (Compose); missing memoization/keys
+- **Image handling**: full-size images decoded for thumbnails, no caching
+- **App weight**: bloated JS bundle or binary, unused dependencies
+
+**Score 0-4**: 0=Janky everywhere, 1=Major problems (unvirtualized lists, slow launch), 2=Partial, 3=Good (minor improvements possible), 4=Excellent (fast launch, smooth scroll, lean)
+
+### 3. Appearance & Theming
+
+**Check for**:
+- **Hard-coded colors**: raw hex instead of semantic system colors (iOS) / Material color roles (Android) / design tokens
+- **Broken dark appearance**: missing dark variants, poor contrast in dark, quick inverts
+- **Dynamic Color** (Android 12+): no static fallback scheme, or ignored where it fits
+- **Off-platform materials**: hand-rolled blur/glassmorphism instead of system materials or tonal elevation
+
+**Score 0-4**: 0=Hard-coded everything, 1=Minimal tokens, 2=Partial (tokens exist, inconsistently used), 3=Good (minor hard-coded values), 4=Excellent (semantic throughout, both appearances first-class)
+
+### 4. Platform Conformance (CRITICAL)
+
+Score against the loaded platform reference(s), including their slop tests. **Check for**:
+- **Broken system gestures**: edge-swipe back disabled (iOS), predictive Back hijacked (Android)
+- **Inset violations**: content under the notch, Dynamic Island, home indicator, status bar, or keyboard
+- **Off-platform navigation**: custom global nav, overloaded tab bars, iOS patterns on Android or vice versa
+- **Web-shaped controls**: HTML-style buttons, custom toggles, hover-dependent affordances
+- **Icon drift**: mixed icon sets instead of SF Symbols / Material Symbols
+- **AI tells**: the shared absolute bans still apply (AI palette, gradient text, hero metrics)
+
+**Score 0-4**: 0=Web port (nothing native), 1=Heavy violations (3-4 kinds), 2=Some (1-2 noticeable), 3=Mostly conformant (subtle issues), 4=Fully native (a fluent user trusts every screen)
+
+### 5. Adaptivity
+
+**Check for**:
+- **Stretched phone layouts**: tablet/iPad rendering a scaled-up phone UI instead of using size classes / window size classes
+- **Orientation breakage**: landscape clipping, ignored, or locked without reason
+- **Keyboard/IME handling**: inputs hidden behind the keyboard, no inset adjustment
+- **Multitasking**: iPad Split View / Android multi-window breaking layout
+- **Foldables**: hinge-unaware layouts on posture change (Android)
+
+**Score 0-4**: 0=One screen size only, 1=Major breakage (landscape or tablet broken), 2=Partial, 3=Good (minor edge cases), 4=Excellent (adapts across sizes, orientations, and windowing)
+
+## Generate Report
+
+### Audit Health Score
+
+| # | Dimension | Score | Key Finding |
+|---|-----------|-------|-------------|
+| 1 | Accessibility | ? | [most critical issue or "--"] |
+| 2 | Performance | ? | |
+| 3 | Appearance & Theming | ? | |
+| 4 | Platform Conformance | ? | |
+| 5 | Adaptivity | ? | |
+| **Total** | | **??/20** | **[Rating band]** |
+
+**Rating bands**: 18-20 Excellent (minor polish), 14-17 Good (address weak dimensions), 10-13 Acceptable (significant work needed), 6-9 Poor (major overhaul), 0-5 Critical (fundamental issues)
+
+### Platform Conformance Verdict
+**Start here.** Pass/fail: does this read as a native app or a ported website? List specific violations. Be brutally honest.
+
+### Executive Summary
+- Audit Health Score: **??/20** ([rating band])
+- Total issues found (count by severity: P0/P1/P2/P3)
+- Top 3-5 critical issues
+- Recommended next steps
+
+### Detailed Findings by Severity
+
+Tag every issue with **P0-P3 severity**:
+- **P0 Blocking**: Prevents task completion. Fix immediately
+- **P1 Major**: Significant difficulty or platform-guideline violation. Fix before release
+- **P2 Minor**: Annoyance, workaround exists. Fix in next pass
+- **P3 Polish**: Nice-to-fix, no real user impact. Fix if time permits
+
+For each issue, document:
+- **[P?] Issue name**
+- **Location**: Screen, file, line
+- **Category**: Accessibility / Performance / Theming / Conformance / Adaptivity
+- **Impact**: How it affects users
+- **Guideline**: The HIG / Material rule it violates (if applicable)
+- **Recommendation**: How to fix it
+- **Suggested command**: Which command to use (prefer: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset)
+
+### Patterns & Systemic Issues
+
+Identify recurring problems that indicate systemic gaps rather than one-off mistakes:
+- "Hard-coded colors appear in 15+ screens, should use semantic colors"
+- "Touch targets consistently below 44 pt throughout the tab bar and list rows"
+
+### Positive Findings
+
+Note what's working well: good practices to maintain and replicate.
+
+## Recommended Actions
+
+List recommended commands in priority order (P0 first, then P1, then P2):
+
+1. **[P?] `/command-name`**: Brief description (specific context from audit findings)
+2. **[P?] `/command-name`**: Brief description (specific context)
+
+**Rules**: Only recommend commands from: /impeccable adapt, /impeccable animate, /impeccable audit, /impeccable bolder, /impeccable clarify, /impeccable colorize, /impeccable critique, /impeccable delight, /impeccable distill, /impeccable document, /impeccable harden, /impeccable layout, /impeccable onboard, /impeccable optimize, /impeccable overdrive, /impeccable polish, /impeccable quieter, /impeccable shape, /impeccable typeset. Map findings to the most appropriate command. End with `/impeccable polish` as the final step if any fixes were recommended.
+
+After presenting the summary, tell the user:
+
+> You can ask me to run these one at a time, all at once, or in any order you prefer.
+>
+> Re-run `/impeccable audit` after fixes to see your score improve.
+
+**IMPORTANT**: Be thorough but actionable. Too many P3 issues creates noise. Focus on what actually matters.
+
+**NEVER**:
+- Report issues without explaining impact (why does this matter?)
+- Provide generic recommendations (be specific and actionable)
+- Skip positive findings (celebrate what works)
+- Forget to prioritize (everything can't be P0)
+- Report false positives without verification
diff --git a/.github/skills/impeccable/reference/bolder.md b/.github/skills/impeccable/reference/bolder.md
new file mode 100644
index 0000000..f6f12a9
--- /dev/null
+++ b/.github/skills/impeccable/reference/bolder.md
@@ -0,0 +1,120 @@
+When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact by making the existing design language more decisive, specific, and committed.
+
+---
+
+## Register
+
+Brand: "bolder" means distinctive. Express a stronger point of view through hierarchy, pacing, proportion, copy, evidence, and one committed visual idea.
+
+Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, sharper information density, and more decisive prioritization. The amplification is in clarity, not drama.
+
+---
+
+## Assess Current State
+
+Analyze what makes the design feel too safe or boring:
+
+1. **Identify weakness sources**:
+ - **Generic choices**: The page could belong to any product in the category.
+ - **Timid scale**: Everything is medium-sized with no clear lead.
+ - **Low contrast**: Important and supporting elements have similar visual weight.
+ - **Static**: The surface has no meaningful moment of emphasis.
+ - **Predictable**: The composition follows a default pattern without a point of view.
+ - **Flat hierarchy**: Nothing stands out or commands attention.
+
+2. **Understand the context**:
+ - What is the brand personality?
+ - What is the purpose of this surface?
+ - Who is the audience?
+ - What design system, tokens, components, and visual conventions already exist?
+
+If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
+
+**CRITICAL**: "Bolder" does not mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random noise.
+
+**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
+
+## Design-System Lock
+
+If the project has `DESIGN.md`, tokens, theme variables, or established component styles, treat that system as the boundary. Make the existing language stronger before adding new language.
+
+Do not invent new colors, gradients, radii, shadows, fonts, decorative backgrounds, or effects just because the request says "bolder." A bolder pass should usually change emphasis, proportion, rhythm, density, contrast, copy, artifact specificity, and layout relationships while staying inside the documented system.
+
+If the existing system is genuinely too limited to express the bolder direction, stop and ask the user before expanding it. Name the exact additions, the role each would play, and why the current system cannot do the job. If the user approves expansion, update the design system or tokens alongside the implementation.
+
+## Plan Amplification
+
+Create a strategy to increase impact while maintaining coherence:
+
+- **Focal point**: Pick one thing the viewer should remember, then make the rest support it.
+- **System levers**: Identify which existing tokens, components, layout patterns, and copy structures can carry more weight.
+- **Risk budget**: Decide how far the surface can push while still feeling like the same product or brand.
+- **Hierarchy amplification**: Increase contrast between primary, secondary, and tertiary content instead of making every element louder.
+
+**IMPORTANT**: Bold design must still be usable. Impact without function is just decoration.
+
+## Amplify the Design
+
+Systematically increase impact through intention, not a menu of effects:
+
+### Typography Amplification
+- Strengthen the existing type hierarchy before changing typefaces.
+- Make important text meaningfully more dominant, and make supporting text quieter.
+- Use weight, measure, spacing, and line breaks to sharpen the point of view.
+- Add or replace fonts only after user-approved design-system expansion.
+
+### Color Amplification
+- Use the existing palette more decisively before adding colors.
+- Shift the proportion, placement, and contrast of documented colors to clarify meaning.
+- Treat any new color, gradient, or tint ramp as a design-system expansion that requires user approval.
+- Keep color tied to hierarchy, state, or brand meaning; do not use it as surface decoration.
+
+### Spatial Amplification
+- Change proportion, density, alignment, and sequencing so the composition has a stronger point of view.
+- Create clearer contrast between dense evidence and open breathing room.
+- Let layout express priority and narrative order before adding ornament.
+- Preserve responsive behavior and avoid text overflow at every breakpoint.
+
+### Surface Amplification
+- Use existing surface, border, radius, and shadow rules more deliberately.
+- Remove timid half-measures: either give an element a clear role or simplify it.
+- Add texture, depth, illustration, or decorative treatments only when already established by the system or explicitly approved.
+- Make real product artifacts, imagery, data, or copy carry attention before reaching for effects.
+
+### Motion & Animation
+- Design one meaningful moment of emphasis when motion genuinely supports the point.
+- Make interaction feedback feel more decisive without becoming distracting.
+- Keep transitions smooth and intentional.
+- **Bolder != scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold.
+
+### Composition Boldness
+- Make the dominant idea unmistakable.
+- Use layout tension, sequencing, contrast, and restraint to create a stronger read.
+- Let the page's structure communicate priority before adding decorative layers.
+- If every element is louder, the composition is not bolder; it is flatter.
+
+**NEVER**:
+- Add undocumented design-system primitives without user approval
+- Add effects randomly without purpose
+- Hide weak hierarchy behind decoration
+- Sacrifice readability for aesthetics
+- Make everything bold; contrast is the point
+- Ignore accessibility
+- Overwhelm with motion
+- Copy trendy aesthetics blindly
+
+## Verify Quality
+
+Ensure amplification maintains usability and coherence:
+
+- **System-faithful**: Did the pass make the existing design language stronger before adding anything new?
+- **No undocumented drift**: Are new colors, gradients, shadows, radii, fonts, and effects either absent or explicitly approved and documented?
+- **NOT AI slop**: Does this look like every other AI-generated "bold" design? If yes, start over.
+- **Still functional**: Can users accomplish tasks without distraction?
+- **Coherent**: Does everything feel intentional and unified?
+- **Memorable**: Will users remember this experience for the intended reason?
+- **Performant and accessible**: Does the result stay fast, readable, responsive, and WCAG-conscious?
+
+**The test**: If you showed this to someone and said "AI made this bolder," would they believe you immediately? If yes, you've failed. Bold means distinctive, not "more AI effects."
+
+When the result feels right, hand off to `/impeccable polish` for the final pass.
diff --git a/.github/skills/impeccable/reference/brand.md b/.github/skills/impeccable/reference/brand.md
new file mode 100644
index 0000000..a461c54
--- /dev/null
+++ b/.github/skills/impeccable/reference/brand.md
@@ -0,0 +1,108 @@
+# Brand register
+
+When design IS the product: brand sites, landing pages, marketing surfaces, campaign pages, portfolios, long-form content, about pages. The deliverable is the design itself; a visitor's impression is the thing being made.
+
+The register spans every genre. A tech brand (Stripe, Linear, Vercel). A luxury brand (a hotel, a fashion house). A consumer product (a restaurant, a travel site, a CPG packaging page). A creative studio, an agency portfolio, a band's album page. They all share the stance (*communicate, not transact*) and diverge wildly in aesthetic. Don't collapse them into a single look.
+
+## The brand slop test
+
+If someone could look at this and say "AI made that" without hesitation, it's failed. The bar is distinctiveness; a visitor should ask "how was this made?", not "which AI made this?"
+
+Brand isn't a neutral register. AI-generated landing pages have flooded the internet, and average is no longer findable. Restraint without intent now reads as mediocre, not refined. Brand surfaces need a POV, a specific audience, a willingness to risk strangeness. Go big or go home.
+
+**The second slop test: aesthetic lane.** Before committing to moves, name the reference. A Klim-style specimen page is one lane; Stripe-minimal is another; Liquid-Death-acid-maximalism is another. Don't drift into editorial-magazine aesthetics on a brief that isn't editorial. A hiking brand with Cormorant italic drop caps has the wrong register within the register.
+
+Then the inverse test: in one sentence, describe what you're about to build the way a competitor would describe theirs. If that sentence fits the modal landing page in the category, restart.
+
+## Typography
+
+### Font selection procedure
+
+Every project. Never skip.
+
+1. Read the brief. Write three concrete brand-voice words. Not "modern" or "elegant," but "warm and mechanical and opinionated" or "calm and clinical and careful." Physical-object words.
+2. List the three fonts you'd reach for by reflex. If any appear in the reflex-reject list below, reject them; they are training-data defaults and they create monoculture.
+3. Browse a real catalog (Google Fonts, Pangram Pangram, Future Fonts, Adobe Fonts, ABC Dinamo, Klim, Velvetyne) with the three words in mind. Find the font for the brand as a *physical object*: a museum caption, a 1970s terminal manual, a fabric label, a cheap-newsprint children's book, a concert poster, a receipt from a mid-century diner. Reject the first thing that "looks designy."
+4. Cross-check. "Elegant" is not necessarily serif. "Technical" is not necessarily sans. "Warm" is not Fraunces. If the final pick lines up with the original reflex, start over.
+
+### Reflex-reject list
+
+Training-data defaults. Ban list. Look further:
+
+Fraunces · Newsreader · Lora · Crimson · Crimson Pro · Crimson Text · Playfair Display · Cormorant · Cormorant Garamond · Syne · IBM Plex Mono · IBM Plex Sans · IBM Plex Serif · Space Mono · Space Grotesk · Inter · DM Sans · DM Serif Display · DM Serif Text · Outfit · Plus Jakarta Sans · Instrument Sans · Instrument Serif
+
+### Reflex-reject aesthetic lanes
+
+Parallel to the font list. Currently saturated aesthetic families that have flooded brand surfaces. If a brief lands in one of these lanes without a register reason that *requires* it (a literal magazine, a literal terminal, a literal industrial signage system), it's the second-order training reflex: the trap one tier deeper than picking a Fraunces font. Look further.
+
+- **Editorial-typographic.** Display serif (often italic) + small mono labels + ruled separators + monochromatic restraint. Klim-influenced, magazine-cover affectation. By 2026, every Stripe-adjacent and Notion-adjacent brand has landed here. The fingerprint: three rule-separated columns, an italic Fraunces / Recoleta / Newsreader headline, lowercase track-spaced metadata, no imagery.
+
+(More entries land here on the same cadence the font list updates. Brutalist-utility and acid-maximalism may join when they saturate. Removing entries when they fall back below saturation is also fine.)
+
+The reflex-reject lists apply to **new design choices**. When the existing brand has already committed to a font or a lane as part of its identity, identity-preservation wins; variants on an existing surface don't second-guess what's already shipping. The reflex-reject lists are for greenfield decisions and for departure-mode variants in [live.md](live.md).
+
+### Pairing and voice
+
+Distinctive + refined is the goal. The specific shape depends on the brand, not on the brand's category. A category ("restaurant", "dev tool", "magazine", "fintech") is not a recipe; treating it as one is the first-order reflex SKILL.md warns against.
+
+Two families minimum is the rule *only* when the voice needs it. A single well-chosen family with committed weight/size contrast is stronger than a timid display+body pair.
+
+### Scale
+
+Modular scale, fluid `clamp()` for headings, ≥1.25 ratio between steps. Flat scales (1.1× apart) read as uncommitted.
+
+Light text on dark backgrounds: add 0.05–0.1 to line-height. Light type reads as lighter weight and needs more breathing room.
+
+## Color
+
+Brand surfaces have permission for Committed, Full palette, and Drenched strategies. Use them. A single saturated color spread across a hero is not excess; it's voice. A beige-and-muted-slate landing page ignores the register.
+
+- Name a real reference before picking a strategy. "Klim Type Foundry #ff4500 orange drench", "Stripe purple-on-white restraint", "Liquid Death acid-green full palette", "Mailchimp yellow full palette", "Condé Nast Traveler muted navy restraint", "Vercel pure black monochrome". Unnamed ambition becomes beige.
+- Palette IS voice. A calm brand and a restless brand should not share palette mechanics.
+- When the strategy is Committed or Drenched, color carries the brand. Don't hedge with neutrals around the edges. Commit.
+- Don't converge across projects. Each brand surface differentiates from the last.
+- When a cultural-symbol palette is the obvious pull, reach past it. Let the cultural reading come from typography, imagery, and copy, not the palette.
+
+## Layout
+
+- Asymmetric compositions are one option. Break the grid intentionally for emphasis.
+- Fluid spacing with `clamp()` that breathes on larger viewports. Vary for rhythm: generous separations, tight groupings.
+- For image-led briefs (hotels, restaurants, magazines, photography), full-bleed hero imagery with overlaid menu and centered headline is a canonical move; let the photograph be the design.
+- When cards ARE the right affordance, use `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` for breakpoint-free responsiveness.
+
+## Imagery
+
+Brand surfaces lean on imagery. A restaurant, hotel, magazine, or product landing page without any imagery reads as incomplete, not as restrained. A solid-color rectangle where a hero image should go is worse than a representative stock photo.
+
+**When the brief implies imagery, you must ship imagery.** Zero images is a bug, not a design choice. "Restraint" is not an excuse. If the approved comp or brief is image-led, ship real project assets, generated raster assets, or a credible canvas/SVG/WebGL scene. Do not replace photographic, architectural, product, or place imagery with generic CSS panels, decorative diagrams, cards, bullets, or copy.
+
+- **For greenfield work without local assets, use stock imagery.** Unsplash is the default. The URL shape is `https://images.unsplash.com/photo-{id}?auto=format&fit=crop&w=1600&q=80`. **Verify the URLs before referencing them.** If you have an image-search MCP, web-fetch tool, or browser access, use it to find real photo IDs and confirm they resolve. Guessed IDs (even ones that look real) often 404 and ship as broken-image placeholders. Without a verification path, pick fewer photos you're confident exist over more that you guessed; never substitute colored `` placeholders.
+- **Search for the brand's physical object**, not the generic category: "handmade pasta on a scratched wooden table" beats "Italian food"; "cypress trees above a limestone hotel facade at dusk" beats "luxury hotel".
+- **One decisive photo beats five mediocre ones.** Hero imagery should commit to a mood; padding with more stock doesn't rescue an indecisive one.
+- **Alt text is part of the voice.** "Coastal fettuccine, hand-cut, served on the terrace" beats "pasta dish".
+
+"Imagery" here is broader than stock photography: product screenshots, custom data visualizations, generated SVG, and canvas/WebGL scenes are all imagery. Text-only pages where typography alone carries the entire visual weight are the failure mode.
+
+## Motion
+
+- One well-orchestrated page-load beats scattered micro-interactions, when the brand invites it. Some brands skip entrance motion entirely; the restraint is the voice.
+
+## Brand bans (on top of the shared absolute bans)
+
+- Monospace as lazy shorthand for "technical / developer." If the brand isn't technical, mono reads as costume.
+- Large rounded-corner icons above every heading. Screams template.
+- Single-family pages that picked the family by reflex, not voice. (A single family chosen deliberately is fine.)
+- All-caps body copy. Reserve caps for short labels and headings.
+- Timid palettes and average layouts. Safe = invisible.
+- Zero imagery on a brief that implies imagery (restaurant, hotel, food, travel, fashion, photography, hobbyist). Colored blocks where a hero photo belongs.
+- Defaulting to editorial-magazine aesthetics (display serif + italic + drop caps + broadsheet grid) on briefs that aren't magazine-shaped. Editorial is ONE aesthetic lane, not the default brand aesthetic.
+- Repeated tiny uppercase tracked labels above every section heading. A single strong kicker can be voice; repeating it as section grammar is AI scaffolding unless it's a deliberate, named brand system.
+
+## Brand permissions
+
+Brand can afford things product can't. Take them.
+
+- Ambitious first-load motion. Reveals and typographic choreography that earn their place; not fade-on-scroll for every section.
+- Single-purpose viewports. One dominant idea per fold, long scroll, deliberate pacing.
+- Unexpected color strategies. Palette IS voice; a calm brand and a restless brand should not share palette mechanics.
+- Art direction per section. Different sections can have different visual worlds if the narrative demands it. Consistency of voice beats consistency of treatment.
diff --git a/.github/skills/impeccable/reference/clarify.md b/.github/skills/impeccable/reference/clarify.md
new file mode 100644
index 0000000..00ee978
--- /dev/null
+++ b/.github/skills/impeccable/reference/clarify.md
@@ -0,0 +1,288 @@
+> **Additional context needed**: audience technical level and users' mental state in context.
+
+Find the unclear, confusing, or poorly written interface text and rewrite it. Vague copy creates support tickets and abandonment; specific copy gets users through the task.
+
+
+---
+
+## Assess Current Copy
+
+Identify what makes the text unclear or ineffective:
+
+1. **Find clarity problems**:
+ - **Jargon**: Technical terms users won't understand
+ - **Ambiguity**: Multiple interpretations possible
+ - **Passive voice**: "Your file has been uploaded" vs "We uploaded your file"
+ - **Length**: Too wordy or too terse
+ - **Assumptions**: Assuming user knowledge they don't have
+ - **Missing context**: Users don't know what to do or why
+ - **Tone mismatch**: Too formal, too casual, or inappropriate for situation
+
+2. **Understand the context**:
+ - Who's the audience? (Technical? General? First-time users?)
+ - What's the user's mental state? (Stressed during error? Confident during success?)
+ - What's the action? (What do we want users to do?)
+ - What's the constraint? (Character limits? Space limitations?)
+
+**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets.
+
+## Plan Copy Improvements
+
+Create a strategy for clearer communication:
+
+- **Primary message**: What's the ONE thing users need to know?
+- **Action needed**: What should users do next (if anything)?
+- **Tone**: How should this feel? (Helpful? Apologetic? Encouraging?)
+- **Constraints**: Length limits, brand voice, localization considerations
+
+**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words.
+
+## Improve Copy Systematically
+
+Refine text across these common areas:
+
+### Error Messages
+**Bad**: "Error 403: Forbidden"
+**Good**: "You don't have permission to view this page. Contact your admin for access."
+
+**Bad**: "Invalid input"
+**Good**: "Email addresses need an @ symbol. Try: name@example.com"
+
+**Principles**:
+- Explain what went wrong in plain language
+- Suggest how to fix it
+- Don't blame the user
+- Include examples when helpful
+- Link to help/support if applicable
+
+### Form Labels & Instructions
+**Bad**: "DOB (MM/DD/YYYY)"
+**Good**: "Date of birth" (with placeholder showing format)
+
+**Bad**: "Enter value here"
+**Good**: "Your email address" or "Company name"
+
+**Principles**:
+- Use clear, specific labels (not generic placeholders)
+- Show format expectations with examples
+- Explain why you're asking (when not obvious)
+- Put instructions before the field, not after
+- Keep required field indicators clear
+
+### Button & CTA Text
+**Bad**: "Click here" | "Submit" | "OK"
+**Good**: "Create account" | "Save changes" | "Got it, thanks"
+
+**Principles**:
+- Describe the action specifically
+- Use active voice (verb + noun)
+- Match user's mental model
+- Be specific ("Save" is better than "OK")
+
+### Help Text & Tooltips
+**Bad**: "This is the username field"
+**Good**: "Choose a username. You can change this later in Settings."
+
+**Principles**:
+- Add value (don't just repeat the label)
+- Answer the implicit question ("What is this?" or "Why do you need this?")
+- Keep it brief but complete
+- Link to detailed docs if needed
+
+### Empty States
+**Bad**: "No items"
+**Good**: "No projects yet. Create your first project to get started."
+
+**Principles**:
+- Explain why it's empty (if not obvious)
+- Show next action clearly
+- Make it welcoming, not dead-end
+
+### Success Messages
+**Bad**: "Success"
+**Good**: "Settings saved! Your changes will take effect immediately."
+
+**Principles**:
+- Confirm what happened
+- Explain what happens next (if relevant)
+- Be brief but complete
+- Match the user's emotional moment (celebrate big wins)
+
+### Loading States
+**Bad**: "Loading..." (for 30+ seconds)
+**Good**: "Analyzing your data... this usually takes 30-60 seconds"
+
+**Principles**:
+- Set expectations (how long?)
+- Explain what's happening (when it's not obvious)
+- Show progress when possible
+- Offer escape hatch if appropriate ("Cancel")
+
+### Confirmation Dialogs
+**Bad**: "Are you sure?"
+**Good**: "Delete 'Project Alpha'? This can't be undone."
+
+**Principles**:
+- State the specific action
+- Explain consequences (especially for destructive actions)
+- Use clear button labels ("Delete project" not "Yes")
+- Don't overuse confirmations (only for risky actions)
+
+### Navigation & Wayfinding
+**Bad**: Generic labels like "Items" | "Things" | "Stuff"
+**Good**: Specific labels like "Your projects" | "Team members" | "Settings"
+
+**Principles**:
+- Be specific and descriptive
+- Use language users understand (not internal jargon)
+- Make hierarchy clear
+- Consider information scent (breadcrumbs, current location)
+
+## Apply Clarity Principles
+
+Every piece of copy should follow these rules:
+
+1. **Be specific**: "Enter email" not "Enter value"
+2. **Be concise**: Cut unnecessary words (but don't sacrifice clarity)
+3. **Be active**: "Save changes" not "Changes will be saved"
+4. **Be human**: "Oops, something went wrong" not "System error encountered"
+5. **Tell users what to do**, not just what happened
+6. **Be consistent**: Use same terms throughout (don't vary for variety)
+
+**NEVER**:
+- Use jargon without explanation
+- Blame users ("You made an error" → "This field is required")
+- Be vague ("Something went wrong" without explanation)
+- Use passive voice unnecessarily
+- Write overly long explanations (be concise)
+- Use humor for errors (be empathetic instead)
+- Assume technical knowledge
+- Vary terminology (pick one term and stick with it)
+- Repeat information (headers restating intros, redundant explanations)
+- Use placeholders as the only labels (they disappear when users type)
+
+## Verify Improvements
+
+Test that copy improvements work:
+
+- **Comprehension**: Can users understand without context?
+- **Actionability**: Do users know what to do next?
+- **Brevity**: Is it as short as possible while remaining clear?
+- **Consistency**: Does it match terminology elsewhere?
+- **Tone**: Is it appropriate for the situation?
+
+When the copy reads cleanly, hand off to `/impeccable polish` for the final pass.
+
+---
+
+## Reference Material
+
+The sections below were previously `ux-writing.md` and live inline now so the clarify flow has its deep UX-writing reference in one place.
+
+### UX Writing
+
+#### The Button Label Problem
+
+**Never use "OK", "Submit", or "Yes/No".** These are lazy and ambiguous. Use specific verb + object patterns:
+
+| Bad | Good | Why |
+|-----|------|-----|
+| OK | Save changes | Says what will happen |
+| Submit | Create account | Outcome-focused |
+| Yes | Delete message | Confirms the action |
+| Cancel | Keep editing | Clarifies what "cancel" means |
+| Click here | Download PDF | Describes the destination |
+
+**For destructive actions**, name the destruction:
+- "Delete" not "Remove" (delete is permanent, remove implies recoverable)
+- "Delete 5 items" not "Delete selected" (show the count)
+
+#### Error Messages: The Formula
+
+Every error message should answer: (1) What happened? (2) Why? (3) How to fix it? Example: "Email address isn't valid. Please include an @ symbol." not "Invalid input".
+
+##### Error Message Templates
+
+| Situation | Template |
+|-----------|----------|
+| **Format error** | "[Field] needs to be [format]. Example: [example]" |
+| **Missing required** | "Please enter [what's missing]" |
+| **Permission denied** | "You don't have access to [thing]. [What to do instead]" |
+| **Network error** | "We couldn't reach [thing]. Check your connection and [action]." |
+| **Server error** | "Something went wrong on our end. We're looking into it. [Alternative action]" |
+
+##### Don't Blame the User
+
+Reframe errors: "Please enter a date in MM/DD/YYYY format" not "You entered an invalid date".
+
+#### Empty States Are Opportunities
+
+Empty states are onboarding moments: (1) Acknowledge briefly, (2) Explain the value of filling it, (3) Provide a clear action. "No projects yet. Create your first one to get started." not just "No items".
+
+#### Voice vs Tone
+
+**Voice** is your brand's personality, consistent everywhere.
+**Tone** adapts to the moment.
+
+| Moment | Tone Shift |
+|--------|------------|
+| Success | Celebratory, brief: "Done! Your changes are live." |
+| Error | Empathetic, helpful: "That didn't work. Here's what to try..." |
+| Loading | Reassuring: "Saving your work..." |
+| Destructive confirm | Serious, clear: "Delete this project? This can't be undone." |
+
+**Never use humor for errors.** Users are already frustrated. Be helpful, not cute.
+
+#### Writing for Accessibility
+
+**Link text** must have standalone meaning: "View pricing plans" not "Click here". **Alt text** describes information, not the image: "Revenue increased 40% in Q4" not "Chart". Use `alt=""` for decorative images. **Icon buttons** need `aria-label` for screen reader context.
+
+#### Writing for Translation
+
+##### Plan for Expansion
+
+German text is ~30% longer than English. Allocate space:
+
+| Language | Expansion |
+|----------|-----------|
+| German | +30% |
+| French | +20% |
+| Finnish | +30-40% |
+| Chinese | -30% (fewer chars, but same width) |
+
+##### Translation-Friendly Patterns
+
+Keep numbers separate ("New messages: 3" not "You have 3 new messages"). Use full sentences as single strings (word order varies by language). Avoid abbreviations ("5 minutes ago" not "5 mins ago"). Give translators context about where strings appear.
+
+#### Consistency: The Terminology Problem
+
+Pick one term and stick with it:
+
+| Inconsistent | Consistent |
+|--------------|------------|
+| Delete / Remove / Trash | Delete |
+| Settings / Preferences / Options | Settings |
+| Sign in / Log in / Enter | Sign in |
+| Create / Add / New | Create |
+
+Build a terminology glossary and enforce it. Variety creates confusion.
+
+#### Avoid Redundant Copy
+
+If the heading explains it, the intro is redundant. If the button is clear, don't explain it again. Say it once, say it well.
+
+#### Loading States
+
+Be specific: "Saving your draft..." not "Loading...". For long waits, set expectations ("This usually takes 30 seconds") or show progress.
+
+#### Confirmation Dialogs: Use Sparingly
+
+Most confirmation dialogs are design failures; consider undo instead. When you must confirm: name the action, explain consequences, use specific button labels ("Delete project" / "Keep project", not "Yes" / "No").
+
+#### Form Instructions
+
+Show format with placeholders, not instructions. For non-obvious fields, explain why you're asking.
+
+---
+
+**Avoid**: Jargon without explanation. Blaming users ("You made an error" → "This field is required"). Vague errors ("Something went wrong"). Varying terminology for variety. Humor for errors.
diff --git a/.github/skills/impeccable/reference/codex.md b/.github/skills/impeccable/reference/codex.md
new file mode 100644
index 0000000..d563af9
--- /dev/null
+++ b/.github/skills/impeccable/reference/codex.md
@@ -0,0 +1,105 @@
+# Codex: Visual Direction & Asset Production
+
+This file is loaded by `/impeccable craft` when the harness has native image generation (currently Codex via `image_gen`). Other harnesses skip it. It covers the two craft steps that depend on real image generation: landing the visual direction, and producing the raster assets the implementation will compose.
+
+Read this *before* generating any images. The order matters, and the per-step user pauses are what keep generated imagery from drifting away from the brief.
+
+### Four stop points before code
+
+Steps A through D each end with the user. Do not advance past any of them on your own read of the situation.
+
+1. **STOP after Step A questions.** Wait for answers.
+2. **STOP after Step B palette generation.** Wait for "confirm palette."
+3. **STOP after Step C mocks.** Wait for direction approval or delegation.
+4. **Only after Step D approves a direction** do you return to craft.md Step 4 and write code.
+
+Prior shape approval does **not** satisfy any of these. Shape's "confirm or override" advances you into Step A; it is not a substitute for it.
+
+## Step A: Explore Directions with the User
+
+Before generating anything, run a brief direction conversation grounded in the shape brief.
+
+**Step A is required even when shape just produced a confirmed brief.** The shape questions and Step A questions cover different ground: shape pins purpose, content, scope; Step A pins palette, atmosphere, and named visual references for the comps you're about to generate. The only time you can skip Step A is when the user has already answered these exact palette/atmosphere/reference questions in the same session.
+
+Ask **2-3 targeted questions** about visual lane, color strategy, atmosphere, and named anchor references. Don't enumerate generic menus; tie each question to the shape brief's answers. Example shape-grounded questions:
+
+- "Brief says 'specimen-page restraint.' Are we closer to a quiet typographic page or a wider editorial spread with hero imagery?"
+- "Palette strategy from shape was 'Committed.' Which one color carries the surface (a brand-driven pick rather than a default warm-or-cool framing)? (And no, the answer isn't a cream/sand body bg; that's the saturated AI default.)"
+
+**STOP and wait for answers.** These pin the palette before any pixel gets generated. Do not proceed to Step B until the user has responded.
+
+## Step B: Generate the Brand Palette First
+
+Generate **one** palette artifact before any mocks. This is a small, focused image: typography pairing on the chosen background, primary + accent color swatches, one signature ornament or motif. Single image, single pass.
+
+Why palette first: mocks generated against a vague color sense produce noise that drowns out the structural decisions. A confirmed palette is the first concrete contract for everything downstream.
+
+Show the palette to the user. Ask one question: "This is the palette I'm locking in for the mocks. Confirm, or call out what to shift?"
+
+**STOP and wait for confirmation.** Do not generate mocks against an unconfirmed palette. "Probably good enough" is the wrong call here; the palette is the contract for everything downstream.
+
+## Step C: Generate 1-3 Visual Mocks Against the Palette
+
+Once the palette is confirmed, generate **1 to 3** high-fidelity north-star comps. Each mock must use the confirmed palette and typography. Mocks differ in *structural* direction (hierarchy, topology, density, composition), not in color or motif.
+
+- Brand work: push visual identity, composition, mood, and signature motifs.
+- Product work: push hierarchy, topology, density, tone, grounded in realistic product structure.
+- Landing pages and long-form brand surfaces: show enough of the second fold to establish the system beyond the hero.
+
+Use the `image_gen` tool directly (or via the imagegen skill when available). Don't ask the user to install anything.
+
+## Step D: Approval Loop
+
+Show the comps. Ask what carries forward. Iterate until **one direction is approved** or the user explicitly delegates.
+
+**STOP and wait for the approval or the delegation.** Do not begin Step E or return to craft.md Step 4 until a single direction is named. If the user delegates, pick the strongest direction and explain it from the brief, not personal taste.
+
+Before moving to assets, summarize what to carry into code and what *not* to literalize from the mock. This is the handoff between visual exploration and semantic implementation.
+
+## Step E: Mock Fidelity Inventory
+
+Inventory the approved mock's major visible ingredients. For each, decide implementation: semantic HTML/CSS/SVG, generated raster, sourced raster, icon library, canvas/WebGL, or accepted omission.
+
+Common ingredients to inventory:
+
+- Hero silhouette and dominant composition
+- Signature motifs (planets, devices, portraits, charts, route lines, insets, badges, etc.)
+- Nav and primary CTA treatment
+- Section sequence, especially the second fold
+- Image-native content the concept depends on
+- Typography, density, color/material treatment, motion cues
+
+Treat the mock as a north star, not a screenshot to trace. Don't rasterize core UI text. But if the live result lacks the mock's major ingredients, the implementation is wrong.
+
+If a photographic, architectural, product, or place-led mock becomes generic CSS scenery, decorative diagrams, bullets, or copy, stop and fix it. That's a broken implementation, not a harmless interpretation.
+
+Don't substitute a different hero composition or visual driver post-approval without user sign-off.
+
+## Step F: Asset Slicing via the Asset Producer
+
+Raster ingredients identified in Step E need clean production assets. Use the bundled `impeccable_asset_producer` subagent rather than producing inline.
+
+Spawn it as a scoped subagent. If you do not have explicit permission to use agents, stop and ask:
+
+```text
+Asset production will work better as a scoped subagent job. Should I spawn the Impeccable asset producer subagent for this step?
+```
+
+Pass to the agent:
+
+- Approved mock path or screenshot reference
+- Crop paths or a contact sheet with crop ids
+- Output directory
+- Required dimensions, format, transparency needs
+- Avoid list
+- Notes on what should remain semantic HTML/CSS/SVG instead of raster
+
+Attach image generation capability to the spawned agent when the harness supports it. Do **not** load image-generation reference material into the parent thread.
+
+Inline asset production is allowed only if the user declines subagents, the harness cannot spawn the authorized agent, or the user explicitly asks for single-thread mode.
+
+Prefer HTML/CSS/SVG/canvas when they can credibly reproduce an ingredient; reach for real, generated, or stock imagery when the mock or subject matter calls for actual visual content.
+
+## After This File
+
+Once Steps A through F are complete, return to `craft.md` Step 5 (Build to Production Quality). The implementation builds against the confirmed palette, approved mock, and the assets the producer wrote.
diff --git a/.github/skills/impeccable/reference/colorize.md b/.github/skills/impeccable/reference/colorize.md
new file mode 100644
index 0000000..2457f60
--- /dev/null
+++ b/.github/skills/impeccable/reference/colorize.md
@@ -0,0 +1,257 @@
+> **Additional context needed**: existing brand colors.
+
+Replace timid grayscale or single-accent designs with a strategic palette: pick a color strategy, choose a hue family that fits the brand, then apply color with intent. More color ≠ better. Strategic color beats rainbow vomit.
+
+---
+
+## Register
+
+Brand: palette IS voice. Pick a color strategy first per SKILL.md (Restrained / Committed / Full palette / Drenched) and follow its dosage. Committed, Full palette, and Drenched deliberately exceed the ≤10% rule; that rule is Restrained only. Unexpected combinations are allowed; a dominant color can own the page when the chosen strategy calls for it.
+
+Product: semantic-first and almost always Restrained. Accent color is reserved for primary action, current selection, and state indicators. Not decoration. Every color has a consistent meaning across every screen.
+
+---
+
+## Assess Color Opportunity
+
+Analyze the current state and identify opportunities:
+
+1. **Understand current state**:
+ - **Color absence**: Pure grayscale? Limited neutrals? One timid accent?
+ - **Missed opportunities**: Where could color add meaning, hierarchy, or delight?
+ - **Context**: What's appropriate for this domain and audience?
+ - **Brand**: Are there existing brand colors we should use?
+
+2. **Identify where color adds value**:
+ - **Semantic meaning**: Success (green), error (red), warning (yellow/orange), info (blue)
+ - **Hierarchy**: Drawing attention to important elements
+ - **Categorization**: Different sections, types, or states
+ - **Emotional tone**: Warmth, energy, trust, creativity
+ - **Wayfinding**: Helping users navigate and understand structure
+ - **Delight**: Moments of visual interest and personality
+
+If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
+
+**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose.
+
+## Plan Color Strategy
+
+Create a purposeful color introduction plan:
+
+- **Color palette**: What colors match the brand/context? (Choose 2-4 colors max beyond neutrals)
+- **Dominant color**: Which color owns 60% of colored elements?
+- **Accent colors**: Which colors provide contrast and highlights? (30% and 10%)
+- **Application strategy**: Where does each color appear and why?
+
+**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more.
+
+## Introduce Color Strategically
+
+Add color systematically across these dimensions:
+
+### Semantic Color
+- **State indicators**:
+ - Success: Green tones (emerald, forest, mint)
+ - Error: Red/pink tones (rose, crimson, coral)
+ - Warning: Orange/amber tones
+ - Info: Blue tones (sky, ocean, indigo)
+ - Neutral: Gray/slate for inactive states
+
+- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.)
+- **Progress indicators**: Colored bars, rings, or charts showing completion or health
+
+### Accent Color Application
+- **Primary actions**: Color the most important buttons/CTAs
+- **Links**: Add color to clickable text (maintain accessibility)
+- **Icons**: Colorize key icons for recognition and personality
+- **Headers/titles**: Add color to section headers or key labels
+- **Hover states**: Introduce color on interaction
+
+### Background & Surfaces
+- **Tinted backgrounds**: If you replace pure gray, tint toward the brand hue, not toward a generic-warm-or-cool pair. The default-warm-tint (`oklch(97% 0.01 60)` and its neighbors) is now the AI cream/sand giveaway. Be specific to the brand or stay neutral.
+- **Colored sections**: Use subtle background colors to separate areas
+- **Gradient backgrounds**: Add depth with subtle, intentional gradients (not generic purple-blue)
+- **Cards & surfaces**: Tint cards or surfaces toward the brand, not "for warmth" by reflex
+
+**Use OKLCH for color**: It's perceptually uniform, meaning equal steps in lightness *look* equal. Great for generating harmonious scales.
+
+### Data Visualization
+- **Charts & graphs**: Use color to encode categories or values
+- **Heatmaps**: Color intensity shows density or importance
+- **Comparison**: Color coding for different datasets or timeframes
+
+### Borders & Accents
+- **Hairline borders**: 1px colored borders on full perimeter (not side-stripes; see the absolute ban on `border-left/right > 1px`)
+- **Underlines**: Color underlines for emphasis or active states
+- **Dividers**: Subtle colored dividers instead of gray lines
+- **Focus rings**: Colored focus indicators matching brand
+- **Surface tints**: A 4-8% background wash of the accent color instead of a stripe
+
+**NEVER**: `border-left` or `border-right` greater than 1px as a colored accent stripe. This is one of the three absolute bans in the parent skill. If you want to mark a card as "active" or "warning", use a full hairline border, a background tint, a leading glyph, or a numbered prefix. Not a side stripe.
+
+### Typography Color
+- **Colored headings**: Use brand colors for section headings (maintain contrast)
+- **Highlight text**: Color for emphasis or categories
+- **Labels & tags**: Small colored labels for metadata or categories
+
+### Decorative Elements
+- **Illustrations**: Add colored illustrations or icons
+- **Shapes**: Geometric shapes in brand colors as background elements
+- **Gradients**: Colorful gradient overlays or mesh backgrounds
+- **Blobs/organic shapes**: Soft colored shapes for visual interest
+
+## Balance & Refinement
+
+Ensure color addition improves rather than overwhelms:
+
+### Maintain Hierarchy
+- **Dominant color** (60%): Primary brand color or most used accent
+- **Secondary color** (30%): Supporting color for variety
+- **Accent color** (10%): High contrast for key moments
+- **Neutrals** (remaining): Gray/black/white for structure
+
+### Accessibility
+- **Contrast ratios**: Ensure WCAG compliance (4.5:1 for text, 3:1 for UI components)
+- **Don't rely on color alone**: Use icons, labels, or patterns alongside color
+- **Test for color blindness**: Verify red/green combinations work for all users
+
+### Cohesion
+- **Consistent palette**: Use colors from defined palette, not arbitrary choices
+- **Systematic application**: Same color meanings throughout (green always = success)
+- **Temperature consistency**: Warm palette stays warm, cool stays cool
+
+**NEVER**:
+- Use every color in the rainbow (choose 2-4 colors beyond neutrals)
+- Apply color randomly without semantic meaning
+- Put gray text on colored backgrounds. It looks washed out; use a darker shade of the background color or transparency instead
+- Violate WCAG contrast requirements
+- Use color as the only indicator (accessibility issue)
+- Make everything colorful (defeats the purpose)
+- Default to purple-blue gradients (AI slop aesthetic)
+
+## Verify Color Addition
+
+Test that colorization improves the experience:
+
+- **Better hierarchy**: Does color guide attention appropriately?
+- **Clearer meaning**: Does color help users understand states/categories?
+- **More engaging**: Does the interface feel warmer and more inviting?
+- **Still accessible**: Do all color combinations meet WCAG standards?
+- **Not overwhelming**: Is color balanced and purposeful?
+
+When the palette earns its place, hand off to `/impeccable polish` for the final pass.
+
+## Live-mode signature params
+
+When invoked from live mode, each variant MUST declare a `color-amount` param so the user can dial between a restrained accent and a drenched surface without regeneration. Author the variant's CSS against `var(--p-color-amount, 0.5)`, typically as the alpha multiplier on backgrounds, or as a scaling factor on the chroma axis in an OKLCH expression. 0 = neutral/monochrome, 1 = full saturation / dominant coverage.
+
+```json
+{"id":"color-amount","kind":"range","min":0,"max":1,"step":0.05,"default":0.5,"label":"Color amount"}
+```
+
+Layer 1-2 variant-specific params on top: palette selection (`steps` with named options), temperature warmth, or tint vs. true color. See `reference/live.md` for the full params contract.
+
+---
+
+## Reference Material
+
+The sections below were previously `color-and-contrast.md` and live inline now so the colorize flow has its deep color reference in one place.
+
+### Color & Contrast
+
+#### Color Spaces: Use OKLCH
+
+**Stop using HSL.** Use OKLCH (or LCH) instead. It's perceptually uniform, meaning equal steps in lightness *look* equal, unlike HSL where 50% lightness in yellow looks bright while 50% in blue looks dark.
+
+The OKLCH function takes three components: `oklch(lightness chroma hue)` where lightness is 0-100%, chroma is roughly 0-0.4, and hue is 0-360. To build a primary color and its lighter / darker variants, hold the chroma+hue roughly constant and vary the lightness, but **reduce chroma as you approach white or black**, because high chroma at extreme lightness looks garish.
+
+The hue you pick is a brand decision and should not come from a default. Do not reach for blue (hue 250) or warm orange (hue 60) by reflex; those are the dominant AI-design defaults, not the right answer for any specific brand.
+
+#### Building Functional Palettes
+
+##### Tinted Neutrals
+
+**Pure gray is dead.** A neutral with zero chroma feels lifeless next to a colored brand. Add a tiny chroma value (0.005-0.015) to all your neutrals, hued toward whatever your brand color is. The chroma is small enough not to read as "tinted" consciously, but it creates subconscious cohesion between brand color and UI surfaces.
+
+The hue you tint toward should come from THIS project's brand, not from a "warm = friendly, cool = tech" formula. If your brand color is teal, your neutrals lean toward teal. If your brand color is amber, they lean toward amber. The point is cohesion with the SPECIFIC brand, not a stock palette.
+
+**Avoid** the trap of always tinting toward warm orange or always tinting toward cool blue. Those are the two laziest defaults and they create their own monoculture across projects.
+
+##### Palette Structure
+
+A complete system needs:
+
+| Role | Purpose | Example |
+|------|---------|---------|
+| **Primary** | Brand, CTAs, key actions | 1 color, 3-5 shades |
+| **Neutral** | Text, backgrounds, borders | 9-11 shade scale |
+| **Semantic** | Success, error, warning, info | 4 colors, 2-3 shades each |
+| **Surface** | Cards, modals, overlays | 2-3 elevation levels |
+
+**Skip secondary/tertiary unless you need them.** Most apps work fine with one accent color. Adding more creates decision fatigue and visual noise.
+
+##### The 60-30-10 Rule (Applied Correctly)
+
+This rule is about **visual weight**, not pixel count:
+
+- **60%**: Neutral backgrounds, white space, base surfaces
+- **30%**: Secondary colors: text, borders, inactive states
+- **10%**: Accent: CTAs, highlights, focus states
+
+The common mistake: using the accent color everywhere because it's "the brand color." Accent colors work *because* they're rare. Overuse kills their power.
+
+#### Contrast & Accessibility
+
+##### WCAG Requirements
+
+| Content Type | AA Minimum | AAA Target |
+|--------------|------------|------------|
+| Body text | 4.5:1 | 7:1 |
+| Large text (18px+ or 14px bold) | 3:1 | 4.5:1 |
+| UI components, icons | 3:1 | 4.5:1 |
+| Non-essential decorations | None | None |
+
+##### Dangerous Color Combinations
+
+These commonly fail contrast or cause readability issues:
+
+- Light gray text on white (the #1 accessibility fail)
+- Red text on green background (or vice versa): 8% of men can't distinguish these
+- Blue text on red background (vibrates visually)
+- Yellow text on white (almost always fails)
+- Thin light text on images (unpredictable contrast)
+
+##### Testing
+
+Don't trust your eyes. Use tools:
+
+- [WebAIM Contrast Checker](https://webaim.org/resources/contrastchecker/)
+- Browser DevTools → Rendering → Emulate vision deficiencies
+- [Polypane](https://polypane.app/) for real-time testing
+
+#### Theming: Light & Dark Mode
+
+##### Dark Mode Is Not Inverted Light Mode
+
+You can't just swap colors. Dark mode requires different design decisions:
+
+| Light Mode | Dark Mode |
+|------------|-----------|
+| Shadows for depth | Lighter surfaces for depth (no shadows) |
+| Dark text on light | Light text on dark (reduce font weight) |
+| Vibrant accents | Desaturate accents slightly |
+| White backgrounds | Either pure black or a deep surface that fits the brand (a brand-tinted near-black at oklch 12-18% works too) |
+
+In dark mode, depth comes from surface lightness, not shadow. Build a 3-step surface scale where higher elevations are lighter (e.g. 15% / 20% / 25% lightness). Use the SAME hue and chroma as your brand color (whatever it is for THIS project; do not reach for blue) and only vary the lightness. Reduce body text weight slightly (e.g. 350 instead of 400) because light text on dark reads as heavier than dark text on light.
+
+##### Token Hierarchy
+
+Use two layers: primitive tokens (`--blue-500`) and semantic tokens (`--color-primary: var(--blue-500)`). For dark mode, only redefine the semantic layer; primitives stay the same.
+
+#### Alpha Is A Design Smell
+
+Heavy use of transparency (rgba, hsla) usually means an incomplete palette. Alpha creates unpredictable contrast, performance overhead, and inconsistency. Define explicit overlay colors for each context instead. Exception: focus rings and interactive states where see-through is needed.
+
+---
+
+**Avoid**: Relying on color alone to convey information. Creating palettes without clear roles for each color. Skipping color blindness testing (8% of men affected).
diff --git a/.github/skills/impeccable/reference/craft.md b/.github/skills/impeccable/reference/craft.md
new file mode 100644
index 0000000..2c7bd99
--- /dev/null
+++ b/.github/skills/impeccable/reference/craft.md
@@ -0,0 +1,123 @@
+# Craft Flow
+
+Build a feature with impeccable UX and UI quality: shape the design, land the visual direction, build real production code, inspect and improve in-browser until it meets a high-end studio bar.
+
+Before writing code, you need: PRODUCT.md loaded, register identified and the matching reference loaded, and a confirmed design direction for this task (either from `shape` or supplied by the user). PRODUCT.md is project context, not a task-specific brief.
+
+Treat any approved visual direction (generated mock or stated reference) as a concrete contract for composition, hierarchy, density, atmosphere, signature motifs, and distinctive visual moves. Don't let mocks replace structure, copy, accessibility, or state design. But if the live result lacks the approved direction's major ingredients, the implementation is wrong.
+
+### Gates: do not compress
+
+Craft has **multiple user gates**, not one. When the harness has native image generation (Codex via `image_gen`), the gate sequence before code is:
+
+1. **Shape brief confirmed** (Step 1)
+2. **Direction questions answered** (codex.md Step A)
+3. **Palette confirmed** (codex.md Step B)
+4. **One mock direction approved or delegated** (codex.md Step D)
+
+You must stop at every gate. **Shape confirmation alone is NOT a green light to start coding.** It is the green light to begin codex.md Step A. Compressing gates 2 through 4 because the shape brief felt complete is the dominant failure mode of this flow.
+
+When the harness lacks native image generation, gates 2-4 collapse into the brief itself, and shape confirmation does advance straight to code.
+
+## Step 0: Project Foundation
+
+Before shape, before code: figure out what kind of project you're working in.
+
+Look at the working directory. Run `ls`. Check for:
+
+- An existing framework: `astro.config.mjs/ts`, `next.config.js/ts`, `nuxt.config.ts`, `svelte.config.js`, `vite.config.js/ts`, `package.json` with framework deps, `Cargo.toml` + Leptos/Yew, `Gemfile` + Rails. **If found, use it.** Do not start a parallel build, do not introduce a second framework, do not write to `dist/` or `build/` directly. Whatever pipeline the project has, respect it.
+- An existing component library or design system: `src/components/`, `app/components/`, a `tokens.css` / `theme.ts`, an `astro.config` `integrations`. Read what's there before adding to it.
+- An existing icon set: `lucide-react`, `@phosphor-icons/react`, `@iconify/*`, hand-rolled SVG sprites in `assets/icons/`. **Use what's already in the project**; don't introduce a second set.
+
+If the directory is empty (greenfield), don't pick a framework silently. Ask the user via the AskUserQuestion tool, with sensible defaults framed by the brief:
+
+```text
+What should this be built on?
+ - Astro (default for content-led brand sites, landing pages, marketing surfaces)
+ - SvelteKit / Next.js / Nuxt (when the brief implies an app surface or significant interactivity)
+ - Single index.html (one-shot demo, prototype, or a deliberately framework-free experiment)
+```
+
+Default: Astro for brand briefs, the project's existing framework for product briefs. Ask once; don't re-ask mid-task.
+
+## Step 1: Shape the Design
+
+Run /impeccable shape, passing along whatever feature description the user provided. Shape is **required** for craft; it is what produces a confirmed direction.
+
+Present the shape output and stop. Wait for the user to confirm, override, or course-correct before writing code.
+
+If the user already supplied a confirmed brief or ran shape separately, use it and skip this step.
+
+When the original prompt + PRODUCT.md already answer scope, content, and visual direction with no real ambiguity, the shape output can be **compact** (3-5 bullets stating what you're building and the visual lane, ending with one or two specific questions or "confirm or override"). The full 10-section structured brief is reserved for genuinely ambiguous, multi-screen, or stakeholder-heavy tasks. Don't pad a clear brief into a long one to look thorough; equally, don't skip the pause to look efficient.
+
+If the harness has native image generation (Codex), a compact shape's "confirm or override" advances to **Step 3 and the codex.md flow**, not to Step 4. Phrase the closing line accordingly: "Confirm or override; once we lock direction, I'll run a couple of palette and reference questions before generating any mocks." This stops the model from reading shape confirmation as code-green.
+
+## Step 2: Load References
+
+Based on the design brief's "Recommended References" section, consult the relevant impeccable reference files. At minimum, always consult:
+
+- [layout.md](layout.md) for layout, spacing, grid, container queries, optical adjustments
+- [typeset.md](typeset.md) for type hierarchy, font selection, web font loading, OpenType features (Reference Material section)
+
+Then add references based on the brief's needs:
+- Complex interactions or forms? Consult [interaction-design.md](interaction-design.md)
+- Animation or transitions? Consult [animate.md](animate.md) (Reference Material covers motion materials, durations, easing, perceived performance)
+- Color-heavy or themed? Consult [colorize.md](colorize.md) (Reference Material covers OKLCH, palette structure, dark mode, contrast)
+- Responsive requirements? Consult [adapt.md](adapt.md) (Reference Material covers breakpoints, input methods, safe areas, responsive images)
+- Heavy on copy, labels, or errors? Consult [clarify.md](clarify.md) (Reference Material covers button labels, error formula, voice/tone, translation)
+
+## Step 3: Visual Direction & Assets (Harness-Gated)
+
+If the harness has **native image generation** (currently Codex via `image_gen`), this step is mandatory. **Stop and load [codex.md](codex.md)**. It covers palette generation, mock exploration, the approval loop, mock-fidelity inventory, and asset slicing via the `impeccable_asset_producer` subagent. Follow Steps A-F in that file, then return here for Step 4.
+
+If the harness lacks native image generation, **state in one line that the visual-direction-by-generation step is being skipped because the harness lacks native image generation, then proceed**. The one-line announcement is required; it forces a conscious decision instead of letting the step quietly evaporate. The brief is your only visual reference. Implement directly from it, treating any named anchor references and the brief's "Design Direction" as the contract.
+
+Whether you generated mocks or not: don't replace required imagery with generic cards, bullets, emoji, fake metrics, decorative CSS panels, or filler copy. Image-led briefs (restaurants, hotels, magazines, photography, hobbyist communities, food, travel, fashion, product) need real or sourced imagery in the build, not CSS scenery.
+
+## Step 4: Build to Production Quality
+
+**Precondition.** If Step 3 routed you to codex.md (native image generation available), Steps A through D in that file must be complete before any code: questions answered, palette confirmed, mocks generated, one direction approved or delegated. **Do not mention implementation, file paths, or patch plans until that's done.** A confirmed shape brief is not enough; the model that compressed those gates is the model that already failed this flow.
+
+Implement the feature following the design brief. Build in passes so structure, visual system, states, motion/media, and responsive behavior each get deliberate attention. The list below is the definition of done, not inspiration.
+
+### Production bar
+
+- **Real content.** No placeholder copy, placeholder images, dead links, fake controls, or unused scaffold at presentation time.
+- **Preserve the approved mock's major ingredients.** Missing hero objects, world/product imagery, section structure, CTA/nav treatment, or distinctive motifs are blocking defects unless the user accepted the change.
+- **Semantic first.** Real headings, landmarks, labels, form associations, button/link semantics, accessible names, state announcements where needed.
+- **Deliberate spacing and alignment.** No default gaps, arbitrary margins, unbalanced whitespace, or accidental optical misalignment.
+- **Intentional typography.** Chosen loading strategy, clear hierarchy, readable measure, stable line breaks, no overflow at any width.
+- **Realistic state coverage.** Default, hover, focus-visible, active, disabled, loading, error, success, empty, overflow, long/short text, first-run.
+- **Finished interaction quality.** Keyboard paths, touch targets, feedback timing, scroll behavior, state transitions, no hover-only functionality.
+- **Coherent icon set.** Use the project's established set; otherwise pick one library or use accessible text. Don't mix.
+- **Respect the build pipeline.** Edit source files and run the project's build (`npm run build` or equivalent). Don't write to `build/` / `dist/` / `.next/` with `cat`, heredoc, or Bash redirects; that skips asset hashing, image optimization, code splitting, and CSS extraction, and produces output the dev server won't serve.
+- **Verify image URLs before referencing them.** Use image-search MCP or web-fetch when available; guessed photo IDs ship as broken-image placeholders. Without verification, prefer fewer images you're confident about.
+- **Optimized imagery and media.** Correct dimensions, useful alt text, lazy loading below the fold, modern formats when practical, responsive `srcset`/`picture` for raster, no project-referenced asset left outside the workspace.
+- **Premium motion.** Use atmospheric blur, filter, mask, shadow, reveal when they improve the experience. Avoid casual layout-property animation, bound expensive effects, verify smoothness in-browser, respect reduced motion, and avoid choreography that blocks task completion.
+- **Maintainable.** Reusable local patterns, clear component boundaries, project conventions. No rasterized UI text or one-off hacks when a local pattern exists.
+- **Technically clean.** Production build passes, no console errors, no avoidable layout shift, no needless dependencies, no broken asset paths.
+- **Ask when uncertain.** If a discovery materially changes the brief or approved direction, stop and ask. Don't guess.
+
+## Step 5: Iterate Visually
+
+Look at what you built like a designer would. Your eyes are whatever the harness gives you: a connected browser, a screenshotting tool, Playwright, or asking the user. Use them for responsive testing (mobile, tablet, desktop minimum) and general visual validation.
+
+If your tool returns a file path, read the PNG back into the conversation. A screenshot you didn't read doesn't count.
+
+For long-form brand surfaces, inspect major sections individually. Thumbnails hide spacing, clipping, and cascade defects.
+
+After the first pass, write an honest critique against the brief, the approved mock's major ingredients (hero silhouette, motifs, imagery, nav/CTA, density), and impeccable's DON'Ts. Patch material defects and re-inspect. **Don't invent defects to demonstrate iteration.** A confident "first pass clean, shipping" beats a fake fix.
+
+Actively check: responsive behavior (composes, not shrinks), every state (empty / error / loading / edge), craft details (spacing, alignment, hierarchy, contrast, motion timing, focus), performance basics. The exit bar: defensible in a high-end studio review.
+
+Detector or QA output is defect evidence only; never proof the work is finished.
+
+## Step 6: Present
+
+Present the result to the user:
+- Show the feature in its primary state
+- Summarize the browser/viewports checked and the most important fixes made after inspection
+- Walk through the key states (empty, error, responsive)
+- Explain design decisions that connect back to the design brief and, when used, the chosen north-star mock. Include any accepted deviations from the mock; do not hide unimplemented mock ingredients.
+- Note any remaining limitations or follow-up risks honestly
+- Ask: "What's working? What isn't?"
diff --git a/.github/skills/impeccable/reference/critique.md b/.github/skills/impeccable/reference/critique.md
new file mode 100644
index 0000000..b6ccc00
--- /dev/null
+++ b/.github/skills/impeccable/reference/critique.md
@@ -0,0 +1,780 @@
+### Purpose
+
+Resolve one stable target, run two independent assessments, synthesize a design critique, persist a snapshot, and ask the user what to improve next. The chat response is the primary deliverable; the snapshot is an archive/backlog for future commands.
+
+### Hard Invariants
+
+- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
+- Assessment A and B MUST run as two isolated sub-agents whenever a sub-agent/Task tool is exposed. Running them inline in this context is "possible" but is NOT permitted; it is a degraded run. Inline is allowed ONLY when no sub-agent tool exists (or the user declined, on harnesses that ask).
+- If you degrade for any reason, the report's first line MUST be a banner: `⚠️ DEGRADED: single-context (
)`. A silent degraded critique is a failed critique.
+- Assessment A must finish before detector findings enter the parent synthesis context. Detector output is deterministic, but it still anchors judgment.
+- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
+- Viewable targets require browser inspection when available.
+- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
+- Do not claim a user-visible overlay exists unless script injection succeeded and the detector ran in the page.
+
+### Setup
+
+1. **Resolve the target** to a concrete file path or URL. Prefer a source path over a dev-server URL when both identify the same surface; ports drift, paths do not.
+ - "the homepage" -> `site/pages/index.astro` or `index.html`
+ - "the settings modal" -> the primary component file
+ - "this page" -> the current URL or source file
+2. **Compute the slug**:
+ ```bash
+ node .github/skills/impeccable/scripts/critique-storage.mjs slug ""
+ ```
+ Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique.
+3. **Read `.impeccable/critique/ignore.md`** if it exists. Drop matching findings silently; it is the only prior-run input critique consumes.
+
+### Assessment Orchestration
+
+Delegate Assessment A and Assessment B to separate sub-agents. They must not see each other's output. Do not show findings to the user until synthesis.
+
+Sub-agent gate (all harnesses):
+- Unless a harness-specific gate below overrides this, spawn A and B as two isolated, parallel sub-agents whenever a sub-agent/Task tool is exposed. This is the default and is mandatory; do not run them inline because it is faster.
+- "Unavailable" means exactly one thing: no sub-agent/Task tool is exposed in this session (or, on harnesses that ask, the user declined). It does not mean inconvenient.
+- If and only if sub-agents are unavailable, fall back sequentially: finish and record Assessment A, then run Assessment B, then synthesize, and emit the degraded banner.
+- Whichever path you take, declare it in the report header (see Report header provenance). Skipping sub-agents without the banner is the most common failure of this command.
+
+If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
+
+### Assessment A: Design Review
+
+Read relevant source files and visually inspect the live page when browser automation is available. Think like a design director.
+
+Evaluate:
+- **AI slop**: Would someone believe "AI made this" immediately? Check all DON'T guidance from the parent Impeccable skill.
+- **Holistic design**: hierarchy, IA, emotional fit, discoverability, composition, typography, color, accessibility, states, copy, and edge cases.
+- **Cognitive load**: consult the [Cognitive Load Assessment](#cognitive-load-assessment) section below; report checklist failures and decision points with >4 visible options.
+- **Emotional journey**: peak-end rule, emotional valleys, reassurance at high-stakes moments.
+- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4.
+
+Return: AI slop verdict, heuristic scores, cognitive load, emotional journey, 2-3 strengths, 3-5 priority issues, persona red flags, minor observations, and provocative questions.
+
+### Assessment B: Detector + Browser Evidence
+
+Run the bundled detector and browser visualization evidence. Assessment B is mandatory and must remain isolated from Assessment A until both are complete.
+
+CLI scan:
+```bash
+node .github/skills/impeccable/scripts/detect.mjs --json [target]
+```
+
+- Pass markup files/directories as `[target]`; do not pass CSS-only files.
+- For URLs, skip CLI scan and use browser visualization.
+- For very large trees (500+ scannable files), narrow scope or ask.
+- Exit code 0 = clean; 2 = findings.
+- If the detector entrypoint is missing or fails to load, report deterministic scan unavailable and continue with browser/manual review.
+
+Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
+
+1. Create a fresh tab and navigate. Prefer the harness's native/browser-canvas screenshot path before hand-rolling a Playwright/Puppeteer script; only fall back to a custom script when no native browser tool is exposed.
+2. Preflight mutable injection by setting `document.title` and appending a `
+ * Re-scan: window.impeccableScan()
+ */
+(function () {
+if (typeof window === 'undefined') return;
+// --- cli/engine/shared/constants.mjs ---
+// ─── Section 1: Constants ───────────────────────────────────────────────────
+
+const SAFE_TAGS = new Set([
+ 'blockquote', 'nav', 'a', 'input', 'textarea', 'select',
+ 'pre', 'code', 'span', 'th', 'td', 'tr', 'li', 'label',
+ 'button', 'hr', 'html', 'head', 'body', 'script', 'style',
+ 'link', 'meta', 'title', 'br', 'img', 'svg', 'path', 'circle',
+ 'rect', 'line', 'polyline', 'polygon', 'g', 'defs', 'use',
+]);
+
+// Per-check safe-tags override for the border (side-tab / border-accent)
+// rule. We intentionally re-allow here because card-shaped clickable
+// labels (e.g. .checklist-item wrapping a checkbox + content) are one of the
+// canonical side-tab anti-pattern shapes and must be detected. The rule's
+// other preconditions (non-neutral color, width >= 2px on a single side,
+// radius > 0 or width >= 3, element size >= 20x20 in the browser path)
+// already filter out plain inline form labels so this does not introduce
+// false positives. See modern-color-borders.html for the test matrix.
+const BORDER_SAFE_TAGS = new Set(
+ [...SAFE_TAGS].filter(t => t !== 'label')
+);
+
+const OVERUSED_FONTS = new Set([
+ // Older monoculture (still ubiquitous):
+ 'inter', 'roboto', 'open sans', 'lato', 'montserrat', 'arial', 'helvetica',
+ // Newer monoculture (the Anthropic-skill / Vercel / GitHub default wave):
+ 'fraunces', 'instrument sans', 'instrument serif',
+ 'geist', 'geist sans', 'geist mono',
+ 'mona sans',
+ 'plus jakarta sans', 'space grotesk', 'recoleta',
+]);
+
+// Brand-associated fonts: don't flag these as "overused" on the brand's own domains.
+// Keys are font names, values are arrays of hostname suffixes where the font is allowed.
+const GOOGLE_DOMAINS = [
+ 'google.com', 'youtube.com', 'android.com', 'chromium.org',
+ 'chrome.com', 'web.dev', 'gstatic.com', 'firebase.google.com',
+];
+const VERCEL_DOMAINS = ['vercel.com', 'nextjs.org', 'v0.app'];
+const GITHUB_DOMAINS = ['github.com', 'githubnext.com'];
+const BRAND_FONT_DOMAINS = {
+ 'roboto': GOOGLE_DOMAINS,
+ 'google sans': GOOGLE_DOMAINS,
+ 'product sans': GOOGLE_DOMAINS,
+ 'geist': VERCEL_DOMAINS,
+ 'geist sans': VERCEL_DOMAINS,
+ 'geist mono': VERCEL_DOMAINS,
+ 'mona sans': GITHUB_DOMAINS,
+};
+
+function isBrandFontOnOwnDomain(font) {
+ if (typeof location === 'undefined') return false;
+ const allowed = BRAND_FONT_DOMAINS[font];
+ if (!allowed) return false;
+ const host = location.hostname.toLowerCase();
+ return allowed.some(suffix => host === suffix || host.endsWith('.' + suffix));
+}
+
+const GENERIC_FONTS = new Set([
+ 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
+ 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded',
+ '-apple-system', 'blinkmacsystemfont', 'segoe ui',
+ 'inherit', 'initial', 'unset', 'revert',
+]);
+
+// WCAG large text thresholds are defined in points: 18pt normal text and
+// 14pt bold text. Browsers expose font-size in CSS pixels at 96px per inch.
+const WCAG_LARGE_TEXT_PX = 18 * (96 / 72);
+const WCAG_LARGE_BOLD_TEXT_PX = 14 * (96 / 72);
+
+// Serif faces that show up in italic-display heroes. The rule also fires when
+// the primary face is unknown but the stack ends in the generic `serif` token,
+// which catches custom/private faces with a serif fallback.
+const KNOWN_SERIF_FONTS = new Set([
+ 'fraunces', 'recoleta', 'newsreader', 'playfair display', 'playfair',
+ 'cormorant', 'cormorant garamond', 'garamond', 'eb garamond',
+ 'tiempos', 'tiempos headline', 'tiempos text',
+ 'lora', 'vollkorn', 'spectral',
+ 'source serif pro', 'source serif 4', 'source serif',
+ 'ibm plex serif', 'merriweather',
+ 'libre caslon', 'libre baskerville', 'baskerville',
+ 'georgia', 'times new roman', 'times',
+ 'dm serif display', 'dm serif text',
+ 'instrument serif', 'gt sectra', 'ogg', 'canela',
+ 'freight display', 'freight text',
+]);
+
+// --- cli/engine/registry/antipatterns.mjs ---
+const ANTIPATTERNS = [
+ // ── AI slop: tells that something was AI-generated ──
+ {
+ id: 'side-tab',
+ category: 'slop',
+ name: 'Side-tab accent border',
+ description:
+ 'Thick colored border on one side of a card — the most recognizable tell of AI-generated UIs. Use a subtler accent or remove it entirely.',
+ skillSection: 'Visual Details',
+ skillGuideline: 'colored accent stripe',
+ },
+ {
+ id: 'border-accent-on-rounded',
+ category: 'slop',
+ name: 'Border accent on rounded element',
+ description:
+ 'Thick accent border on a rounded card — the border clashes with the rounded corners. Remove the border or the border-radius.',
+ skillSection: 'Visual Details',
+ skillGuideline: 'colored accent stripe',
+ },
+ {
+ id: 'overused-font',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Overused font',
+ description:
+ 'Inter, Roboto, Fraunces, Geist, Plus Jakarta Sans, and Space Grotesk are used on so many sites they no longer feel distinctive. Each new wave of AI-generated UIs converges on the same handful of faces. Choose a face that gives your interface personality.',
+ skillSection: 'Typography',
+ skillGuideline: 'overused fonts like Inter',
+ },
+ {
+ id: 'single-font',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Single font for everything',
+ description:
+ 'Only one font family is used for the entire page. Pair a distinctive display font with a refined body font to create typographic hierarchy.',
+ skillSection: 'Typography',
+ skillGuideline: 'only one font family for the entire page',
+ },
+ {
+ id: 'flat-type-hierarchy',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Flat type hierarchy',
+ description:
+ 'Font sizes are too close together — no clear visual hierarchy. Use fewer sizes with more contrast (aim for at least a 1.25 ratio between steps).',
+ skillSection: 'Typography',
+ skillGuideline: 'flat type hierarchy',
+ },
+ {
+ id: 'gradient-text',
+ category: 'slop',
+ name: 'Gradient text',
+ description:
+ 'Gradient text is decorative rather than meaningful — a common AI tell, especially on headings and metrics. Use solid colors for text.',
+ skillSection: 'Color & Contrast',
+ skillGuideline: 'gradient text for',
+ },
+ {
+ id: 'ai-color-palette',
+ category: 'slop',
+ name: 'AI color palette',
+ description:
+ 'Purple/violet gradients and cyan-on-dark are the most recognizable tells of AI-generated UIs. Choose a distinctive, intentional palette.',
+ skillSection: 'Color & Contrast',
+ skillGuideline: 'AI color palette',
+ },
+ {
+ id: 'cream-palette',
+ category: 'slop',
+ name: 'Cream / beige palette',
+ description:
+ 'A warm cream or beige page background has become the default "tasteful" AI surface, reached for by reflex. Choose a background that comes from a deliberate palette, not the safe warm off-white.',
+ skillSection: 'Color & Contrast',
+ skillGuideline: 'cream and beige as the default surface',
+ },
+ {
+ id: 'nested-cards',
+ category: 'slop',
+ scopes: ['layout'],
+ name: 'Nested cards',
+ description:
+ 'Cards inside cards create visual noise and excessive depth. Flatten the hierarchy — use spacing, typography, and dividers instead of nesting containers.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'Nest cards inside cards',
+ },
+ {
+ id: 'monotonous-spacing',
+ category: 'slop',
+ scopes: ['layout'],
+ name: 'Monotonous spacing',
+ description:
+ 'The same spacing value used everywhere — no rhythm, no variation. Use tight groupings for related items and generous separations between sections.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'same spacing everywhere',
+ },
+ {
+ id: 'bounce-easing',
+ category: 'slop',
+ name: 'Bounce or elastic easing',
+ description:
+ 'Bounce and elastic easing feel dated and tacky. Real objects decelerate smoothly — use exponential easing (ease-out-quart/quint/expo) instead.',
+ skillSection: 'Motion',
+ skillGuideline: 'bounce or elastic easing',
+ },
+ {
+ id: 'dark-glow',
+ category: 'slop',
+ name: 'Dark mode with glowing accents',
+ description:
+ 'Dark backgrounds with colored box-shadow glows are the default "cool" look of AI-generated UIs. Use subtle, purposeful lighting instead — or skip the dark theme entirely.',
+ skillSection: 'Color & Contrast',
+ skillGuideline: 'dark mode with glowing accents',
+ },
+ {
+ id: 'icon-tile-stack',
+ category: 'slop',
+ scopes: ['layout'],
+ name: 'Icon tile stacked above heading',
+ description:
+ 'A small rounded-square icon container above a heading is the universal AI feature-card template — every generator outputs this exact shape. Try a side-by-side icon and heading, or let the icon sit in flow without its own container.',
+ skillSection: 'Typography',
+ skillGuideline: 'large icons with rounded corners above every heading',
+ },
+ {
+ id: 'italic-serif-display',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Italic serif display headline',
+ description:
+ 'Oversized italic serif (Fraunces, Recoleta, Playfair, Newsreader-italic) as the primary hero headline reads as taste in isolation but has become the universal AI-startup landing page hero. Set roman, or move to a non-serif display face. Editorial / magazine register may legitimately want this — judge by context.',
+ skillSection: 'Typography',
+ skillGuideline: 'oversized italic serif as the hero headline',
+ },
+ {
+ id: 'hero-eyebrow-chip',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Hero eyebrow / pill chip',
+ description:
+ 'A tiny uppercase letter-spaced label sitting immediately above an oversized hero headline — or the same shape rendered as a pill chip — is now the default AI SaaS hero. Drop the eyebrow, integrate the kicker into the headline, or run it as a navigation breadcrumb instead.',
+ skillSection: 'Typography',
+ skillGuideline: 'tiny uppercase tracked label above the hero headline',
+ },
+ {
+ id: 'repeated-section-kickers',
+ category: 'slop',
+ scopes: ['type'],
+ severity: 'advisory',
+ name: 'Repeated section kicker labels',
+ description:
+ 'Repeating tiny uppercase tracked labels above section headings turns a brand page into AI editorial scaffolding. Replace them with stronger structure, artifacts, imagery, or a deliberate brand system.',
+ skillSection: 'Typography',
+ skillGuideline: 'repeated eyebrow or kicker labels as section scaffolding',
+ },
+ {
+ id: 'numbered-section-markers',
+ category: 'slop',
+ scopes: ['layout'],
+ severity: 'advisory',
+ name: 'Numbered section markers (01 / 02 / 03)',
+ description:
+ 'Numbered display markers as section labels (01, 02, 03) are the AI editorial scaffold one tier deeper than tracked eyebrow chips. If you find yourself reaching for them, choose a different section cadence.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'numbered section markers',
+ },
+ {
+ id: 'em-dash-overuse',
+ category: 'slop',
+ name: 'Em-dash overuse',
+ description:
+ 'More than two em-dashes (— or --) in body copy is an AI cadence tell. Use commas, colons, periods, or parentheses instead.',
+ skillSection: 'Copy',
+ skillGuideline: 'no em dashes',
+ },
+ {
+ id: 'marketing-buzzword',
+ category: 'slop',
+ name: 'Marketing buzzword',
+ description:
+ 'Generic SaaS phrases (streamline / empower / supercharge / world-class / enterprise-grade / next-generation / cutting-edge / etc) are instant AI tells. Pick a specific verb and noun that says what the product literally does.',
+ skillSection: 'Copy',
+ skillGuideline: 'marketing buzzwords',
+ },
+ {
+ id: 'aphoristic-cadence',
+ category: 'slop',
+ name: 'Aphoristic-cadence copy',
+ description:
+ 'Three or more sections landing on a short rebuttal sentence ("X. No Y." / "X. Just Y.") or a manufactured-contrast aphorism ("Not a feature. A platform.") reads as AI cadence, not voice. Once is fine; the pattern is the tell.',
+ skillSection: 'Copy',
+ skillGuideline: 'aphoristic cadence',
+ },
+ {
+ id: 'oversized-h1',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Oversized hero headline',
+ description:
+ 'A full-sentence headline set at display size ends up dominating the viewport, leaving no room for anything else above the fold. A punchy one- or two-word headline at that size is fine — the problem is a long headline blown up too large. Set long headlines smaller, or tighten the copy.',
+ skillSection: 'Typography',
+ skillGuideline: 'long headline set at display size',
+ },
+ {
+ id: 'extreme-negative-tracking',
+ category: 'slop',
+ scopes: ['type'],
+ name: 'Crushed letter spacing',
+ description:
+ 'Letter-spacing pulled tighter than the point where characters keep their own shapes costs legibility. Tighten display type optically, not destructively.',
+ skillSection: 'Typography',
+ skillGuideline: 'letter spacing crushed past legibility',
+ },
+ {
+ id: 'broken-image',
+ category: 'quality',
+ name: 'Broken or placeholder image',
+ description:
+ ' tags with empty src, missing src, or placeholder values ship as broken-image boxes. Use real images, generated assets, or remove the tag.',
+ skillSection: 'Imagery',
+ skillGuideline: 'broken image references',
+ },
+
+ // ── Quality: general design and accessibility issues ──
+ {
+ id: 'gray-on-color',
+ category: 'quality',
+ name: 'Gray text on colored background',
+ description:
+ 'Gray text looks washed out on colored backgrounds. Use a darker shade of the background color instead, or white/near-white for contrast.',
+ skillSection: 'Color & Contrast',
+ skillGuideline: 'gray text on colored backgrounds',
+ },
+ {
+ id: 'low-contrast',
+ category: 'quality',
+ name: 'Low contrast text',
+ description:
+ 'Text does not meet WCAG AA contrast requirements (4.5:1 for body, 3:1 for large text). Increase the contrast between text and background.',
+ },
+ {
+ id: 'layout-transition',
+ category: 'quality',
+ name: 'Layout property animation',
+ description:
+ 'Animating width, height, padding, or margin causes layout thrash and janky performance. Use transform and opacity instead, or grid-template-rows for height animations.',
+ skillSection: 'Motion',
+ skillGuideline: 'Animate layout properties',
+ },
+ {
+ id: 'line-length',
+ category: 'quality',
+ scopes: ['type', 'layout'],
+ name: 'Line length too long',
+ description:
+ 'Text lines wider than ~80 characters are hard to read. The eye loses its place tracking back to the start of the next line. Add a max-width (65ch to 75ch) to text containers.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'wrap beyond ~80 characters',
+ },
+ {
+ id: 'cramped-padding',
+ category: 'quality',
+ scopes: ['layout'],
+ name: 'Cramped padding',
+ description:
+ 'Text is too close to the edge of its container. Two shapes: (1) an element with its own text where the padding is too low for the font size, and (2) a wrapper with text-bearing children and near-zero padding against a visible boundary (border, outline, or non-transparent background) — children land flush against the boundary line. Add at least 8px (ideally 12–16px) of padding inside bordered, outlined, or colored containers.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'inside bordered or colored containers',
+ },
+ {
+ id: 'body-text-viewport-edge',
+ category: 'quality',
+ scopes: ['layout'],
+ name: 'Body text touching viewport edge',
+ description:
+ 'Body paragraphs render flush against the left or right viewport edge with no container providing horizontal padding. Wrap content in a container with at least 16px (ideally 24-32px) of horizontal padding, or apply max-width with mx-auto.',
+ },
+ {
+ id: 'tight-leading',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'Tight line height',
+ description:
+ 'Line height below 1.3x the font size makes multi-line text hard to read. Use 1.5 to 1.7 for body text so lines have room to breathe.',
+ },
+ {
+ id: 'skipped-heading',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'Skipped heading level',
+ description:
+ 'Heading levels should not skip (e.g. h1 then h3 with no h2). Screen readers use heading hierarchy for navigation. Skipping levels breaks the document outline.',
+ },
+ {
+ id: 'justified-text',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'Justified text',
+ description:
+ 'Justified text without hyphenation creates uneven word spacing ("rivers of white"). Use text-align: left for body text, or enable hyphens: auto if you must justify.',
+ },
+ {
+ id: 'tiny-text',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'Tiny body text',
+ description:
+ 'Body text below 12px is hard to read, especially on high-DPI screens. Use at least 14px for body content, 16px is ideal.',
+ },
+ {
+ id: 'all-caps-body',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'All-caps body text',
+ description:
+ 'Long passages in uppercase are hard to read. We recognize words by shape (ascenders and descenders), which all-caps removes. Reserve uppercase for short labels and headings.',
+ skillSection: 'Typography',
+ skillGuideline: 'long body passages in uppercase',
+ },
+ {
+ id: 'wide-tracking',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'Wide letter spacing on body text',
+ description:
+ 'Letter spacing above 0.05em on body text disrupts natural character groupings and slows reading. Reserve wide tracking for short uppercase labels only.',
+ },
+ {
+ id: 'text-overflow',
+ category: 'quality',
+ scopes: ['layout'],
+ name: 'Content overflowing its container',
+ description:
+ 'Content renders wider than its container, spilling out or forcing a horizontal scrollbar. Let text wrap, constrain widths, or give the region a deliberate scroll affordance.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'content wider than its container',
+ },
+ {
+ id: 'clipped-overflow-container',
+ category: 'quality',
+ scopes: ['layout'],
+ name: 'Positioned child clipped by overflow container',
+ description:
+ 'A clipping container (overflow hidden or clip) wrapping an absolutely-positioned child cuts off tooltips, menus, and popovers that need to escape. Let the overflow be visible, or move the positioned layer out of the clip.',
+ skillSection: 'Layout & Space',
+ skillGuideline: 'overflow container clipping positioned children',
+ },
+ {
+ id: 'design-system-font',
+ category: 'quality',
+ scopes: ['type'],
+ name: 'Font outside DESIGN.md',
+ description:
+ 'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
+ skillSection: 'Typography',
+ skillGuideline: 'font family outside the project design system',
+ },
+ {
+ id: 'design-system-color',
+ category: 'quality',
+ severity: 'advisory',
+ name: 'Color outside DESIGN.md',
+ description:
+ 'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
+ skillSection: 'Color & Contrast',
+ skillGuideline: 'literal color outside the project design system',
+ },
+ {
+ id: 'design-system-radius',
+ category: 'quality',
+ severity: 'advisory',
+ name: 'Radius outside DESIGN.md',
+ description:
+ 'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
+ skillSection: 'Visual Details',
+ skillGuideline: 'border radius outside the project design system',
+ },
+ {
+ id: 'design-system-font-size',
+ category: 'quality',
+ severity: 'advisory',
+ scopes: ['type'],
+ name: 'Font size outside DESIGN.md',
+ description:
+ 'A literal font-size is off the type ramp documented in DESIGN.md typography. Use a documented size step or update the design system if the new step is intentional.',
+ skillSection: 'Typography',
+ skillGuideline: 'font size outside the project design system',
+ },
+
+ // ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
+ {
+ id: 'gpt-thin-border-wide-shadow',
+ category: 'slop',
+ severity: 'advisory',
+ gated: 'gpt',
+ name: 'Hairline border with wide shadow',
+ description:
+ 'A hairline border paired with a wide, diffuse shadow is a recurring generated-UI signature. Commit to one — a defined edge or a soft elevation — rather than both at once.',
+ skillSection: 'Visual Details',
+ skillGuideline: 'hairline border plus wide diffuse shadow',
+ },
+ {
+ id: 'repeating-stripes-gradient',
+ category: 'slop',
+ severity: 'advisory',
+ gated: 'gpt',
+ name: 'Repeating-gradient stripes',
+ description:
+ 'Repeating-gradient stripes used as surface decoration are a recurring generated-UI signature. Reach for a deliberate texture or leave the surface plain.',
+ skillSection: 'Visual Details',
+ skillGuideline: 'repeating-gradient decorative stripes',
+ },
+ {
+ id: 'codex-grid-background',
+ category: 'slop',
+ severity: 'advisory',
+ gated: 'gpt',
+ name: 'Decorative grid-line background',
+ description:
+ 'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
+ skillSection: 'Visual Details',
+ skillGuideline: 'two-axis grid-line gradient background',
+ },
+ {
+ id: 'theater-slop-phrase',
+ category: 'slop',
+ severity: 'advisory',
+ gated: 'gpt',
+ name: 'Theater framing copy',
+ description:
+ 'Dismissing something as "theater" is a recurring generated-copy tic. Say plainly what the thing does or does not do.',
+ skillSection: 'Copy',
+ skillGuideline: 'theater framing copy',
+ },
+ {
+ id: 'image-hover-transform',
+ category: 'slop',
+ severity: 'advisory',
+ gated: 'gemini',
+ name: 'Image hover transform',
+ description:
+ 'Scaling or rotating an image on hover is a recurring generated-UI signature. Let imagery sit still, or use a subtler, purposeful interaction.',
+ skillSection: 'Motion',
+ skillGuideline: 'image scale or rotate on hover',
+ },
+];
+
+// --- cli/engine/shared/color.mjs ---
+// ─── Section 2: Color Utilities ─────────────────────────────────────────────
+
+function isNeutralColor(color) {
+ if (!color || color === 'transparent') return true;
+
+ // rgb/rgba — use channel spread. Threshold 30 ≈ 11.7% of the 0–255 range.
+ const rgb = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
+ if (rgb) {
+ return (Math.max(+rgb[1], +rgb[2], +rgb[3]) - Math.min(+rgb[1], +rgb[2], +rgb[3])) < 30;
+ }
+
+ // oklch()/lch() — chroma is the second numeric component.
+ // oklch chroma is ~0–0.4 in sRGB gamut; >= 0.02 reads as tinted, not gray.
+ // lch chroma is ~0–150; >= 3 reads as tinted. jsdom emits both formats
+ // literally (it does NOT convert them to rgb).
+ const oklch = color.match(/oklch\(\s*[\d.]+%?\s*([\d.-]+)/i);
+ if (oklch) return parseFloat(oklch[1]) < 0.02;
+ const lch = color.match(/lch\(\s*[\d.]+%?\s*([\d.-]+)/i);
+ if (lch) return parseFloat(lch[1]) < 3;
+
+ // oklab()/lab() — a and b are signed axes; chroma = sqrt(a² + b²).
+ // oklab a/b are ~-0.4..0.4, threshold 0.02. lab a/b are ~-128..127, threshold 3.
+ const oklab = color.match(/oklab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
+ if (oklab) {
+ const a = parseFloat(oklab[1]), b = parseFloat(oklab[2]);
+ return Math.hypot(a, b) < 0.02;
+ }
+ const lab = color.match(/lab\(\s*[\d.]+%?\s*([\d.-]+)\s+([\d.-]+)/i);
+ if (lab) {
+ const a = parseFloat(lab[1]), b = parseFloat(lab[2]);
+ return Math.hypot(a, b) < 3;
+ }
+
+ // hsl/hsla — saturation is the second numeric component (percent).
+ // Modern jsdom usually converts hsl() to rgb, but handle it directly for
+ // safety across versions and for any engine that preserves the format.
+ const hsl = color.match(/hsla?\(\s*[\d.-]+\s*,?\s*([\d.]+)%/i);
+ if (hsl) return parseFloat(hsl[1]) < 10;
+
+ // hwb(hue whiteness% blackness%) — a pixel is fully gray when
+ // whiteness + blackness >= 100; chroma-like saturation = 1 - (w+b)/100.
+ const hwb = color.match(/hwb\(\s*[\d.-]+\s+([\d.]+)%\s+([\d.]+)%/i);
+ if (hwb) {
+ const w = parseFloat(hwb[1]), b = parseFloat(hwb[2]);
+ return (1 - Math.min(100, w + b) / 100) < 0.1;
+ }
+
+ // Unknown / unrecognized format — err on the side of DETECTING rather
+ // than silently skipping. This is the opposite of the previous default,
+ // which was the root cause of the oklch bug.
+ return false;
+}
+
+function parseRgb(color) {
+ if (!color || color === 'transparent') return null;
+ const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);
+ if (!m) return null;
+ return { r: +m[1], g: +m[2], b: +m[3], a: m[4] !== undefined ? +m[4] : 1 };
+}
+
+function relativeLuminance({ r, g, b }) {
+ const [rs, gs, bs] = [r / 255, g / 255, b / 255].map(c =>
+ c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
+ );
+ return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
+}
+
+function contrastRatio(c1, c2) {
+ const l1 = relativeLuminance(c1);
+ const l2 = relativeLuminance(c2);
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
+}
+
+function parseGradientColors(bgImage) {
+ if (!bgImage || !bgImage.includes('gradient')) return [];
+ const colors = [];
+ for (const m of bgImage.matchAll(/rgba?\([^)]+\)/g)) {
+ const c = parseRgb(m[0]);
+ if (c) colors.push(c);
+ }
+ for (const m of bgImage.matchAll(/#([0-9a-f]{6}|[0-9a-f]{3})\b/gi)) {
+ const h = m[1];
+ if (h.length === 6) {
+ colors.push({ r: parseInt(h.slice(0,2),16), g: parseInt(h.slice(2,4),16), b: parseInt(h.slice(4,6),16), a: 1 });
+ } else {
+ colors.push({ r: parseInt(h[0]+h[0],16), g: parseInt(h[1]+h[1],16), b: parseInt(h[2]+h[2],16), a: 1 });
+ }
+ }
+ return colors;
+}
+
+function hasChroma(c, threshold = 30) {
+ if (!c) return false;
+ return (Math.max(c.r, c.g, c.b) - Math.min(c.r, c.g, c.b)) >= threshold;
+}
+
+function getHue(c) {
+ if (!c) return 0;
+ const r = c.r / 255, g = c.g / 255, b = c.b / 255;
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
+ if (max === min) return 0;
+ const d = max - min;
+ let h;
+ if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
+ else if (max === g) h = ((b - r) / d + 2) / 6;
+ else h = ((r - g) / d + 4) / 6;
+ return Math.round(h * 360);
+}
+
+function colorToHex(c) {
+ if (!c) return '?';
+ return '#' + [c.r, c.g, c.b].map(v => v.toString(16).padStart(2, '0')).join('');
+}
+
+// --- cli/engine/shared/fonts.mjs ---
+const GOOGLE_FONTS_URL_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
+
+function normalizeGoogleFontFamilyParam(value) {
+ return String(value || '')
+ .split('|')
+ .map(part => part.split(':')[0].trim().toLowerCase())
+ .filter(Boolean);
+}
+
+function extractGoogleFontFamilies(text) {
+ const families = [];
+ if (!text) return families;
+
+ GOOGLE_FONTS_URL_RE.lastIndex = 0;
+ let urlMatch;
+ while ((urlMatch = GOOGLE_FONTS_URL_RE.exec(text)) !== null) {
+ const url = urlMatch[0];
+ const queryStart = url.indexOf('?');
+ if (queryStart === -1) continue;
+
+ const params = new URLSearchParams(url.slice(queryStart + 1).replace(/&/g, '&'));
+ for (const value of params.getAll('family')) {
+ families.push(...normalizeGoogleFontFamilyParam(value));
+ }
+ }
+
+ return families;
+}
+
+// --- cli/engine/rules/checks.mjs ---
+const DETECTOR_IS_BROWSER = typeof window !== 'undefined';
+
+// ─── Section 3: Pure Detection ──────────────────────────────────────────────
+
+function checkBorders(tag, widths, colors, radius) {
+ if (BORDER_SAFE_TAGS.has(tag)) return [];
+ const findings = [];
+ const sides = ['Top', 'Right', 'Bottom', 'Left'];
+
+ for (const side of sides) {
+ const w = widths[side];
+ if (w < 1 || isNeutralColor(colors[side])) continue;
+
+ const otherSides = sides.filter(s => s !== side);
+ const maxOther = Math.max(...otherSides.map(s => widths[s]));
+ if (!(w >= 2 && (maxOther <= 1 || w >= maxOther * 2))) continue;
+
+ const sn = side.toLowerCase();
+ const isSide = side === 'Left' || side === 'Right';
+
+ if (isSide) {
+ if (radius > 0) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
+ else if (w >= 3) findings.push({ id: 'side-tab', snippet: `border-${sn}: ${w}px` });
+ } else {
+ if (radius > 0 && w >= 2) findings.push({ id: 'border-accent-on-rounded', snippet: `border-${sn}: ${w}px + border-radius: ${radius}px` });
+ }
+ }
+
+ return findings;
+}
+
+// Returns true if the given text is composed entirely of emoji characters
+// (plus whitespace / variation selectors). Emojis render as multicolor glyphs
+// regardless of CSS `color`, so contrast checks against the element's text
+// color are meaningless for these nodes.
+const EMOJI_CHAR_RE = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/u;
+const EMOJI_CHARS_GLOBAL = /[\u{1F1E6}-\u{1F1FF}\u{1F300}-\u{1F9FF}\u{1FA00}-\u{1FAFF}\u{2600}-\u{27BF}\u{2300}-\u{23FF}\u{FE0F}\u{200D}\u{1F3FB}-\u{1F3FF}]/gu;
+function isEmojiOnlyText(text) {
+ if (!text) return false;
+ if (!EMOJI_CHAR_RE.test(text)) return false;
+ return text.replace(EMOJI_CHARS_GLOBAL, '').trim() === '';
+}
+
+function checkColors(opts) {
+ const { tag, textColor, bgColor, effectiveBg, effectiveBgStops, fontSize, fontWeight, hasDirectText, isEmojiOnly, bgClip, bgImage, classList } = opts;
+ if (SAFE_TAGS.has(tag)) {
+ // Exception for and elements styled as buttons. SAFE_TAGS
+ // exists to suppress contrast noise on inline links and unstyled controls,
+ // where the element has no own background and the contrast against the
+ // ancestor surface is already the intended visual. When the element has
+ // its own opaque background and direct text, it is a styled button — and
+ // contrast on its own surface is a real, frequent bug worth flagging.
+ const isStyledButton = (tag === 'a' || tag === 'button')
+ && hasDirectText
+ && bgColor && bgColor.a > 0.5;
+ if (!isStyledButton) return [];
+ }
+ const findings = [];
+
+ if (hasDirectText && textColor && !isEmojiOnly) {
+ // Run background-dependent checks against either a solid bg or, if the
+ // ancestor is a gradient, against every gradient stop (use the worst case).
+ const bgs = effectiveBg ? [effectiveBg] : (effectiveBgStops && effectiveBgStops.length ? effectiveBgStops : null);
+ if (bgs) {
+ // Gray on colored background — flag if every stop is chromatic
+ const textLum = relativeLuminance(textColor);
+ const isGray = !hasChroma(textColor, 20) && textLum > 0.05 && textLum < 0.85;
+ if (isGray && bgs.every(b => hasChroma(b, 40))) {
+ const bgLabel = effectiveBg ? colorToHex(effectiveBg) : `gradient(${bgs.map(colorToHex).join(', ')})`;
+ findings.push({ id: 'gray-on-color', snippet: `text ${colorToHex(textColor)} on bg ${bgLabel}` });
+ }
+
+ // Low contrast (WCAG AA) — worst case across all bg stops
+ const ratios = bgs.map(b => contrastRatio(textColor, b));
+ let worstIdx = 0;
+ for (let i = 1; i < ratios.length; i++) if (ratios[i] < ratios[worstIdx]) worstIdx = i;
+ const ratio = ratios[worstIdx];
+ const isLargeText = fontSize >= WCAG_LARGE_TEXT_PX || (fontSize >= WCAG_LARGE_BOLD_TEXT_PX && fontWeight >= 700);
+ const threshold = isLargeText ? 3.0 : 4.5;
+ if (ratio < threshold) {
+ // Skip the false-positive class where text has alpha < 1 AND we
+ // couldn't find an opaque ancestor (effectiveBg is null, we're
+ // comparing against gradient-stop fallback). In jsdom mode the
+ // detector can't resolve `var(--X)` color tokens, so a dark
+ // section sitting between the text and the body's decorative
+ // gradient is invisible to us — we end up measuring contrast
+ // against the body's paper-grain noise instead of the real
+ // local bg. Real low-contrast bugs use alpha=1 and have a
+ // resolvable opaque ancestor; semi-transparent Tailwind tokens
+ // like `text-paper/60` on `bg-ink` sections are the FP pattern.
+ const isAlphaFallbackFP = !DETECTOR_IS_BROWSER && !effectiveBg && (textColor.a != null && textColor.a < 1);
+ if (!isAlphaFallbackFP) {
+ findings.push({ id: 'low-contrast', snippet: `${ratio.toFixed(1)}:1 (need ${threshold}:1) — text ${colorToHex(textColor)} on ${colorToHex(bgs[worstIdx])}` });
+ }
+ }
+ }
+
+ // AI palette: purple/violet on headings
+ if (hasChroma(textColor, 50)) {
+ const hue = getHue(textColor);
+ if (hue >= 260 && hue <= 310 && (['h1', 'h2', 'h3'].includes(tag) || fontSize >= 20)) {
+ findings.push({ id: 'ai-color-palette', snippet: `Purple/violet text (${colorToHex(textColor)}) on heading` });
+ }
+ }
+ }
+
+ // Gradient text
+ if (bgClip === 'text' && bgImage && bgImage.includes('gradient')) {
+ findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
+ }
+
+ // Tailwind class checks
+ if (classList) {
+ const classStr = typeof classList === 'string' ? classList : Array.from(classList).join(' ');
+
+ const grayMatch = classStr.match(/\btext-(?:gray|slate|zinc|neutral|stone)-\d+\b/);
+ const colorBgMatch = classStr.match(/\bbg-(?:red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-\d+\b/);
+ if (grayMatch && colorBgMatch) {
+ findings.push({ id: 'gray-on-color', snippet: `${grayMatch[0]} on ${colorBgMatch[0]}` });
+ }
+
+ if (/\bbg-clip-text\b/.test(classStr) && /\bbg-gradient-to-/.test(classStr)) {
+ findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
+ }
+
+ const purpleText = classStr.match(/\btext-(?:purple|violet|indigo)-\d+\b/);
+ if (purpleText && (['h1', 'h2', 'h3'].includes(tag) || /\btext-(?:[2-9]xl)\b/.test(classStr))) {
+ findings.push({ id: 'ai-color-palette', snippet: `${purpleText[0]} on heading` });
+ }
+
+ if (/\bfrom-(?:purple|violet|indigo)-\d+\b/.test(classStr) && /\bto-(?:purple|violet|indigo|blue|cyan|pink|fuchsia)-\d+\b/.test(classStr)) {
+ findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet gradient (Tailwind)' });
+ }
+ }
+
+ return findings;
+}
+
+function isCardLikeFromProps(hasShadow, hasBorder, hasRadius, hasBg) {
+ if (!hasShadow && !hasBorder) return false;
+ return hasRadius || hasBg;
+}
+
+const HEADING_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
+
+// Pure check: given a heading and metrics about its previousElementSibling,
+// decide if the sibling is the canonical "icon-tile-stacked-above-heading" shape.
+//
+// Triggers when ALL of the following hold for the sibling:
+// • size 32–128px on both axes (not too small, not a hero image)
+// • aspect ratio 0.7–1.4 (squarish — excludes wide thumbnails / pill badges)
+// • has a non-transparent background-color, background-image, OR a visible border
+// (covers solid colors, white-with-border, gradients — anything that visually
+// defines a tile)
+// • border-radius < width/2 (excludes round avatars; rounded squares pass)
+// • contains an or icon-class element that's smaller than the tile
+// • the tile sits above the heading (its bottom is above the heading's top)
+function checkIconTile(opts) {
+ const { headingTag, headingText, headingTop,
+ siblingTag, siblingWidth, siblingHeight, siblingBottom,
+ siblingBgColor, siblingBgImage, siblingBorderWidth, siblingBorderRadius,
+ hasIconChild, iconChildWidth } = opts;
+ if (!HEADING_TAGS.has(headingTag)) return [];
+ if (!siblingTag) return [];
+ // Don't recurse into nested headings (e.g. h2 above h3 in a section header)
+ if (HEADING_TAGS.has(siblingTag)) return [];
+
+ // Size window: 32–128px on each axis
+ if (!(siblingWidth >= 32 && siblingWidth <= 128)) return [];
+ if (!(siblingHeight >= 32 && siblingHeight <= 128)) return [];
+
+ // Squarish aspect ratio
+ const ratio = siblingWidth / siblingHeight;
+ if (ratio < 0.7 || ratio > 1.4) return [];
+
+ // Must have something that visually defines the tile
+ const bgVisible = (siblingBgColor && siblingBgColor.a > 0.1)
+ || (siblingBgImage && siblingBgImage !== 'none' && siblingBgImage !== '');
+ const borderVisible = siblingBorderWidth > 0;
+ if (!bgVisible && !borderVisible) return [];
+
+ // Exclude circles (avatars). Rounded squares pass.
+ if (siblingBorderRadius >= siblingWidth / 2) return [];
+
+ // Must contain an icon element smaller than the tile
+ if (!hasIconChild) return [];
+ if (iconChildWidth && iconChildWidth >= siblingWidth * 0.95) return [];
+
+ // Vertical stacking: tile must end above where the heading starts.
+ // (Allow the check to skip when both top/bottom are 0 — jsdom layout case.)
+ if (headingTop && siblingBottom && siblingBottom > headingTop + 4) return [];
+
+ const text = (headingText || '').trim().slice(0, 60);
+ return [{
+ id: 'icon-tile-stack',
+ snippet: `${Math.round(siblingWidth)}x${Math.round(siblingHeight)}px icon tile above ${headingTag} "${text}"`,
+ }];
+}
+
+// Resolve the primary (non-generic) face from a font-family string and return
+// whether the resolved primary is serif. Two paths:
+// 1. Primary face is in KNOWN_SERIF_FONTS → serif.
+// 2. Primary face is unknown but the stack ends in the generic `serif`
+// token → treat as serif. Authors who declare `font-family: 'X', serif`
+// almost always have a serif primary; a sans declared with a serif
+// fallback is a code smell, not the common case.
+// Returns { primary, isSerif } so the snippet can name the face.
+function resolveSerif(fontFamily) {
+ if (!fontFamily) return { primary: null, isSerif: false };
+ const tokens = fontFamily.split(',').map(f => f.trim().replace(/^['"]|['"]$/g, '').toLowerCase());
+ const primary = tokens.find(f => f && !GENERIC_FONTS.has(f)) || null;
+ if (!primary) return { primary: null, isSerif: false };
+ if (KNOWN_SERIF_FONTS.has(primary)) return { primary, isSerif: true };
+ if (tokens.includes('serif')) return { primary, isSerif: true };
+ return { primary, isSerif: false };
+}
+
+function checkItalicSerif(opts) {
+ const { tag, fontStyle, fontFamily, fontSize, headingText } = opts;
+ if (fontStyle !== 'italic') return [];
+ // Anchor the rule on hero-scale text. h1 is the canonical hero element;
+ // h2 ≥ 48px catches the cases where the design demotes the visual hero
+ // to an h2 but keeps the size.
+ if (tag !== 'h1' && !(tag === 'h2' && fontSize >= 48)) return [];
+ if (fontSize < 48) return [];
+ const { primary, isSerif } = resolveSerif(fontFamily);
+ if (!isSerif) return [];
+
+ const text = (headingText || '').trim().slice(0, 60);
+ return [{
+ id: 'italic-serif-display',
+ snippet: `italic serif ${tag} (${primary || 'serif'}) at ${Math.round(fontSize)}px "${text}"`,
+ }];
+}
+
+// Color saturation check. Returns true when the color has visible
+// chroma — i.e., it's an "accent color" rather than near-neutral.
+// Handles rgb()/rgba(), #hex, oklch(), and hsl(). var() refs are
+// expected to be pre-resolved by the caller.
+function isAccentColor(cssColor) {
+ if (!cssColor) return false;
+ const s = String(cssColor).trim();
+ // rgb / rgba — direct channel-distance check.
+ const rgbM = /rgba?\(\s*(\d+)\s*,?\s+|\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s.replace(/rgba?\(\s*/, 'rgb(').replace(/,/g, ', '));
+ const rgbStrict = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(s);
+ if (rgbStrict) {
+ const r = +rgbStrict[1], g = +rgbStrict[2], b = +rgbStrict[3];
+ return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
+ }
+ // #hex — 3, 4, 6, or 8 digit.
+ const hexM = /^#([0-9a-f]{3,8})\b/i.exec(s);
+ if (hexM) {
+ let h = hexM[1];
+ if (h.length === 3 || h.length === 4) h = h.split('').map((c) => c + c).join('').slice(0, 6);
+ else h = h.slice(0, 6);
+ if (h.length === 6) {
+ const r = parseInt(h.slice(0, 2), 16);
+ const g = parseInt(h.slice(2, 4), 16);
+ const b = parseInt(h.slice(4, 6), 16);
+ return (Math.max(r, g, b) - Math.min(r, g, b)) >= 40;
+ }
+ }
+ // oklch(L C H) — chroma C is what matters. Typical neutral grays
+ // have C < 0.02; visible accents are 0.05+. CSS minification can
+ // collapse spaces between L% and C ("oklch(43%.15 34)"), so we
+ // extract all numbers and take the second rather than matching a
+ // strict L-then-whitespace-then-C pattern.
+ if (/^oklch\(/i.test(s)) {
+ const nums = s.match(/\d*\.\d+|\d+/g);
+ if (nums && nums.length >= 2) {
+ const c = parseFloat(nums[1]);
+ return !Number.isNaN(c) && c >= 0.05;
+ }
+ }
+ // hsl(H, S%, L%) — saturation > 20% reads as accent.
+ const hslM = /hsla?\(\s*[\d.]+\s*,\s*([\d.]+)%/i.exec(s);
+ if (hslM) {
+ const sat = parseFloat(hslM[1]);
+ return !Number.isNaN(sat) && sat >= 20;
+ }
+ return false;
+}
+
+// Sibling-relationship rule. Anchor on a hero-scale h1, look at the
+// previousElementSibling, and gate on EITHER the classic tracked-
+// uppercase eyebrow OR the modern accent-colored bold eyebrow.
+function checkHeroEyebrow(opts) {
+ const {
+ headingTag, headingText, headingFontSize,
+ siblingTag, siblingText, siblingTextTransform,
+ siblingFontSize, siblingLetterSpacing,
+ siblingFontWeight, siblingColor,
+ } = opts;
+ if (headingTag !== 'h1') return [];
+ // We previously gated on headingFontSize >= 48 to anchor "hero scale".
+ // But modern hero h1s use clamp() / vw / var(--text-*), none of which
+ // jsdom can resolve — the computed value comes back as "2em" or
+ // "var(--text-9xl)" and parseFloat returns 2 or NaN. The gate fails
+ // on virtually every Tailwind v4 / framework build. The other gates
+ // (sibling text 2-60 chars, font-size ≤ 14px, accent-bold OR
+ // tracked-caps) are tight enough to avoid false positives on non-
+ // hero h1s — a tiny tan label directly above any h1 is the
+ // antipattern regardless of how big the h1 ends up.
+ if (!siblingTag) return [];
+ // An h2 above an h1 is a different anti-pattern (heading hierarchy / dual
+ // headings) — never an eyebrow.
+ if (HEADING_TAGS.has(siblingTag)) return [];
+
+ const text = (siblingText || '').trim();
+ if (text.length < 2 || text.length > 60) return [];
+ if (!(siblingFontSize > 0 && siblingFontSize <= 14)) return [];
+
+ // Branch A: classic tracked-uppercase eyebrow.
+ const isUppercased = siblingTextTransform === 'uppercase'
+ || (/[A-Z]/.test(text) && !/[a-z]/.test(text));
+ const isClassicTracked = isUppercased && siblingLetterSpacing >= 1.6;
+
+ // Branch B: modern accent-bold eyebrow — sentence case, low
+ // tracking, but bold + accent-colored. The style choices changed;
+ // the pattern is the same kicker-above-headline anti-pattern.
+ const weight = Number(siblingFontWeight) || 400;
+ const isAccentBold = weight >= 700 && isAccentColor(siblingColor || '');
+
+ if (!isClassicTracked && !isAccentBold) return [];
+
+ const headingTextSnippet = (headingText || '').trim().slice(0, 60);
+ const eyebrowSnippet = text.slice(0, 40);
+ const style = isClassicTracked ? 'tracked-caps' : 'accent-bold';
+ return [{
+ id: 'hero-eyebrow-chip',
+ snippet: `eyebrow chip (${style}) "${eyebrowSnippet}" above ${headingTag} "${headingTextSnippet}"`,
+ }];
+}
+
+function checkRepeatedSectionKickers(opts) {
+ const { candidates, minCount = 3 } = opts;
+ if (!Array.isArray(candidates) || candidates.length < minCount) return [];
+ return candidates.map(candidate => ({
+ id: 'repeated-section-kickers',
+ snippet: `repeated section kicker "${candidate.kickerText}" before ${candidate.headingTag} "${candidate.headingText}" (${candidates.length} on page)`,
+ }));
+}
+
+const LAYOUT_TRANSITION_PROPS = new Set([
+ 'width', 'height', 'padding', 'margin',
+ 'max-height', 'max-width', 'min-height', 'min-width',
+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
+ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
+]);
+
+function checkMotion(opts) {
+ const { tag, transitionProperty, animationName, timingFunctions, classList } = opts;
+ if (SAFE_TAGS.has(tag)) return [];
+ const findings = [];
+
+ // --- Bounce/elastic easing ---
+ if (animationName && animationName !== 'none' && /bounce|elastic|wobble|jiggle|spring/i.test(animationName)) {
+ findings.push({ id: 'bounce-easing', snippet: `animation: ${animationName}` });
+ }
+ if (classList && /\banimate-bounce\b/.test(classList)) {
+ findings.push({ id: 'bounce-easing', snippet: 'animate-bounce (Tailwind)' });
+ }
+
+ // Check timing functions for overshoot cubic-bezier (y values outside [0, 1])
+ if (timingFunctions) {
+ const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
+ let m;
+ while ((m = bezierRe.exec(timingFunctions)) !== null) {
+ const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
+ if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
+ findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${m[1]}, ${m[2]}, ${m[3]}, ${m[4]})` });
+ break;
+ }
+ }
+ }
+
+ // --- Layout property transition ---
+ if (transitionProperty && transitionProperty !== 'all' && transitionProperty !== 'none') {
+ const props = transitionProperty.split(',').map(p => p.trim().toLowerCase());
+ const layoutFound = props.filter(p => LAYOUT_TRANSITION_PROPS.has(p));
+ if (layoutFound.length > 0) {
+ findings.push({ id: 'layout-transition', snippet: `transition: ${layoutFound.join(', ')}` });
+ }
+ }
+
+ return findings;
+}
+
+function checkGlow(opts) {
+ const { boxShadow, effectiveBg } = opts;
+ if (!boxShadow || boxShadow === 'none') return [];
+ if (!effectiveBg) return [];
+
+ // Only flag on dark backgrounds (luminance < 0.1)
+ const bgLum = relativeLuminance(effectiveBg);
+ if (bgLum >= 0.1) return [];
+
+ // Split multiple shadows (commas not inside parentheses)
+ const parts = boxShadow.split(/,(?![^(]*\))/);
+ for (const shadow of parts) {
+ const colorMatch = shadow.match(/rgba?\([^)]+\)/);
+ if (!colorMatch) continue;
+ const color = parseRgb(colorMatch[0]);
+ if (!color || !hasChroma(color, 30)) continue;
+
+ // Extract px values — in computed style: "color Xpx Ypx BLURpx [SPREADpx]"
+ const afterColor = shadow.substring(shadow.indexOf(colorMatch[0]) + colorMatch[0].length);
+ const beforeColor = shadow.substring(0, shadow.indexOf(colorMatch[0]));
+ const pxVals = [...beforeColor.matchAll(/([\d.]+)px/g), ...afterColor.matchAll(/([\d.]+)px/g)]
+ .map(m => parseFloat(m[1]));
+
+ // Third value is blur (offset-x, offset-y, blur, [spread])
+ if (pxVals.length >= 3 && pxVals[2] > 4) {
+ return [{ id: 'dark-glow', snippet: `Colored glow (${colorToHex(color)}) on dark background` }];
+ }
+ }
+
+ return [];
+}
+
+/**
+ * Regex-on-HTML checks shared between browser and Node page-level detection.
+ * These don't need DOM access, just the raw HTML string.
+ */
+function checkHtmlPatterns(html) {
+ const findings = [];
+
+ // --- Color ---
+
+ // AI color palette: purple/violet
+ const purpleHexRe = /#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9|6366f1|764ba2|667eea)\b/gi;
+ if (purpleHexRe.test(html)) {
+ const purpleTextRe = /(?:(?:^|;)\s*color\s*:\s*(?:.*?)(?:#(?:7c3aed|8b5cf6|a855f7|9333ea|7e22ce|6d28d9))|gradient.*?#(?:7c3aed|8b5cf6|a855f7|764ba2|667eea))/gi;
+ if (purpleTextRe.test(html)) {
+ findings.push({ id: 'ai-color-palette', snippet: 'Purple/violet accent colors detected' });
+ }
+ }
+
+ // Gradient text (background-clip: text + gradient)
+ const gradientRe = /(?:-webkit-)?background-clip\s*:\s*text/gi;
+ let gm;
+ while ((gm = gradientRe.exec(html)) !== null) {
+ const start = Math.max(0, gm.index - 200);
+ const context = html.substring(start, gm.index + gm[0].length + 200);
+ if (/gradient/i.test(context)) {
+ findings.push({ id: 'gradient-text', snippet: 'background-clip: text + gradient' });
+ break;
+ }
+ }
+ if (/\bbg-clip-text\b/.test(html) && /\bbg-gradient-to-/.test(html)) {
+ findings.push({ id: 'gradient-text', snippet: 'bg-clip-text + bg-gradient (Tailwind)' });
+ }
+
+ // --- Layout ---
+
+ // Monotonous spacing
+ const spacingValues = [];
+ const spacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*(\d+)px/gi;
+ let sm;
+ while ((sm = spacingRe.exec(html)) !== null) {
+ const v = parseInt(sm[1], 10);
+ if (v > 0 && v < 200) spacingValues.push(v);
+ }
+ const gapRe = /gap\s*:\s*(\d+)px/gi;
+ while ((sm = gapRe.exec(html)) !== null) {
+ spacingValues.push(parseInt(sm[1], 10));
+ }
+ const twSpaceRe = /\b(?:p|px|py|pt|pb|pl|pr|m|mx|my|mt|mb|ml|mr|gap)-(\d+)\b/g;
+ while ((sm = twSpaceRe.exec(html)) !== null) {
+ spacingValues.push(parseInt(sm[1], 10) * 4);
+ }
+ const remSpacingRe = /(?:padding|margin)(?:-(?:top|right|bottom|left))?\s*:\s*([\d.]+)rem/gi;
+ while ((sm = remSpacingRe.exec(html)) !== null) {
+ const v = Math.round(parseFloat(sm[1]) * 16);
+ if (v > 0 && v < 200) spacingValues.push(v);
+ }
+ const roundedSpacing = spacingValues.map(v => Math.round(v / 4) * 4);
+ if (roundedSpacing.length >= 10) {
+ const counts = {};
+ for (const v of roundedSpacing) counts[v] = (counts[v] || 0) + 1;
+ const maxCount = Math.max(...Object.values(counts));
+ const dominantPct = maxCount / roundedSpacing.length;
+ const unique = [...new Set(roundedSpacing)].filter(v => v > 0);
+ if (dominantPct > 0.6 && unique.length <= 3) {
+ const dominant = Object.entries(counts).sort((a, b) => b[1] - a[1])[0][0];
+ findings.push({
+ id: 'monotonous-spacing',
+ snippet: `~${dominant}px used ${maxCount}/${roundedSpacing.length} times (${Math.round(dominantPct * 100)}%)`,
+ });
+ }
+ }
+
+ // --- Motion ---
+
+ // Bounce/elastic animation names
+ const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
+ const bounceMatch = bounceRe.exec(html);
+ if (bounceMatch) {
+ const animationToken = bounceMatch[1]
+ .split(/[,\s]+/)
+ .find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
+ findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
+ }
+
+ // Overshoot cubic-bezier
+ const bezierRe = /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g;
+ let bm;
+ while ((bm = bezierRe.exec(html)) !== null) {
+ const y1 = parseFloat(bm[2]), y2 = parseFloat(bm[4]);
+ if (y1 < -0.1 || y1 > 1.1 || y2 < -0.1 || y2 > 1.1) {
+ findings.push({ id: 'bounce-easing', snippet: `cubic-bezier(${bm[1]}, ${bm[2]}, ${bm[3]}, ${bm[4]})` });
+ break;
+ }
+ }
+
+ // Layout property transitions
+ const transRe = /transition(?:-property)?\s*:\s*([^;{}]+)/gi;
+ let tm;
+ while ((tm = transRe.exec(html)) !== null) {
+ const val = tm[1].toLowerCase();
+ if (/\ball\b/.test(val)) continue;
+ const found = val.match(/\b(?:(?:max|min)-)?(?:width|height)\b|\bpadding(?:-(?:top|right|bottom|left))?\b|\bmargin(?:-(?:top|right|bottom|left))?\b/gi);
+ if (found) {
+ findings.push({ id: 'layout-transition', snippet: `transition: ${found.join(', ')}` });
+ break;
+ }
+ }
+
+ // --- Dark glow ---
+
+ const darkBgRe = /background(?:-color)?\s*:\s*(?:#(?:0[0-9a-f]|1[0-9a-f]|2[0-3])[0-9a-f]{4}\b|#(?:0|1)[0-9a-f]{2}\b|rgb\(\s*(\d{1,2})\s*,\s*(\d{1,2})\s*,\s*(\d{1,2})\s*\))/gi;
+ const twDarkBg = /\bbg-(?:gray|slate|zinc|neutral|stone)-(?:9\d{2}|800)\b/;
+ if (darkBgRe.test(html) || twDarkBg.test(html)) {
+ const shadowRe = /box-shadow\s*:\s*([^;{}]+)/gi;
+ let shm;
+ while ((shm = shadowRe.exec(html)) !== null) {
+ const val = shm[1];
+ const colorMatch = val.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
+ if (!colorMatch) continue;
+ const [r, g, b] = [+colorMatch[1], +colorMatch[2], +colorMatch[3]];
+ if ((Math.max(r, g, b) - Math.min(r, g, b)) < 30) continue;
+ const pxVals = [...val.matchAll(/(\d+)px|(? +(p[1] || p[2]));
+ if (pxVals.length >= 3 && pxVals[2] > 4) {
+ findings.push({ id: 'dark-glow', snippet: `Colored glow (rgb(${r},${g},${b})) on dark page` });
+ break;
+ }
+ }
+ }
+
+ // --- Provider tells (gated): repeating-gradient stripes (GPT) ---
+ if (/repeating-(?:linear|radial|conic)-gradient\s*\(/i.test(html)) {
+ findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
+ }
+
+ // --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
+ // The Codex grid tell is two hairline `linear-gradient(... 1px,
+ // transparent 1px)` layers (one per axis) tiled by a repeating
+ // `background-size` cell. Both signals must co-occur in the SAME style block
+ // (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
+ // tiling background-size is a fixed crosshair, not a grid, and a single
+ // hairline is a legitimate ruled line. Scoping to one block also stops
+ // unrelated single-axis rules on separate elements from adding up across the
+ // page. Count hairlines only inside `background`/`background-image` values so
+ // a hairline in an unrelated property (mask-image, border-image) can't stand
+ // in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
+ // nested parens, so match the hairline stop directly rather than parsing
+ // whole gradient layers.
+ {
+ const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
+ const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
+ const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
+ const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
+ let blk;
+ while ((blk = blockRe.exec(html)) !== null) {
+ const block = blk[1] || blk[2] || blk[3] || '';
+ if (!gridSizeRe.test(block)) continue;
+ let hairlineCount = 0;
+ let bm;
+ bgDeclRe.lastIndex = 0;
+ while ((bm = bgDeclRe.exec(block)) !== null) {
+ const stops = bm[1].match(hairlineRe);
+ if (stops) hairlineCount += stops.length;
+ }
+ if (hairlineCount >= 2) {
+ findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
+ break;
+ }
+ }
+ }
+
+ // --- Provider tells (gated): "X theater" framing copy (GPT) ---
+ // Lives here (regex-on-HTML) rather than in the text-content analyzers so it
+ // runs in the bundled browser path too, not just the CLI/static path.
+ {
+ const bodyText = html
+ .replace(/\n' +
+ open + ' ' + MARKER_CLOSE_TEXT + ' ' + close + '\n'
+ );
+}
+
+function detectLineEnding(content) {
+ if (content.includes('\r\n')) return '\r\n';
+ if (content.includes('\r')) return '\r';
+ return '\n';
+}
+
+function normalizeLineEndings(content, lineEnding) {
+ return lineEnding === '\n' ? content : content.replace(/\n/g, lineEnding);
+}
+
+function readLineEndingAt(content, index) {
+ if (content[index] === '\r' && content[index + 1] === '\n') return '\r\n';
+ if (content[index] === '\n') return '\n';
+ if (content[index] === '\r') return '\r';
+ return '';
+}
+
+function insertTag(content, config, port, filePath) {
+ const lineEnding = detectLineEnding(content);
+ const block = normalizeLineEndings(buildTagBlock(config.commentSyntax, port, filePath), lineEnding);
+ // insertBefore: match the LAST occurrence. Anchors like `
` open near the top of the document.
+ const idx = content.indexOf(config.insertAfter);
+ if (idx === -1) return content;
+ const after = idx + config.insertAfter.length;
+ // Preserve an existing trailing newline if the anchor already has one.
+ // Slice the remainder from the original anchor offset, not prefix.length:
+ // in the no-newline case prefix is one char longer than the anchor (the
+ // appended '\n'), so slicing by prefix.length would drop the first real
+ // character after the anchor (#227).
+ const existingNewline = readLineEndingAt(content, after);
+ const prefix = content.slice(0, after) + (existingNewline || lineEnding);
+ const rest = content.slice(after + existingNewline.length);
+ return prefix + block + rest;
+}
+
+/**
+ * Remove the live script block. Matches either HTML or JSX comment markers
+ * regardless of config (so stale tags from a wrong config can still be cleaned).
+ *
+ * Indent-preserving: captures any whitespace immediately preceding the opener
+ * marker and re-emits it in place of the removed block. `insertTag` inserted
+ * the block *after* the original line's indent and *before* the anchor (e.g.
+ * `` naturally
+ // belong at the end, and the same literal can appear earlier in code blocks
+ // within rendered documentation pages.
+ if (config.insertBefore) {
+ const idx = content.lastIndexOf(config.insertBefore);
+ if (idx === -1) return content;
+ return content.slice(0, idx) + block + content.slice(idx);
+ }
+ // insertAfter: match the FIRST occurrence — typical anchors like `
` or
+ // `
`), which moved the indent onto the opener line and left the anchor
+ * unindented. Replacing the whole block (plus its trailing newline) with just
+ * the captured indent hands the indent back to the anchor that follows.
+ */
+function removeTag(content, _syntax) {
+ const patterns = [
+ /([ \t]*)[\s\S]*?([ \t]*(?:\r\n|\n|\r|$)?)/,
+ /([ \t]*)\{\/\*\s*impeccable-live-start\s*\*\/\}[\s\S]*?\{\/\*\s*impeccable-live-end\s*\*\/\}([ \t]*(?:\r\n|\n|\r|$)?)/,
+ ];
+ for (const pat of patterns) {
+ let changed = false;
+ let next = content;
+ do {
+ content = next;
+ next = content.replace(pat, (_match, leadingIndent, trailing = '') => {
+ if (/[\r\n]/.test(trailing)) return leadingIndent;
+ return leadingIndent || trailing || '';
+ });
+ if (next !== content) changed = true;
+ } while (next !== content);
+ if (changed) return next;
+ }
+ return content;
+}
+
+// ---------------------------------------------------------------------------
+// Content-Security-Policy meta-tag patcher
+//
+// When the user's HTML carries ` `,
+// the cross-origin load of /live.js (and the SSE/POST connection back to
+// localhost:PORT) is blocked unless the CSP explicitly allows that origin.
+//
+// On insert: append `http://localhost:PORT` to `script-src` and `connect-src`,
+// and stash the original `content` value in a `data-impeccable-csp-original`
+// attribute (base64) so revert is exact.
+//
+// On remove: detect the marker attribute, decode it, restore the original
+// content value verbatim, drop the marker.
+//
+// Header-based CSP (Next.js headers, Nuxt routeRules, SvelteKit kit.csp,
+// shared helpers) is NOT patched here — those need framework-specific config
+// edits and are handled via the existing detect-csp.mjs reference output.
+// Only the in-source meta-tag form gets the auto-patch.
+// ---------------------------------------------------------------------------
+
+const CSP_MARKER_ATTR = 'data-impeccable-csp-original';
+
+function findCspMetaTags(content) {
+ const out = [];
+ const tagRe = / ]*?)\/?>/gis;
+ let m;
+ while ((m = tagRe.exec(content)) !== null) {
+ const attrs = m[1];
+ if (!/(http-equiv|httpEquiv)\s*=\s*(['"])Content-Security-Policy\2/i.test(attrs)) continue;
+ out.push({ start: m.index, end: m.index + m[0].length, full: m[0], attrs });
+ }
+ return out;
+}
+
+function getAttr(attrs, name) {
+ const re = new RegExp(`\\b${name}\\s*=\\s*(['"])([\\s\\S]*?)\\1`, 'i');
+ const m = attrs.match(re);
+ return m ? { quote: m[1], value: m[2], full: m[0] } : null;
+}
+
+function appendOriginToDirective(csp, directive, origin) {
+ const re = new RegExp(`(^|;)(\\s*)(${directive})\\s+([^;]*)`, 'i');
+ const m = csp.match(re);
+ if (m) {
+ const tokens = m[4].trim().split(/\s+/);
+ if (tokens.includes(origin)) return csp;
+ return csp.replace(re, `${m[1]}${m[2]}${m[3]} ${[...tokens, origin].join(' ')}`);
+ }
+ // Directive missing — add it. Use 'self' + origin so we don't inadvertently
+ // narrow the policy compared to the default-src fallback (most users with
+ // an explicit CSP have 'self' there).
+ return csp.trim().replace(/;?\s*$/, '') + `; ${directive} 'self' ${origin}`;
+}
+
+export function patchCspMeta(content, port) {
+ const tags = findCspMetaTags(content);
+ if (tags.length === 0) return content;
+ const origin = `http://localhost:${port}`;
+
+ // Walk last-to-first so prior splices don't invalidate later indices.
+ let result = content;
+ for (let i = tags.length - 1; i >= 0; i--) {
+ const tag = tags[i];
+ const attrs = tag.attrs;
+ if (getAttr(attrs, CSP_MARKER_ATTR)) continue; // already patched
+ const contentAttr = getAttr(attrs, 'content');
+ if (!contentAttr) continue;
+
+ const original = contentAttr.value;
+ let patched = original;
+ patched = appendOriginToDirective(patched, 'script-src', origin);
+ patched = appendOriginToDirective(patched, 'connect-src', origin);
+ // The shader overlay during 'generating' creates a screenshot via
+ // URL.createObjectURL, producing a `blob:` URL — img-src 'self' rejects
+ // those. Add `blob:` so the overlay doesn't throw a CSP violation.
+ patched = appendOriginToDirective(patched, 'img-src', 'blob:');
+ if (patched === original) continue;
+
+ const newContentAttr = `content=${contentAttr.quote}${patched}${contentAttr.quote}`;
+ const marker = `${CSP_MARKER_ATTR}="${Buffer.from(original, 'utf-8').toString('base64')}"`;
+ // The tagRe captures any whitespace between the last attribute and the
+ // closing `/>` as part of `attrs`. Naively appending ` ${marker}` after
+ // a replace would land it BEFORE that trailing space, leaving a double
+ // space inside attrs and clobbering the space before `/>`. Split off
+ // the trailing whitespace, splice the marker into the attribute body,
+ // and re-append the original trailing whitespace so a self-closing
+ // ` ` round-trips byte-for-byte.
+ const trailingWs = (attrs.match(/[ \t]*$/) || [''])[0];
+ const attrsBody = attrs.slice(0, attrs.length - trailingWs.length);
+ const newAttrs = attrsBody.replace(contentAttr.full, newContentAttr) + ' ' + marker + trailingWs;
+ const newTag = tag.full.replace(attrs, newAttrs);
+
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
+ }
+ return result;
+}
+
+export function revertCspMeta(content) {
+ const tags = findCspMetaTags(content);
+ if (tags.length === 0) return content;
+
+ let result = content;
+ for (let i = tags.length - 1; i >= 0; i--) {
+ const tag = tags[i];
+ const origAttr = getAttr(tag.attrs, CSP_MARKER_ATTR);
+ if (!origAttr) continue;
+ const contentAttr = getAttr(tag.attrs, 'content');
+ if (!contentAttr) continue;
+
+ let originalValue;
+ try { originalValue = Buffer.from(origAttr.value, 'base64').toString('utf-8'); }
+ catch { continue; }
+
+ const newContentAttr = `content=${contentAttr.quote}${originalValue}${contentAttr.quote}`;
+ let newAttrs = tag.attrs.replace(contentAttr.full, newContentAttr);
+ // Drop the marker attribute and any single space immediately preceding it.
+ newAttrs = newAttrs.replace(new RegExp(`\\s*${origAttr.full}`), '');
+ const newTag = tag.full.replace(tag.attrs, newAttrs);
+
+ result = result.slice(0, tag.start) + newTag + result.slice(tag.end);
+ }
+ return result;
+}
+
+// ---------------------------------------------------------------------------
+// Auto-execute
+// ---------------------------------------------------------------------------
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-inject.mjs') || _running?.endsWith('live-inject.mjs/')) {
+ injectCli();
+}
+
+export { insertTag, removeTag, validateConfig, buildTagBlock };
+// patchCspMeta + revertCspMeta are exported above where they're defined.
diff --git a/.github/skills/impeccable/scripts/live-insert.mjs b/.github/skills/impeccable/scripts/live-insert.mjs
new file mode 100644
index 0000000..0ed3caf
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-insert.mjs
@@ -0,0 +1,272 @@
+/**
+ * CLI helper: find an anchor element in source and splice an insert-variant
+ * wrapper before or after it (no original variant — net-new content).
+ *
+ * Usage:
+ * node live-insert.mjs --id SESSION_ID --count N --position after \
+ * --classes "hero" --tag section [--file path]
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import {
+ buildSearchQueries,
+ findElement,
+ findAllElements,
+ filterByText,
+ findFileWithQuery,
+ detectCommentSyntax,
+ detectStyleMode,
+ buildCssAuthoring,
+ buildCssSelectorPrefixExamples,
+} from './live-wrap.mjs';
+import {
+ buildSvelteComponentCssAuthoring,
+ scaffoldSvelteComponentInsertSession,
+ shouldUseSvelteComponentInjection,
+} from './live/svelte-component.mjs';
+
+const INSERT_POSITIONS = new Set(['before', 'after']);
+
+export function isInsertPosition(value) {
+ return INSERT_POSITIONS.has(value);
+}
+
+export function computeInsertLine(startLine, endLine, position) {
+ return position === 'before' ? startLine : endLine + 1;
+}
+
+export function buildInsertWrapperLines({ id, count, indent, commentSyntax, isJsx }) {
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
+ const attrs =
+ 'data-impeccable-variants="' + id + '" ' +
+ 'data-impeccable-mode="insert" ' +
+ 'data-impeccable-variant-count="' + count + '" ' +
+ styleContents;
+
+ if (isJsx) {
+ return [
+ indent + '
',
+ indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ indent + '
',
+ ];
+ }
+
+ return [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '
',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '
',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+}
+
+function argVal(args, flag) {
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+function resolveElementMatch({ lines, queries, tag, text }) {
+ if (text) {
+ const candidates = [];
+ for (const q of queries) {
+ const all = findAllElements(lines, q, tag);
+ for (const c of all) {
+ if (!candidates.some((x) => x.startLine === c.startLine)) candidates.push(c);
+ }
+ if (candidates.length === 1) break;
+ }
+ if (candidates.length === 0) return { error: 'element_not_found' };
+ if (candidates.length === 1) return { match: candidates[0] };
+ const filtered = filterByText(candidates, lines, text);
+ if (filtered.length === 1) return { match: filtered[0] };
+ if (filtered.length === 0) return { match: candidates[0] };
+ return { error: 'element_ambiguous', candidates: filtered };
+ }
+
+ for (const q of queries) {
+ const match = findElement(lines, q, tag);
+ if (match) return { match };
+ }
+ return { error: 'element_not_found' };
+}
+
+export async function insertCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-insert.mjs [options]
+
+Find an anchor element in source and splice an insert-variant wrapper.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+ --position POS before | after (relative to the anchor element)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the anchor element
+ --classes A,B,C Comma-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --text TEXT Anchor textContent for disambiguation (~80 chars)
+
+Output (JSON):
+ { mode: "insert", file, position, insertLine, commentSyntax, styleMode, styleTag, cssAuthoring }`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3', 10);
+ const position = argVal(args, '--position');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+ const text = argVal(args, '--text');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!position) { console.error('Missing --position (before | after)'); process.exit(1); }
+ if (!isInsertPosition(position)) { console.error('Invalid --position: ' + position); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+ const genOpts = { cwd: process.cwd() };
+
+ let targetFile = filePath;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
+ if (targetFile) break;
+ }
+ if (!targetFile) {
+ let generatedHit = null;
+ for (const q of queries) {
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
+ if (generatedHit) break;
+ }
+ console.error(JSON.stringify({
+ error: generatedHit ? 'element_not_in_source' : 'element_not_found',
+ fallback: 'agent-driven',
+ hint: 'See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ } else if (isGeneratedFile(targetFile, genOpts)) {
+ console.error(JSON.stringify({
+ error: 'file_is_generated',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
+ }));
+ process.exit(1);
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+ const resolved = resolveElementMatch({ lines, queries, tag, text });
+
+ if (resolved.error === 'element_ambiguous') {
+ console.error(JSON.stringify({
+ error: 'element_ambiguous',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), targetFile),
+ candidates: resolved.candidates.map((c) => ({
+ startLine: c.startLine + 1,
+ endLine: c.endLine + 1,
+ })),
+ }));
+ process.exit(1);
+ }
+ if (!resolved.match) {
+ console.error(JSON.stringify({ error: 'element_not_found', fallback: 'agent-driven' }));
+ process.exit(1);
+ }
+
+ const { startLine, endLine } = resolved.match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const styleMode = detectStyleMode(targetFile);
+ const isJsx = commentSyntax.open === '{/*';
+ const spliceIndex = computeInsertLine(startLine, endLine, position);
+ const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
+
+ if (shouldUseSvelteComponentInjection(targetFile)) {
+ const session = scaffoldSvelteComponentInsertSession({
+ id,
+ count,
+ sourceFile: relTargetFile,
+ insertLine: spliceIndex + 1,
+ position,
+ anchorStartLine: startLine + 1,
+ anchorEndLine: endLine + 1,
+ anchorLines: lines.slice(startLine, endLine + 1),
+ cwd: process.cwd(),
+ });
+ console.log(JSON.stringify({
+ mode: 'insert',
+ position,
+ file: session.manifestFile,
+ sourceFile: relTargetFile,
+ previewMode: 'svelte-component',
+ componentDir: session.componentDir,
+ propContract: session.propContract,
+ insertLine: 1,
+ sourceInsertLine: spliceIndex + 1,
+ anchorStartLine: startLine + 1,
+ anchorEndLine: endLine + 1,
+ commentSyntax,
+ styleMode: 'svelte-component',
+ styleTag: null,
+ cssSelectorPrefixExamples: [],
+ cssAuthoring: buildSvelteComponentCssAuthoring(count),
+ }));
+ return;
+ }
+
+ const indent = lines[spliceIndex]?.match(/^(\s*)/)?.[1]
+ ?? lines[startLine]?.match(/^(\s*)/)?.[1]
+ ?? '';
+
+ const wrapperLines = buildInsertWrapperLines({
+ id,
+ count,
+ indent,
+ commentSyntax,
+ isJsx,
+ });
+
+ const newLines = [
+ ...lines.slice(0, spliceIndex),
+ ...wrapperLines,
+ ...lines.slice(spliceIndex),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ const insertLine = spliceIndex + 3;
+
+ console.log(JSON.stringify({
+ mode: 'insert',
+ position,
+ file: relTargetFile,
+ insertLine: insertLine + 1,
+ commentSyntax,
+ styleMode: styleMode.mode,
+ styleTag: styleMode.styleTag,
+ cssSelectorPrefixExamples: buildCssSelectorPrefixExamples(styleMode.mode, count),
+ cssAuthoring: buildCssAuthoring(styleMode, count),
+ }));
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-insert.mjs') || _running?.endsWith('live-insert.mjs/')) {
+ insertCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-manual-edit-evidence.mjs b/.github/skills/impeccable/scripts/live-manual-edit-evidence.mjs
new file mode 100644
index 0000000..dd10e96
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-manual-edit-evidence.mjs
@@ -0,0 +1,363 @@
+#!/usr/bin/env node
+/**
+ * Collect evidence for pending live copy edits.
+ *
+ * This module intentionally does not edit source files and does not choose a
+ * winner. It gathers staged browser edits, rendered context, framework source
+ * hints, and likely source candidates so the AI copy-edit batch runner can make
+ * source changes with full repo context.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import { readBuffer, getBufferPath } from './live/manual-edits-buffer.mjs';
+
+const EVIDENCE_VERSION = 1;
+const TEXT_EXTENSIONS = new Set(['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro', '.js', '.mjs', '.ts']);
+const SEARCH_DIRS = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', 'site', 'lib', 'data'];
+const STRONG_LITERAL_MATCH_LIMIT = 8;
+const WEAK_LITERAL_MATCH_LIMIT = 4;
+const OBJECT_KEY_MATCH_LIMIT = 8;
+const LOCATOR_MATCH_LIMIT = 4;
+const CONTEXT_MATCH_LIMIT = 8;
+const CONTEXT_MATCH_PER_HINT = 2;
+const SKIP_DIRS = new Set([
+ 'node_modules',
+ '.git',
+ '.impeccable',
+ '.astro',
+ '.next',
+ '.nuxt',
+ '.svelte-kit',
+ 'dist',
+ 'build',
+ 'out',
+ 'coverage',
+]);
+
+export function buildManualEditEvidence({ cwd = process.cwd(), pageUrl = null } = {}) {
+ const buffer = readBuffer(cwd);
+ const entries = pageUrl
+ ? buffer.entries.filter((entry) => entry.pageUrl === pageUrl)
+ : buffer.entries;
+ const opCount = countOps(entries);
+
+ if (opCount === 0) {
+ return {
+ pageUrl,
+ count: 0,
+ entries: [],
+ ops: [],
+ candidates: [],
+ };
+ }
+
+ const searchFiles = collectSearchFiles(cwd);
+ const ops = flattenOps(entries);
+ const candidates = ops.map((op) => buildCandidatesForOp(op, cwd, searchFiles));
+ return {
+ version: EVIDENCE_VERSION,
+ pageUrl: pageUrl || null,
+ count: opCount,
+ entries,
+ ops,
+ context: {
+ cwd,
+ bufferPath: path.relative(cwd, getBufferPath(cwd)),
+ totalEntries: entries.length,
+ totalOps: opCount,
+ },
+ candidates,
+ };
+}
+
+function countOps(entries) {
+ let count = 0;
+ for (const entry of entries) count += Array.isArray(entry.ops) ? entry.ops.length : 0;
+ return count;
+}
+
+function flattenOps(entries) {
+ const out = [];
+ for (const entry of entries) {
+ const contextHintsByRef = buildContextHintsByRef(entry);
+ for (const op of entry.ops || []) {
+ out.push({
+ entryId: entry.id,
+ pageUrl: entry.pageUrl,
+ ref: op.ref,
+ contextRef: op.contextRef || null,
+ tag: op.tag,
+ elementId: op.elementId || null,
+ classes: Array.isArray(op.classes) ? op.classes : [],
+ originalText: op.originalText,
+ newText: op.newText,
+ deleted: op.deleted === true,
+ sourceHint: op.sourceHint || null,
+ leaf: op.leaf || null,
+ nearbyEditableTexts: Array.isArray(op.nearbyEditableTexts) ? op.nearbyEditableTexts : [],
+ container: op.container || null,
+ contextHints: contextHintsByRef.get(op.ref) || [],
+ });
+ }
+ }
+ return out;
+}
+
+function buildContextHintsByRef(entry) {
+ const map = new Map();
+ for (const op of entry.ops || []) {
+ const hints = new Set();
+ const add = (value) => {
+ const text = normalizeText(decodeBasicHtml(String(value || '')));
+ if (text.length < 3 || text.length > 160) return;
+ if (text === normalizeText(op.originalText) || text === normalizeText(op.newText)) return;
+ hints.add(text);
+ };
+
+ for (const item of op.nearbyEditableTexts || []) {
+ add(typeof item === 'string' ? item : item?.text);
+ }
+ const outer = typeof entry.element?.outerHTML === 'string' ? entry.element.outerHTML : '';
+ for (const match of outer.matchAll(/data-impeccable-original-text="([^"]*)"/g)) add(match[1]);
+ if (typeof entry.element?.textContent === 'string') {
+ for (const chunk of entry.element.textContent.split(/\s{2,}|\n|\t/)) add(chunk);
+ }
+ map.set(op.ref, [...hints].slice(0, 16));
+ }
+ return map;
+}
+
+function buildCandidatesForOp(op, cwd, searchFiles) {
+ const originalText = String(op.originalText || '');
+ const contextNeedles = op.contextHints || [];
+ return {
+ entryId: op.entryId,
+ ref: op.ref,
+ originalText,
+ sourceHint: analyzeSourceHint(op, cwd),
+ textMatches: originalText ? findLiteralMatches(searchFiles, originalText, { max: literalMatchLimit(originalText) }) : [],
+ objectKeyMatches: originalText ? findObjectKeyMatches(searchFiles, originalText, { max: OBJECT_KEY_MATCH_LIMIT }) : [],
+ locatorMatches: findLocatorMatches(searchFiles, op, { max: LOCATOR_MATCH_LIMIT }),
+ contextTextMatches: findContextMatches(searchFiles, contextNeedles, { maxPerHint: CONTEXT_MATCH_PER_HINT, max: CONTEXT_MATCH_LIMIT }),
+ };
+}
+
+function literalMatchLimit(text) {
+ return isWeakSourceNeedle(text) ? WEAK_LITERAL_MATCH_LIMIT : STRONG_LITERAL_MATCH_LIMIT;
+}
+
+function isWeakSourceNeedle(text) {
+ const normalized = normalizeText(text);
+ return normalized.length < 4 || /^[\d.,+\-%\s]+$/.test(normalized);
+}
+
+function analyzeSourceHint(op, cwd) {
+ const hint = normalizeSourceHint(op.sourceHint);
+ if (!hint.file) return null;
+ const file = path.resolve(cwd, hint.file);
+ const relativeFile = path.relative(cwd, file);
+ if (!isPathInsideOrEqual(cwd, file)) {
+ return { ...hint, status: 'outside_cwd', relativeFile: hint.file };
+ }
+ if (!fs.existsSync(file)) {
+ return { ...hint, status: 'file_missing', relativeFile };
+ }
+ if (isGeneratedFile(file, { cwd })) {
+ return { ...hint, status: 'generated', relativeFile };
+ }
+
+ const content = fs.readFileSync(file, 'utf-8');
+ const lines = content.split('\n');
+ const line = hint.line || 1;
+ const start = Math.max(0, line - 4);
+ const end = Math.min(lines.length, line + 3);
+ const windowText = lines.slice(start, end).join('\n');
+ const containsOriginalText = typeof op.originalText === 'string' && windowText.includes(op.originalText);
+ return {
+ ...hint,
+ status: containsOriginalText ? 'ok' : 'text_not_found_near_hint',
+ relativeFile,
+ excerpt: lines.slice(start, end).map((text, index) => ({
+ line: start + index + 1,
+ text: text.slice(0, 240),
+ })),
+ };
+}
+
+function normalizeSourceHint(hint) {
+ if (!hint || typeof hint !== 'object') return {};
+ let line = Number.isFinite(Number(hint.line)) ? Number(hint.line) : null;
+ let column = Number.isFinite(Number(hint.column)) ? Number(hint.column) : null;
+ if ((!line || !column) && typeof hint.loc === 'string') {
+ const match = hint.loc.match(/^(\d+)(?::(\d+))?/);
+ if (match) {
+ line = Number(match[1]);
+ if (match[2]) column = Number(match[2]);
+ }
+ }
+ return {
+ file: typeof hint.file === 'string' ? hint.file : '',
+ loc: typeof hint.loc === 'string' ? hint.loc : '',
+ line,
+ column,
+ };
+}
+
+function collectSearchFiles(cwd) {
+ const out = [];
+ const seenDirs = new Set();
+ const seenFiles = new Set();
+ for (const dir of SEARCH_DIRS) {
+ scanDir(path.join(cwd, dir), cwd, seenDirs, seenFiles, out, 0);
+ }
+ scanRootFiles(cwd, seenFiles, out);
+ return out;
+}
+
+function scanDir(dir, cwd, seenDirs, seenFiles, out, depth) {
+ if (depth > 7 || !fs.existsSync(dir)) return;
+ let realDir;
+ try { realDir = fs.realpathSync(dir); } catch { return; }
+ if (seenDirs.has(realDir)) return;
+ seenDirs.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ const fullPath = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (SKIP_DIRS.has(entry.name)) continue;
+ scanDir(fullPath, cwd, seenDirs, seenFiles, out, depth + 1);
+ continue;
+ }
+ if (!entry.isFile() || !TEXT_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
+ maybeAddSearchFile(fullPath, cwd, seenFiles, out);
+ }
+}
+
+function scanRootFiles(cwd, seenFiles, out) {
+ let entries;
+ try { entries = fs.readdirSync(cwd, { withFileTypes: true }); } catch { return; }
+ for (const entry of entries) {
+ if (!entry.isFile() || !TEXT_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue;
+ maybeAddSearchFile(path.join(cwd, entry.name), cwd, seenFiles, out);
+ }
+}
+
+function maybeAddSearchFile(file, cwd, seenFiles, out) {
+ let realFile;
+ try { realFile = fs.realpathSync(file); } catch { return; }
+ if (seenFiles.has(realFile)) return;
+ seenFiles.add(realFile);
+ if (isGeneratedFile(file, { cwd })) return;
+ let content;
+ try { content = fs.readFileSync(file, 'utf-8'); } catch { return; }
+ out.push({ file, relativeFile: path.relative(cwd, file), content, lines: content.split('\n') });
+}
+
+function findLiteralMatches(searchFiles, needle, { max }) {
+ return findMatches(searchFiles, needle, { kind: 'text', max });
+}
+
+function findObjectKeyMatches(searchFiles, text, { max }) {
+ const re = new RegExp('(["\\\'`])' + escapeRegExp(text) + '\\1(?=\\s*:)', 'g');
+ const out = [];
+ for (const file of searchFiles) {
+ for (const match of file.content.matchAll(re)) {
+ out.push(matchForIndex(file, match.index, 'object_key', text));
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findLocatorMatches(searchFiles, op, { max }) {
+ const needles = [];
+ if (op.elementId) needles.push({ kind: 'id', needle: op.elementId });
+ for (const cls of op.classes || []) {
+ if (cls) needles.push({ kind: 'class', needle: cls });
+ }
+ if (op.tag) needles.push({ kind: 'tag', needle: '<' + op.tag });
+
+ const out = [];
+ const seen = new Set();
+ for (const { kind, needle } of needles) {
+ for (const match of findMatches(searchFiles, needle, { kind, max })) {
+ const key = match.file + ':' + match.line + ':' + kind + ':' + needle;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...match, needle });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findContextMatches(searchFiles, hints, { maxPerHint, max }) {
+ const out = [];
+ const seen = new Set();
+ for (const hint of hints || []) {
+ for (const match of findMatches(searchFiles, hint, { kind: 'context', max: maxPerHint })) {
+ const key = match.file + ':' + match.line + ':' + hint;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({ ...match, needle: hint });
+ if (out.length >= max) return out;
+ }
+ }
+ return out;
+}
+
+function findMatches(searchFiles, needle, { kind, max }) {
+ const text = String(needle || '');
+ if (!text) return [];
+ const out = [];
+ for (const file of searchFiles) {
+ let index = 0;
+ while (out.length < max) {
+ index = file.content.indexOf(text, index);
+ if (index === -1) break;
+ out.push(matchForIndex(file, index, kind, text));
+ index += Math.max(1, text.length);
+ }
+ if (out.length >= max) break;
+ }
+ return out;
+}
+
+function matchForIndex(file, index, kind, needle) {
+ const line = file.content.slice(0, index).split('\n').length;
+ const lineText = file.lines[line - 1] || '';
+ return {
+ kind,
+ file: file.relativeFile,
+ line,
+ needle,
+ excerpt: lineText.trim().slice(0, 240),
+ };
+}
+
+function isPathInsideOrEqual(cwd, file) {
+ const rel = path.relative(path.resolve(cwd), path.resolve(file));
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
+}
+
+function normalizeText(value) {
+ return String(value || '').replace(/\s+/g, ' ').trim();
+}
+
+function decodeBasicHtml(value) {
+ return value
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/'/g, "'")
+ .replace(/&/g, '&')
+ .replace(/</g, '<')
+ .replace(/>/g, '>');
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/.github/skills/impeccable/scripts/live-poll.mjs b/.github/skills/impeccable/scripts/live-poll.mjs
new file mode 100644
index 0000000..740161e
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-poll.mjs
@@ -0,0 +1,384 @@
+/**
+ * CLI client for the live variant mode poll/reply protocol.
+ *
+ * Usage:
+ * node /live-poll.mjs # Block until browser event, print JSON
+ * node /live-poll.mjs --stream # Experimental: keep polling; one JSON line per event
+ * node /live-poll.mjs --timeout=600000 # Custom timeout (ms); default is long-poll friendly
+ * node /live-poll.mjs --reply done # Reply "done" to event
+ * node /live-poll.mjs --reply error "msg" # Reply with error
+ */
+
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { completionAckForAcceptResult, completionTypeForAcceptResult } from './live/completion.mjs';
+import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
+
+// Absolute path to a sibling script in this skill's scripts dir, so runtime
+// error hints print a directly-runnable command instead of a placeholder.
+const SELF_DIR = path.dirname(fileURLToPath(import.meta.url));
+const scriptCmd = (name) => `node "${path.join(SELF_DIR, name)}"`;
+
+// Node's built-in fetch (undici under the hood) enforces a 300s headers
+// timeout that can't be lowered per-request. We cap each request below
+// that ceiling and loop in `pollOnce` to synthesize a long poll without
+// depending on the standalone undici package.
+export const PER_REQUEST_TIMEOUT_MS = 270_000;
+export const DEFAULT_EVENT_LEASE_MS = 600_000;
+
+const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_edit_apply']);
+
+function readServerInfo() {
+ const record = readLiveServerInfo(process.cwd());
+ if (!record) {
+ console.error(`No running live server found. Start one with: ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ return record.info;
+}
+
+export function buildPollReplyPayload(token, { id, type, message, file, data }) {
+ return { token, id, type, message, file, data };
+}
+
+export function manualApplyPollBanner(event = {}) {
+ const id = event.id || 'EVENT_ID';
+ return [
+ `Manual Apply action required: edit source, then reply with \`live-poll.mjs --reply ${id} done --data ''\`.`,
+ 'The JSON data must include status, appliedEntryIds, failed, files, and notes; summary counters are only a recovery fallback.',
+ 'Do not run live-commit-manual-edits.mjs for this leased event.',
+ 'Do not poll again before replying.',
+ ].join('\n') + '\n';
+}
+
+/**
+ * Parse `--reply [--file path] [--data ''] [message]` argv
+ * into a reply object. Returns null when `--reply` is absent. Throws (code
+ * INVALID_REPLY_ARGS) when the reply shape is missing its event id/status and
+ * INVALID_DATA_JSON when `--data` is present but not valid JSON.
+ */
+export function parseReplyArgs(args) {
+ const replyIdx = args.indexOf('--reply');
+ if (replyIdx === -1) return null;
+ const id = args[replyIdx + 1];
+ const status = args[replyIdx + 2];
+ validateReplyArgs({ id, status });
+ const fileIdx = args.indexOf('--file');
+ const file = fileIdx !== -1 && fileIdx + 1 < args.length ? args[fileIdx + 1] : undefined;
+ const dataIdx = args.indexOf('--data');
+ let data;
+ if (dataIdx !== -1 && dataIdx + 1 < args.length) {
+ try {
+ data = JSON.parse(args[dataIdx + 1]);
+ } catch (err) {
+ const wrapped = new Error('--data must be valid JSON: ' + err.message);
+ wrapped.code = 'INVALID_DATA_JSON';
+ throw wrapped;
+ }
+ }
+ const message = args.find((a, i) =>
+ i > replyIdx + 2
+ && !a.startsWith('--')
+ && i !== fileIdx + 1
+ && i !== dataIdx + 1
+ ) || undefined;
+ return { id, type: status, message, file, data };
+}
+
+function validateReplyArgs({ id, status }) {
+ const usage = `Usage: ${scriptCmd('live-poll.mjs')} --reply [--file path] [--data ''] [message]`;
+ if (!id || id.startsWith('--')) {
+ const err = new Error(`${usage}\nMissing event id after --reply.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+ if (['done', 'error', 'complete', 'discard', 'discarded'].includes(id)) {
+ const err = new Error(`${usage}\nThe value after --reply must be the event id, not the status ${JSON.stringify(id)}. Use --reply EVENT_ID ${id}.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+ if (!status || status.startsWith('--')) {
+ const err = new Error(`${usage}\nMissing reply status after event id ${JSON.stringify(id)}.`);
+ err.code = 'INVALID_REPLY_ARGS';
+ throw err;
+ }
+}
+
+export function requiresAgentReply(event) {
+ return EVENT_TYPES_NEEDING_AGENT_REPLY.has(event?.type);
+}
+
+export async function postReply(base, token, reply) {
+ const res = await fetch(`${base}/poll`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(buildPollReplyPayload(token, reply)),
+ });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ const parts = [body.error || res.statusText, body.reason, body.hint].filter(Boolean);
+ throw new Error(parts.join(': '));
+ }
+}
+
+export async function fetchServerStatus(base, token) {
+ const res = await fetch(`${base}/status?token=${token}`);
+ if (res.status === 401) {
+ const err = new Error('Authentication failed. The server token may have changed.');
+ err.code = 'AUTH_FAILED';
+ throw err;
+ }
+ if (!res.ok) {
+ throw new Error(`Status failed: ${res.status} ${res.statusText}`);
+ }
+ return res.json();
+}
+
+export function isEventPending(status, eventId) {
+ return (status.pendingEvents || []).some((entry) => entry.id === eventId);
+}
+
+export async function waitForEventAck(base, token, eventId, {
+ pollIntervalMs = 400,
+ maxWaitMs = 600_000,
+} = {}) {
+ const deadline = Date.now() + maxWaitMs;
+ while (Date.now() < deadline) {
+ const status = await fetchServerStatus(base, token);
+ if (!isEventPending(status, eventId)) return true;
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
+ }
+ return false;
+}
+
+export async function fetchNextEvent(base, token, { totalDeadline } = {}) {
+ while (true) {
+ if (totalDeadline && Date.now() >= totalDeadline) {
+ return { type: 'timeout' };
+ }
+
+ const remaining = totalDeadline
+ ? totalDeadline - Date.now()
+ : PER_REQUEST_TIMEOUT_MS;
+ const slice = Math.min(Math.max(remaining, 1000), PER_REQUEST_TIMEOUT_MS);
+ const res = await fetch(`${base}/poll?token=${token}&timeout=${slice}&leaseMs=${DEFAULT_EVENT_LEASE_MS}`);
+
+ if (res.status === 401) {
+ const err = new Error('Authentication failed. The server token may have changed.');
+ err.code = 'AUTH_FAILED';
+ throw err;
+ }
+
+ if (!res.ok) {
+ throw new Error(`Poll failed: ${res.status} ${res.statusText}`);
+ }
+
+ const next = await res.json();
+ if (next?.type === 'timeout') {
+ if (totalDeadline && Date.now() < totalDeadline) continue;
+ if (!totalDeadline) continue;
+ return next;
+ }
+ return next;
+ }
+}
+
+export async function augmentEventWithAcceptHandling(event, base, token) {
+ if (event.type !== 'accept' && event.type !== 'discard') return event;
+
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
+ const acceptScript = path.join(__dirname, 'live-accept.mjs');
+ const scriptArgs = buildAcceptScriptArgs(event);
+
+ try {
+ const out = execFileSync(
+ 'node',
+ [acceptScript, ...scriptArgs],
+ { encoding: 'utf-8', cwd: process.cwd(), timeout: 30_000 },
+ );
+ event._acceptResult = JSON.parse(out.trim());
+ } catch (err) {
+ event._acceptResult = { handled: false, mode: 'error', error: err.message };
+ }
+
+ const completionType = completionTypeForAcceptResult(event.type, event._acceptResult);
+ try {
+ await postReply(base, token, {
+ id: event.id,
+ type: completionType,
+ message: event._acceptResult?.error,
+ file: event._acceptResult?.file,
+ data: event._acceptResult?.carbonize === true ? { carbonize: true } : undefined,
+ });
+ } catch (err) {
+ event._completionAck = { ok: false, error: err.message };
+ }
+ if (!event._completionAck) {
+ event._completionAck = completionAckForAcceptResult(event.id, completionType, event._acceptResult);
+ }
+
+ return event;
+}
+
+export function buildAcceptScriptArgs(event) {
+ const scriptArgs = event.type === 'discard'
+ ? ['--id', String(event.id), '--discard']
+ : ['--id', String(event.id), '--variant', String(event.variantId)];
+ if (event.pageUrl) scriptArgs.push('--page-url', String(event.pageUrl));
+ if (event.type === 'accept' && event.paramValues && Object.keys(event.paramValues).length > 0) {
+ scriptArgs.push('--param-values', JSON.stringify(event.paramValues));
+ }
+ return scriptArgs;
+}
+
+export function writeCarbonizeBanner(event) {
+ if (event.type === 'manual_edit_apply') {
+ process.stderr.write('\n' + manualApplyPollBanner(event) + '\n');
+ }
+ if (event._acceptResult?.carbonize === true) {
+ process.stderr.write('\n⚠ Carbonize cleanup REQUIRED before next poll. After cleanup, run live-complete.mjs --id ' + event.id + '. See reference/live.md "Required after accept".\n\n');
+ }
+}
+
+export function printPollEvent(event) {
+ console.log(JSON.stringify(event));
+}
+
+export async function runPollOnce(base, token, { totalTimeout = 600_000 } = {}) {
+ const deadline = Date.now() + totalTimeout;
+ const event = await fetchNextEvent(base, token, { totalDeadline: deadline });
+ await augmentEventWithAcceptHandling(event, base, token);
+ writeCarbonizeBanner(event);
+ printPollEvent(event);
+ return event;
+}
+
+export async function runPollStream(base, token, {
+ ackTimeoutMs = 600_000,
+ ackPollIntervalMs = 400,
+ shouldContinue = () => true,
+} = {}) {
+ process.stderr.write('[impeccable-poll] stream mode: one JSON object per line on stdout; use --reply while this process stays running\n');
+
+ while (shouldContinue()) {
+ const event = await fetchNextEvent(base, token);
+ await augmentEventWithAcceptHandling(event, base, token);
+ writeCarbonizeBanner(event);
+ printPollEvent(event);
+
+ if (event.type === 'exit') return event;
+
+ if (requiresAgentReply(event)) {
+ const acked = await waitForEventAck(base, token, event.id, {
+ pollIntervalMs: ackPollIntervalMs,
+ maxWaitMs: ackTimeoutMs,
+ });
+ if (!acked) {
+ const err = new Error(`Timed out waiting for --reply on event ${event.id}`);
+ err.code = 'ACK_TIMEOUT';
+ throw err;
+ }
+ }
+ }
+
+ return null;
+}
+
+function handlePollError(err) {
+ if (err.code === 'AUTH_FAILED') {
+ console.error(err.message);
+ console.error(`Try restarting: ${scriptCmd('live-server.mjs')} stop && ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
+ process.exit(1);
+ }
+ if (err.code === 'ACK_TIMEOUT') {
+ console.error(err.message);
+ process.exit(1);
+ }
+ console.error('Poll failed:', err.message);
+ process.exit(1);
+}
+
+export async function pollCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable poll [options]
+
+Wait for a browser event from the live variant server, or reply to one.
+
+Modes:
+ poll Block until a browser event arrives, print JSON, exit
+ poll --stream Keep polling; print one JSON line per event (see live.md)
+ poll --reply done Reply "done" to event (replace or insert generate)
+ poll --reply steer_done Reply after handling a steer event (unlocks Steer bar)
+ poll --reply error "msg" Reply with an error message
+ poll --reply done --data ''
+ Reply with a structured JSON result (manual_edit_apply)
+
+Options:
+ --timeout=MS One-shot poll timeout in ms (default: 600000). Ignored in --stream mode
+ --ack-timeout=MS Stream mode: max wait for --reply after generate/steer (default: 600000)
+ --file PATH Attach a source file path to the reply (generate/steer flow)
+ --data JSON Attach a JSON result object to the reply (manual_edit_apply flow). Must be valid JSON
+ --help Show this help message
+
+Harness note:
+ Default one-shot mode is the portable contract for Claude Code, Codex, and Cursor.
+ --stream is experimental for harnesses with fast incremental stdout; do not use on Cursor.`);
+ process.exit(0);
+ }
+
+ const info = readServerInfo();
+ const base = `http://localhost:${info.port}`;
+
+ // Reply mode: node /live-poll.mjs --reply [--file path] [--data ''] [message]
+ if (args.includes('--reply')) {
+ let reply;
+ try {
+ reply = parseReplyArgs(args);
+ } catch (err) {
+ console.error(err.message);
+ process.exit(1);
+ }
+
+ try {
+ await postReply(base, info.token, reply);
+ } catch (err) {
+ if (err.cause?.code === 'ECONNREFUSED') {
+ console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
+ } else {
+ console.error('Reply failed:', err.message);
+ }
+ process.exit(1);
+ }
+ return;
+ }
+
+ const streamMode = args.includes('--stream');
+ const ackTimeoutArg = args.find((a) => a.startsWith('--ack-timeout='));
+ const ackTimeoutMs = ackTimeoutArg ? parseInt(ackTimeoutArg.split('=')[1], 10) : 600_000;
+
+ try {
+ if (streamMode) {
+ await runPollStream(base, info.token, { ackTimeoutMs });
+ return;
+ }
+
+ const timeoutArg = args.find((a) => a.startsWith('--timeout='));
+ const totalTimeout = timeoutArg ? parseInt(timeoutArg.split('=')[1], 10) : 600_000;
+ await runPollOnce(base, info.token, { totalTimeout });
+ } catch (err) {
+ handlePollError(err);
+ }
+}
+
+// Auto-execute when run directly
+const _running = process.argv[1];
+if (_running?.endsWith('live-poll.mjs') || _running?.endsWith('live-poll.mjs/')) {
+ pollCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-resume.mjs b/.github/skills/impeccable/scripts/live-resume.mjs
new file mode 100644
index 0000000..74284d4
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-resume.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+/**
+ * Recover the next agent action from the durable live-session journal.
+ */
+
+import { createLiveSessionStore } from './live/session-store.mjs';
+
+function manualApplyReplyCommand(eventOrId = 'EVENT_ID') {
+ const id = typeof eventOrId === 'string' ? eventOrId : eventOrId?.id || 'EVENT_ID';
+ return `live-poll.mjs --reply ${id} done --data ''`;
+}
+
+export function manualApplyResumeHint(event = {}) {
+ const summary = event.manualApplySummary || summarizeManualApplyEvent(event);
+ const parts = [];
+ if (summary.pageUrl) parts.push(`page ${summary.pageUrl}`);
+ if (summary.chunk) parts.push(`chunk ${summary.chunk.index}/${summary.chunk.total}`);
+ if (Number.isFinite(summary.opCount)) parts.push(`${summary.opCount} op(s)`);
+ if (Number.isFinite(summary.entryCount)) parts.push(`${summary.entryCount} entr${summary.entryCount === 1 ? 'y' : 'ies'}`);
+ if (summary.files?.length) parts.push(`likely files: ${summary.files.join(', ')}`);
+ const scope = parts.length ? ` (${parts.join(', ')})` : '';
+ return `Manual Apply pending${scope}. If you have not already leased it, run live-poll.mjs. Apply the source edits from the manual_edit_apply batch, then reply with ${manualApplyReplyCommand(event.id)}. Polling only leases this work item; it does not commit source edits. Do not run live-commit-manual-edits.mjs for this leased event. Do not poll again before replying.`;
+}
+
+function summarizeManualApplyEvent(event = {}) {
+ const entries = Array.isArray(event.batch?.entries) ? event.batch.entries : [];
+ const opCount = entries.reduce((sum, entry) => sum + (Array.isArray(entry.ops) ? entry.ops.length : 0), 0);
+ return {
+ pageUrl: event.pageUrl || null,
+ chunk: event.chunk || null,
+ entryCount: entries.length,
+ opCount,
+ files: collectManualApplyFiles(event.batch),
+ };
+}
+
+function collectManualApplyFiles(batch) {
+ const files = [];
+ for (const entry of batch?.entries || []) {
+ for (const op of entry.ops || []) files.push(op.sourceHint?.file);
+ }
+ for (const candidate of batch?.candidates || []) {
+ files.push(candidate.sourceHint?.relativeFile, candidate.sourceHint?.file);
+ for (const item of candidate.textMatches || []) files.push(item.file);
+ for (const item of candidate.objectKeyMatches || []) files.push(item.file);
+ for (const item of candidate.locatorMatches || []) files.push(item.file);
+ for (const item of candidate.contextTextMatches || []) files.push(item.file);
+ }
+ return [...new Set(files.filter((file) => typeof file === 'string' && file.length > 0))].sort();
+}
+
+function parseArgs(argv) {
+ const out = { id: null };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--id') out.id = argv[++i];
+ else if (arg.startsWith('--id=')) out.id = arg.slice('--id='.length);
+ else if (arg === '--help' || arg === '-h') out.help = true;
+ }
+ return out;
+}
+
+export async function resumeCli() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help) {
+ console.log(`Usage: node live-resume.mjs [--id SESSION_ID]\n\nPrint the active durable session checkpoint and the next safe agent action.`);
+ return;
+ }
+
+ const store = createLiveSessionStore({ cwd: process.cwd(), sessionId: args.id || undefined });
+ const snapshot = args.id ? store.getSnapshot(args.id) : store.listActiveSessions()[0] || null;
+ if (!snapshot) {
+ console.log(JSON.stringify({ active: false, nextAction: 'No active durable live session found.' }, null, 2));
+ return;
+ }
+
+ const pending = snapshot.pendingEvent || null;
+ const nextAction = pending
+ ? pending.type === 'manual_edit_apply'
+ ? manualApplyResumeHint(pending)
+ : `Run live-poll.mjs, handle ${pending.type} ${pending.id}, then acknowledge with live-poll.mjs --reply ${pending.id} done.`
+ : snapshot.phase === 'carbonize_required'
+ ? `Finish carbonize cleanup${snapshot.sourceFile ? ` in ${snapshot.sourceFile}` : ''}, then run live-complete.mjs --id ${snapshot.id}.`
+ : snapshot.phase === 'accept_requested'
+ ? `Run live-complete.mjs --id ${snapshot.id} after verifying the accepted variant is written.`
+ : `Inspect ${snapshot.id}; no pending agent event is currently queued.`;
+
+ console.log(JSON.stringify({ active: true, snapshot, pendingEvent: pending, nextAction }, null, 2));
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-resume.mjs') || _running?.endsWith('live-resume.mjs/')) {
+ resumeCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-server.mjs b/.github/skills/impeccable/scripts/live-server.mjs
new file mode 100644
index 0000000..5735f2a
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-server.mjs
@@ -0,0 +1,1137 @@
+#!/usr/bin/env node
+/**
+ * Live variant mode server (self-contained, zero dependencies).
+ *
+ * Serves the browser script (/live.js), the detection overlay (/detect.js),
+ * uses Server-Sent Events (SSE) for server→browser push, and HTTP POST for
+ * browser→server events. Agent communicates via HTTP long-poll (/poll).
+ *
+ * Usage:
+ * node /live-server.mjs # start
+ * node /live-server.mjs stop # stop + remove injected live.js tag
+ * node /live-server.mjs stop --keep-inject # stop only
+ * node /live-server.mjs --help
+ */
+
+import http from 'node:http';
+import { randomUUID } from 'node:crypto';
+import { spawn, execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import net from 'node:net';
+import { fileURLToPath } from 'node:url';
+import { parseDesignMd } from './lib/design-parser.mjs';
+import { loadContext } from './context.mjs';
+import {
+ assembleLiveBrowserScript,
+ assertLiveBrowserScriptParts,
+ readLiveBrowserScriptParts,
+ resolveLiveBrowserScriptParts,
+} from './live/browser-script-parts.mjs';
+import { createLiveSessionStore } from './live/session-store.mjs';
+import { validateEvent } from './live/event-validation.mjs';
+import { createManualEditRoutes } from './live/manual-edit-routes.mjs';
+import { LIVE_COMMANDS } from './live/vocabulary.mjs';
+import {
+ getDesignSidecarPath,
+ getLiveDir,
+ getLiveAnnotationsDir,
+ IMPECCABLE_COMMAND_PREFIX,
+ readLiveServerInfo,
+ removeLiveServerInfo,
+ resolveDesignSidecarPath,
+ writeLiveServerInfo,
+} from './lib/impeccable-paths.mjs';
+import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
+import {
+ createManualApplyController,
+ summarizeManualApplyFailures,
+} from './live/manual-apply.mjs';
+import {
+ applyDeferredSvelteComponentAccepts,
+ removeAllSvelteComponentSessions,
+} from './live/svelte-component.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+// PRODUCT.md / DESIGN.md live wherever context.mjs resolves. The generated
+// DESIGN sidecar is project-local at .impeccable/design.json, with legacy
+// DESIGN.json fallback for existing projects.
+const PROJECT_CONTEXT = loadContext(process.cwd());
+const CONTEXT_DIR = PROJECT_CONTEXT.contextDir;
+const DESIGN_MD_PATH = PROJECT_CONTEXT.designPath
+ ? path.resolve(process.cwd(), PROJECT_CONTEXT.designPath)
+ : null;
+const DEFAULT_POLL_TIMEOUT = 600_000; // 10 min — agent re-polls on timeout anyway
+const SSE_HEARTBEAT_INTERVAL = 30_000; // keepalive ping every 30s
+
+// ---------------------------------------------------------------------------
+// Port detection
+// ---------------------------------------------------------------------------
+
+async function findOpenPort(start = 8400) {
+ return new Promise((resolve) => {
+ const srv = net.createServer();
+ srv.listen(start, '127.0.0.1', () => {
+ const port = srv.address().port;
+ srv.close(() => resolve(port));
+ });
+ srv.on('error', () => resolve(findOpenPort(start + 1)));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Session state
+// ---------------------------------------------------------------------------
+
+const state = {
+ token: null,
+ port: null,
+ sseClients: new Set(), // SSE response objects (server→browser push)
+ pendingEvents: [], // browser events waiting for agent ack ({ event, leaseUntil })
+ pendingPolls: [], // agent poll callbacks waiting for browser events
+ nextEventSeq: 1,
+ lastAgentPollingBroadcast: null,
+ exitTimer: null,
+ sessionDir: null, // per-session tmp dir for annotation screenshots
+ sessionStore: null,
+ leaseTimer: null,
+ manualEditActivity: null,
+ nextManualEditSeq: 1,
+ // Deferreds for in-flight chat-routed Apply events. Keyed by event id; each
+ // entry is resolved when the chat agent POSTs an ack carrying the batch
+ // result, or rejected when the hard timeout fires.
+ pendingApplyDeferreds: new Map(),
+ // Updated whenever a /poll long-poll request arrives or is resolved with an
+ // event. Used to detect "a chat agent is likely attached" without requiring
+ // a poll to be parked at the exact moment we dispatch.
+ lastPollAt: 0,
+ timedOutApplyIds: new Map(),
+};
+
+const CHAT_POLL_FRESHNESS_MS = 60_000;
+const POLL_LEASE_EXPIRY_TIMER_GRACE_MS = 2;
+const DEBUG_MANUAL_EDIT_EVENTS = /^(1|true|yes)$/i.test(process.env.IMPECCABLE_LIVE_DEBUG_EVENTS || '');
+
+const manualApply = createManualApplyController({
+ pendingEvents: state.pendingEvents,
+ pendingApplyDeferreds: state.pendingApplyDeferreds,
+ timedOutApplyIds: state.timedOutApplyIds,
+ enqueueEvent,
+ acknowledgePendingEvent,
+ flushPendingPolls,
+ recordManualEditActivity,
+ cwd: () => process.cwd(),
+});
+
+const manualEditRoutes = createManualEditRoutes({
+ getToken: () => state.token,
+ manualApply,
+ recordManualEditActivity,
+ getManualEditStatus,
+ chatAgentLikelyActive,
+ cwd: () => process.cwd(),
+ env: () => process.env,
+});
+
+function chatAgentLikelyActive() {
+ if (state.pendingPolls.length > 0) return true;
+ if (!state.lastPollAt) return false;
+ return Date.now() - state.lastPollAt < CHAT_POLL_FRESHNESS_MS;
+}
+
+// Cap per-annotation upload size. A full 1920×1080 PNG is typically <1 MB;
+// cap at 10 MB to guard against runaway writes from a misbehaving client.
+const MAX_ANNOTATION_BYTES = 10 * 1024 * 1024;
+
+function enqueueEvent(event) {
+ if (!event || (event.id && state.pendingEvents.some((entry) => entry.event?.id === event.id && entry.event?.type === event.type))) return;
+ state.pendingEvents.push({ event, leaseUntil: 0, seq: state.nextEventSeq++ });
+ flushPendingPolls();
+}
+
+function restorePendingEventsFromStore() {
+ if (!state.sessionStore) return;
+ for (const snapshot of state.sessionStore.listActiveSessions()) {
+ if (snapshot.pendingEvent) enqueueEvent(snapshot.pendingEvent);
+ }
+}
+
+function findAvailablePendingEvent(now = Date.now()) {
+ for (const entry of state.pendingEvents) {
+ if (entry.leaseUntil && entry.leaseUntil > now) continue;
+ return entry;
+ }
+ return null;
+}
+
+function leaseEvent(entry, leaseMs) {
+ if (!entry.event?.id) {
+ const idx = state.pendingEvents.indexOf(entry);
+ if (idx !== -1) state.pendingEvents.splice(idx, 1);
+ return entry.event;
+ }
+ entry.leaseUntil = Date.now() + leaseMs;
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return entry.event;
+}
+
+function acknowledgePendingEvent(id) {
+ if (!id) return false;
+ const idx = state.pendingEvents.findIndex((entry) => entry.event?.id === id);
+ if (idx === -1) return false;
+ const acknowledged = state.pendingEvents[idx].event;
+ state.pendingEvents.splice(idx, 1);
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return acknowledged;
+}
+
+function findPendingEventById(id) {
+ if (!id) return null;
+ const entry = state.pendingEvents.find((item) => item.event?.id === id);
+ return entry?.event || null;
+}
+
+function summarizePendingEventForStatus(entry) {
+ const event = entry.event || {};
+ const summary = {
+ id: event.id,
+ type: event.type,
+ leased: !!(entry.leaseUntil && entry.leaseUntil > Date.now()),
+ leaseUntil: entry.leaseUntil || null,
+ };
+ if (event.type === 'manual_edit_apply') {
+ summary.pageUrl = event.pageUrl || null;
+ summary.chunk = event.chunk || null;
+ summary.repair = event.repair || null;
+ summary.evidencePath = event.evidencePath || null;
+ summary.agentAction = event.agentAction || manualApply.buildAgentAction(event);
+ summary.manualApplySummary = manualApply.summarizeEvent(event, manualApply.getDeferred(event.id)?.batch || event.batch);
+ }
+ return summary;
+}
+
+function summarizeActiveSessionForClient(snapshot = {}) {
+ return {
+ id: snapshot.id,
+ phase: snapshot.phase,
+ pageUrl: snapshot.pageUrl ?? null,
+ sourceFile: snapshot.sourceFile ?? null,
+ previewFile: snapshot.previewFile ?? null,
+ previewMode: snapshot.previewMode ?? null,
+ expectedVariants: snapshot.expectedVariants ?? 0,
+ arrivedVariants: snapshot.arrivedVariants ?? 0,
+ visibleVariant: snapshot.visibleVariant ?? null,
+ checkpointRevision: snapshot.checkpointRevision ?? 0,
+ paramValues: snapshot.paramValues || {},
+ };
+}
+
+function activeSessionSummaries() {
+ if (!state.sessionStore) return [];
+ return state.sessionStore.listActiveSessions().map((snapshot) => summarizeActiveSessionForClient(snapshot));
+}
+
+function cancelQueuedAnonymousExitEvents() {
+ let removed = 0;
+ for (let i = state.pendingEvents.length - 1; i >= 0; i -= 1) {
+ const event = state.pendingEvents[i]?.event;
+ if (event?.type !== 'exit' || event.id) continue;
+ state.pendingEvents.splice(i, 1);
+ removed += 1;
+ }
+ if (removed > 0) {
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ }
+ return removed;
+}
+
+function scheduleLeaseFlush() {
+ if (state.leaseTimer) {
+ clearTimeout(state.leaseTimer);
+ state.leaseTimer = null;
+ }
+ const now = Date.now();
+ const nextLeaseUntil = state.pendingEvents
+ .map((entry) => entry.leaseUntil || 0)
+ .filter((leaseUntil) => leaseUntil > now)
+ .sort((a, b) => a - b)[0];
+ if (!nextLeaseUntil) return;
+ state.leaseTimer = setTimeout(() => {
+ state.leaseTimer = null;
+ flushPendingPolls();
+ broadcastAgentPollingIfChanged();
+ }, Math.max(0, nextLeaseUntil - now + POLL_LEASE_EXPIRY_TIMER_GRACE_MS));
+}
+
+function flushPendingPolls() {
+ let changed = false;
+ while (state.pendingPolls.length > 0) {
+ const entry = findAvailablePendingEvent();
+ if (!entry) {
+ scheduleLeaseFlush();
+ broadcastAgentPollingIfChanged();
+ return;
+ }
+ const poll = state.pendingPolls.shift();
+ poll.resolve(leaseEvent(entry, poll.leaseMs));
+ changed = true;
+ }
+ scheduleLeaseFlush();
+ if (changed) broadcastAgentPollingIfChanged();
+}
+
+function agentPollingConnected() {
+ const now = Date.now();
+ return state.pendingPolls.length > 0
+ || state.pendingEvents.some((entry) => entry.leaseUntil && entry.leaseUntil > now);
+}
+
+function broadcastAgentPollingIfChanged() {
+ const connected = agentPollingConnected();
+ if (state.lastAgentPollingBroadcast === connected) return;
+ state.lastAgentPollingBroadcast = connected;
+ broadcast({ type: 'agent_polling', connected });
+}
+
+/** Push a message to all connected SSE clients. */
+function broadcast(msg) {
+ const data = 'data: ' + JSON.stringify(msg) + '\n\n';
+ for (const res of state.sseClients) {
+ try { res.write(data); } catch { /* client gone */ }
+ }
+}
+
+function recordManualEditActivity(type, details = {}) {
+ const entry = {
+ seq: state.nextManualEditSeq++,
+ type,
+ ts: new Date().toISOString(),
+ ...details,
+ };
+ state.manualEditActivity = entry;
+ if (DEBUG_MANUAL_EDIT_EVENTS) {
+ try {
+ const filePath = path.join(getLiveDir(process.cwd()), 'manual-edit-events.jsonl');
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.appendFileSync(filePath, JSON.stringify(entry) + '\n');
+ } catch {
+ /* diagnostics are best-effort; never block live mode on observability */
+ }
+ }
+ broadcast(entry);
+ return entry;
+}
+
+function getManualEditStatus() {
+ try {
+ const { totalCount, perPage } = countPendingByPage(process.cwd());
+ return { totalCount, perPage, lastActivity: state.manualEditActivity };
+ } catch (err) {
+ return {
+ totalCount: null,
+ perPage: {},
+ lastActivity: state.manualEditActivity,
+ error: err.message,
+ };
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Load scripts
+// ---------------------------------------------------------------------------
+
+function loadBrowserScripts() {
+ // Detection script: prefer the skill-bundled detector, then fall back to
+ // source/npm package locations for local development and older installs.
+ // This one IS cached — detect.js rarely changes during a session.
+ const detectPaths = [
+ path.join(__dirname, 'detector', 'detect-antipatterns-browser.js'),
+ path.join(__dirname, '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ path.join(__dirname, '..', '..', '..', '..', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ path.join(process.cwd(), 'node_modules', 'impeccable', 'cli', 'engine', 'detect-antipatterns-browser.js'),
+ ];
+ let detectScript = '';
+ for (const p of detectPaths) {
+ try { detectScript = fs.readFileSync(p, 'utf-8'); break; } catch { /* try next */ }
+ }
+
+ // Browser script parts: DO NOT cache. Return paths so the /live.js handler
+ // can re-read every part on each request. Editing browser code during
+ // iteration should land on the next tab reload, not require a server restart.
+ const liveScriptParts = resolveLiveBrowserScriptParts(__dirname);
+ try {
+ assertLiveBrowserScriptParts(liveScriptParts);
+ } catch (err) {
+ process.stderr.write('Error: ' + err.message + '\n');
+ process.exit(1);
+ }
+
+ return { detectScript, liveScriptParts };
+}
+
+function hasProjectContext() {
+ // PRODUCT.md carries brand voice / anti-references — that's what determines
+ // whether variants are brand-aware. DESIGN.md (visual tokens) is a separate
+ // concern, surfaced by the design panel's own empty state.
+ return !!PROJECT_CONTEXT.hasProduct;
+}
+
+function statOrNull(filePath) {
+ try { return fs.statSync(filePath); } catch { return null; }
+}
+
+// HTTP request handler
+// ---------------------------------------------------------------------------
+
+function createRequestHandler({ detectScript, liveScriptParts }) {
+ return (req, res) => {
+ const url = new URL(req.url, `http://localhost:${state.port}`);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
+
+ const p = url.pathname;
+
+ // --- Scripts ---
+ if (p === '/live.js') {
+ // Re-read from disk each request so edits to live-browser.js land on
+ // the next tab reload. No-store headers prevent browser caching across
+ // sessions — during iteration, a cached old script silently breaks
+ // every subsequent session.
+ let parts;
+ try {
+ parts = readLiveBrowserScriptParts(liveScriptParts);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'text/plain' });
+ res.end('Error reading live browser scripts: ' + err.message);
+ return;
+ }
+ const body = assembleLiveBrowserScript({
+ token: state.token,
+ port: state.port,
+ vocabulary: LIVE_COMMANDS,
+ commandPrefix: IMPECCABLE_COMMAND_PREFIX,
+ parts,
+ });
+ res.writeHead(200, {
+ 'Content-Type': 'application/javascript',
+ 'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0',
+ 'Pragma': 'no-cache',
+ });
+ res.end(body);
+ return;
+ }
+ if (p === '/detect.js' || p === '/') {
+ if (!detectScript) { res.writeHead(404); res.end('Not available'); return; }
+ res.writeHead(200, { 'Content-Type': 'application/javascript' });
+ res.end(detectScript);
+ return;
+ }
+
+ // --- Vendored modern-screenshot (UMD build) ---
+ // Lazy-loaded by live.js when the user clicks Go; exposes
+ // window.modernScreenshot.domToBlob(...) for capture.
+ if (p === '/modern-screenshot.js') {
+ const vendorPath = path.join(__dirname, 'modern-screenshot.umd.js');
+ try {
+ res.writeHead(200, {
+ 'Content-Type': 'application/javascript',
+ 'Cache-Control': 'public, max-age=31536000, immutable',
+ });
+ res.end(fs.readFileSync(vendorPath));
+ } catch {
+ res.writeHead(404); res.end('Vendor script not found');
+ }
+ return;
+ }
+
+ // --- Annotation upload (browser → server, raw PNG body) ---
+ // Client generates the eventId, POSTs the PNG, then POSTs the generate
+ // event with screenshotPath already set. Keeps bytes out of the SSE/poll
+ // bridge and preserves the "one shot from the user's POV" UX.
+ if (p === '/annotation' && req.method === 'POST') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const eventId = url.searchParams.get('eventId');
+ if (!eventId || !/^[A-Za-z0-9_-]{1,64}$/.test(eventId)) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid eventId' }));
+ return;
+ }
+ if ((req.headers['content-type'] || '').toLowerCase() !== 'image/png') {
+ res.writeHead(415, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Content-Type must be image/png' }));
+ return;
+ }
+ if (!state.sessionDir) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Session dir unavailable' }));
+ return;
+ }
+ const chunks = [];
+ let total = 0;
+ let aborted = false;
+ req.on('data', (c) => {
+ if (aborted) return;
+ total += c.length;
+ if (total > MAX_ANNOTATION_BYTES) {
+ aborted = true;
+ res.writeHead(413, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Payload too large' }));
+ req.destroy();
+ return;
+ }
+ chunks.push(c);
+ });
+ req.on('end', () => {
+ if (aborted) return;
+ const absPath = path.join(state.sessionDir, eventId + '.png');
+ try {
+ fs.writeFileSync(absPath, Buffer.concat(chunks));
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Write failed: ' + err.message }));
+ return;
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, path: absPath }));
+ });
+ req.on('error', () => {
+ if (!aborted) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Upload failed' }));
+ }
+ });
+ return;
+ }
+
+ // --- Health ---
+ if (p === '/status') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Unauthorized' })); return; }
+ const sessions = activeSessionSummaries();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok',
+ port: state.port,
+ connectedClients: state.sseClients.size,
+ pendingEvents: state.pendingEvents.map((entry) => summarizePendingEventForStatus(entry)),
+ agentPolling: agentPollingConnected(),
+ activeSessions: sessions,
+ manualEdits: getManualEditStatus(),
+ }));
+ return;
+ }
+
+ if (p === '/health') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ status: 'ok', port: state.port, mode: 'variant',
+ hasProjectContext: hasProjectContext(),
+ connectedClients: state.sseClients.size,
+ }));
+ return;
+ }
+
+ // --- Design system (unified v2 response) + raw ---
+ // /design-system.json returns both parsed DESIGN.md and .impeccable/design.json
+ // sidecar when present. Panel merges them:
+ // { present, parsed, sidecar, hasMd, hasSidecar,
+ // mdNewerThanJson, parseError?, sidecarError? }
+ // - parsed: output of parseDesignMd (frontmatter
+ // + six canonical sections) when DESIGN.md exists.
+ // - sidecar: .impeccable/design.json contents when present.
+ // Expected shape: schemaVersion 2, carrying
+ // extensions + components + narrative.
+ // /design-system/raw returns DESIGN.md markdown verbatim
+ if (p === '/design-system.json' || p === '/design-system/raw') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+
+ const mdPath = DESIGN_MD_PATH;
+ const jsonPath = resolveDesignSidecarPath(process.cwd(), PROJECT_CONTEXT.designContextDir || CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
+ const mdStat = statOrNull(mdPath);
+ const jsonStat = statOrNull(jsonPath);
+
+ if (p === '/design-system/raw') {
+ if (!mdStat) { res.writeHead(404); res.end('Not found'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/markdown; charset=utf-8' });
+ res.end(fs.readFileSync(mdPath, 'utf-8'));
+ return;
+ }
+
+ if (!mdStat && !jsonStat) {
+ res.writeHead(404, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ present: false }));
+ return;
+ }
+
+ const response = {
+ present: true,
+ hasMd: !!mdStat,
+ hasSidecar: !!jsonStat,
+ mdNewerThanJson: !!(mdStat && jsonStat && mdStat.mtimeMs > jsonStat.mtimeMs + 1000),
+ };
+
+ if (mdStat) {
+ try {
+ response.parsed = parseDesignMd(fs.readFileSync(mdPath, 'utf-8'));
+ } catch (err) {
+ response.parseError = err.message;
+ }
+ }
+
+ if (jsonStat) {
+ try {
+ response.sidecar = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
+ } catch (err) {
+ response.sidecarError = 'Failed to parse .impeccable/design.json: ' + err.message;
+ }
+ }
+
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(response));
+ return;
+ }
+
+ // --- Source file (no-HMR fallback) ---
+ if (p === '/source') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ const filePath = url.searchParams.get('path');
+ if (!filePath || filePath.includes('..')) { res.writeHead(400); res.end('Bad path'); return; }
+ const absPath = path.resolve(process.cwd(), filePath);
+ if (!absPath.startsWith(process.cwd())) { res.writeHead(403); res.end('Forbidden'); return; }
+ let content;
+ try { content = fs.readFileSync(absPath, 'utf-8'); }
+ catch { res.writeHead(404); res.end('File not found'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ res.end(content);
+ return;
+ }
+
+ // --- SSE: server→browser push (replaces WebSocket) ---
+ if (p === '/events' && req.method === 'GET') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ clearTimeout(state.exitTimer);
+ state.exitTimer = null;
+ cancelQueuedAnonymousExitEvents();
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ });
+ res.write('data: ' + JSON.stringify({
+ type: 'connected',
+ hasProjectContext: hasProjectContext(),
+ agentPolling: agentPollingConnected(),
+ activeSessions: activeSessionSummaries(),
+ }) + '\n\n');
+
+ state.sseClients.add(res);
+
+ // Keepalive: SSE comment every 30s prevents silent connection drops.
+ const heartbeat = setInterval(() => {
+ try { res.write(': keepalive\n\n'); } catch { clearInterval(heartbeat); }
+ }, SSE_HEARTBEAT_INTERVAL);
+
+ req.on('close', () => {
+ clearInterval(heartbeat);
+ state.sseClients.delete(res);
+ if (state.sseClients.size === 0) {
+ clearTimeout(state.exitTimer);
+ state.exitTimer = setTimeout(() => {
+ if (state.sseClients.size === 0) enqueueEvent({ type: 'exit' });
+ }, 8000);
+ }
+ });
+ return;
+ }
+
+ if (manualEditRoutes(req, res, url)) return;
+
+ // --- Browser→server events (replaces WebSocket messages) ---
+ if (p === '/events' && req.method === 'POST') {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ // Defense in depth: manual copy edits must use the staged stash/apply
+ // endpoints. The direct Save event path is disabled in the browser.
+ if (msg.type === 'manual_edits') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'manual_edits must POST to /manual-edit-stash, not /events' }));
+ return;
+ }
+ if (msg.type === 'manual_edit_apply') {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'manual_edit_apply is disabled; use /manual-edit-stash then /manual-edit-commit' }));
+ return;
+ }
+ const error = validateEvent(msg);
+ if (error) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error }));
+ return;
+ }
+ if (state.sessionStore && msg.id) {
+ try {
+ state.sessionStore.appendEvent(msg);
+ } catch (err) {
+ res.writeHead(500, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'session_store_append_failed', message: err.message }));
+ return;
+ }
+ }
+ if (msg.type === 'exit') {
+ cleanupSvelteComponentSessionsBeforeExit();
+ }
+ if (msg.type !== 'checkpoint') {
+ enqueueEvent(msg);
+ }
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+ return;
+ }
+
+ // --- Stop ---
+ if (p === '/stop') {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.end('stopping');
+ shutdown();
+ return;
+ }
+
+ // --- Agent poll ---
+ if (p === '/poll' && req.method === 'GET') {
+ handlePollGet(req, res, url);
+ return;
+ }
+ if (p === '/poll' && req.method === 'POST') {
+ handlePollPost(req, res);
+ return;
+ }
+
+ res.writeHead(404); res.end('Not found');
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Agent poll endpoints (unchanged from WS version)
+// ---------------------------------------------------------------------------
+
+function handlePollGet(req, res, url) {
+ const token = url.searchParams.get('token');
+ if (token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ state.lastPollAt = Date.now();
+ const timeout = parseInt(url.searchParams.get('timeout') || DEFAULT_POLL_TIMEOUT, 10);
+ const leaseMs = parseInt(url.searchParams.get('leaseMs') || '30000', 10);
+ const available = findAvailablePendingEvent();
+ if (available) {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(leaseEvent(available, leaseMs)));
+ return;
+ }
+ const poll = { resolve, leaseMs };
+ const timer = setTimeout(() => {
+ const idx = state.pendingPolls.indexOf(poll);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ broadcastAgentPollingIfChanged();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ type: 'timeout' }));
+ }, timeout);
+ function resolve(event) {
+ clearTimeout(timer);
+ state.lastPollAt = Date.now();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(event));
+ }
+ state.pendingPolls.push(poll);
+ broadcastAgentPollingIfChanged();
+ scheduleLeaseFlush();
+ req.on('close', () => {
+ clearTimeout(timer);
+ const idx = state.pendingPolls.indexOf(poll);
+ if (idx !== -1) state.pendingPolls.splice(idx, 1);
+ broadcastAgentPollingIfChanged();
+ });
+}
+
+function sessionFileMetadataFromPollReply(file) {
+ if (!file || typeof file !== 'string') return { file };
+ const normalized = file.split(path.sep).join('/');
+ const base = { file: normalized };
+ if (!normalized.endsWith('/manifest.json') && normalized !== 'manifest.json') return base;
+ if (!normalized.includes('node_modules/.impeccable-live/') && !normalized.includes('src/lib/impeccable/')) return base;
+
+ let full;
+ try {
+ full = path.resolve(process.cwd(), normalized);
+ const rel = path.relative(process.cwd(), full);
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return base;
+ } catch {
+ return base;
+ }
+
+ try {
+ const manifest = JSON.parse(fs.readFileSync(full, 'utf-8'));
+ if (manifest?.previewMode !== 'svelte-component' || !manifest.sourceFile) return base;
+ return {
+ file: String(manifest.sourceFile).split(path.sep).join('/'),
+ sourceFile: String(manifest.sourceFile).split(path.sep).join('/'),
+ previewFile: normalized,
+ previewMode: 'svelte-component',
+ };
+ } catch {
+ return base;
+ }
+}
+
+function handlePollPost(req, res) {
+ let body = '';
+ req.on('data', (c) => { body += c; });
+ req.on('end', () => {
+ let msg;
+ try { msg = JSON.parse(body); } catch {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
+ return;
+ }
+ if (msg.token !== state.token) {
+ res.writeHead(401, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
+ return;
+ }
+ const pendingApplyDeferred = manualApply.getDeferred(msg.id);
+ if (pendingApplyDeferred) {
+ const validation = manualApply.validateResultMessage(msg, pendingApplyDeferred);
+ if (!validation.ok) {
+ recordManualEditActivity('manual_edit_apply_reply_invalid', {
+ id: msg.id,
+ pageUrl: pendingApplyDeferred.pageUrl,
+ chunk: pendingApplyDeferred.event?.chunk || null,
+ repair: pendingApplyDeferred.event?.repair || null,
+ reason: validation.body?.reason || validation.body?.error || 'invalid_manual_apply_result',
+ status: msg.data?.status || null,
+ });
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify(validation.body));
+ return;
+ }
+ recordManualEditActivity('manual_edit_apply_reply_received', {
+ id: msg.id,
+ pageUrl: pendingApplyDeferred.pageUrl,
+ chunk: pendingApplyDeferred.event?.chunk || null,
+ repair: pendingApplyDeferred.event?.repair || null,
+ status: validation.result.status,
+ appliedCount: validation.result.appliedEntryIds.length,
+ failed: summarizeManualApplyFailures(validation.result.failed),
+ fileCount: validation.result.files.length,
+ noteCount: validation.result.notes.length,
+ });
+ manualApply.resolveDeferred(msg.id, validation.result);
+ acknowledgePendingEvent(msg.id);
+ flushPendingPolls();
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ return;
+ }
+ if (manualApply.hasTimedOutId(msg.id)) {
+ const rollback = manualApply.rollbackTimedOutReply(msg);
+ recordManualEditActivity('manual_edit_apply_stale_reply_rejected', {
+ id: msg.id,
+ rolledBackFileCount: rollback.rolledBackFiles?.length || 0,
+ rollbackFailureCount: rollback.rollbackFailures?.length || 0,
+ });
+ res.writeHead(409, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ error: 'stale_manual_edit_apply_reply', ...rollback }));
+ return;
+ }
+ const pendingEventBeforeAck = findPendingEventById(msg.id);
+ if (pendingEventBeforeAck?.type === 'steer' && msg.type === 'steer_done'
+ && !msg.file && !(typeof msg.message === 'string' && msg.message.trim())) {
+ res.writeHead(400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ error: 'steer_done_requires_file_or_message',
+ hint: 'Reply with --file after writing source, or include a message explaining an intentional no-op.',
+ }));
+ return;
+ }
+ const acknowledgedEvent = acknowledgePendingEvent(msg.id);
+ let skipJournalReply = false;
+ let existingSession = null;
+ if (!acknowledgedEvent && state.sessionStore && msg.id) {
+ try {
+ existingSession = state.sessionStore.getSnapshot(msg.id, { includeCompleted: true });
+ if (!existingSession?.updatedAt) existingSession = null;
+ skipJournalReply = existingSession?.phase === 'completed' || existingSession?.phase === 'discarded';
+ } catch { /* fall through and record the reply normally */ }
+ }
+ if (!acknowledgedEvent && !existingSession) {
+ recordManualEditActivity('manual_edit_poll_reply_unknown', {
+ id: msg.id || null,
+ type: msg.type || null,
+ });
+ res.writeHead(msg.id ? 404 : 400, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({
+ error: msg.id ? 'unknown_poll_reply_id' : 'missing_poll_reply_id',
+ id: msg.id,
+ }));
+ return;
+ }
+ const replyFileMeta = sessionFileMetadataFromPollReply(msg.file);
+ if (state.sessionStore && msg.id && !skipJournalReply) {
+ try {
+ const eventType = msg.type === 'steer_done'
+ ? 'steer_done'
+ : msg.type === 'discard' || msg.type === 'discarded'
+ ? 'discarded'
+ : msg.type === 'complete'
+ ? 'complete'
+ : msg.type === 'error'
+ ? 'agent_error'
+ : 'agent_done';
+ state.sessionStore.appendEvent({
+ type: eventType,
+ id: msg.id,
+ file: replyFileMeta.file,
+ sourceFile: replyFileMeta.sourceFile,
+ previewFile: replyFileMeta.previewFile,
+ previewMode: replyFileMeta.previewMode,
+ message: msg.message,
+ sourceEventType: acknowledgedEvent?.type,
+ carbonize: msg.data?.carbonize === true,
+ });
+ } catch { /* keep reply path best-effort; browser still needs SSE */ }
+ }
+ flushPendingPolls();
+ // Forward the reply to the browser via SSE
+ broadcast({
+ type: msg.type || 'done',
+ id: msg.id,
+ message: msg.message,
+ file: msg.file,
+ sourceFile: replyFileMeta.sourceFile,
+ previewFile: replyFileMeta.previewFile,
+ previewMode: replyFileMeta.previewMode,
+ data: msg.data,
+ });
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ res.end(JSON.stringify({ ok: true }));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Lifecycle
+// ---------------------------------------------------------------------------
+
+let httpServer = null;
+
+function shutdown() {
+ cleanupSvelteComponentSessionsBeforeExit();
+ removeLiveServerInfo(process.cwd());
+ if (state.leaseTimer) clearTimeout(state.leaseTimer);
+ state.leaseTimer = null;
+ if (state.sessionDir) {
+ try { fs.rmSync(state.sessionDir, { recursive: true, force: true }); } catch {}
+ }
+ for (const res of state.sseClients) { try { res.end(); } catch {} }
+ state.sseClients.clear();
+ for (const poll of state.pendingPolls) poll.resolve({ type: 'exit' });
+ state.pendingPolls.length = 0;
+ if (httpServer) httpServer.close();
+ process.exit(0);
+}
+
+function cleanupSvelteComponentSessionsBeforeExit() {
+ try {
+ removeAllSvelteComponentSessions(process.cwd());
+ } catch (err) {
+ console.warn('[impeccable] Svelte component session cleanup failed:', err.message);
+ }
+}
+
+function applyLegacyDeferredAcceptsOnStartup() {
+ try {
+ const result = applyDeferredSvelteComponentAccepts(process.cwd());
+ if (result.applied > 0 || result.failed > 0) {
+ console.log('[impeccable] applied legacy deferred Svelte component accepts:', JSON.stringify(result));
+ }
+ } catch (err) {
+ console.warn('[impeccable] legacy deferred Svelte component accept apply failed:', err.message);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+const args = process.argv.slice(2);
+
+if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: node live-server.mjs [options]
+
+Start the live variant mode server (zero dependencies).
+
+Commands:
+ (default) Start the server (foreground)
+ stop Stop the server and remove the injected live.js script tag
+ stop --keep-inject Stop the server only (leave the script tag in the HTML entry)
+
+Options:
+ --background Start detached, print connection JSON to stdout, then exit
+ --port=PORT Use a specific port (default: auto-detect starting at 8400)
+ --keep-inject Only with stop: skip live-inject.mjs --remove
+ --help Show this help
+
+Endpoints:
+ /live.js Browser script (element picker + variant cycling)
+ /detect.js Detection overlay (backwards compatible)
+ /modern-screenshot.js Vendored modern-screenshot UMD build (lazy-loaded by live.js)
+ /annotation POST raw image/png to stage a variant screenshot
+ /events SSE stream (server→browser) + POST (browser→server)
+ /poll Long-poll for agent CLI
+ /manual-edit-stash Stage browser copy edits
+ /manual-edit-commit Apply staged browser copy edits
+ /manual-edit-discard Discard staged browser copy edits
+ /source Raw source file reader (no-HMR fallback)
+ /status Durable recovery status (token-protected)
+ /health Health check`);
+ process.exit(0);
+}
+
+if (args.includes('stop')) {
+ const keepInject = args.includes('--keep-inject');
+ try {
+ const { info } = readLiveServerInfo(process.cwd()) || {};
+ const res = await fetch(`http://localhost:${info.port}/stop?token=${info.token}`);
+ if (res.ok) console.log(`Stopped live server on port ${info.port}.`);
+ } catch {
+ console.log('No running live server found.');
+ }
+ if (!keepInject) {
+ const injectPath = path.join(__dirname, 'live-inject.mjs');
+ try {
+ const out = execFileSync(process.execPath, [injectPath, '--remove'], {
+ encoding: 'utf-8',
+ cwd: process.cwd(),
+ });
+ const line = out.trim().split('\n').filter(Boolean).pop();
+ if (line) {
+ try {
+ const j = JSON.parse(line);
+ if (j.removed === true) {
+ console.log(`Removed live script tag from ${j.file}.`);
+ }
+ } catch {
+ /* ignore non-JSON lines */
+ }
+ }
+ } catch (err) {
+ const detail = err.stderr?.toString?.().trim?.()
+ || err.stdout?.toString?.().trim?.()
+ || err.message
+ || String(err);
+ console.warn(`Note: could not remove live script tag (${detail.split('\n')[0]})`);
+ }
+ }
+ process.exit(0);
+}
+
+// --background: spawn a detached child server, wait for it to be ready,
+// print the connection JSON, then exit. This keeps the startup command
+// simple (no shell backgrounding or chained commands).
+if (args.includes('--background')) {
+ const childArgs = args.filter(a => a !== '--background');
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), ...childArgs], {
+ detached: true,
+ stdio: 'ignore',
+ cwd: process.cwd(),
+ });
+ child.unref();
+
+ // Poll for the PID file (the child writes it once the HTTP server is listening).
+ const deadline = Date.now() + 10_000;
+ while (Date.now() < deadline) {
+ try {
+ const { info } = readLiveServerInfo(process.cwd()) || {};
+ if (info.pid !== process.pid) {
+ // Output JSON so the agent can read port + token from stdout.
+ console.log(JSON.stringify(info));
+ process.exit(0);
+ }
+ } catch { /* not ready yet */ }
+ await new Promise(r => setTimeout(r, 200));
+ }
+ console.error('Timed out waiting for live server to start.');
+ process.exit(1);
+}
+
+// Check for existing session
+const existingRecord = readLiveServerInfo(process.cwd());
+if (existingRecord?.info) {
+ const existing = existingRecord.info;
+ try {
+ process.kill(existing.pid, 0);
+ console.error(`Live server already running on port ${existing.port} (pid ${existing.pid}).`);
+ console.error('Stop it first with: node ' + path.basename(fileURLToPath(import.meta.url)) + ' stop');
+ process.exit(1);
+ } catch {
+ try { fs.unlinkSync(existingRecord.path); } catch {}
+ }
+}
+
+state.token = randomUUID();
+state.sessionStore = createLiveSessionStore({ cwd: process.cwd() });
+manualApply.rollbackTransaction({
+ reason: 'manual_edit_server_start_recovered_abandoned_transaction',
+});
+applyLegacyDeferredAcceptsOnStartup();
+restorePendingEventsFromStore();
+manualApply.pruneStaleEvidence();
+const portArg = args.find(a => a.startsWith('--port='));
+state.port = portArg ? parseInt(portArg.split('=')[1], 10) : await findOpenPort();
+// Annotation screenshots live in the project root so the agent's Read tool
+// doesn't trip a per-file permission prompt. Sessioned by token so concurrent
+// projects (or quick restarts) don't collide.
+const annotRoot = getLiveAnnotationsDir(process.cwd());
+fs.mkdirSync(annotRoot, { recursive: true });
+state.sessionDir = fs.mkdtempSync(path.join(annotRoot, 'session-'));
+
+const { detectScript, liveScriptParts } = loadBrowserScripts();
+httpServer = http.createServer(createRequestHandler({ detectScript, liveScriptParts }));
+
+httpServer.listen(state.port, '127.0.0.1', () => {
+ writeLiveServerInfo(process.cwd(), { pid: process.pid, port: state.port, token: state.token });
+ const url = `http://localhost:${state.port}`;
+ console.log(`\nImpeccable live server running on ${url}`);
+ console.log(`Token: ${state.token}\n`);
+ console.log(`Script: ${url}/live.js`);
+ console.log('Inject: managed by live-inject.mjs; Astro source tags use is:inline automatically.');
+ console.log(`Stop: node ${path.basename(fileURLToPath(import.meta.url))} stop`);
+});
+
+process.on('SIGINT', shutdown);
+process.on('SIGTERM', shutdown);
diff --git a/.github/skills/impeccable/scripts/live-status.mjs b/.github/skills/impeccable/scripts/live-status.mjs
new file mode 100644
index 0000000..f7e4649
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-status.mjs
@@ -0,0 +1,61 @@
+#!/usr/bin/env node
+/**
+ * Print durable recovery status for Impeccable live sessions.
+ */
+
+import { createLiveSessionStore } from './live/session-store.mjs';
+import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
+import { manualApplyResumeHint } from './live-resume.mjs';
+
+function readServerInfo() {
+ return readLiveServerInfo(process.cwd())?.info || null;
+}
+
+async function fetchServerStatus(info) {
+ if (!info) return null;
+ try {
+ const res = await fetch(`http://localhost:${info.port}/status?token=${info.token}`);
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+export async function statusCli() {
+ const info = readServerInfo();
+ const server = await fetchServerStatus(info);
+ const store = createLiveSessionStore({ cwd: process.cwd() });
+ const activeSessions = store.listActiveSessions();
+ const manualApply = findPendingManualApply(server, activeSessions);
+ const payload = {
+ liveServer: server ? {
+ status: server.status,
+ port: server.port,
+ connectedClients: server.connectedClients,
+ agentPolling: server.agentPolling,
+ pendingEvents: server.pendingEvents,
+ } : null,
+ activeSessions: server?.activeSessions || activeSessions,
+ recoveryHint: manualApply
+ ? manualApplyResumeHint(manualApply)
+ : server
+ ? 'Run live-poll.mjs to continue pending work, or live-complete.mjs --id after manual cleanup.'
+ : 'Start live-server.mjs to requeue pending durable events, then run live-poll.mjs.',
+ };
+ console.log(JSON.stringify(payload, null, 2));
+}
+
+function findPendingManualApply(server, activeSessions) {
+ const fromServer = server?.pendingEvents?.find((event) => event?.type === 'manual_edit_apply');
+ if (fromServer) return fromServer;
+ const fromSession = activeSessions
+ ?.map((session) => session.pendingEvent)
+ .find((event) => event?.type === 'manual_edit_apply');
+ return fromSession || null;
+}
+
+const _running = process.argv[1];
+if (_running?.endsWith('live-status.mjs') || _running?.endsWith('live-status.mjs/')) {
+ statusCli();
+}
diff --git a/.github/skills/impeccable/scripts/live-target.mjs b/.github/skills/impeccable/scripts/live-target.mjs
new file mode 100644
index 0000000..498bc55
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-target.mjs
@@ -0,0 +1,30 @@
+import path from 'node:path';
+import { resolveProjectRoot } from './context.mjs';
+import { parseTargetPath } from './lib/target-args.mjs';
+
+export function resolveLiveTarget(cwd = process.cwd(), args = []) {
+ const originalCwd = path.resolve(cwd);
+ let targetPath = null;
+ try {
+ targetPath = parseTargetPath(args, { strict: true });
+ } catch (err) {
+ if (err?.name === 'TargetArgError') {
+ process.stderr.write(`${err.message}\n`);
+ process.exit(1);
+ }
+ throw err;
+ }
+ const absoluteTargetPath = targetPath
+ ? path.isAbsolute(targetPath) ? targetPath : path.resolve(originalCwd, targetPath)
+ : null;
+ const projectRoot = targetPath
+ ? resolveProjectRoot(originalCwd, { targetPath: absoluteTargetPath })
+ : originalCwd;
+ return {
+ originalCwd,
+ projectRoot,
+ targetPath,
+ absoluteTargetPath,
+ targetOptions: absoluteTargetPath ? { targetPath: absoluteTargetPath } : {},
+ };
+}
diff --git a/.github/skills/impeccable/scripts/live-wrap.mjs b/.github/skills/impeccable/scripts/live-wrap.mjs
new file mode 100644
index 0000000..438c01b
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live-wrap.mjs
@@ -0,0 +1,894 @@
+/**
+ * CLI helper: find an element in source and wrap it in a variant container.
+ *
+ * Usage:
+ * node /live-wrap.mjs --id SESSION_ID --count N --query "hero-combined-left" [--file path]
+ *
+ * Searches project files for the element matching the query (class name, ID, or
+ * text snippet), wraps it with the variant scaffolding, and prints the file path
+ * + line range where the agent should insert variant HTML.
+ *
+ * This replaces 3-4 agent tool calls (grep + read + edit) with a single CLI call.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { isGeneratedFile } from './lib/is-generated.mjs';
+import { readBuffer as readManualEditsBuffer } from './live/manual-edits-buffer.mjs';
+import {
+ buildSvelteComponentCssAuthoring,
+ scaffoldSvelteComponentSession,
+ shouldUseSvelteComponentInjection,
+} from './live/svelte-component.mjs';
+
+const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
+
+export async function wrapCli() {
+ const args = process.argv.slice(2);
+
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`Usage: impeccable wrap [options]
+
+Find an element in source and wrap it in a variant container.
+
+Required:
+ --id ID Session ID for the variant wrapper
+ --count N Number of expected variants (1-8)
+
+Element identification (at least one required):
+ --element-id ID HTML id attribute of the element
+ --classes A,B,C Comma- or space-separated CSS class names
+ --tag TAG Tag name (div, section, etc.)
+ --query TEXT Fallback: raw text to search for
+
+Optional:
+ --file PATH Source file to search in (skips auto-detection)
+ --text TEXT Picked element's textContent. Used to disambiguate when
+ classes/tag match multiple sibling elements (e.g. a list
+ of s with the same className). Pass the first ~80
+ chars of event.element.textContent.
+ --page-url URL Current page URL. Required when pending manual edits may
+ affect the picked source block. Pending edits are filtered
+ to this page so an edit on /a doesn't bleed into /b.
+ --help Show this help message
+
+Output (JSON):
+ { file, startLine, endLine, insertLine, commentSyntax }
+
+The agent should insert variant HTML at insertLine.`);
+ process.exit(0);
+ }
+
+ const id = argVal(args, '--id');
+ const count = parseInt(argVal(args, '--count') || '3');
+ const elementId = argVal(args, '--element-id');
+ const classes = argVal(args, '--classes');
+ const tag = argVal(args, '--tag');
+ const query = argVal(args, '--query');
+ const filePath = argVal(args, '--file');
+ const text = argVal(args, '--text');
+ const pageUrl = argVal(args, '--page-url');
+
+ if (!id) { console.error('Missing --id'); process.exit(1); }
+ if (!elementId && !classes && !query) {
+ console.error('Need at least one of: --element-id, --classes, --query');
+ process.exit(1);
+ }
+
+ // Build search queries in priority order (most specific first)
+ const queries = buildSearchQueries(elementId, classes, tag, query);
+
+ const genOpts = { cwd: process.cwd() };
+
+ // Find the source file. Generated files are excluded from auto-search so we
+ // don't silently write variants into a file the next build will wipe.
+ let targetFile = filePath;
+ let matchedQuery = null;
+ if (!targetFile) {
+ for (const q of queries) {
+ targetFile = findFileWithQuery(q, process.cwd(), genOpts);
+ if (targetFile) { matchedQuery = q; break; }
+ }
+ if (!targetFile) {
+ // Nothing in source. Did the element show up in a generated file? That
+ // tells the agent "fall back to the agent-driven flow" vs "element just
+ // doesn't exist in this project."
+ let generatedHit = null;
+ for (const q of queries) {
+ generatedHit = findFileWithQuery(q, process.cwd(), { ...genOpts, includeGenerated: true });
+ if (generatedHit) break;
+ }
+ if (generatedHit) {
+ console.error(JSON.stringify({
+ error: 'element_not_in_source',
+ fallback: 'agent-driven',
+ generatedMatch: path.relative(process.cwd(), generatedHit),
+ hint: 'Element found only in a generated file. See "Handle fallback" in live.md.',
+ }));
+ } else {
+ console.error(JSON.stringify({
+ error: 'element_not_found',
+ fallback: 'agent-driven',
+ hint: 'Element not found in any project file. It may be runtime-injected (JS component, etc.). See "Handle fallback" in live.md.',
+ }));
+ }
+ process.exit(1);
+ }
+ } else {
+ if (isGeneratedFile(targetFile, genOpts)) {
+ console.error(JSON.stringify({
+ error: 'file_is_generated',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), path.resolve(process.cwd(), targetFile)),
+ hint: 'Explicit --file points at a generated file. Writing here gets wiped by the next build. See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ matchedQuery = queries[0];
+ }
+
+ const content = fs.readFileSync(targetFile, 'utf-8');
+ const lines = content.split('\n');
+
+ // Find the element, trying each query in priority order. When `--text` is
+ // supplied, collect every candidate the queries surface and disambiguate
+ // by the picked element's textContent. Without `--text`, fall back to the
+ // legacy first-match behavior so unmodified callers keep working.
+ let match = null;
+ if (text) {
+ const candidates = [];
+ for (const q of queries) {
+ const all = findAllElements(lines, q, tag);
+ for (const c of all) {
+ if (!candidates.some((x) => x.startLine === c.startLine)) {
+ candidates.push(c);
+ }
+ }
+ // Once a more-specific query (ID, full className combo) yielded a unique
+ // result, stop — falling through to the loose tag+single-class query
+ // would readmit the siblings we just disambiguated past.
+ if (candidates.length === 1) break;
+ }
+ if (candidates.length === 0) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ if (candidates.length === 1) {
+ match = candidates[0];
+ } else {
+ const filtered = filterByText(candidates, lines, text);
+ if (filtered.length === 1) {
+ match = filtered[0];
+ } else if (filtered.length === 0) {
+ // Source uses dynamic content (`{title} ` etc.) so the
+ // browser-side textContent doesn't appear literally in source. Fall
+ // back to first-match rather than refusing — this is the same
+ // behavior unmodified callers see, just preserved.
+ match = candidates[0];
+ } else {
+ // Multiple candidates ALSO match the text. Truly ambiguous — refuse
+ // rather than pick wrong, and hand the agent the candidate locations
+ // so it can disambiguate by reading the file.
+ console.error(JSON.stringify({
+ error: 'element_ambiguous',
+ fallback: 'agent-driven',
+ file: path.relative(process.cwd(), targetFile),
+ candidates: filtered.map((c) => ({
+ startLine: c.startLine + 1,
+ endLine: c.endLine + 1,
+ })),
+ hint: 'Multiple source elements match both classes/tag and textContent. Pass --element-id, a more specific --text, or write the wrapper manually. See "Handle fallback" in live.md.',
+ }));
+ process.exit(1);
+ }
+ }
+ } else {
+ for (const q of queries) {
+ match = findElement(lines, q, tag);
+ if (match) break;
+ }
+ if (!match) {
+ console.error(JSON.stringify({ error: 'Found file but could not locate element in ' + targetFile + '. Searched for: ' + queries.join(', ') }));
+ process.exit(1);
+ }
+ }
+
+ const { startLine, endLine } = match;
+ const commentSyntax = detectCommentSyntax(targetFile);
+ const styleMode = detectStyleMode(targetFile);
+ const isJsx = commentSyntax.open === '{/*';
+ const indent = lines[startLine].match(/^(\s*)/)[1];
+
+ // Extract the original element. Reindent under the wrapper while preserving
+ // the relative depth between lines — `l.trimStart()` would strip ALL leading
+ // whitespace and collapse e.g. `` (6/8/6 spaces)
+ // to a single uniform indent, so on accept/discard the round-trip restores
+ // the inner element at its parent's depth instead of nested inside it.
+ // Strip only the COMMON minimum leading whitespace across the picked lines;
+ // `deindentContent` on the accept side already mirrors this convention.
+ let originalLines = lines.slice(startLine, endLine + 1);
+
+ // Buffer-aware "original" content: if the user has pending manual edits for
+ // this page whose originalText appears in the picked source range, apply
+ // them so the wrap block's "original" variant reflects what the user was
+ // looking at (their edited DOM), not the raw source. Source itself stays
+ // untouched here — only the wrap block's embedded "original" copy is
+ // adjusted. The pending edits remain in the buffer until committed.
+ //
+ // Apply buffered edits only when the browser provided the current page URL.
+ // Without it, fail if pending edits plausibly touch this exact source range;
+ // otherwise skip buffer awareness so unrelated staged edits on another page
+ // do not block normal wrap work.
+ let pendingBuffer = { entries: [] };
+ try { pendingBuffer = readManualEditsBuffer(process.cwd()); } catch {}
+ const pendingEntriesForTarget = pageUrl
+ ? []
+ : pendingEntriesThatMayAffectWrap(pendingBuffer.entries, targetFile, originalLines, startLine, process.cwd());
+ if (pendingEntriesForTarget.length > 0) {
+ console.error(JSON.stringify({
+ error: 'missing_page_url_with_pending_edits',
+ pendingEntries: pendingEntriesForTarget.length,
+ hint: 'Pending manual edits may affect the selected source block. Pass --page-url=$event.pageUrl so the wrap block reflects the user\'s staged DOM.',
+ }));
+ process.exit(1);
+ }
+ if (pageUrl) {
+ const failedBufferedOps = [];
+ for (const entry of pendingBuffer.entries || []) {
+ if (entry.pageUrl !== pageUrl) continue;
+ for (const op of entry.ops || []) {
+ const mayAffectWrap = manualEditMayAffectWrap(op, targetFile, originalLines, startLine, process.cwd());
+ const result = applyBufferedManualEditToLines(originalLines, startLine, op);
+ if (result.changed) {
+ originalLines = result.lines;
+ continue;
+ }
+ if (!mayAffectWrap) continue;
+ failedBufferedOps.push({
+ entryId: entry.id,
+ ref: op?.ref || null,
+ originalText: op?.originalText || null,
+ reason: 'ambiguous_or_unmatched_pending_edit',
+ });
+ }
+ }
+ if (failedBufferedOps.length > 0) {
+ console.error(JSON.stringify({
+ error: 'manual_edit_buffer_apply_failed',
+ pendingOps: failedBufferedOps,
+ hint: 'A staged copy edit appears to affect the selected source block, but could not be applied unambiguously to the wrap original. Apply or discard copy edits first, or write the wrapper manually.',
+ }));
+ process.exit(1);
+ }
+ }
+
+ const originalBaseIndent = minLeadingSpaces(originalLines);
+ const reindentOriginal = (extra) => originalLines
+ .map((l) => (l.trim() === '' ? '' : indent + extra + l.slice(originalBaseIndent)))
+ .join('\n');
+ const originalIndented = reindentOriginal(' ');
+ const relTargetFile = path.relative(process.cwd(), targetFile).split(path.sep).join('/');
+ const useSvelteComponent = shouldUseSvelteComponentInjection(targetFile);
+
+ // Wrapper attributes differ by syntax. HTML allows plain string attrs;
+ // JSX requires object-literal style and parses string attrs as HTML (which
+ // either type-errors or renders a literal CSS string).
+ const styleContents = isJsx ? 'style={{ display: "contents" }}' : 'style="display: contents"';
+
+ // JSX/TSX guard: the picked element occupies a single JSX child slot
+ // (inside `return (...)`, an array `.map(...)`, an `asChild` branch, or
+ // any other expression position). Replacing it with `comment + +
+ // comment` yields three adjacent siblings — invalid JSX. We can't use a
+ // Fragment `<>>` either: parents that clone children (Radix `asChild`,
+ // Headless UI, etc.) hit "Invalid prop supplied to React.Fragment" when
+ // they try to pass an `id` through.
+ //
+ // Solution: keep the wrapper `
` as the single JSX-slot child and
+ // tuck both marker comments INSIDE it. accept/discard then expands its
+ // replacement range to include the wrapper's `
` open / close lines
+ // so the entire scaffold gets removed cleanly.
+ const wrapperLines = isJsx ? [
+ indent + '
',
+ indent + ' ' + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + '
',
+ reindentOriginal(' '),
+ indent + '
',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + ' ' + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ indent + '
',
+ ] : [
+ indent + commentSyntax.open + ' impeccable-variants-start ' + id + ' ' + commentSyntax.close,
+ indent + '
',
+ indent + ' ' + commentSyntax.open + ' Original ' + commentSyntax.close,
+ indent + '
',
+ originalIndented,
+ indent + '
',
+ indent + ' ' + commentSyntax.open + ' Variants: insert below this line ' + commentSyntax.close,
+ indent + '
',
+ indent + commentSyntax.open + ' impeccable-variants-end ' + id + ' ' + commentSyntax.close,
+ ];
+
+ let outputFile = targetFile;
+ let outputLines;
+ let outputStartLine = startLine + 1;
+ let outputEndLine = startLine + wrapperLines.length + (originalLines.length - 1);
+ let insertLine;
+ let svelteSession = null;
+
+ if (useSvelteComponent) {
+ // Svelte/SvelteKit resets component-local state on markup HMR updates.
+ // Keep generation source-neutral: agents write real variant components
+ // under the generated componentDir, the browser mounts them into the live
+ // DOM, and live-accept.mjs inlines the accepted variant back into the route.
+ svelteSession = scaffoldSvelteComponentSession({
+ id,
+ count,
+ sourceFile: relTargetFile,
+ sourceStartLine: startLine + 1,
+ sourceEndLine: endLine + 1,
+ originalLines,
+ cwd: process.cwd(),
+ });
+ outputFile = path.resolve(process.cwd(), svelteSession.manifestFile);
+ outputStartLine = 1;
+ outputEndLine = 1;
+ insertLine = 1;
+ } else {
+ // Replace the original element with the wrapper
+ const newLines = [
+ ...lines.slice(0, startLine),
+ ...wrapperLines,
+ ...lines.slice(endLine + 1),
+ ];
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
+
+ // Calculate insert line (the "insert below this line" comment).
+ // 0-indexed file position. Both HTML and JSX wrappers have 6 lines above
+ // the insert marker (HTML: start-comment + outer-div + Original-comment +
+ // original-div + content + close-original-div; JSX: outer-div +
+ // start-comment + Original-comment + original-div + content +
+ // close-original-div). Multi-line originals push the marker by their
+ // extra line count.
+ insertLine = startLine + 6 + (originalLines.length - 1) + 1;
+ }
+
+ const outputRelFile = path.relative(process.cwd(), outputFile).split(path.sep).join('/');
+
+ const svelteComponentAuthoring = useSvelteComponent ? buildSvelteComponentCssAuthoring(count) : null;
+
+ console.log(JSON.stringify({
+ file: outputRelFile,
+ sourceFile: useSvelteComponent ? relTargetFile : undefined,
+ previewMode: useSvelteComponent ? 'svelte-component' : undefined,
+ componentDir: svelteSession?.componentDir,
+ propContract: svelteSession?.propContract,
+ sourceStartLine: useSvelteComponent ? startLine + 1 : undefined,
+ sourceEndLine: useSvelteComponent ? endLine + 1 : undefined,
+ startLine: outputStartLine, // 1-indexed for the agent
+ // wrapperLines is an array but one element (the original-content slot)
+ // is a `\n`-joined multi-line string, so the actual file-row count is
+ // wrapperLines.length + (originalLines.length - 1). Without the offset,
+ // endLine pointed inside the wrapper for any picked element that
+ // spanned more than one source line.
+ endLine: outputEndLine, // 1-indexed
+ insertLine, // 1-indexed: where variants go
+ commentSyntax: commentSyntax,
+ styleMode: useSvelteComponent ? 'svelte-component' : styleMode.mode,
+ styleTag: useSvelteComponent ? null : styleMode.styleTag,
+ cssSelectorPrefixExamples: useSvelteComponent ? [] : buildCssSelectorPrefixExamples(styleMode.mode, count),
+ cssAuthoring: useSvelteComponent ? svelteComponentAuthoring : buildCssAuthoring(styleMode, count),
+ originalLineCount: originalLines.length,
+ }));
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function argVal(args, flag) {
+ const prefix = flag + '=';
+ for (const arg of args) {
+ if (arg.startsWith(prefix)) return arg.slice(prefix.length);
+ }
+ const idx = args.indexOf(flag);
+ return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
+}
+
+function pendingEntriesThatMayAffectWrap(entries, targetFile, originalLines, selectionStartLine, cwd) {
+ const targetAbs = path.resolve(cwd, targetFile);
+ return (entries || []).filter((entry) => {
+ return (entry.ops || []).some((op) => {
+ return manualEditMayAffectWrap(op, targetAbs, originalLines, selectionStartLine, cwd);
+ });
+ });
+}
+
+function manualEditMayAffectWrap(op, targetFile, originalLines, selectionStartLine, cwd) {
+ const targetAbs = path.resolve(cwd, targetFile);
+ if (manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd)) return true;
+ if (manualEditLocatorMatchesSelection(op, originalLines)) return true;
+ if (typeof op?.originalText === 'string' && op.originalText.length > 0) {
+ return originalLines.join('\n').includes(op.originalText);
+ }
+ return false;
+}
+
+function manualEditHintFallsInsideSelection(op, targetAbs, originalLines, selectionStartLine, cwd) {
+ const hintFile = op?.sourceHint?.file;
+ const hintedLine = Number(op?.sourceHint?.line);
+ if (!hintFile || !Number.isFinite(hintedLine)) return false;
+ const hintAbs = path.isAbsolute(hintFile) ? hintFile : path.resolve(cwd, hintFile);
+ if (path.resolve(hintAbs) !== targetAbs) return false;
+ const hintedIndex = hintedLine - 1 - selectionStartLine;
+ return hintedIndex >= 0
+ && hintedIndex < originalLines.length
+ && typeof op?.originalText === 'string'
+ && originalLines[hintedIndex].includes(op.originalText);
+}
+
+function manualEditLocatorMatchesSelection(op, originalLines) {
+ if (!op || typeof op.originalText !== 'string' || op.originalText.length === 0) return false;
+ return originalLines.some((line) => (
+ line.includes(op.originalText) && lineMatchesManualEditLocator(line, op)
+ ));
+}
+
+function applyBufferedManualEditToLines(originalLines, selectionStartLine, op) {
+ if (
+ !op
+ || typeof op.originalText !== 'string'
+ || op.originalText.length === 0
+ || typeof op.newText !== 'string'
+ ) {
+ return { lines: originalLines, changed: false };
+ }
+
+ const replaceLine = (lineIndex) => ({
+ lines: originalLines.map((line, index) => (
+ index === lineIndex ? replaceOnce(line, op.originalText, op.newText) : line
+ )),
+ changed: true,
+ });
+
+ const hintedLine = Number(op.sourceHint?.line);
+ if (Number.isFinite(hintedLine)) {
+ const hintedIndex = hintedLine - 1 - selectionStartLine;
+ if (hintedIndex >= 0 && hintedIndex < originalLines.length && originalLines[hintedIndex].includes(op.originalText)) {
+ return replaceLine(hintedIndex);
+ }
+ }
+
+ const locatorMatches = [];
+ for (let index = 0; index < originalLines.length; index += 1) {
+ const line = originalLines[index];
+ if (!line.includes(op.originalText)) continue;
+ if (!lineMatchesManualEditLocator(line, op)) continue;
+ locatorMatches.push(index);
+ }
+ if (locatorMatches.length === 1) return replaceLine(locatorMatches[0]);
+
+ const originalBlock = originalLines.join('\n');
+ if (countOccurrences(originalBlock, op.originalText) === 1) {
+ return {
+ lines: replaceOnce(originalBlock, op.originalText, op.newText).split('\n'),
+ changed: true,
+ };
+ }
+
+ return { lines: originalLines, changed: false };
+}
+
+function lineMatchesManualEditLocator(line, op) {
+ if (op.tag) {
+ const tagRe = new RegExp('<\\s*' + escapeRegExp(op.tag) + '(?=[\\s>/]|$)', 'i');
+ if (!tagRe.test(line)) return false;
+ }
+
+ if (op.elementId) {
+ const id = escapeRegExp(op.elementId);
+ const idRe = new RegExp('\\bid\\s*=\\s*["\']' + id + '["\']');
+ if (!idRe.test(line)) return false;
+ }
+
+ const classes = Array.isArray(op.classes) ? op.classes.filter(Boolean) : [];
+ for (const className of classes) {
+ if (!line.includes(className)) return false;
+ }
+
+ return true;
+}
+
+function replaceOnce(value, needle, replacement) {
+ const index = value.indexOf(needle);
+ if (index === -1) return value;
+ return value.slice(0, index) + replacement + value.slice(index + needle.length);
+}
+
+function countOccurrences(value, needle) {
+ if (!needle) return 0;
+ let count = 0;
+ let index = 0;
+ while (true) {
+ index = value.indexOf(needle, index);
+ if (index === -1) return count;
+ count += 1;
+ index += needle.length;
+ }
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+/**
+ * Build search query strings in priority order (most specific first).
+ * ID is most reliable, then specific class combos, then single classes, then raw query.
+ */
+function buildSearchQueries(elementId, classes, tag, query) {
+ const queries = [];
+
+ // 1. ID is the most specific
+ if (elementId) {
+ queries.push('id="' + elementId + '"');
+ }
+
+ // 2. Full class attribute match (for elements with distinctive multi-class combos).
+ // Emit both class="..." (HTML) and className="..." (React/JSX) so whichever
+ // convention the file uses will match.
+ if (classes) {
+ const classList = splitClassList(classes);
+ if (classList.length > 1) {
+ const joined = classList.join(' ');
+ const sorted = [...classList].sort((a, b) => b.length - a.length);
+ queries.push('class="' + joined + '"');
+ queries.push('className="' + joined + '"');
+ for (const className of sorted) {
+ queries.push(className);
+ }
+ } else if (classList.length === 1) {
+ queries.push(classList[0]);
+ }
+ }
+
+ // 3. Tag + class combo (e.g.,
).
+ // Same dual-emit for JSX compatibility.
+ if (tag && classes) {
+ const firstClass = splitClassList(classes)[0];
+ queries.push('<' + tag + ' class="' + firstClass);
+ queries.push('<' + tag + ' className="' + firstClass);
+ }
+
+ // 4. Raw fallback query
+ if (query) {
+ queries.push(query);
+ }
+
+ return queries;
+}
+
+function splitClassList(classes) {
+ return String(classes).split(/[,\s]+/).map(c => c.trim()).filter(Boolean);
+}
+
+function attrEscapeDouble(str) {
+ return String(str)
+ .replace(/&/g, '&')
+ .replace(/"/g, '"')
+ .replace(//g, '>');
+}
+
+function detectCommentSyntax(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.jsx' || ext === '.tsx') {
+ return { open: '{/*', close: '*/}' };
+ }
+ // HTML, Vue, Svelte, Astro all use HTML comments
+ return { open: '' };
+}
+
+function detectStyleMode(filePath) {
+ const ext = path.extname(filePath).toLowerCase();
+ if (ext === '.astro') {
+ return {
+ mode: 'astro-global-prefixed',
+ styleTag: ' close.',
+ 'Prefix every preview selector with the matching [data-impeccable-variant="N"] selector.',
+ 'Keep selectors anchored to the generated variant wrapper; do not rely on component CSS scoping for preview rules.',
+ ],
+ forbidden: [
+ 'Do not use @scope for this styleMode.',
+ 'Do not wrap style content in a JSX/TSX template literal ({` ... `}); that syntax is for .tsx/.jsx only.',
+ 'Do not put { immediately after the style opening tag; Astro parses { as expression syntax.',
+ ],
+ };
+ }
+ return {
+ mode: styleMode.mode,
+ styleTag: styleMode.styleTag,
+ strategy: 'scope-rule',
+ rulePattern: '@scope ([data-impeccable-variant="N"]) { :scope > .variant-class { ... } }',
+ selectorExamples: variantNumbers.map((n) => `@scope ([data-impeccable-variant="${n}"]) { :scope > .variant-class { ... } }`),
+ requirements: [
+ 'Use @scope blocks keyed to each [data-impeccable-variant="N"] wrapper.',
+ 'Inside each @scope block, make :scope rules step into the replacement element with a descendant combinator.',
+ 'Use the styleTag exactly; do not add framework-specific style attributes unless this object says to.',
+ ],
+ forbidden: [
+ 'Do not use global [data-impeccable-variant="N"] selector prefixes for this styleMode.',
+ 'Do not add is:inline to the style tag for this styleMode.',
+ ],
+ };
+}
+
+/**
+ * Search project files for the query string (class name, ID, etc.)
+ * Returns the first matching file path, or null.
+ */
+function findFileWithQuery(query, cwd, genOpts = {}) {
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
+ const seen = new Set();
+
+ for (const dir of searchDirs) {
+ const absDir = path.join(cwd, dir);
+ if (!fs.existsSync(absDir)) continue;
+ const result = searchDir(absDir, query, seen, 0, genOpts);
+ if (result) return result;
+ }
+ return null;
+}
+
+function searchDir(dir, query, seen, depth, genOpts) {
+ if (depth > 5) return null; // don't go too deep
+ const realDir = fs.realpathSync(dir);
+ if (seen.has(realDir)) return null;
+ seen.add(realDir);
+
+ let entries;
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
+ catch { return null; }
+
+ // Check files first
+ for (const entry of entries) {
+ if (!entry.isFile()) continue;
+ const ext = path.extname(entry.name).toLowerCase();
+ if (!EXTENSIONS.includes(ext)) continue;
+
+ const filePath = path.join(dir, entry.name);
+ if (!genOpts.includeGenerated && isGeneratedFile(filePath, genOpts)) continue;
+ try {
+ const content = fs.readFileSync(filePath, 'utf-8');
+ if (content.includes(query)) return filePath;
+ } catch { /* skip unreadable files */ }
+ }
+
+ // Then recurse into directories. Always skip node_modules and .git (never
+ // project content). dist/build/out are left to the isGeneratedFile guard so
+ // the includeGenerated second-pass can still find the element there and
+ // report `generatedMatch`.
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name === 'node_modules' || entry.name === '.git') continue;
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1, genOpts);
+ if (result) return result;
+ }
+
+ return null;
+}
+
+/**
+ * Regex that matches a tag opener on a line. Allows the tag name to be
+ * followed by whitespace, `>`, `/`, or end-of-line so that multi-line JSX
+ * openers (e.g. ``) are recognised.
+ */
+const OPENER_RE = /<([A-Za-z][A-Za-z0-9]*)(?=[\s/>]|$)/;
+
+/**
+ * Find the element's start and end line in the file.
+ *
+ * `query` is a class name, attribute fragment (`class="..."`, `className="..."`,
+ * `id="..."`), or a raw text snippet. Because a query can appear on a
+ * continuation line of a multi-line tag (e.g. the `className="..."` row of a
+ * `` JSX tag), we walk backward from the match
+ * line to find the actual tag opener. When `tag` is provided, opener candidates
+ * must match that tag name.
+ */
+/**
+ * Return the smallest leading-whitespace count across a set of lines,
+ * ignoring blank lines (whose indent isn't load-bearing). Used to compute
+ * the common base indent of a multi-line picked element so reindenting
+ * under the wrapper preserves the relative depth between lines.
+ */
+function minLeadingSpaces(lines) {
+ let min = Infinity;
+ for (const l of lines) {
+ if (l.trim() === '') continue;
+ const m = l.match(/^(\s*)/);
+ if (m && m[1].length < min) min = m[1].length;
+ }
+ return min === Infinity ? 0 : min;
+}
+
+function findElement(lines, query, tag = null) {
+ // Iterate all matches — the first substring hit isn't always the right one.
+ for (let i = 0; i < lines.length; i++) {
+ if (!lines[i].includes(query)) continue;
+
+ const stripped = lines[i].trim();
+ if (stripped.startsWith(').
+ */
+export function extractMustacheExpressions(text) {
+ const expressions = [];
+ const seen = new Set();
+ const lines = String(text || '').split('\n');
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (trimmed.startsWith('\n`
+ : '';
+ return `${buildPropsScript(contract)}${propsComment}${originalWithProps.trim()}\n\n\n`;
+}
+
+function buildInsertVariantStub(variantNum) {
+ return `${buildPropsScript([])}Insert variant ${variantNum}
\n\n\n`;
+}
+
+export function scaffoldSvelteComponentSession({
+ id,
+ count,
+ sourceFile,
+ sourceStartLine,
+ sourceEndLine,
+ originalLines,
+ cwd = process.cwd(),
+}) {
+ ensureRuntimeHelper(cwd);
+ const dir = componentSessionDir(id, cwd);
+ fs.mkdirSync(dir, { recursive: true });
+
+ const originalMarkup = originalLines.join('\n');
+ const contract = buildPropContract(extractMustacheExpressions(originalMarkup));
+ const originalWithProps = substituteExprsWithProps(originalMarkup, contract);
+
+ const manifest = {
+ id,
+ previewMode: 'svelte-component',
+ sourceFile: sourceFile.split(path.sep).join('/'),
+ sourceStartLine,
+ sourceEndLine,
+ count,
+ propContract: contract,
+ originalMarkup,
+ componentDir: path.relative(cwd, dir).split(path.sep).join('/'),
+ runtimeModule: `/${SVELTE_RUNTIME_FILE}`,
+ };
+
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
+
+ for (let n = 1; n <= count; n++) {
+ const variantFile = path.join(dir, `v${n}.svelte`);
+ if (!fs.existsSync(variantFile)) {
+ fs.writeFileSync(variantFile, buildVariantStub(n, originalWithProps, contract), 'utf-8');
+ }
+ }
+
+ return {
+ manifest,
+ manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'),
+ componentDir: manifest.componentDir,
+ propContract: contract,
+ };
+}
+
+export function scaffoldSvelteComponentInsertSession({
+ id,
+ count,
+ sourceFile,
+ insertLine,
+ position,
+ anchorStartLine,
+ anchorEndLine,
+ anchorLines,
+ cwd = process.cwd(),
+}) {
+ ensureRuntimeHelper(cwd);
+ const dir = componentSessionDir(id, cwd);
+ fs.mkdirSync(dir, { recursive: true });
+
+ const anchorMarkup = (anchorLines || []).join('\n');
+ const manifest = {
+ id,
+ mode: 'insert',
+ previewMode: 'svelte-component',
+ sourceFile: sourceFile.split(path.sep).join('/'),
+ insertLine,
+ position,
+ anchorStartLine,
+ anchorEndLine,
+ originalMarkup: anchorMarkup,
+ anchorMarkup,
+ count,
+ propContract: [],
+ componentDir: path.relative(cwd, dir).split(path.sep).join('/'),
+ runtimeModule: `/${SVELTE_RUNTIME_FILE}`,
+ };
+
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
+
+ for (let n = 1; n <= count; n++) {
+ const variantFile = path.join(dir, `v${n}.svelte`);
+ if (!fs.existsSync(variantFile)) {
+ fs.writeFileSync(variantFile, buildInsertVariantStub(n), 'utf-8');
+ }
+ }
+
+ return {
+ manifest,
+ manifestFile: path.relative(cwd, path.join(dir, 'manifest.json')).split(path.sep).join('/'),
+ componentDir: manifest.componentDir,
+ propContract: [],
+ };
+}
+
+export function findSvelteComponentManifest(id, cwd = process.cwd()) {
+ const direct = manifestPathForSession(id, cwd);
+ if (fs.existsSync(direct)) {
+ return readManifest(direct);
+ }
+ const root = path.join(cwd, SVELTE_COMPONENT_ROOT);
+ if (!fs.existsSync(root)) return null;
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ const candidate = path.join(root, entry.name, 'manifest.json');
+ if (!fs.existsSync(candidate)) continue;
+ try {
+ const manifest = readManifest(candidate);
+ if (manifest?.id === id) return { ...manifest, manifestPath: candidate };
+ } catch { /* skip */ }
+ }
+ return null;
+}
+
+export function readManifest(manifestPath) {
+ const data = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ return {
+ ...data,
+ manifestPath,
+ };
+}
+
+export function resolveSourceFile(sourceFile, cwd = process.cwd()) {
+ if (!sourceFile || path.isAbsolute(sourceFile)) {
+ throw new Error('Invalid svelte-component source file');
+ }
+ const full = path.resolve(cwd, sourceFile);
+ const rel = path.relative(cwd, full);
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
+ throw new Error('Svelte-component source file escapes project root');
+ }
+ if (!fs.existsSync(full)) {
+ throw new Error('Svelte-component source file not found: ' + sourceFile);
+ }
+ return full;
+}
+
+function appendCssToSvelteStyle(lines, cssLines) {
+ const closeIdx = findLastStyleCloseLine(lines);
+ const prepared = ['', ...cssLines.map((line) => (line.trim() === '' ? '' : ' ' + line.trimStart()))];
+ if (closeIdx === -1) {
+ return [...lines, '', ''];
+ }
+ return [
+ ...lines.slice(0, closeIdx),
+ ...prepared,
+ ...lines.slice(closeIdx),
+ ];
+}
+
+function findLastStyleCloseLine(lines) {
+ for (let i = lines.length - 1; i >= 0; i--) {
+ if (/<\/style\s*>/.test(lines[i])) return i;
+ }
+ return -1;
+}
+
+function bakeParamValuesInCss(cssLines, paramValues) {
+ if (!paramValues || Object.keys(paramValues).length === 0) return cssLines;
+ return cssLines.map((line) => {
+ let out = line;
+ for (const [key, value] of Object.entries(paramValues)) {
+ const varName = `--p-${key}`;
+ out = out.replace(new RegExp(`var\\(${escapeRegExp(varName)}(?:,\\s*[^)]+)?\\)`, 'g'), String(value));
+ }
+ return out;
+ });
+}
+
+function sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues = null, rootTag = 'div') {
+ const css = String((cssLines || []).join('\n'));
+ if (!/data-impeccable-variant|impeccable-variant-ready/.test(css)) return cssLines;
+
+ const rules = parseCssRules(css);
+ const output = [];
+ for (const rule of rules) {
+ appendSanitizedCssRule(output, rule, variantNum, paramValues, rootTag);
+ }
+ return output.join('\n')
+ .split('\n')
+ .map((line) => line.trimEnd())
+ .filter((line) => line.trim() !== '');
+}
+
+function appendSanitizedCssRule(output, rule, variantNum, paramValues, rootTag) {
+ const prelude = rule.prelude.trim();
+ const body = rule.body.trim();
+ if (!prelude || !body || /--impeccable-variant-ready\s*:/.test(body)) return;
+
+ if (/^@scope\b/i.test(prelude)) {
+ if (/data-impeccable-variant/.test(prelude) && !selectorHasVariant(prelude, variantNum)) return;
+ const inner = parseCssRules(body);
+ for (const innerRule of inner) {
+ const rewrittenPrelude = rewriteAcceptedSvelteSelector(innerRule.prelude, variantNum, paramValues, rootTag, true);
+ if (!rewrittenPrelude || /--impeccable-variant-ready\s*:/.test(innerRule.body)) continue;
+ output.push(formatCssRule(rewrittenPrelude, innerRule.body.trim()));
+ }
+ return;
+ }
+
+ const rewrittenPrelude = rewriteAcceptedSvelteSelector(prelude, variantNum, paramValues, rootTag, false);
+ if (!rewrittenPrelude) return;
+ output.push(formatCssRule(rewrittenPrelude, body));
+}
+
+function parseCssRules(css) {
+ const rules = [];
+ const text = String(css || '');
+ let i = 0;
+ while (i < text.length) {
+ while (i < text.length && /\s/.test(text[i])) i++;
+ const preludeStart = i;
+ while (i < text.length && text[i] !== '{') i++;
+ if (i >= text.length) break;
+ const prelude = text.slice(preludeStart, i).trim();
+ i++;
+ const bodyStart = i;
+ let depth = 1;
+ let quote = null;
+ let comment = false;
+ while (i < text.length && depth > 0) {
+ const ch = text[i];
+ const next = text[i + 1];
+ if (comment) {
+ if (ch === '*' && next === '/') {
+ comment = false;
+ i += 2;
+ continue;
+ }
+ i++;
+ continue;
+ }
+ if (quote) {
+ if (ch === '\\') {
+ i += 2;
+ continue;
+ }
+ if (ch === quote) quote = null;
+ i++;
+ continue;
+ }
+ if (ch === '/' && next === '*') {
+ comment = true;
+ i += 2;
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ quote = ch;
+ i++;
+ continue;
+ }
+ if (ch === '{') depth++;
+ else if (ch === '}') depth--;
+ i++;
+ }
+ const body = text.slice(bodyStart, Math.max(bodyStart, i - 1));
+ if (prelude) rules.push({ prelude, body });
+ }
+ return rules;
+}
+
+function rewriteAcceptedSvelteSelector(prelude, variantNum, paramValues, rootTag, fromScope) {
+ const selectors = splitSelectorList(prelude);
+ const rewritten = [];
+ for (const selector of selectors) {
+ const next = rewriteAcceptedSvelteSelectorPart(selector, variantNum, paramValues, rootTag, fromScope);
+ if (next) rewritten.push(next);
+ }
+ return rewritten.join(', ');
+}
+
+function rewriteAcceptedSvelteSelectorPart(selector, variantNum, paramValues, rootTag, fromScope) {
+ let out = selector.trim();
+ const hasVariant = /data-impeccable-variant/.test(out);
+ if (hasVariant && !selectorHasVariant(out, variantNum)) return '';
+ if (hasVariant) {
+ out = out.replace(variantSelectorRegex(variantNum), '');
+ out = out.replace(/\[data-impeccable-variant=(["']).*?\1\]/g, '');
+ }
+
+ const paramResult = rewriteParamSelectors(out, paramValues);
+ if (!paramResult.keep) return '';
+ out = paramResult.selector;
+
+ out = out
+ .replace(/:scope(?:\[[^\]]+\])?\s*>\s*/g, '')
+ .replace(/:scope(?:\[[^\]]+\])?/g, rootTag || '')
+ .replace(/\s+/g, ' ')
+ .trim();
+
+ out = out.replace(/^[>+~]\s*/, '').trim();
+ if (!out && (hasVariant || fromScope)) return rootTag || ':global(*)';
+ return out;
+}
+
+function rewriteParamSelectors(selector, paramValues) {
+ let keep = true;
+ const next = selector.replace(/\[data-p-([A-Za-z0-9_-]+)(?:=(["'])(.*?)\2)?\]/g, (_match, key, _quote, expected) => {
+ if (!paramValues || !Object.prototype.hasOwnProperty.call(paramValues, key)) return '';
+ const actual = paramValues[key];
+ if (expected != null && String(actual) !== String(expected)) {
+ keep = false;
+ return '';
+ }
+ if (expected == null && (actual === false || actual == null || actual === 'false' || actual === 'off' || actual === '0')) {
+ keep = false;
+ return '';
+ }
+ return '';
+ });
+ return { keep, selector: next };
+}
+
+function splitSelectorList(prelude) {
+ const selectors = [];
+ let start = 0;
+ let bracket = 0;
+ let paren = 0;
+ let quote = null;
+ for (let i = 0; i < prelude.length; i++) {
+ const ch = prelude[i];
+ if (quote) {
+ if (ch === '\\') i++;
+ else if (ch === quote) quote = null;
+ continue;
+ }
+ if (ch === '"' || ch === "'") {
+ quote = ch;
+ continue;
+ }
+ if (ch === '[') bracket++;
+ else if (ch === ']') bracket = Math.max(0, bracket - 1);
+ else if (ch === '(') paren++;
+ else if (ch === ')') paren = Math.max(0, paren - 1);
+ else if (ch === ',' && bracket === 0 && paren === 0) {
+ selectors.push(prelude.slice(start, i));
+ start = i + 1;
+ }
+ }
+ selectors.push(prelude.slice(start));
+ return selectors;
+}
+
+function selectorHasVariant(selector, variantNum) {
+ return variantSelectorRegex(variantNum).test(selector);
+}
+
+function variantSelectorRegex(variantNum) {
+ return new RegExp(`\\[data-impeccable-variant=(["'])${escapeRegExp(String(variantNum))}\\1\\]`, 'g');
+}
+
+function formatCssRule(selector, body) {
+ return `${selector} { ${body.trim()} }`;
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+export function inlineSvelteComponentAccept(manifest, variantNum, paramValues = null, cwd = process.cwd()) {
+ const sourceFile = resolveSourceFile(manifest.sourceFile, cwd);
+ const variantPath = path.join(cwd, manifest.componentDir, `v${variantNum}.svelte`);
+ const resultBase = {
+ file: manifest.sourceFile,
+ sourceFile: manifest.sourceFile,
+ previewMode: 'svelte-component',
+ componentDir: manifest.componentDir,
+ carbonize: false,
+ };
+ if (!fs.existsSync(variantPath)) {
+ return { handled: false, error: `Variant ${variantNum} not found`, ...resultBase };
+ }
+
+ const { markup, cssLines } = parseSvelteComponentFile(fs.readFileSync(variantPath, 'utf-8'));
+ if (manifest.mode === 'insert') {
+ return inlineSvelteComponentInsertAccept({
+ manifest,
+ markup,
+ cssLines,
+ variantNum,
+ paramValues,
+ sourceFile,
+ resultBase,
+ cwd,
+ });
+ }
+
+ const rootTag = matchOpeningTag(markup)?.tag || 'div';
+ const contract = manifest.propContract || [];
+ const mergedMarkup = mergeOriginalTopLevelAttrs(markup, manifest.originalMarkup || '');
+ const restoredMarkup = substitutePropsWithExprs(mergedMarkup, contract)
+ .split('\n')
+ .map((line) => line.trimEnd());
+
+ const sourceContent = fs.readFileSync(sourceFile, 'utf-8');
+ const sourceLines = sourceContent.split('\n');
+ const start = Number(manifest.sourceStartLine) - 1;
+ const end = Number(manifest.sourceEndLine) - 1;
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end >= sourceLines.length) {
+ return { handled: false, error: 'Invalid source line range for ' + manifest.sourceFile, ...resultBase };
+ }
+
+ const indent = sourceLines[start].match(/^(\s*)/)?.[1] || '';
+ const indentedMarkup = restoredMarkup.map((line) => {
+ if (line.trim() === '') return '';
+ return indent + line.trimStart();
+ });
+
+ let newLines = [
+ ...sourceLines.slice(0, start),
+ ...indentedMarkup,
+ ...sourceLines.slice(end + 1),
+ ];
+
+ const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag);
+ const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues);
+ if (bakedCss.length > 0) {
+ newLines = appendCssToSvelteStyle(newLines, bakedCss);
+ }
+
+ try {
+ fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8');
+ } catch (err) {
+ return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase };
+ }
+ removeSvelteComponentSession(manifest.id, cwd);
+
+ return {
+ handled: true,
+ ...resultBase,
+ };
+}
+
+function inlineSvelteComponentInsertAccept({
+ manifest,
+ markup,
+ cssLines,
+ variantNum,
+ paramValues,
+ sourceFile,
+ resultBase,
+ cwd,
+}) {
+ if (!svelteMarkupHasVisibleContent(markup)) {
+ return { handled: false, error: 'Accepted Svelte insert variant is empty', ...resultBase };
+ }
+ if (/\bdata-impeccable-[\w-]*\s*=/.test(markup)) {
+ return { handled: false, error: 'Accepted Svelte insert variant contains preview-only data-impeccable attributes', ...resultBase };
+ }
+
+ const rootTag = matchOpeningTag(markup)?.tag || 'div';
+ const restoredMarkup = String(markup || '')
+ .split('\n')
+ .map((line) => line.trimEnd());
+ const sourceContent = fs.readFileSync(sourceFile, 'utf-8');
+ const sourceLines = sourceContent.split('\n');
+ const insertIndex = Number(manifest.insertLine) - 1;
+ if (!Number.isInteger(insertIndex) || insertIndex < 0 || insertIndex > sourceLines.length) {
+ return { handled: false, error: 'Invalid insert line for ' + manifest.sourceFile, ...resultBase };
+ }
+
+ const nearbyLine = sourceLines[insertIndex] ?? sourceLines[insertIndex - 1] ?? '';
+ const indent = nearbyLine.match(/^(\s*)/)?.[1] || '';
+ const indentedMarkup = restoredMarkup.map((line) => {
+ if (line.trim() === '') return '';
+ return indent + line.trimStart();
+ });
+
+ let newLines = [
+ ...sourceLines.slice(0, insertIndex),
+ ...indentedMarkup,
+ ...sourceLines.slice(insertIndex),
+ ];
+
+ const sanitizedCss = sanitizeAcceptedSvelteCss(cssLines, variantNum, paramValues, rootTag);
+ const bakedCss = bakeParamValuesInCss(sanitizedCss, paramValues);
+ if (bakedCss.length > 0) {
+ newLines = appendCssToSvelteStyle(newLines, bakedCss);
+ }
+
+ try {
+ fs.writeFileSync(sourceFile, newLines.join('\n'), 'utf-8');
+ } catch (err) {
+ return { handled: false, error: 'Failed to write Svelte source: ' + err.message, ...resultBase };
+ }
+ removeSvelteComponentSession(manifest.id, cwd);
+
+ return {
+ handled: true,
+ ...resultBase,
+ };
+}
+
+function svelteMarkupHasVisibleContent(markup) {
+ const text = String(markup || '')
+ .replace(/\n\n` + out;
+ }
+ }
+
+ if (!out.includes(SVELTE_LAYOUT_MARKER_OPEN)) {
+ const block = `${SVELTE_LAYOUT_MARKER_OPEN}\n \n${SVELTE_LAYOUT_MARKER_CLOSE}\n`;
+ const renderMatch = out.match(/\{@render\s+children(?:\?\.)?\(\)\s*\}/);
+ const slotMatch = out.match(//);
+ const match = renderMatch || slotMatch;
+ if (match) {
+ out = out.slice(0, match.index) + block + out.slice(match.index);
+ } else {
+ out = out.replace(/\s*$/, '\n\n' + block);
+ }
+ }
+
+ return out;
+}
+
+export function unpatchSvelteLayout(content) {
+ let out = String(content || '');
+ const blockRe = new RegExp(
+ '([ \\t]*)' + escapeRegExp(SVELTE_LAYOUT_MARKER_OPEN)
+ + '\\n \\n'
+ + escapeRegExp(SVELTE_LAYOUT_MARKER_CLOSE)
+ + '\\n?',
+ 'g',
+ );
+ out = out.replace(blockRe, '$1');
+ out = out.replace(new RegExp('^\\s*' + escapeRegExp(SVELTE_ROOT_IMPORT) + '\\s*\\n?', 'gm'), '');
+ out = out.replace(/
+`;
+}
+
+function findSvelteKitAppHtml(cwd, config) {
+ const files = Array.isArray(config?.files) ? config.files : ['src/app.html'];
+ for (const rel of files) {
+ if (rel.includes('*')) continue;
+ const normalized = rel.split(path.sep).join('/');
+ if (!normalized.endsWith('app.html')) continue;
+ const abs = path.join(cwd, normalized);
+ if (fs.existsSync(abs)) return normalized;
+ }
+ const fallback = 'src/app.html';
+ return fs.existsSync(path.join(cwd, fallback)) ? fallback : null;
+}
+
+function findSvelteKitLayout(cwd) {
+ const candidates = [
+ 'src/routes/+layout.svelte',
+ 'src/routes/(app)/+layout.svelte',
+ ];
+ for (const rel of candidates) {
+ if (fs.existsSync(path.join(cwd, rel))) return rel;
+ }
+ return 'src/routes/+layout.svelte';
+}
+
+function defaultSvelteLayout() {
+ return `\n\n{@render children?.()}\n`;
+}
+
+function packageHasSvelteKit(cwd) {
+ const file = path.join(cwd, 'package.json');
+ if (!fs.existsSync(file)) return false;
+ try {
+ const pkg = JSON.parse(fs.readFileSync(file, 'utf-8'));
+ const deps = {
+ ...(pkg.dependencies || {}),
+ ...(pkg.devDependencies || {}),
+ ...(pkg.peerDependencies || {}),
+ };
+ return Boolean(deps['@sveltejs/kit'] || deps['@sveltejs/vite-plugin-svelte'] || deps.svelte);
+ } catch {
+ return false;
+ }
+}
+
+function fileIncludes(file, text) {
+ try {
+ return fs.readFileSync(file, 'utf-8').includes(text);
+ } catch {
+ return false;
+ }
+}
+
+function pruneEmptyDir(dir, stopDir) {
+ let current = dir;
+ while (current.startsWith(stopDir) && current !== stopDir) {
+ try {
+ if (fs.readdirSync(current).length > 0) return;
+ fs.rmdirSync(current);
+ current = path.dirname(current);
+ } catch {
+ return;
+ }
+ }
+}
+
+function escapeRegExp(value) {
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
diff --git a/.github/skills/impeccable/scripts/live/ui-core.mjs b/.github/skills/impeccable/scripts/live/ui-core.mjs
new file mode 100644
index 0000000..bbb2c5c
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live/ui-core.mjs
@@ -0,0 +1,180 @@
+/**
+ * Framework-neutral Impeccable live chrome contract.
+ *
+ * The production browser bundle is intentionally plain DOM so Svelte, React,
+ * Vue, and static adapters can all mount the same chrome. This module is the
+ * testable contract/inventory for that bundle; live-browser.js mirrors these
+ * values at runtime because it is served as a standalone script.
+ */
+
+export const LIVE_CHROME_MOUNT_CONTRACT = Object.freeze([
+ 'root',
+ 'transport',
+ 'state',
+ 'actions',
+]);
+
+export const LIVE_UI_SURFACES = Object.freeze([
+ {
+ key: 'global-bottom-bar',
+ ids: [
+ 'impeccable-live-global-bar',
+ 'impeccable-live-global-bar-brand',
+ 'impeccable-live-pick-toggle',
+ 'impeccable-live-insert-toggle',
+ 'impeccable-live-detect-toggle',
+ 'impeccable-live-detect-badge',
+ 'impeccable-live-design-toggle',
+ 'impeccable-live-page-chat',
+ 'impeccable-live-page-chat-input',
+ 'impeccable-live-page-chat-voice',
+ ],
+ states: ['rest', 'hover', 'focus-visible', 'pressed', 'active', 'tooltip'],
+ },
+ {
+ key: 'pending-copy-edit-dock',
+ ids: ['impeccable-live-pending-dock'],
+ states: ['closed', 'open', 'hover', 'pressed', 'loading', 'rollback', 'keep-fixing'],
+ },
+ {
+ key: 'element-selection-chrome',
+ ids: [
+ 'impeccable-live-highlight',
+ 'impeccable-live-tooltip',
+ 'impeccable-live-bar',
+ 'impeccable-live-selection-pill',
+ 'impeccable-live-input',
+ 'impeccable-live-configure-voice',
+ 'impeccable-live-configure-bar-tooltip',
+ ],
+ states: ['rest', 'hover', 'focus-visible', 'pressed', 'disabled'],
+ },
+ {
+ key: 'action-picker',
+ ids: ['impeccable-live-picker'],
+ states: ['closed', 'open', 'option-hover', 'option-focus'],
+ },
+ {
+ key: 'edit-chrome',
+ ids: ['impeccable-live-edit-badge'],
+ states: ['enabled', 'disabled', 'editing', 'cancel', 'save', 'edited-content'],
+ },
+ {
+ key: 'generating-row',
+ ids: ['impeccable-live-bar', 'impeccable-live-shader'],
+ states: ['action-label', 'animated-dots', 'generating', 'done'],
+ },
+ {
+ key: 'variant-cycling-row',
+ ids: ['impeccable-live-bar', 'impeccable-live-params-panel'],
+ states: ['variant-1', 'variant-2', 'variant-3', 'left-disabled', 'right-disabled', 'dot-click', 'accept', 'discard'],
+ },
+ {
+ key: 'variant-params-panel',
+ ids: ['impeccable-live-params-panel'],
+ states: ['closed', 'open-above', 'open-below', 'range', 'steps', 'toggle'],
+ },
+ {
+ key: 'saving-confirmed-rows',
+ ids: ['impeccable-live-bar'],
+ states: ['saving', 'applying-variant', 'confirmed'],
+ },
+ {
+ key: 'insert-mode-chrome',
+ ids: [
+ 'impeccable-live-insert-line',
+ 'impeccable-live-insert-placeholder',
+ 'impeccable-live-placeholder-resize',
+ 'impeccable-live-insert-input',
+ 'impeccable-live-insert-voice',
+ 'impeccable-live-insert-create',
+ 'impeccable-live-insert-create-tooltip',
+ ],
+ states: ['toggle-active', 'line', 'placeholder', 'resize', 'enabled', 'disabled', 'tooltip'],
+ },
+ {
+ key: 'annotation-chrome',
+ ids: [
+ 'impeccable-live-annot',
+ 'impeccable-live-annot-svg',
+ 'impeccable-live-annot-pins',
+ 'impeccable-live-annot-clear',
+ ],
+ states: ['overlay', 'drawing', 'pin', 'pin-edit', 'clear'],
+ },
+ {
+ key: 'design-system-panel',
+ ids: ['impeccable-live-design-host'],
+ states: ['closed', 'open', 'tabs', 'token-tiles', 'copy'],
+ },
+ {
+ key: 'toasts-and-errors',
+ ids: ['impeccable-live-toast'],
+ states: ['normal', 'error', 'no-variants-mounted'],
+ },
+ {
+ key: 'css-isolation-boundary',
+ ids: ['impeccable-live-root'],
+ states: ['shadow-root', 'style-tags', 'hostile-css'],
+ },
+]);
+
+export const LIVE_UI_COMPONENT_IDS = Object.freeze([
+ ...new Set(LIVE_UI_SURFACES.flatMap((surface) => surface.ids)),
+]);
+
+export function resolveLiveUiRoot(env = globalThis) {
+ const doc = env?.document;
+ const explicit = env?.__IMPECCABLE_LIVE_UI_ROOT__
+ || env?.window?.__IMPECCABLE_LIVE_UI_ROOT__;
+ if (explicit && typeof explicit.appendChild === 'function') return explicit;
+ return doc?.body || null;
+}
+
+export function getLiveUiElementById(id, env = globalThis) {
+ const doc = env?.document;
+ const root = resolveLiveUiRoot(env);
+ if (!id) return null;
+ if (root?.getElementById) {
+ const found = root.getElementById(id);
+ if (found) return found;
+ }
+ if (root?.querySelector) {
+ const found = root.querySelector('#' + escapeCssIdent(id));
+ if (found) return found;
+ }
+ return doc?.getElementById?.(id) || null;
+}
+
+export function appendToLiveUiRoot(el, env = globalThis) {
+ const root = resolveLiveUiRoot(env);
+ if (!root) throw new Error('Impeccable live UI root is not available');
+ root.appendChild(el);
+ return el;
+}
+
+export function appendStyleToLiveUiRoot(styleEl, env = globalThis) {
+ const doc = env?.document;
+ const root = resolveLiveUiRoot(env);
+ if (root && root !== doc?.body) {
+ root.appendChild(styleEl);
+ } else {
+ (doc?.head || doc?.body || root).appendChild(styleEl);
+ }
+ return styleEl;
+}
+
+export function activeElementDeep(doc = globalThis.document) {
+ let active = doc?.activeElement || null;
+ while (active?.shadowRoot?.activeElement) {
+ active = active.shadowRoot.activeElement;
+ }
+ return active;
+}
+
+function escapeCssIdent(value) {
+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
+ return CSS.escape(String(value));
+ }
+ return String(value).replace(/([ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g, '\\$1');
+}
diff --git a/.github/skills/impeccable/scripts/live/vocabulary.mjs b/.github/skills/impeccable/scripts/live/vocabulary.mjs
new file mode 100644
index 0000000..5c7b0b7
--- /dev/null
+++ b/.github/skills/impeccable/scripts/live/vocabulary.mjs
@@ -0,0 +1,36 @@
+/**
+ * Canonical design-command vocabulary for Live Mode: each command's value, human
+ * label, and SVG icon. Icons stack above the chip label; strokes use currentColor
+ * so the icon recolors when its chip is selected.
+ *
+ * Single source of truth, consumed by:
+ * - skill/scripts/live/event-validation.mjs — re-exports VISUAL_ACTIONS.
+ * - skill/scripts/live-browser.js — the real picker. It is served raw and
+ * injected as an IIFE, so it cannot import this at runtime; live-server.mjs
+ * serializes LIVE_COMMANDS into window.__IMPECCABLE_VOCAB__ alongside the
+ * token/port, and live-browser.js builds its ICONS + ACTIONS from that.
+ * - site/components/LiveDemoPalette.astro — the marketing demo palette (imported
+ * at build time).
+ *
+ * Add, rename, or reorder a verb here and all three follow.
+ */
+
+const ICON_ATTRS = 'width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="display:block"';
+
+export const LIVE_COMMANDS = [
+ { value: 'impeccable', label: 'Freeform', icon: ` ` },
+ { value: 'bolder', label: 'Bolder', icon: ` ` },
+ { value: 'quieter', label: 'Quieter', icon: ` ` },
+ { value: 'distill', label: 'Distill', icon: ` ` },
+ { value: 'polish', label: 'Polish', icon: ` ` },
+ { value: 'typeset', label: 'Typeset', icon: ` ` },
+ { value: 'colorize', label: 'Colorize', icon: ` ` },
+ { value: 'layout', label: 'Layout', icon: ` ` },
+ { value: 'adapt', label: 'Adapt', icon: ` ` },
+ { value: 'animate', label: 'Animate', icon: ` ` },
+ { value: 'delight', label: 'Delight', icon: ` ` },
+ { value: 'overdrive', label: 'Overdrive', icon: ` ` },
+];
+
+// Action values accepted by the live event protocol, in palette order.
+export const VISUAL_ACTIONS = LIVE_COMMANDS.map((c) => c.value);
diff --git a/.github/skills/impeccable/scripts/modern-screenshot.umd.js b/.github/skills/impeccable/scripts/modern-screenshot.umd.js
new file mode 100644
index 0000000..a9c5208
--- /dev/null
+++ b/.github/skills/impeccable/scripts/modern-screenshot.umd.js
@@ -0,0 +1,14 @@
+(function(y,v){typeof exports=="object"&&typeof module!="undefined"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(y=typeof globalThis!="undefined"?globalThis:y||self,v(y.modernScreenshot={}))})(this,function(y){"use strict";var rr=Object.defineProperty,nr=Object.defineProperties;var or=Object.getOwnPropertyDescriptors;var Z=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,Me=Object.prototype.propertyIsEnumerable;var Oe=Math.pow,Le=(y,v,N)=>v in y?rr(y,v,{enumerable:!0,configurable:!0,writable:!0,value:N}):y[v]=N,D=(y,v)=>{for(var N in v||(v={}))xe.call(v,N)&&Le(y,N,v[N]);if(Z)for(var N of Z(v))Me.call(v,N)&&Le(y,N,v[N]);return y},M=(y,v)=>nr(y,or(v));var je=(y,v)=>{var N={};for(var R in y)xe.call(y,R)&&v.indexOf(R)<0&&(N[R]=y[R]);if(y!=null&&Z)for(var R of Z(y))v.indexOf(R)<0&&Me.call(y,R)&&(N[R]=y[R]);return N};var C=(y,v,N)=>new Promise((R,O)=>{var X=P=>{try{q(N.next(P))}catch(W){O(W)}},j=P=>{try{q(N.throw(P))}catch(W){O(W)}},q=P=>P.done?R(P.value):Promise.resolve(P.value).then(X,j);q((N=N.apply(y,v)).next())});var Be;function v(e,t){return e[13]=1,e[14]=t>>8,e[15]=t&255,e[16]=t>>8,e[17]=t&255,e}const N=112,R=72,O=89,X=115;let j;function q(){const e=new Int32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r}return e}function P(e){let t=-1;j||(j=q());for(let r=0;r>>8;return t^-1}function W(e){const t=e.length-1;for(let r=t;r>=4;r--)if(e[r-4]===9&&e[r-3]===N&&e[r-2]===R&&e[r-1]===O&&e[r]===X)return r-3;return 0}function ae(e,t,r=!1){const n=new Uint8Array(13);t*=39.3701,n[0]=N,n[1]=R,n[2]=O,n[3]=X,n[4]=t>>>24,n[5]=t>>>16,n[6]=t>>>8,n[7]=t&255,n[8]=n[4],n[9]=n[5],n[10]=n[6],n[11]=n[7],n[12]=1;const i=P(n),a=new Uint8Array(4);if(a[0]=i>>>24,a[1]=i>>>16,a[2]=i>>>8,a[3]=i&255,r){const s=W(e);return e.set(n,s),e.set(a,s+13),e}else{const s=new Uint8Array(4);s[0]=0,s[1]=0,s[2]=0,s[3]=9;const o=new Uint8Array(54);return o.set(e,0),o.set(s,33),o.set(n,37),o.set(a,50),o}}const qe="AAlwSFlz",We="AAAJcEhZ",He="AAAACXBI";function Ve(e){let t=e.indexOf(qe);return t===-1&&(t=e.indexOf(We)),t===-1&&(t=e.indexOf(He)),t}const se="[modern-screenshot]",U=typeof window!="undefined",ze=U&&"Worker"in window,ie=U&&"atob"in window,Xe=U&&"btoa"in window,ee=U?(Be=window.navigator)==null?void 0:Be.userAgent:"",le=ee.includes("Chrome"),G=ee.includes("AppleWebKit")&&!le,te=ee.includes("Firefox"),Ge=e=>e&&"__CONTEXT__"in e,Ye=e=>e.constructor.name==="CSSFontFaceRule",Je=e=>e.constructor.name==="CSSImportRule",Ke=e=>e.constructor.name==="CSSLayerBlockRule",I=e=>e.nodeType===1,H=e=>typeof e.className=="object",ce=e=>e.tagName==="image",Qe=e=>e.tagName==="use",V=e=>I(e)&&typeof e.style!="undefined"&&!H(e),Ze=e=>e.nodeType===8,et=e=>e.nodeType===3,$=e=>e.tagName==="IMG",Y=e=>e.tagName==="VIDEO",tt=e=>e.tagName==="CANVAS",rt=e=>e.tagName==="TEXTAREA",nt=e=>e.tagName==="INPUT",ot=e=>e.tagName==="STYLE",at=e=>e.tagName==="SCRIPT",st=e=>e.tagName==="SELECT",it=e=>e.tagName==="SLOT",lt=e=>e.tagName==="IFRAME",ct=(...e)=>console.warn(se,...e);function ut(e){var r;const t=(r=e==null?void 0:e.createElement)==null?void 0:r.call(e,"canvas");return t&&(t.height=t.width=1),!!t&&"toDataURL"in t&&!!t.toDataURL("image/webp").includes("image/webp")}const re=e=>e.startsWith("data:");function ue(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(U&&e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i)||!U)return e;const r=J().implementation.createHTMLDocument(),n=r.createElement("base"),i=r.createElement("a");return r.head.appendChild(n),r.body.appendChild(i),t&&(n.href=t),i.href=e,i.href}function J(e){var t;return(t=e&&I(e)?e==null?void 0:e.ownerDocument:e)!=null?t:window.document}const K="http://www.w3.org/2000/svg";function fe(e,t,r){const n=J(r).createElementNS(K,"svg");return n.setAttributeNS(null,"width",e.toString()),n.setAttributeNS(null,"height",t.toString()),n.setAttributeNS(null,"viewBox",`0 0 ${e} ${t}`),n}function de(e,t){let r=new XMLSerializer().serializeToString(e);return t&&(r=r.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"")),`data:image/svg+xml;charset=utf-8,${encodeURIComponent(r)}`}function ft(e,t="image/png",r=1){return C(this,null,function*(){try{return yield new Promise((n,i)=>{e.toBlob(a=>{a?n(a):i(new Error("Blob is null"))},t,r)})}catch(n){if(ie)return dt(e.toDataURL(t,r));throw n}})}function dt(e){var o,c;const[t,r]=e.split(","),n=(c=(o=t.match(/data:(.+);/))==null?void 0:o[1])!=null?c:void 0,i=window.atob(r),a=i.length,s=new Uint8Array(a);for(let u=0;u{const i=new FileReader;i.onload=()=>r(i.result),i.onerror=()=>n(i.error),i.onabort=()=>n(new Error(`Failed read blob to ${t}`)),t==="dataUrl"?i.readAsDataURL(e):t==="arrayBuffer"&&i.readAsArrayBuffer(e)})}const gt=e=>ge(e,"dataUrl"),mt=e=>ge(e,"arrayBuffer");function _(e,t){const r=J(t).createElement("img");return r.decoding="sync",r.loading="eager",r.src=e,r}function L(e,t){return new Promise(r=>{const{timeout:n,ownerDocument:i,onError:a,onWarn:s}=t!=null?t:{},o=typeof e=="string"?_(e,J(i)):e;let c=null,u=null;function l(){r(o),c&&clearTimeout(c),u==null||u()}if(n&&(c=setTimeout(l,n)),Y(o)){const d=o.currentSrc||o.src;if(!d)return o.poster?L(o.poster,t).then(r):l();if(o.readyState>=2)return l();const m=l,f=h=>{s==null||s("Failed video load",d,h),a==null||a(h),l()};u=()=>{o.removeEventListener("loadeddata",m),o.removeEventListener("error",f)},o.addEventListener("loadeddata",m,{once:!0}),o.addEventListener("error",f,{once:!0})}else{const d=ce(o)?o.href.baseVal:o.currentSrc||o.src;if(!d)return l();const m=()=>C(this,null,function*(){if($(o)&&"decode"in o)try{yield o.decode()}catch(h){s==null||s("Failed to decode image, trying to render anyway",o.dataset.originalSrc||d,h)}l()}),f=h=>{s==null||s("Failed image load",o.dataset.originalSrc||d,h),l()};if($(o)&&o.complete)return m();u=()=>{o.removeEventListener("load",m),o.removeEventListener("error",f)},o.addEventListener("load",m,{once:!0}),o.addEventListener("error",f,{once:!0})}})}function me(e,t){return C(this,null,function*(){V(e)&&($(e)||Y(e)?yield L(e,t):yield Promise.all(["img","video"].flatMap(r=>Array.from(e.querySelectorAll(r)).map(n=>L(n,t)))))})}const he=function(){let t=0;const r=()=>`0000${(Math.random()*Oe(36,4)<<0).toString(36)}`.slice(-4);return()=>(t+=1,`u${r()}${t}`)}();function we(e){return e==null?void 0:e.split(",").map(t=>t.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}let pe=0;function ht(e){const t=`${se}[#${pe}]`;return pe++,{time:r=>e&&console.time(`${t} ${r}`),timeEnd:r=>e&&console.timeEnd(`${t} ${r}`),warn:(...r)=>e&&ct(...r)}}function wt(e){return{cache:e?"no-cache":"force-cache"}}function k(e,t){return C(this,null,function*(){return Ge(e)?e:ye(e,M(D({},t),{autoDestruct:!0}))})}function ye(e,t){return C(this,null,function*(){var f,h,g,p,E;const{scale:r=1,workerUrl:n,workerNumber:i=1}=t||{},a=!!(t!=null&&t.debug),s=(f=t==null?void 0:t.features)!=null?f:!0,o=(h=e.ownerDocument)!=null?h:U?window.document:void 0,c=(p=(g=e.ownerDocument)==null?void 0:g.defaultView)!=null?p:U?window:void 0,u=new Map,l=M(D({width:0,height:0,quality:1,type:"image/png",scale:r,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:3e4,progress:null,debug:a,fetch:D({requestInit:wt((E=t==null?void 0:t.fetch)==null?void 0:E.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1},t==null?void 0:t.fetch),fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber:i,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1},t),{__CONTEXT__:!0,log:ht(a),node:e,ownerDocument:o,ownerWindow:c,dpi:r===1?null:96*r,svgStyleElement:be(o),svgDefsElement:o==null?void 0:o.createElementNS(K,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:ze&&n&&i?i:0})].map(()=>{try{const b=new Worker(n);return b.onmessage=w=>C(this,null,function*(){var A,F,B,$e;const{url:S,result:T}=w.data;T?(F=(A=u.get(S))==null?void 0:A.resolve)==null||F.call(A,T):($e=(B=u.get(S))==null?void 0:B.reject)==null||$e.call(B,new Error(`Error receiving message from worker: ${S}`))}),b.onmessageerror=w=>{var T,A;const{url:S}=w.data;(A=(T=u.get(S))==null?void 0:T.reject)==null||A.call(T,new Error(`Error receiving message from worker: ${S}`))},b}catch(b){return l.log.warn("Failed to new Worker",b),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[ut(o)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests:u,drawImageCount:0,tasks:[],features:s,isEnable:b=>{var w,S;return b==="restoreScrollPosition"?typeof s=="boolean"?!1:(w=s[b])!=null?w:!1:typeof s=="boolean"?s:(S=s[b])!=null?S:!0},shadowRoots:[]});l.log.time("wait until load"),yield me(e,{timeout:l.timeout,onWarn:l.log.warn}),l.log.timeEnd("wait until load");const{width:d,height:m}=pt(e,l);return l.width=d,l.height=m,l})}function be(e){if(!e)return;const t=e.createElement("style"),r=t.ownerDocument.createTextNode(`
+.______background-clip--text {
+ background-clip: text;
+ -webkit-background-clip: text;
+}
+`);return t.appendChild(r),t}function pt(e,t){let{width:r,height:n}=t;if(I(e)&&(!r||!n)){const i=e.getBoundingClientRect();r=r||i.width||Number(e.getAttribute("width"))||0,n=n||i.height||Number(e.getAttribute("height"))||0}return{width:r,height:n}}function yt(e,t){return C(this,null,function*(){const{log:r,timeout:n,drawImageCount:i,drawImageInterval:a}=t;r.time("image to canvas");const s=yield L(e,{timeout:n,onWarn:t.log.warn}),{canvas:o,context2d:c}=bt(e.ownerDocument,t),u=()=>{try{c==null||c.drawImage(s,0,0,o.width,o.height)}catch(l){t.log.warn("Failed to drawImage",l)}};if(u(),t.isEnable("fixSvgXmlDecode"))for(let l=0;l{setTimeout(()=>{c==null||c.clearRect(0,0,o.width,o.height),u(),d()},l+a)});return t.drawImageCount=0,r.timeEnd("image to canvas"),o})}function bt(e,t){const{width:r,height:n,scale:i,backgroundColor:a,maximumCanvasSize:s}=t,o=e.createElement("canvas");o.width=Math.floor(r*i),o.height=Math.floor(n*i),o.style.width=`${r}px`,o.style.height=`${n}px`,s&&(o.width>s||o.height>s)&&(o.width>s&&o.height>s?o.width>o.height?(o.height*=s/o.width,o.width=s):(o.width*=s/o.height,o.height=s):o.width>s?(o.height*=s/o.width,o.width=s):(o.width*=s/o.height,o.height=s));const c=o.getContext("2d");return c&&a&&(c.fillStyle=a,c.fillRect(0,0,o.width,o.height)),{canvas:o,context2d:c}}function Se(e,t){if(e.ownerDocument)try{const a=e.toDataURL();if(a!=="data:,")return _(a,e.ownerDocument)}catch(a){t.log.warn("Failed to clone canvas",a)}const r=e.cloneNode(!1),n=e.getContext("2d"),i=r.getContext("2d");try{return n&&i&&i.putImageData(n.getImageData(0,0,e.width,e.height),0,0),r}catch(a){t.log.warn("Failed to clone canvas",a)}return r}function St(e,t){var r;try{if((r=e==null?void 0:e.contentDocument)!=null&&r.documentElement)return ne(e.contentDocument.documentElement,t)}catch(n){t.log.warn("Failed to clone iframe",n)}return e.cloneNode(!1)}function Et(e){const t=e.cloneNode(!1);return e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),t.loading==="lazy"&&(t.loading="eager"),t}function Ct(e,t){return C(this,null,function*(){if(e.ownerDocument&&!e.currentSrc&&e.poster)return _(e.poster,e.ownerDocument);const r=e.cloneNode(!1);r.crossOrigin="anonymous",e.currentSrc&&e.currentSrc!==e.src&&(r.src=e.currentSrc);const n=r.ownerDocument;if(n){let i=!0;if(yield L(r,{onError:()=>i=!1,onWarn:t.log.warn}),!i)return e.poster?_(e.poster,e.ownerDocument):r;r.currentTime=e.currentTime,yield new Promise(s=>{r.addEventListener("seeked",s,{once:!0})});const a=n.createElement("canvas");a.width=e.offsetWidth,a.height=e.offsetHeight;try{const s=a.getContext("2d");s&&s.drawImage(r,0,0,a.width,a.height)}catch(s){return t.log.warn("Failed to clone video",s),e.poster?_(e.poster,e.ownerDocument):r}return Se(a,t)}return r})}function Tt(e,t){return tt(e)?Se(e,t):lt(e)?St(e,t):$(e)?Et(e):Y(e)?Ct(e,t):e.cloneNode(!1)}function vt(e){let t=e.sandbox;if(!t){const{ownerDocument:r}=e;try{r&&(t=r.createElement("iframe"),t.id=`__SANDBOX__${he()}`,t.width="0",t.height="0",t.style.visibility="hidden",t.style.position="fixed",r.body.appendChild(t),t.srcdoc=' ',e.sandbox=t)}catch(n){e.log.warn("Failed to getSandBox",n)}}return t}const At=["width","height","-webkit-text-fill-color"],Nt=["stroke","fill"];function Ee(e,t,r){const{defaultComputedStyles:n}=r,i=e.nodeName.toLowerCase(),a=H(e)&&i!=="svg",s=a?Nt.map(g=>[g,e.getAttribute(g)]).filter(([,g])=>g!==null):[],o=[a&&"svg",i,s.map((g,p)=>`${g}=${p}`).join(","),t].filter(Boolean).join(":");if(n.has(o))return n.get(o);const c=vt(r),u=c==null?void 0:c.contentWindow;if(!u)return new Map;const l=u==null?void 0:u.document;let d,m;a?(d=l.createElementNS(K,"svg"),m=d.ownerDocument.createElementNS(d.namespaceURI,i),s.forEach(([g,p])=>{m.setAttributeNS(null,g,p)}),d.appendChild(m)):d=m=l.createElement(i),m.textContent=" ",l.body.appendChild(d);const f=u.getComputedStyle(m,t),h=new Map;for(let g=f.length,p=0;pn.set(d,l));function s(c){const u=e.getPropertyValue(c),l=e.getPropertyPriority(c),d=c.lastIndexOf("-"),m=d>-1?c.substring(0,d):void 0;if(m){let f=a.get(m);f||(f=new Map,a.set(m,f)),f.set(c,[u,l])}t.get(c)===u&&!l||(m?i.push(m):n.set(c,[u,l]))}return n}function Rt(e,t,r,n){var d,m,f,h;const{ownerWindow:i,includeStyleProperties:a,currentParentNodeStyle:s}=n,o=t.style,c=i.getComputedStyle(e),u=Ee(e,null,n);s==null||s.forEach((g,p)=>{u.delete(p)});const l=Ce(c,u,a);l.delete("transition-property"),l.delete("all"),l.delete("d"),l.delete("content"),r&&(l.delete("position"),l.delete("margin-top"),l.delete("margin-right"),l.delete("margin-bottom"),l.delete("margin-left"),l.delete("margin-block-start"),l.delete("margin-block-end"),l.delete("margin-inline-start"),l.delete("margin-inline-end"),l.set("box-sizing",["border-box",""])),((d=l.get("background-clip"))==null?void 0:d[0])==="text"&&t.classList.add("______background-clip--text"),le&&(l.has("font-kerning")||l.set("font-kerning",["normal",""]),(((m=l.get("overflow-x"))==null?void 0:m[0])==="hidden"||((f=l.get("overflow-y"))==null?void 0:f[0])==="hidden")&&((h=l.get("text-overflow"))==null?void 0:h[0])==="ellipsis"&&e.scrollWidth===e.clientWidth&&l.set("text-overflow",["clip",""]));for(let g=o.length,p=0;p{o.setProperty(E,g,p)}),l}function It(e,t){(rt(e)||nt(e)||st(e))&&t.setAttribute("value",e.value)}const kt=["::before","::after"],Dt=["::-webkit-scrollbar","::-webkit-scrollbar-button","::-webkit-scrollbar-thumb","::-webkit-scrollbar-track","::-webkit-scrollbar-track-piece","::-webkit-scrollbar-corner","::-webkit-resizer"];function Pt(e,t,r,n,i){const{ownerWindow:a,svgStyleElement:s,svgStyles:o,currentNodeStyle:c}=n;if(!s||!a)return;function u(l){var w;const d=a.getComputedStyle(e,l);let m=d.getPropertyValue("content");if(!m||m==="none")return;i==null||i(m),m=m.replace(/(')|(")|(counter\(.+\))/g,"");const f=[he()],h=Ee(e,l,n);c==null||c.forEach((S,T)=>{h.delete(T)});const g=Ce(d,h,n.includeStyleProperties);g.delete("content"),g.delete("-webkit-locale"),((w=g.get("background-clip"))==null?void 0:w[0])==="text"&&t.classList.add("______background-clip--text");const p=[`content: '${m}';`];if(g.forEach(([S,T],A)=>{p.push(`${A}: ${S}${T?" !important":""};`)}),p.length===1)return;try{t.className=[t.className,...f].join(" ")}catch(S){n.log.warn("Failed to copyPseudoClass",S);return}const E=p.join(`
+ `);let b=o.get(E);b||(b=[],o.set(E,b)),b.push(`.${f[0]}${l}`)}kt.forEach(u),r&&Dt.forEach(u)}const Te=new Set(["symbol"]);function ve(e,t,r,n,i){return C(this,null,function*(){if(I(r)&&(ot(r)||at(r))||n.filter&&!n.filter(r))return;Te.has(t.nodeName)||Te.has(r.nodeName)?n.currentParentNodeStyle=void 0:n.currentParentNodeStyle=n.currentNodeStyle;const a=yield ne(r,n,!1,i);n.isEnable("restoreScrollPosition")&&Ut(e,a),t.appendChild(a)})}function Ae(e,t,r,n){return C(this,null,function*(){var a;let i=e.firstChild;I(e)&&e.shadowRoot&&(i=(a=e.shadowRoot)==null?void 0:a.firstChild,r.shadowRoots.push(e.shadowRoot));for(let s=i;s;s=s.nextSibling)if(!Ze(s))if(I(s)&&it(s)&&typeof s.assignedNodes=="function"){const o=s.assignedNodes();for(let c=0;ce.clientHeight||e.scrollWidth>e.clientWidth)}const p=(d=h.get("text-transform"))==null?void 0:d[0],E=we((m=h.get("font-family"))==null?void 0:m[0]),b=E?w=>{p==="uppercase"?w=w.toUpperCase():p==="lowercase"?w=w.toLowerCase():p==="capitalize"&&(w=w[0].toUpperCase()+w.substring(1)),E.forEach(S=>{let T=s.get(S);T||s.set(S,T=new Set),w.split("").forEach(A=>T.add(A))})}:void 0;return Pt(e,f,g,t,b),It(e,f),Y(e)||(yield Ae(e,f,t,b)),yield o==null?void 0:o(f),f}const c=e.cloneNode(!1);return yield Ae(e,c,t),yield o==null?void 0:o(c),c})}function Ne(e){if(e.ownerDocument=void 0,e.ownerWindow=void 0,e.svgStyleElement=void 0,e.svgDefsElement=void 0,e.svgStyles.clear(),e.defaultComputedStyles.clear(),e.sandbox){try{e.sandbox.remove()}catch(t){e.log.warn("Failed to destroyContext",t)}e.sandbox=void 0}e.workers=[],e.fontFamilies.clear(),e.fontCssTexts.clear(),e.requests.clear(),e.tasks=[],e.shadowRoots=[]}function Bt(e){const o=e,{url:t,timeout:r,responseType:n}=o,i=je(o,["url","timeout","responseType"]),a=new AbortController,s=r?setTimeout(()=>a.abort(),r):void 0;return fetch(t,D({signal:a.signal},i)).then(c=>{if(!c.ok)throw new Error("Failed fetch, not 2xx response",{cause:c});switch(n){case"arrayBuffer":return c.arrayBuffer();case"dataUrl":return c.blob().then(gt);case"text":default:return c.text()}}).finally(()=>clearTimeout(s))}function z(e,t){const{url:r,requestType:n="text",responseType:i="text",imageDom:a}=t;let s=r;const{timeout:o,acceptOfImage:c,requests:u,fetchFn:l,fetch:{requestInit:d,bypassingCache:m,placeholderImage:f},font:h,workers:g,fontFamilies:p}=e;n==="image"&&(G||te)&&e.drawImageCount++;let E=u.get(r);if(!E){m&&m instanceof RegExp&&m.test(s)&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());const b=n.startsWith("font")&&h&&h.minify,w=new Set;b&&n.split(";")[1].split(",").forEach(F=>{p.has(F)&&p.get(F).forEach(B=>w.add(B))});const S=b&&w.size,T=D({url:s,timeout:o,responseType:S?"arrayBuffer":i,headers:n==="image"?{accept:c}:void 0},d);E={type:n,resolve:void 0,reject:void 0,response:null},E.response=C(this,null,function*(){if(l&&n==="image"){const A=yield l(r);if(A)return A}return!G&&r.startsWith("http")&&g.length?new Promise((A,F)=>{g[u.size&g.length-1].postMessage(D({rawUrl:r},T)),E.resolve=A,E.reject=F}):Bt(T)}).catch(A=>{if(u.delete(r),n==="image"&&f)return e.log.warn("Failed to fetch image base64, trying to use placeholder image",s),typeof f=="string"?f:f(a);throw A}),u.set(r,E)}return E.response}function Re(e,t,r,n){return C(this,null,function*(){if(!Ie(e))return e;for(const[i,a]of $t(e,t))try{const s=yield z(r,{url:a,requestType:n?"image":"text",responseType:"dataUrl"});e=e.replace(Lt(i),`$1${s}$3`)}catch(s){r.log.warn("Failed to fetch css data url",i,s)}return e})}function Ie(e){return/url\((['"]?)([^'"]+?)\1\)/.test(e)}const ke=/url\((['"]?)([^'"]+?)\1\)/g;function $t(e,t){const r=[];return e.replace(ke,(n,i,a)=>(r.push([a,ue(a,t)]),n)),r.filter(([n])=>!re(n))}function Lt(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}const xt=["background-image","border-image-source","-webkit-border-image","-webkit-mask-image","list-style-image"];function Mt(e,t){return xt.map(r=>{const n=e.getPropertyValue(r);return!n||n==="none"?null:((G||te)&&t.drawImageCount++,Re(n,null,t,!0).then(i=>{!i||n===i||e.setProperty(r,i,e.getPropertyPriority(r))}))}).filter(Boolean)}function Ot(e,t){if($(e)){const r=e.currentSrc||e.src;if(!re(r))return[z(t,{url:r,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(n=>{n&&(e.srcset="",e.dataset.originalSrc=r,e.src=n||"")})];(G||te)&&t.drawImageCount++}else if(H(e)&&!re(e.href.baseVal)){const r=e.href.baseVal;return[z(t,{url:r,imageDom:e,requestType:"image",responseType:"dataUrl"}).then(n=>{n&&(e.dataset.originalSrc=r,e.href.baseVal=n||"")})]}return[]}function jt(e,t){var o;const{ownerDocument:r,svgDefsElement:n}=t,i=(o=e.getAttribute("href"))!=null?o:e.getAttribute("xlink:href");if(!i)return[];const[a,s]=i.split("#");if(s){const c=`#${s}`,u=t.shadowRoots.reduce((l,d)=>l!=null?l:d.querySelector(`svg ${c}`),r==null?void 0:r.querySelector(`svg ${c}`));if(a&&e.setAttribute("href",c),n!=null&&n.querySelector(c))return[];if(u)return n==null||n.appendChild(u.cloneNode(!0)),[];if(a)return[z(t,{url:a,responseType:"text"}).then(l=>{n==null||n.insertAdjacentHTML("beforeend",l)})]}return[]}function De(e,t){const{tasks:r}=t;I(e)&&(($(e)||ce(e))&&r.push(...Ot(e,t)),Qe(e)&&r.push(...jt(e,t))),V(e)&&r.push(...Mt(e.style,t)),e.childNodes.forEach(n=>{De(n,t)})}function qt(e,t){return C(this,null,function*(){const{ownerDocument:r,svgStyleElement:n,fontFamilies:i,fontCssTexts:a,tasks:s,font:o}=t;if(!(!r||!n||!i.size))if(o&&o.cssText){const c=Ue(o.cssText,t);n.appendChild(r.createTextNode(`${c}
+`))}else{const c=Array.from(r.styleSheets).filter(f=>{try{return"cssRules"in f&&!!f.cssRules.length}catch(h){return t.log.warn(`Error while reading CSS rules from ${f.href}`,h),!1}}),u=r.implementation.createHTMLDocument(""),l=u.createElement("style");u.head.appendChild(l);const d=l.sheet;yield Promise.all(c.flatMap(f=>Array.from(f.cssRules).map(h=>C(this,null,function*(){if(Je(h)){const g=h.href;let p="";try{p=yield z(t,{url:g,requestType:"text",responseType:"text"})}catch(b){t.log.warn(`Error fetch remote css import from ${g}`,b)}const E=p.replace(ke,(b,w,S)=>b.replace(S,ue(S,g)));for(const b of Ht(E))try{d.insertRule(b,d.cssRules.length)}catch(w){t.log.warn("Error inserting rule from remote css import",{rule:b,error:w})}}})))),d.cssRules.length&&c.push(d);const m=[];c.forEach(f=>{oe(f.cssRules,m)}),m.filter(f=>{var h;return Ye(f)&&Ie(f.style.getPropertyValue("src"))&&((h=we(f.style.getPropertyValue("font-family")))==null?void 0:h.some(g=>i.has(g)))}).forEach(f=>{const h=f,g=a.get(h.cssText);g?n.appendChild(r.createTextNode(`${g}
+`)):s.push(Re(h.cssText,h.parentStyleSheet?h.parentStyleSheet.href:null,t).then(p=>{p=Ue(p,t),a.set(h.cssText,p),n.appendChild(r.createTextNode(`${p}
+`))}))})}})}const Wt=/(\/\*[\s\S]*?\*\/)/g,Pe=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;function Ht(e){if(e==null)return[];const t=[];let r=e.replace(Wt,"");for(;;){const a=Pe.exec(r);if(!a)break;t.push(a[0])}r=r.replace(Pe,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let a=n.exec(r);if(a)i.lastIndex=n.lastIndex;else if(a=i.exec(r),a)n.lastIndex=i.lastIndex;else break;t.push(a[0])}return t}const Vt=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,zt=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Ue(e,t){const{font:r}=t,n=r?r==null?void 0:r.preferredFormat:void 0;return n?e.replace(zt,i=>{for(;;){const[a,,s]=Vt.exec(i)||[];if(!s)return"";if(s===n)return`src: ${a};`}}):e}function oe(e,t=[]){for(const r of Array.from(e))Ke(r)?t.push(...oe(r.cssRules)):"cssRules"in r?oe(r.cssRules,t):t.push(r);return t}const Xt=/\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;function Gt(e){return Xt.test(e.innerHTML)}function _e(e,t){return C(this,null,function*(){const r=yield k(e,t);if(I(r.node)&&H(r.node)&&!Gt(r.node))return r.node;const{ownerDocument:n,log:i,tasks:a,svgStyleElement:s,svgDefsElement:o,svgStyles:c,font:u,progress:l,autoDestruct:d,onCloneNode:m,onEmbedNode:f,onCreateForeignObjectSvg:h}=r;i.time("clone node");const g=yield ne(r.node,r,!0);if(s&&n){let S="";c.forEach((T,A)=>{S+=`${T.join(`,
+`)} {
+ ${A}
+}
+`}),s.appendChild(n.createTextNode(S))}i.timeEnd("clone node"),yield m==null?void 0:m(g),u!==!1&&I(g)&&(i.time("embed web font"),yield qt(g,r),i.timeEnd("embed web font")),i.time("embed node"),De(g,r);const p=a.length;let E=0;const b=()=>C(this,null,function*(){for(;;){const S=a.pop();if(!S)break;try{yield S}catch(T){r.log.warn("Failed to run task",T)}l==null||l(++E,p)}});l==null||l(E,p),yield Promise.all([...Array.from({length:4})].map(b)),i.timeEnd("embed node"),yield f==null?void 0:f(g);const w=Yt(g,r);return o&&w.insertBefore(o,w.children[0]),s&&w.insertBefore(s,w.children[0]),d&&Ne(r),yield h==null?void 0:h(w),w})}function Yt(e,t){const{width:r,height:n}=t,i=fe(r,n,e.ownerDocument),a=i.ownerDocument.createElementNS(i.namespaceURI,"foreignObject");return a.setAttributeNS(null,"x","0%"),a.setAttributeNS(null,"y","0%"),a.setAttributeNS(null,"width","100%"),a.setAttributeNS(null,"height","100%"),a.append(e),i.appendChild(a),i}function Q(e,t){return C(this,null,function*(){var s;const r=yield k(e,t),n=yield _e(r),i=de(n,r.isEnable("removeControlCharacter"));r.autoDestruct||(r.svgStyleElement=be(r.ownerDocument),r.svgDefsElement=(s=r.ownerDocument)==null?void 0:s.createElementNS(K,"defs"),r.svgStyles.clear());const a=_(i,n.ownerDocument);return yield yt(a,r)})}function Jt(e,t){return C(this,null,function*(){const r=yield k(e,t),{log:n,type:i,quality:a,dpi:s}=r,o=yield Q(r);n.time("canvas to blob");const c=yield ft(o,i,a);if(["image/png","image/jpeg"].includes(i)&&s){const u=yield mt(c.slice(0,33));let l=new Uint8Array(u);return i==="image/png"?l=ae(l,s):i==="image/jpeg"&&(l=v(l,s)),n.timeEnd("canvas to blob"),new Blob([l,c.slice(33)],{type:i})}return n.timeEnd("canvas to blob"),c})}function x(e,t){return C(this,null,function*(){const r=yield k(e,t),{log:n,quality:i,type:a,dpi:s}=r,o=yield Q(r);n.time("canvas to data url");let c=o.toDataURL(a,i);if(["image/png","image/jpeg"].includes(a)&&s&&ie&&Xe){const[u,l]=c.split(",");let d=0,m=!1;if(a==="image/png"){const w=Ve(l);w>=0?(d=Math.ceil((w+28)/3)*4,m=!0):d=33/3*4}else a==="image/jpeg"&&(d=18/3*4);const f=l.substring(0,d),h=l.substring(d),g=window.atob(f),p=new Uint8Array(g.length);for(let w=0;w # hash to a seed (deterministic)
+ *
+ * Env vars:
+ * IMPECCABLE_PALETTE_SEED — same as --from; useful for the eval harness
+ * to make runs reproducible.
+ */
+
+import crypto from 'node:crypto';
+
+// Seeds are inlined (129 entries, hand-curated via a tinder review of
+// ~400 candidates from ColorHunt + synthesis + Radix/brand/Pantone anchors).
+// Each carries a mood + strategy the judging model produced — surfaced as
+// hints, not commands; the brief still drives composition.
+const SEEDS = [
+ { id: "seed-200", oklch: [0.360, 0.137, 0.0],
+ mood: "Aesop apothecary shelf — oxblood bottle glass against linen, considered and unhurried",
+ strategy: "Seed is a deep desaturated red-brown that reads as brand ink itself; I push primary darker toward bottle-glass oxblood, pair with a pure white surface so the red does the work, and use a clear pale-blush accent that can carry dark text in pills." },
+ { id: "seed-000", oklch: [0.400, 0.130, 0.0],
+ mood: "oxblood leather banquette in a 1940s steakhouse — low lamplight on dark wood and burgundy",
+ strategy: "Near-black bg with the faintest red undertone lets the oxblood primary glow like lamplit leather; warm cream ink and a brass accent complete the chophouse register." },
+ { id: "seed-002", oklch: [0.450, 0.150, 0.0],
+ mood: "darkroom red light — analog photography, blood-warm safelight glow on chemical trays",
+ strategy: "Near-black surface with a deep oxblood primary lets the seed function like a safelight in a darkroom — the bg disappears so the red becomes the only emotional signal." },
+ { id: "seed-003", oklch: [0.500, 0.194, 0.0],
+ mood: "darkroom safelight — the deep oxblood glow of analog photography, chemical and contemplative",
+ strategy: "Anchored the seed as primary against pure near-black so the red reads like a single illuminated bulb in a developing room, with cool desaturated ink to evoke silver gelatin print tones." },
+ { id: "seed-004", oklch: [0.546, 0.204, 3.4],
+ mood: "midnight boudoir — velvet rose under low lamplight, perfumed and intimate",
+ strategy: "Near-black surface lets the rose seed glow like silk in shadow; a warm champagne accent provides the candle-flame counterpoint without breaking the hush." },
+ { id: "seed-005", oklch: [0.550, 0.180, 0.0],
+ mood: "smoldering vermillion at dusk — the last red ember in a blacksmith's forge, iron-rich and quietly violent",
+ strategy: "Near-black gallery surround lets the seed read as glowing forged metal; ink stays warm-off-white, accent shifts to a hotter ember orange so the primary feels like cooling steel against a fresh strike." },
+ { id: "seed-201", oklch: [0.647, 0.262, 0.3],
+ mood: "Figma plugin marketplace red — confident product-brand crimson, the kind a modern dev tool uses for a 'live' indicator or a primary CTA on a pristine docs page",
+ strategy: "Pure white surface lets a high-chroma crimson primary do all the brand work, paired with a hue-shifted warm coral accent for hierarchy without competing saturation" },
+ { id: "seed-006", oklch: [0.650, 0.160, 0.0],
+ mood: "1960s Italian cinema — Technicolor lipstick red against a darkened theater",
+ strategy: "Pure near-black surface lets a saturated cinematic red and its warm peach accent perform like film light projected in a dark room — the brand colors carry the drama, the bg disappears." },
+ { id: "seed-008", oklch: [0.520, 0.200, 10.4],
+ mood: "Negroni hour at a Milanese bar — bittersweet crimson, vermouth and amaro under low tungsten",
+ strategy: "Seed is a saturated red-crimson with cinematic weight, so I sit it on near-black to let the primary glow like backlit liquor, with a warmer amber accent acting as the citrus twist against the bitter red." },
+ { id: "seed-010", oklch: [0.563, 0.223, 11.0],
+ mood: "Negroni hour on a Milan rooftop — bittersweet crimson, aperitivo light, polished restraint",
+ strategy: "Seed is a vivid carmine-red with strong chroma, so the surface gets out of the way (pure white) and lets the primary do the aperitivo work, with a cooled garnet accent for tension." },
+ { id: "seed-202", oklch: [0.643, 0.247, 7.0],
+ mood: "Glossier brand pink — modern beauty editorial, confident and current",
+ strategy: "Pure white bg lets a saturated rose-red primary do all the brand work, paired with a deeper crimson accent for hierarchy — the Stripe/Glossier move where the color carries the mood." },
+ { id: "seed-013", oklch: [0.400, 0.130, 20.0],
+ mood: "Tuscan cellar at dusk — aged terracotta, oxidized iron, the deep red of decanted Sangiovese",
+ strategy: "Black surface lets the oxblood seed and copper accent glow like firelight on cellar stone; brand colors carry all the warmth while the room recedes." },
+ { id: "seed-014", oklch: [0.450, 0.150, 20.0],
+ mood: "smoldering tannery — oxblood leather, cured under low workshop light",
+ strategy: "Anchor the deep oxblood seed as primary against a near-black architectural ground, then lift with a single warm ember accent so the leather reads burnished rather than bloody." },
+ { id: "seed-016", oklch: [0.550, 0.180, 20.0],
+ mood: "Negroni hour on a Roman terrace — bitter campari red, vermouth, late golden light spilling on white linen",
+ strategy: "Pure white surface lets the campari-red primary do all the emotional work, paired with a deeper oxblood accent for bittersweet depth — Italian aperitivo restraint, not warmth-washed." },
+ { id: "seed-205", oklch: [0.634, 0.254, 17.6],
+ mood: "Aesop apothecary bottle — considered red-coral on a clinical white surface, the kind of brand restraint where one saturated object does all the work",
+ strategy: "Default A pure white surface lets a single coral-red primary carry the entire brand voice; accent shifts to a deeper oxblood for hierarchy without competing chroma." },
+ { id: "seed-011", oklch: [0.639, 0.207, 13.5],
+ mood: "Aperitivo hour in Milan — Campari glow on a white marble bar, crisp and effervescent",
+ strategy: "Pure white gallery backdrop lets the Campari-red primary ring like a single bitter note; ink is near-black with a whisper of warmth, accent shifts to a deeper oxblood for hierarchy without competing hues." },
+ { id: "seed-015", oklch: [0.527, 0.202, 22.7],
+ mood: "Negroni hour on a Milanese terrace — bittersweet vermillion, aperitivo glassware catching low sun",
+ strategy: "Seed becomes a saturated aperitivo-red primary against pure white so the color carries the bittersweet warmth alone, paired with a deep oxblood accent for typographic gravitas." },
+ { id: "seed-023", oklch: [0.427, 0.175, 29.2],
+ mood: "blacksmith's forge at dusk — iron heated to ember red, the deep glow of oxidized metal and quenching oil",
+ strategy: "Pure black bg lets the seed's ember-red glow radiate like hot iron in a dark forge; accent shifts to a copper-amber to suggest scaling metal and sparks, while ink stays near-white for tool-precise legibility." },
+ { id: "seed-206", oklch: [0.614, 0.234, 28.2],
+ mood: "Aesop apothecary bottle — considered red-orange on lab-white, calm utility with a single confident pigment",
+ strategy: "Pure white surface lets a saturated vermilion primary do all the brand work, paired with a deep oxblood accent for hierarchy without introducing a second hue family" },
+ { id: "seed-029", oklch: [0.665, 0.222, 25.7],
+ mood: "Negroni hour at a Milanese bar — bittersweet orange-red liqueur catching late afternoon light on polished marble",
+ strategy: "Pure white surface lets the seed's vermilion read like Campari in a glass; a deeper oxblood accent provides the bitter depth, with neutral graphite ink keeping the editorial restraint of Italian design." },
+ { id: "seed-022", oklch: [0.418, 0.155, 27.2],
+ mood: "Pompeiian red fresco — oxidized cinnabar on a museum wall, archaeological gravity",
+ strategy: "Pure black gallery surface lets the seed's iron-oxide red read as a lit artifact; accent shifts to an aged terracotta amber, so primary and accent form a fired-clay duet against neutral void." },
+ { id: "seed-024", oklch: [0.464, 0.169, 26.9],
+ mood: "Mid-century darkroom under the safelight — developer trays, oxblood leather, the quiet patience of a print emerging",
+ strategy: "Seed becomes a deep oxblood primary; surface stays pure black so the red glows like a safelight, with a warmer ember accent for hierarchy" },
+ { id: "seed-026", oklch: [0.489, 0.190, 28.3],
+ mood: "smoldering ember in a blacksmith's forge — iron-hot rust, soot, and controlled fire",
+ strategy: "Near-black soot background lets the seed's red-orange glow like heated metal; ink is bone-white, accent is a cooler tempered-steel orange that creates internal heat gradient with the primary." },
+ { id: "seed-027", oklch: [0.568, 0.208, 27.1],
+ mood: "Sicilian blood orange at golden hour — citrus rind, terracotta, sun on stucco",
+ strategy: "Seed reads as vivid blood-orange — picked pure white surface so the citrus-red primary and a deep oxblood accent do all the emotional work, like a Loro Piana editorial spread." },
+ { id: "seed-028", oklch: [0.591, 0.172, 24.0],
+ mood: "Sienna-fired ceramic studio at dusk — terracotta cooling on a wheel, hands still dusted with slip",
+ strategy: "Pure black stage lets the fired-clay primary glow like a kiln ember, with a deeper oxblood accent providing tonal weight rather than hue contrast — a monochrome warm-axis play." },
+ { id: "seed-033", oklch: [0.544, 0.169, 31.3],
+ mood: "1960s Italian terracotta workshop — fired clay, espresso, late-afternoon Mediterranean dust",
+ strategy: "Pure black ground lets the seed's burnt-sienna primary glow like a lit kiln, with a deeper oxblood accent for restrained warmth tension — the brand carries the heat, the surface stays out." },
+ { id: "seed-207", oklch: [0.564, 0.231, 29.1],
+ mood: "Aesop apothecary bottle — considered red oxide, the calm authority of a well-made object on a white shelf",
+ strategy: "Seed becomes the singular brand voice against pure white, with a deeper oxblood accent for hierarchy — the surface disappears so the red does all the speaking." },
+ { id: "seed-035", oklch: [0.663, 0.153, 32.1],
+ mood: "Aesop apothecary bottle — clay-fired warmth, considered retail",
+ strategy: "Pure white surface lets the terracotta primary do the brand work, paired with a deep umber ink and a cooler clay accent for editorial tension." },
+ { id: "seed-037", oklch: [0.590, 0.188, 35.8],
+ mood: "Aesop apothecary bottle — considered terracotta, herbalist restraint, the warmth comes from the glass not the room",
+ strategy: "Seed becomes a muted terracotta primary against pure white so the brand's warmth carries entirely through the color itself; accent shifts to a deeper umber for quiet hierarchy." },
+ { id: "seed-038", oklch: [0.652, 0.229, 34.8],
+ mood: "blown-glass furnace at dusk — molten orange iron pulled from the kiln, a craftsman's signature heat",
+ strategy: "Pure black stage so the seed reads as live ember; primary holds the seed's heat, accent shifts to a brass-amber a hue-step away for a 1.7+ contrast pairing without leaving the fire." },
+ { id: "seed-039", oklch: [0.653, 0.185, 33.5],
+ mood: "Aesop apothecary bottle — considered terracotta, quiet retail craft",
+ strategy: "Seed becomes a grounded clay primary against pure white, paired with a deeper umber accent so the warmth lives entirely in the brand marks, not the surface." },
+ { id: "seed-167", oklch: [0.495, 0.134, 36.0],
+ mood: "Aesop apothecary shelf — burnished terracotta on clinical white, considered craft pharmacy",
+ strategy: "Treat the seed as a brand-carrying burnt-sienna against a pure paper-white surface so the warmth lives entirely in the primary, with a deep umber accent pulled along the same warm axis for typographic gravity." },
+ { id: "seed-147", oklch: [0.500, 0.151, 40.0],
+ mood: "Aesop apothecary shelf — considered terracotta, pharmacy restraint, the brand color does the work against clinical white",
+ strategy: "Anchor the seed's burnt-sienna primary against a pure white surface so the rust speaks alone, with a deep umber ink and a cooler clay accent to give the palette product-brand discipline rather than environmental warmth." },
+ { id: "seed-040", oklch: [0.660, 0.201, 40.0],
+ mood: "Aesop apothecary bottle — amber glass on a clean dispensary shelf, considered and clinical-warm",
+ strategy: "Seed becomes a burnt-amber primary against pure white so the bottle-glass color does the emotional work; accent shifts to a deep olive-bronze for the apothecary-label pairing." },
+ { id: "seed-041", oklch: [0.673, 0.217, 38.6],
+ mood: "Aesop apothecary shelf — considered orange glass, clinical retail restraint",
+ strategy: "Pure white surface lets the burnt-orange primary do all the brand work, with a deep ink-brown for editorial gravity and a muted clay accent that reads as a sibling, not a contrast." },
+ { id: "seed-042", oklch: [0.688, 0.133, 35.8],
+ mood: "Aesop apothecary shelf — terracotta glass, considered retail",
+ strategy: "Seed becomes a warm clay primary against pure white so the bottle-on-marble retail feel comes from the brand color alone; a deeper umber accent gives the label-print contrast." },
+ { id: "seed-043", oklch: [0.781, 0.119, 38.1],
+ mood: "Aesop apothecary catalogue — considered terracotta, dermatological restraint, the warm color doing all the work against clinical white",
+ strategy: "Pure white surface lets the seed's warm clay tone read as the entire brand voice, paired with a deeper umber accent for hierarchy without competing with the primary's warmth." },
+ { id: "seed-168", oklch: [0.400, 0.103, 50.0],
+ mood: "Aesop apothecary bottle — amber glass on a clinical white shelf, considered and pharmaceutical",
+ strategy: "Pure white surface lets the deep amber primary act like tinted glass against a clean shelf; accent is a muted clay that complements without competing, keeping the brand quiet and product-led." },
+ { id: "seed-044", oklch: [0.568, 0.149, 45.9],
+ mood: "1970s desert highway at golden hour — sun-faded terracotta, denim dust, the warmth of a Polaroid pulled from a glovebox",
+ strategy: "Seed becomes a burnt-sienna primary against pure white so the terracotta does all the emotional work; a deep indigo accent acts as the denim shadow opposing the sun, creating the era's signature warm/cool tension without tinting the page." },
+ { id: "seed-045", oklch: [0.607, 0.163, 47.7],
+ mood: "Aesop apothecary shelf — considered amber glass, clinical restraint, craft pharmacy",
+ strategy: "Pure white bg lets the burnt-amber primary do the apothecary work alone, paired with a deeper umber accent and graphite ink for editorial calm." },
+ { id: "seed-046", oklch: [0.653, 0.175, 45.0],
+ mood: "Aesop apothecary shelf — considered amber glass, quiet luxury, restrained craft",
+ strategy: "Pure black backdrop lets the warm amber primary glow like backlit apothecary glass, with a deeper rust accent providing tonal depth in the same hue family — monochromatic warm against neutral void." },
+ { id: "seed-047", oklch: [0.695, 0.205, 43.2],
+ mood: "Aesop apothecary label — sun-warmed amber glass on a clinical countertop, restrained botanical pharmacy",
+ strategy: "Pure white surface lets the burnt-amber primary and a deeper sienna accent do all the brand work, like an apothecary bottle photographed under daylight." },
+ { id: "seed-051", oklch: [0.704, 0.189, 49.0],
+ mood: "blacksmith's forge at dusk — glowing iron, hammered copper, ember light against cooling steel",
+ strategy: "Pure near-black surface lets the seed's molten orange burn like heated metal; accent shifts to a deeper amber-red to suggest the cooling end of the same iron, while ink stays a clean off-white so type reads like chalk on slate." },
+ { id: "seed-171", oklch: [0.550, 0.124, 60.0],
+ mood: "Klim Type Foundry specimen page — considered ochre on paper, design-school-honest",
+ strategy: "Seed becomes a muted ochre primary on pure white; accent is a deep ink-navy pulled across the wheel for editorial contrast without warmth-pooling in the bg" },
+ { id: "seed-148", oklch: [0.650, 0.146, 60.0],
+ mood: "Klim-style editorial gold — late-afternoon paper light on a serif specimen sheet, considered and dry",
+ strategy: "Hold the seed's amber as primary on a pure white page so the gold reads as ink rather than atmosphere, and pair with a deep aubergine accent for typographic contrast." },
+ { id: "seed-052", oklch: [0.700, 0.130, 60.0],
+ mood: "late-afternoon terracotta studio — sun-warmed clay, hands-on craft, the hour before dusk",
+ strategy: "Seed is a saturated amber-ochre with strong environmental association (ceramics, adobe, sunlit plaster), so I lean into Exception (a) with a faintly warm bone surface that reads as lime-washed wall, then deepen the seed slightly for primary and pair it with a fired-clay rust accent for hand-thrown warmth." },
+ { id: "seed-053", oklch: [0.773, 0.157, 56.6],
+ mood: "late-summer apricot orchard at golden hour — sun-warmed fruit, considered Californian craft",
+ strategy: "Seed is a juicy mid-warm orange at daylight luminance — leaning optimistic/editorial, so pure white surface lets the apricot primary glow without muddying it; a deep wine accent provides the bite." },
+ { id: "seed-149", oklch: [0.600, 0.124, 70.0],
+ mood: "1970s desert highway — late-afternoon amber light on chrome and asphalt",
+ strategy: "Anchor the amber seed as primary against pure black so the warm hue reads as headlight glow against night; a cooler dusk-mauve accent provides the complementary tension of horizon vs. sun." },
+ { id: "seed-054", oklch: [0.740, 0.162, 68.1],
+ mood: "late-afternoon honey on terracotta — Mediterranean stucco at golden hour, sun-baked amber",
+ strategy: "Seed is a saturated honey-amber at high lightness; pairing it with pure black lets the warmth read as luminous gold against gravity, like lamplight in a dark room." },
+ { id: "seed-055", oklch: [0.774, 0.174, 65.1],
+ mood: "late-summer honey hour — amber light slanting through a west-facing window, optimistic and golden",
+ strategy: "Anchor a saturated honey-amber primary on pure white so the warmth radiates from the brand itself, then pair with a deep teak accent for grounded contrast rather than tinting the canvas." },
+ { id: "seed-056", oklch: [0.691, 0.146, 74.6],
+ mood: "Klim-style modern publishing house — late-afternoon paper warmth, considered editorial gold",
+ strategy: "Pure white surface so the amber seed becomes the brand voice; ink stays near-black neutral and accent shifts to a deep ink-blue to give the gold something structural to lean on." },
+ { id: "seed-150", oklch: [0.750, 0.148, 80.0],
+ mood: "Klim Type Foundry specimen page — late-summer editorial gold, considered and grown-up",
+ strategy: "Pure white surface lets a single restrained ochre primary do all the brand work, paired with a deep ink-blue accent for typographic contrast in the Klim/Commercial Type tradition." },
+ { id: "seed-058", oklch: [0.764, 0.120, 77.1],
+ mood: "Klim Type Foundry specimen page — late-afternoon ochre, considered editorial typography",
+ strategy: "Pure white surface lets the ochre primary do the brand work, paired with a deep ink-blue accent for editorial contrast — the type-foundry move where one warm hue carries the whole feeling against neutral paper." },
+ { id: "seed-059", oklch: [0.784, 0.144, 79.8],
+ mood: "late afternoon in a Tuscan limonaia — sun-cured amber on whitewashed plaster",
+ strategy: "Pure white surface lets the saffron-amber primary and a deep olive accent carry the Mediterranean warmth, with split-complementary tension between gold and a quiet evergreen." },
+ { id: "seed-061", oklch: [0.817, 0.161, 75.1],
+ mood: "late-afternoon honey on Tuscan limestone — golden hour, slow and luminous",
+ strategy: "Pure white surface lets the amber primary glow like sunlight on a wall, paired with a deep terracotta accent for warm tonal contrast within the same hue family." },
+ { id: "seed-063", oklch: [0.842, 0.165, 91.3],
+ mood: "late-afternoon Tuscan sun on limestone — golden hour, considered, optimistic",
+ strategy: "Pure white surface lets the amber-gold primary radiate as the mood-carrier, with a deep aubergine accent providing the long shadow that golden light needs to feel three-dimensional." },
+ { id: "seed-174", oklch: [0.350, 0.075, 110.0],
+ mood: "olive grove at late afternoon — sun-cured leaves, dust, and quiet Mediterranean weight",
+ strategy: "Pure white surface lets a deep, sun-cured olive primary do the emotional work, with a burnt-terracotta accent providing the warm-earth counterpoint olive groves are known for." },
+ { id: "seed-117", oklch: [0.650, 0.100, 110.0],
+ mood: "Klim-style editorial sage — late-summer foundry catalogue, considered olive-yellow on paper",
+ strategy: "Seed sits at olive-chartreuse; treating it as a quiet typographic primary on pure paper, with a deeper bronze-olive accent for hierarchy — the color does the work, the page disappears." },
+ { id: "seed-118", oklch: [0.750, 0.090, 110.0],
+ mood: "Klim Type Foundry specimen page — late-summer olive light on a working specimen, the honesty of a type designer showing their work",
+ strategy: "Pure white bg lets a desaturated olive-yellow primary do the editorial work, with a deeper olive-bronze accent providing typographic emphasis the way a specimen uses one heavy weight against the body roman." },
+ { id: "seed-065", oklch: [0.797, 0.166, 113.1],
+ mood: "late-summer olive grove at noon — sun-bleached leaves, dry stone, Mediterranean glare",
+ strategy: "Hold the seed as a luminous chartreuse-olive primary against pure white so the color reads as sunlit foliage, pairing it with a deep umber accent for the dry-stone contrast." },
+ { id: "seed-176", oklch: [0.300, 0.071, 120.0],
+ mood: "moss-darkened apothecary jar — herbal, shadowed, mid-19th-century botanical study",
+ strategy: "Seed is a deep desaturated olive-green that reads as preserved botanical pigment; I anchor it on pure white so the dim moss-green primary feels like ink on a herbarium page, with a warm ochre accent supplying the aged-paper counterpoint." },
+ { id: "seed-155", oklch: [0.550, 0.142, 130.0],
+ mood: "moss-bed forest floor at noon — chlorophyll, lichen, sunlit fern",
+ strategy: "Seed is a confident mid-olive green with strong chroma; mood is daylight botanical, so I let the brand greens do the work on a pure paper-white bg and pair with a warm umber accent for fern-against-bark contrast." },
+ { id: "seed-119", oklch: [0.600, 0.154, 130.0],
+ mood: "moss garden at Saihō-ji — damp stone, filtered green light through old cedar",
+ strategy: "Pure near-black bg lets the seed's mossy green glow like wet lichen under low light; accent shifts to a pale ochre-gold like sun catching through canopy." },
+ { id: "seed-179", oklch: [0.300, 0.096, 140.0],
+ mood: "moss on wet stone — forest floor at dusk, deep botanical hush",
+ strategy: "Kept the seed's deep moss green as primary against a near-black surface so the green reads as living shadow, with a pale lichen accent providing the single point of light." },
+ { id: "seed-180", oklch: [0.350, 0.110, 140.0],
+ mood: "moss-darkened apothecary — herbal tinctures in amber glass, pressed botanicals, the deep green of a conservatory at dusk",
+ strategy: "Near-black bg with a whisper of green undertone lets the seed's deep moss read as luminous foliage; a warm parchment accent provides the apothecary-label counterpoint without breaking the herbal register." },
+ { id: "seed-120", oklch: [0.650, 0.100, 140.0],
+ mood: "moss on weathered stone — quiet botanical garden conservatory at midday",
+ strategy: "Pure white bg lets the muted sage-green primary read as a considered botanical mark, with a deeper terracotta accent providing earthen counterpoint without breaking the gallery-like restraint." },
+ { id: "seed-121", oklch: [0.750, 0.090, 140.0],
+ mood: "moss garden at Saihō-ji — diffuse green light filtered through wet stone and lichen",
+ strategy: "Pure near-black bg lets the muted sage-green primary glow like lichen under low light; a warm pale-bone accent acts as the single ray of sun cutting through canopy." },
+ { id: "seed-182", oklch: [0.400, 0.106, 150.0],
+ mood: "moss garden at Saiho-ji — deep cultivated green under wet stone shadow, contemplative and damp",
+ strategy: "Near-black bg with the faintest cool-green undertone evokes shaded stone; primary holds the seed's moss tone while accent shifts to a lichen-yellow for organic counterpoint without breaking the hush." },
+ { id: "seed-157", oklch: [0.550, 0.145, 150.0],
+ mood: "moss garden at Saiho-ji — damp stone, filtered green light through cedar canopy",
+ strategy: "Near-black bg with a faint green undertone evokes deep forest shadow; primary holds the seed's verdant register while accent shifts to a pale lichen-cream to mimic light catching moss." },
+ { id: "seed-122", oklch: [0.600, 0.158, 150.0],
+ mood: "forest floor at first light — moss, lichen, and clean morning air",
+ strategy: "Seed reads as a living, daylight green; surface stays pure white so the green carries the freshness, with a cool teal accent pulling it toward dew rather than earth." },
+ { id: "seed-195", oklch: [0.650, 0.150, 145.0],
+ mood: "Considered horticulture brand — botanical research lab, the green of a healthy stem photographed in clean daylight",
+ strategy: "Pure white surface lets the seed's vegetal green carry the entire brand voice, paired with a deep forest ink and a warm clay accent for editorial contrast." },
+ { id: "seed-183", oklch: [0.350, 0.077, 160.0],
+ mood: "moss-stained apothecary — deep forest glass, herbal tinctures shelved in low candlelight",
+ strategy: "Anchored the seed as primary and built a near-black dark surface with whisper-tinted green to evoke aged apothecary glass, letting the green glow rather than shout." },
+ { id: "seed-184", oklch: [0.400, 0.087, 160.0],
+ mood: "deep forest apothecary — moss, bottle glass, and herbal tincture under afternoon light",
+ strategy: "Seed becomes a botanical-bottle-green primary on pure white, paired with a warm clove-amber accent to evoke herbal pharmacy contrast without tinting the surface." },
+ { id: "seed-158", oklch: [0.550, 0.119, 160.0],
+ mood: "moss on wet stone — forest floor after rain, mineral and quiet",
+ strategy: "Pure white surface lets the deep mossy green carry the entire mood; accent shifts to a damp slate-teal to sit beside primary like lichen on stone without competing." },
+ { id: "seed-159", oklch: [0.600, 0.130, 160.0],
+ mood: "moss-covered forest apothecary — herbal tinctures in amber glass, eucalyptus shadow",
+ strategy: "Anchored the green seed in a near-black backdrop so it reads like botanical glassware lit from within, with a warm amber accent pulled across the wheel to evoke tincture bottles against dark wood." },
+ { id: "seed-185", oklch: [0.450, 0.086, 170.0],
+ mood: "weathered copper patina on a Pacific Northwest greenhouse — oxidized teal, glass light, botanical hush",
+ strategy: "Seed sits as a deep oxidized-teal primary against pure white so the patina reads as pigment, not atmosphere; a rust-copper accent completes the verdigris/oxidation story across the warm-cool axis." },
+ { id: "seed-124", oklch: [0.750, 0.080, 170.0],
+ mood: "sea-glass on a foggy Pacific shoreline — weathered, mineral, quietly oxidized",
+ strategy: "Seed is a soft desaturated teal-green; pairing it on pure white lets the mineral primary read as patinated copper-glass, with a deeper kelp-toned primary and a rusted coral accent to spark the muted teal against its complement." },
+ { id: "seed-160", oklch: [0.550, 0.095, 180.0],
+ mood: "weathered copper patina on a museum bronze — oxidized teal, conservatorial quiet",
+ strategy: "Pure near-black gallery surround lets the patina-teal primary glow like a lit artifact, with a warm verdigris-adjacent accent providing the oxidation contrast against the cool seed." },
+ { id: "seed-161", oklch: [0.720, 0.100, 188.0],
+ mood: "climate-tech dashboard — calm verdigris on plain paper, the quiet confidence of an instrument that just works",
+ strategy: "Seed teal carries the entire mood as a single considered brand color on pure white, with a desaturated copper accent providing warm signal against the cool primary without competing for attention." },
+ { id: "seed-186", oklch: [0.450, 0.074, 200.0],
+ mood: "deep hydrothermal vent — mineral teal under pressure, the cold blue-green of oxidized copper in submerged light",
+ strategy: "Near-black surface lets the mineral teal glow as if lit from within; accent shifts toward verdigris-copper to suggest patina on submerged metal, while ink stays cool-neutral to keep the register austere rather than aquatic-cute." },
+ { id: "seed-125", oklch: [0.650, 0.100, 200.0],
+ mood: "climate-tech dashboard — calm operational teal, the color of clean water data and atmospheric sensors",
+ strategy: "Pure white surface lets a single muted-teal primary do all the brand work, with a deeper marine accent providing hierarchy without competing chroma." },
+ { id: "seed-126", oklch: [0.750, 0.080, 200.0],
+ mood: "climate-tech product brand — quiet competence, dashboards for hard infrastructure problems",
+ strategy: "Hold the seed's muted teal as primary, pair with a sharper cyan-leaning accent for interactive lift, and let a pure white surface do the disappearing act so the brand reads as a tool, not an atmosphere." },
+ { id: "seed-162", oklch: [0.550, 0.091, 210.0],
+ mood: "weathered nautical instrument — patinated brass on oxidized steel, the cool blue-grey of a ship's chronometer at dawn",
+ strategy: "Pure white surface lets the muted teal-steel primary read as a precise instrument mark, with a warm brass accent providing the single point of patina against clinical white." },
+ { id: "seed-163", oklch: [0.450, 0.086, 230.0],
+ mood: "deep harbor at dusk — weathered nautical instruments, brass dials on oxidized steel",
+ strategy: "Near-black background with subtle cool tint evokes the marine dusk; primary holds the seed's teal-blue while a warm brass accent creates the instrument-on-steel tension." },
+ { id: "seed-164", oklch: [0.550, 0.105, 230.0],
+ mood: "deep harbor at dawn — cold steel water, fog-muted light, the quiet before the boats leave",
+ strategy: "Pure near-black bg lets the seed's cold marine blue read as a luminous beacon, while a pale frost-cyan accent evokes diffused dawn light cutting through fog." },
+ { id: "seed-127", oklch: [0.650, 0.100, 230.0],
+ mood: "climate-tech dashboard — atmospheric sensor blue, calm operational clarity",
+ strategy: "Anchor the seed as a confident mid-blue primary on pure white so the brand color carries all the atmospheric feeling, with a deep navy accent for hierarchy and a soft slate muted for body text." },
+ { id: "seed-128", oklch: [0.750, 0.080, 230.0],
+ mood: "climate-tech dashboard — calm atmospheric data, considered sky-blue",
+ strategy: "Pure white surface lets the muted sky-blue primary carry the meteorological calm, with a deep-navy accent providing readable weight against the soft primary." },
+ { id: "seed-187", oklch: [0.350, 0.078, 240.0],
+ mood: "deep harbor at blue hour — wet stone, cold steel, the quiet before night fully lands",
+ strategy: "Near-black architectural bg with a hint of marine chroma lets the seed read as ambient atmosphere rather than UI chrome; a cooler steel accent sits opposite the warmer-shifted primary for navigational clarity." },
+ { id: "seed-077", oklch: [0.578, 0.130, 241.7],
+ mood: "pre-dawn signal tower — cold blue solitude, instruments glowing against the dark",
+ strategy: "Pure near-black bg lets the seed's cold tower-light blue glow as the sole emotional source, with a frost-cyan accent acting as a secondary indicator light." },
+ { id: "seed-188", oklch: [0.400, 0.110, 250.0],
+ mood: "Linear's considered indigo — the calm authority of a well-built developer tool, blueprint ink on a clean page",
+ strategy: "Held the seed as a deep indigo primary against pure white so the brand color carries all the gravity; accent shifts to a cooler, brighter cyan-blue to create a crisp hierarchy pair without warming the surface." },
+ { id: "seed-165", oklch: [0.450, 0.123, 250.0],
+ mood: "blueprint room at dusk — drafting table, graphite, civic-engineering blue",
+ strategy: "Seed is a mid-deep architectural blue with real chroma and no environmental cue, so I stay out of the way with a pure white surface and let the primary do all the talking, pairing it with a burnt-ochre accent for drafting-pencil contrast." },
+ { id: "seed-079", oklch: [0.478, 0.136, 251.8],
+ mood: "twilight cartography — the blue of deep dusk over open water, precise and navigational",
+ strategy: "Pure white surface lets the seed's oceanic blue act as a single navigational anchor, with a warm amber accent struck across it like a lighthouse beam at dusk." },
+ { id: "seed-080", oklch: [0.541, 0.122, 248.2],
+ mood: "Linear-style considered tool blue — the calm, exact register of a modern engineering app where every pixel is intentional",
+ strategy: "Pure white surface lets the considered indigo-blue primary carry the entire brand; a deeper navy accent provides hierarchy without warmth, keeping the palette in a single cool family for that focused-software feel" },
+ { id: "seed-166", oklch: [0.550, 0.149, 250.0],
+ mood: "pre-dawn flight deck — instrument glow against deep cobalt sky, precise and quietly intense",
+ strategy: "Near-black bg with the faintest cool tint reads like a darkened cockpit; the seed becomes a luminous instrument-blue primary, paired with a warm amber accent that mimics avionics readouts for unmistakable signal contrast." },
+ { id: "seed-081", oklch: [0.650, 0.160, 250.0],
+ mood: "deep-sea research vessel at dawn — instrument glow against cold steel light",
+ strategy: "Pure near-white bg keeps the palette technical and instrument-like; the seed blue holds as primary while a desaturated steel-cyan accent reads like signal readouts on glass." },
+ { id: "seed-082", oklch: [0.742, 0.140, 247.4],
+ mood: "high-altitude flight deck at dawn — cold cabin instruments glowing against a sky still holding night",
+ strategy: "Near-black cockpit ground with a faint blue cast lets the seed read as an illuminated instrument; primary holds the seed, accent shifts to cyan for signal/indicator contrast." },
+ { id: "seed-210", oklch: [0.360, 0.140, 260.0],
+ mood: "Linear-style considered tool indigo — late-night focused work, the deep blue of a code editor at 2am where everything else falls away",
+ strategy: "Pure black bg lets the indigo primary carry all the cognitive-focus weight, with a slightly brighter periwinkle accent for interactive lift — the surface disappears so the tool feels weightless." },
+ { id: "seed-189", oklch: [0.400, 0.130, 260.0],
+ mood: "pre-dawn observatory — cold instrument blue, star-chart precision",
+ strategy: "Seed becomes the primary on pure black so the deep instrument-blue glows like a calibration light, with a faint cyan accent reading as starlight against the void." },
+ { id: "seed-211", oklch: [0.420, 0.161, 260.0],
+ mood: "Linear's considered indigo — the tool-for-thought blue of focused product work, calm authority without coldness",
+ strategy: "Hold the seed as a deep indigo primary against pure white, then pair with a slightly warmer, lighter periwinkle accent to create gentle hue separation without breaking the disciplined tool-brand register." },
+ { id: "seed-129", oklch: [0.450, 0.150, 260.0],
+ mood: "pre-dawn observatory — deep cobalt sky just before astronomical twilight, instruments cool to the touch",
+ strategy: "Near-black surface lets the cobalt seed read as luminous starlight; a single warm amber accent acts as the calibration lamp against the cold blue field." },
+ { id: "seed-084", oklch: [0.476, 0.207, 261.2],
+ mood: "pre-dawn flight deck — instrument glow against deep cobalt sky, precise and awake",
+ strategy: "Default B black bg lets the cobalt primary read as a luminous instrument signal, with a cyan accent striking the analogous 'cockpit display' relationship." },
+ { id: "seed-085", oklch: [0.681, 0.132, 258.4],
+ mood: "pre-dawn flight deck — instrument glow against deep cobalt sky",
+ strategy: "Anchored the seed as a luminous primary against a near-black architectural ground, with a warm amber accent acting as the single instrument light cutting through cold blue." },
+ { id: "seed-086", oklch: [0.767, 0.106, 255.9],
+ mood: "Scandinavian winter morning — quiet light through frost, pale sky over snow",
+ strategy: "Anchored a pure white editorial stage so the seed's cool sky-blue reads as crisp polar light, with a deeper navy primary providing the only saturated weight — like a single dark pine against snow." },
+ { id: "seed-083", oklch: [0.340, 0.159, 262.4],
+ mood: "deep cobalt twilight — the moment after sunset when the sky goes electric blue and city windows start to glow",
+ strategy: "Pure black stage lets the cobalt seed act as a luminous neon-window glow, with a warm amber accent across the wheel for the lit-window contrast." },
+ { id: "seed-212", oklch: [0.360, 0.219, 270.0],
+ mood: "Linear-grade tooling indigo — considered software for people who care about craft",
+ strategy: "Anchored the deep indigo seed as primary on a pure white surface so the brand color carries all the weight, with a slightly cooler violet-blue accent for hierarchy without competing chroma." },
+ { id: "seed-130", oklch: [0.400, 0.150, 270.0],
+ mood: "Linear-grade indigo — considered productivity tool, ink on paper, no theatrics",
+ strategy: "Pure white surface lets a deep cool indigo carry all the brand weight, paired with a slightly warmer violet-blue accent for hierarchy without acid." },
+ { id: "seed-213", oklch: [0.411, 0.241, 267.9],
+ mood: "Linear-style indigo — considered tool surface, the kind of blue-violet that sits behind a developer's keyboard at 11pm without shouting",
+ strategy: "Pure black canvas lets a saturated indigo primary do all the brand work, with a cooler cyan-violet accent providing UI signal without competing." },
+ { id: "seed-131", oklch: [0.450, 0.180, 270.0],
+ mood: "monastic indigo dusk — vespers light through stained glass, contemplative and severe",
+ strategy: "Seed becomes a deep indigo primary against pure near-black so the violet reads as luminous stained-glass against architectural shadow, with a cooler iris accent for tonal lift." },
+ { id: "seed-088", oklch: [0.476, 0.158, 268.5],
+ mood: "pre-dawn astronomer's notebook — deep indigo sky just before the stars fade, ink and graphite",
+ strategy: "Near-black bg with the faintest cool tint to evoke night sky without theatrics; primary holds the seed's indigo, accent shifts to a paler periwinkle for stellar contrast, keeping the palette monochromatic-cool and observational." },
+ { id: "seed-196", oklch: [0.530, 0.130, 268.0],
+ mood: "Linear-style considered tool indigo — the deep-focus blue-violet of a thoughtfully built productivity surface, the color of a well-typeset keyboard shortcut",
+ strategy: "Pure white bg lets the indigo seed do all the brand work as primary, with a slightly darker, more saturated violet-shifted accent for hierarchy and interactive states — the surface disappears so the brand color reads as the entire identity." },
+ { id: "seed-132", oklch: [0.700, 0.120, 270.0],
+ mood: "Linear-style considered tool indigo — the quiet violet of a focused product workspace, late-afternoon thinking",
+ strategy: "Pure white surface lets a muted indigo-violet primary and a slightly cooler accent do all the brand work, keeping the register calm and software-like rather than theatrical." },
+ { id: "seed-090", oklch: [0.445, 0.206, 279.1],
+ mood: "Linear-style considered tool indigo — the violet of a focused product surface, not a nightclub",
+ strategy: "Anchor the seed as a confident product primary on pure white, with a cooler indigo-shift accent that reads as a sibling tool color, so the brand violet does all the emotional work." },
+ { id: "seed-133", oklch: [0.500, 0.160, 280.0],
+ mood: "Linear-adjacent indigo — considered productivity tool, the violet of a thinking workspace",
+ strategy: "Seed becomes a measured indigo primary on pure white; accent shifts to a cooler blue-violet to create hierarchy without nightclub saturation, letting the brand color do all the emotional work." },
+ { id: "seed-094", oklch: [0.533, 0.125, 294.3],
+ mood: "Linear-style considered tool indigo — the violet of a focused product surface, calm authority for a creative workspace",
+ strategy: "Pure white canvas lets the indigo-violet primary carry the entire brand voice; accent shifts hue slightly toward blue for a cool, tool-like duotone rather than warm decorative pairing." },
+ { id: "seed-137", oklch: [0.700, 0.120, 290.0],
+ mood: "Linear-adjacent indigo — the considered tool, late-evening focus mode, software made for people who care about craft",
+ strategy: "Pure black surface lets a single restrained indigo-violet carry the brand, with a cooler periwinkle accent providing UI hierarchy without competing — Vercel/Linear dark-mode discipline." },
+ { id: "seed-100", oklch: [0.450, 0.150, 330.0],
+ mood: "velvet boudoir at last call — bruised orchid and lipstick traces under low lamplight",
+ strategy: "Pure near-black surface lets a deep magenta-rose primary smolder while a warm peach accent acts like skin-lit lamplight — drama lives in the brand pair, not the room." },
+ { id: "seed-103", oklch: [0.650, 0.160, 330.0],
+ mood: "1980s Memphis boudoir — powder-pink neon humming against lacquered black, lipstick and lacquer",
+ strategy: "Near-black gallery surface lets the magenta-pink seed read as lit neon; accent shifts to warm coral to create cinematic dichromatic tension without competing chroma." },
+ { id: "seed-228", oklch: [0.360, 0.147, 340.0],
+ mood: "Figma-era creative tool plum — considered productivity software for designers, the inky violet of a serif wordmark on a marketing site",
+ strategy: "Held the seed as a deep plum primary against pure white so the brand color does the emotional work; paired with a muted rose accent for warmth without breaking the productivity-tool restraint." },
+ { id: "seed-107", oklch: [0.500, 0.200, 340.0],
+ mood: "Figma plum — creative-tool confidence, considered magenta for a modern design product",
+ strategy: "Pure white surface lets a saturated magenta-plum primary carry all the brand voice, paired with a cooler violet-leaning accent for hierarchy without competing." },
+ { id: "seed-198", oklch: [0.600, 0.210, 340.0],
+ mood: "Figma-era creative tool plum — confident, considered, made for makers",
+ strategy: "Anchor a saturated plum primary against pure white so the brand color does all the emotional work, with a deeper magenta-rose accent for hierarchy." },
+ { id: "seed-112", oklch: [0.754, 0.193, 343.4],
+ mood: "Figma-era creative tool — confident pink primary doing the brand work on a clean canvas, the way Linear uses indigo or Stripe uses violet",
+ strategy: "Anchor the seed pink as a saturated brand primary on pure white so the color carries all the personality; pair with a cooler plum accent to give the pink something to push against without competing." },
+ { id: "seed-229", oklch: [0.420, 0.163, 350.0],
+ mood: "considered fintech rose — the deep magenta of a modern product brand (think Stripe-adjacent, but rotated toward berry), confident and current",
+ strategy: "pure white surface lets a single deep berry-rose primary do all the brand work, paired with a cooler indigo accent for the contrast move you see in modern product marketing" },
+ { id: "seed-113", oklch: [0.470, 0.173, 354.8],
+ mood: "1960s velvet rope nightclub — crushed magenta, low light, cigarette smoke catching a spotlight",
+ strategy: "Pure black stage so the seed's smoky magenta reads as a single hot spotlight, paired with a cooler violet accent for the second light cue." },
+ { id: "seed-114", oklch: [0.570, 0.158, 353.3],
+ mood: "fin-de-siècle Parisian rose — velvet curtain, theatre program, lipstick blotted on linen",
+ strategy: "Drop bg to true black so the dusty-rose primary reads as stage-lit silk; accent shifts to a warmer coral-mauve at higher lightness to create gentle hue rotation without breaking the romance." },
+ { id: "seed-199", oklch: [0.650, 0.180, 350.0],
+ mood: "modern fintech rose — the considered pink of a Series B brand mark, confident and current without nostalgia",
+ strategy: "Pure white surface lets a saturated rose primary do the brand work, paired with a deep plum accent for hierarchy — the Stripe move applied to a pink hue." },
+ { id: "seed-115", oklch: [0.636, 0.218, 355.3],
+ mood: "backstage at a cabaret — velvet rope, lipstick mark on a champagne glass",
+ strategy: "Seed reads as a saturated stage-light magenta-red; I push it into pure black so the primary glows like a neon sign and the accent (a cold pearl-pink) acts as the spotlight rim — the room is dark, the color does the singing." },
+ { id: "seed-230", oklch: [0.650, 0.249, 354.5],
+ mood: "Modern fintech rose — the considered pink of a contemporary payments brand: confident, alive, and clear-headed",
+ strategy: "Pure white bg lets a saturated rose-magenta primary carry all the brand energy, paired with a cooler indigo accent for trustworthy contrast — the Stripe move applied to a pink hue." },
+ { id: "seed-231", oklch: [0.682, 0.241, 353.2],
+ mood: "Figma-era creative tool — a confident pink-magenta product brand, the kind a modern design platform uses to feel alive without shouting",
+ strategy: "Default A pure white bg lets the saturated pink-magenta primary do all the brand work, with a near-complementary cool teal accent for tool-like clarity and a neutral ink for editorial calm" },
+ { id: "seed-116", oklch: [0.734, 0.183, 356.8],
+ mood: "modern beauty brand DTC — Glossier-adjacent pink, confident and current without being saccharine",
+ strategy: "Pure white surface so the rose-pink primary carries all the brand warmth, paired with a near-black ink and a desaturated mauve accent for editorial restraint." },
+];
+
+function parseArgs(argv) {
+ const args = { id: null, from: null };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--id' && argv[i + 1]) { args.id = argv[++i]; }
+ else if (a === '--from' && argv[i + 1]) { args.from = argv[++i]; }
+ }
+ return args;
+}
+
+// Hash a key into a stable float in [0, 1) for deterministic weighted picks.
+function hashUnit(key) {
+ const h = crypto.createHash('sha256').update(key).digest();
+ return h.readUInt32BE(0) / 0x100000000;
+}
+
+// The curated library is hue-skewed (more reds/oranges than teals/magentas)
+// because that's where the source material + taste landed. Left uniform, a
+// random pick would land on red ~1/3 of the time. Inverse-frequency weighting
+// gives each seed a weight of 1/(count in its 30° hue bucket), so each hue
+// ZONE is roughly equally likely to be chosen regardless of how many seeds it
+// holds — fair rainbow exposure across runs without pruning the library.
+function buildWeights(seeds) {
+ const bucketCount = {};
+ const bucketOf = (s) => Math.floor(((s.oklch[2] % 360) + 360) % 360 / 30);
+ for (const s of seeds) { const b = bucketOf(s); bucketCount[b] = (bucketCount[b] || 0) + 1; }
+ const weights = seeds.map((s) => 1 / bucketCount[bucketOf(s)]);
+ const total = weights.reduce((a, b) => a + b, 0);
+ return { weights, total };
+}
+
+function weightedPick(seeds, unit) {
+ const { weights, total } = buildWeights(seeds);
+ let target = unit * total;
+ for (let i = 0; i < seeds.length; i++) {
+ target -= weights[i];
+ if (target < 0) return seeds[i];
+ }
+ return seeds[seeds.length - 1];
+}
+
+function pickSeed(seeds, { id, from }) {
+ if (id) {
+ const found = seeds.find(s => s.id === id);
+ if (!found) { console.error(`no seed with id "${id}"`); process.exit(2); }
+ return found;
+ }
+ const envFrom = process.env.IMPECCABLE_PALETTE_SEED;
+ const key = from || envFrom;
+ const unit = key ? hashUnit(key) : Math.random();
+ return weightedPick(seeds, unit);
+}
+
+function fmtOklch([L, C, H]) {
+ return `oklch(${L.toFixed(3)} ${C.toFixed(3)} ${H.toFixed(1)})`;
+}
+
+function hueWord(H) {
+ if (H < 15 || H >= 345) return 'pure red';
+ if (H < 35) return 'warm red / crimson';
+ if (H < 55) return 'warm coral / burnt orange';
+ if (H < 80) return 'orange / honey';
+ if (H < 105) return 'warm amber / honey-gold';
+ if (H < 135) return 'yellow-green / olive';
+ if (H < 170) return 'green';
+ if (H < 200) return 'teal';
+ if (H < 230) return 'sky blue';
+ if (H < 265) return 'cobalt / indigo';
+ if (H < 295) return 'violet / purple';
+ if (H < 330) return 'magenta / pink';
+ return 'deep pink / rose';
+}
+
+// ---------------------------------------------------------------
+
+const args = parseArgs(process.argv.slice(2));
+const seed = pickSeed(SEEDS, args);
+const [L, C, H] = seed.oklch;
+
+// The mood + strategy on each seed were derived by the model that
+// originally judged it. We surface them as *hints*, not commands —
+// the brief should still drive what the seed becomes.
+const moodHint = seed.mood ? ` (one read: "${seed.mood}")` : '';
+const strategyHint = seed.strategy ? `\n - one example strategy: ${seed.strategy}` : '';
+
+// ---------------------------------------------------------------
+// Fat tool-exit response — what the model sees on stdout.
+// ---------------------------------------------------------------
+
+process.stdout.write(`BRAND SEED · ${seed.id}
+
+Seed color (anchor for your primary brand color):
+ ${fmtOklch(seed.oklch)} — ${hueWord(H)}${moodHint}
+
+This is the brand's anchor — a single beautiful color. Compose the rest of
+the palette around it using YOUR judgment, the brief (PRODUCT.md /
+DESIGN.md / the user's prompt), and the color-strategy guidance already in
+SKILL.md.
+
+How to use:
+
+1. Read the brief. Write one specific phrase describing the mood this
+ product calls for. Be granular. Good: "1970s travel poster — sun-baked
+ warmth, considered", "midnight jazz club — smoky brass, saxophone
+ light", "Scandinavian winter morning — quiet light through frost". Bad:
+ "modern and clean", "warm and inviting". The first lets you compose; the
+ second is generic and will produce generic palettes.
+
+2. The seed's hue (${H.toFixed(0)}°) anchors your primary brand color. You
+ choose L and C to match the mood. The same hue can be deep-and-velvet,
+ bright-and-confident, or pale-and-faded — pick the one the mood demands.
+ Primary's hue should stay within ±10° of the seed.${strategyHint}
+
+3. Now compose the full palette in OKLCH (5 more roles):
+ • bg — the most important architectural choice.
+ CORE PRINCIPLE: the mood lives in the BRAND COLORS
+ (primary + accent) and typography, NOT in the surface.
+ Stripe is warm — its purple does that, bg is pure
+ white. Linear is cool — its blue does that, bg is
+ pure. Notion is warm — its accents do that, bg is
+ near-pure-white. Putting warmth in BOTH primary AND
+ bg is the AI cliché.
+
+ DEFAULT A — PURE white: exactly oklch(1.000 0.000 0).
+ Not 0.99, not chroma 0.002. Stripe / Notion / Apple
+ use literal #ffffff. Don't add hidden warmth.
+ Refs: Stripe, Notion, Linear (light), Apple.com,
+ Vercel docs, Figma marketing, Loom, Substack.
+
+ DEFAULT B — PURE black/near-black: L 0.04-0.12,
+ chroma exactly 0.000. No hue tint. Vercel is
+ roughly oklch(0.08 0 0). Pick L for mood; C is 0.
+ Refs: Vercel, A24, Acne, Apple dark, MUBI.
+
+ ALT 2 — TINTED: chroma 0.015-0.05.
+ Use ONLY when:
+ (a) the mood is EXPLICITLY environmental — the surface
+ IS part of the brand (1920s lacquered interior,
+ leather library, ceramic studio, hotel lobby), or
+ (b) the seed itself is desaturated (chroma < 0.10) and
+ needs a tinted surface to read as a brand.
+ NOT for "feels warm" / "modern + warm" / "moody". If
+ your mood says "warm" but doesn't name a specific
+ environment, use PURE white and let primary carry
+ the warmth.
+
+ HEURISTIC: if seed chroma > 0.10 AND mood is product-
+ focused (not environment-focused), it's almost always
+ PURE white. Target distribution across many palettes:
+ ~50% pure white, ~25% pure black, ~25% tinted.
+ • surface — bg pulled slightly toward ink (10-15% mix). Same hue
+ family as bg. Used for cards, panels, sections.
+ • ink — body text color. Must reach ≥7:1 contrast vs bg.
+ Can carry the brand hue at low chroma in light mode
+ (slight warmth or coolness toward the brand).
+ • accent — a SECOND brand color, distinct from primary in BOTH
+ hue AND lightness. Picked to complement the mood (not
+ default-complementary across the wheel). Used for
+ badges, status pills, links, accent rules.
+ • muted — secondary text. Ink pulled 40% toward bg, keeping ink's
+ hue. Must reach ≥3.5:1 contrast vs bg.
+
+4. Pick a color STRATEGY (the four steps from SKILL.md):
+ • Restrained: tinted neutrals + accent ≤10% — product default
+ • Committed: one saturated color carries 30-60% — identity-driven
+ • Full palette: 3-4 named roles each used deliberately — brand work
+ • Drenched: the surface IS the color — campaign, hero, statement
+ The brief picks the strategy. A startup dashboard ≠ a perfume brand.
+
+Hard rules (already in SKILL.md, recapped because the seed step is where
+they actually bite):
+
+ - OKLCH only — never hex. Never #RRGGBB.
+ - ink-vs-bg WCAG contrast ≥ 7 (body text must be readable)
+ - primary chroma ≤ 0.23 (above this, primary glows perceptually and
+ no text on it is readable — acid-bright is a UI failure)
+ - if primary L > 0.78, primary chroma ≤ 0.18 (the fluorescent zone)
+ - primary-vs-accent contrast ≥ 1.7 (they must be visually distinct,
+ not two variants of the same hue at similar lightness)
+ - accent must carry readable text on a filled badge/pill: EITHER
+ saturated (chroma ≥ 0.10) OR clearly light (L ≥ 0.85) OR clearly
+ dark (L ≤ 0.30). Never a muddy mid-tone (L 0.45-0.72 + chroma < 0.10)
+ — taupe/mushroom/dusty-grey accents read as weak and can't hold text
+ either way. Saturate it or push its lightness to a clear light/dark.
+ - avoid the saturated AI attractor zones: claude-beige (warm-cream bg
+ + dusty brown primary), forest-green-on-cream, AI-purple-on-white,
+ navy-cream-with-orange-accent
+
+TEXT-ON-COLOR FILLS — pick by perceptual contrast, not just WCAG. The
+rule applies to ANY element where text sits on a saturated color fill:
+primary buttons, accent buttons, badges, status pills, tag highlights,
+filled callouts. Don't only think "primary button" — apply consistently.
+
+For any saturated mid-luminance color (L between 0.42 and 0.78, chroma ≥
+0.08), use WHITE text (or near-white from your bg), not dark text — even
+if WCAG says dark technically passes. The Helmholtz-Kohlrausch effect
+makes saturated colors appear brighter than their luminance suggests,
+and dark text on a warm-or-cool-saturated fill reads as muddy.
+
+Convention: Stripe orange CTAs, McDonald's red, every fintech orange
+button, Vercel's filled badges, Linear's status pills — all use white
+text on saturated bg fills.
+
+Dark text is correct only on PALE fills (L > 0.85) or PURE-NEUTRAL fills
+(chroma near 0). Everything else: white text.
+
+Return your composed palette in CSS custom properties using OKLCH, then
+build with it. The seed is the start, not the recipe.
+`);
diff --git a/.github/skills/impeccable/scripts/pin.mjs b/.github/skills/impeccable/scripts/pin.mjs
new file mode 100644
index 0000000..52ea270
--- /dev/null
+++ b/.github/skills/impeccable/scripts/pin.mjs
@@ -0,0 +1,221 @@
+#!/usr/bin/env node
+/**
+ * Pin/unpin sub-commands as standalone skill shortcuts.
+ *
+ * Usage:
+ * node /pin.mjs pin
+ * node /pin.mjs unpin
+ *
+ * `pin audit` creates a lightweight audit skill that redirects to Impeccable's audit workflow.
+ * `unpin audit` removes that shortcut.
+ *
+ * The script discovers harness directories (.claude/skills, .cursor/skills, etc.)
+ * in the project root and creates/removes the pin in all of them.
+ */
+
+import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
+import { basename, join, resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+
+// All known harness directories
+const HARNESS_DIRS = [
+ '.claude', '.cursor', '.gemini', '.codex', '.agents',
+ '.trae', '.trae-cn', '.pi', '.opencode', '.kiro', '.rovodev',
+];
+
+const CODEX_HARNESSES = new Set(['.codex', '.agents']);
+
+// Valid sub-command names
+const VALID_COMMANDS = [
+ 'craft', 'init', 'extract', 'document', 'shape',
+ 'critique', 'audit',
+ 'polish', 'bolder', 'quieter', 'distill', 'harden', 'onboard', 'live',
+ 'animate', 'colorize', 'typeset', 'layout', 'delight', 'overdrive',
+ 'clarify', 'adapt', 'optimize',
+];
+
+// Marker to identify pinned skills (so unpin doesn't delete user skills)
+const PIN_MARKER = '';
+
+/**
+ * Walk up from startDir to find a project root.
+ */
+function findProjectRoot(startDir = process.cwd()) {
+ let dir = resolve(startDir);
+ while (dir !== '/') {
+ if (
+ existsSync(join(dir, 'package.json')) ||
+ existsSync(join(dir, '.git')) ||
+ existsSync(join(dir, 'skills-lock.json'))
+ ) {
+ return dir;
+ }
+ const parent = resolve(dir, '..');
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return resolve(startDir);
+}
+
+/**
+ * Find harness skill directories that have an impeccable skill installed.
+ */
+function findHarnessDirs(projectRoot) {
+ const dirs = [];
+ for (const harness of HARNESS_DIRS) {
+ const skillsDir = join(projectRoot, harness, 'skills');
+ // Only pin in harness dirs that already have impeccable installed
+ const impeccableDir = join(skillsDir, 'impeccable');
+ if (existsSync(impeccableDir) || existsSync(join(skillsDir, 'i-impeccable'))) {
+ dirs.push(skillsDir);
+ }
+ }
+ return dirs;
+}
+
+/**
+ * Load command metadata (descriptions for pinned skills).
+ */
+function loadCommandMetadata() {
+ const metadataPath = join(__dirname, 'command-metadata.json');
+ if (existsSync(metadataPath)) {
+ return JSON.parse(readFileSync(metadataPath, 'utf-8'));
+ }
+ return {};
+}
+
+/**
+ * Generate a pinned skill's SKILL.md content.
+ */
+function commandPrefixForSkillsDir(skillsDir) {
+ return CODEX_HARNESSES.has(basename(dirname(skillsDir))) ? '$' : '/';
+}
+
+function generatePinnedSkill(command, metadata, commandPrefix) {
+ const desc = metadata[command]?.description || `Shortcut for ${commandPrefix}impeccable ${command}.`;
+ const hint = metadata[command]?.argumentHint || '[target]';
+
+ return `---
+name: ${command}
+description: "${desc}"
+argument-hint: "${hint}"
+user-invocable: true
+---
+
+${PIN_MARKER}
+
+This is a pinned shortcut for \`${commandPrefix}impeccable ${command}\`.
+
+Invoke ${commandPrefix}impeccable ${command}, passing along any arguments provided here, and follow its instructions.
+`;
+}
+
+/**
+ * Pin a command: create shortcut skill in all harness dirs.
+ */
+function pin(command, projectRoot) {
+ const metadata = loadCommandMetadata();
+ const harnessDirs = findHarnessDirs(projectRoot);
+
+ if (harnessDirs.length === 0) {
+ console.log('No harness directories with impeccable installed found.');
+ return false;
+ }
+
+ let created = 0;
+
+ for (const skillsDir of harnessDirs) {
+ const commandPrefix = commandPrefixForSkillsDir(skillsDir);
+ const content = generatePinnedSkill(command, metadata, commandPrefix);
+ // Check if skill already exists (and isn't a pin)
+ const skillDir = join(skillsDir, command);
+ if (existsSync(skillDir)) {
+ const existingMd = join(skillDir, 'SKILL.md');
+ if (existsSync(existingMd)) {
+ const existing = readFileSync(existingMd, 'utf-8');
+ if (!existing.includes(PIN_MARKER)) {
+ console.log(` SKIP: ${skillDir} (non-pinned skill already exists)`);
+ continue;
+ }
+ }
+ }
+
+ mkdirSync(skillDir, { recursive: true });
+ writeFileSync(join(skillDir, 'SKILL.md'), content, 'utf-8');
+ console.log(` + ${skillDir}`);
+ created++;
+ }
+
+ if (created > 0) {
+ console.log(`\nPinned '${command}' as a standalone shortcut in ${created} location(s).`);
+ console.log('Use the pinned command directly in each harness.');
+ }
+
+ return created > 0;
+}
+
+/**
+ * Unpin a command: remove shortcut skill from all harness dirs.
+ */
+function unpin(command, projectRoot) {
+ const harnessDirs = findHarnessDirs(projectRoot);
+ let removed = 0;
+
+ for (const skillsDir of harnessDirs) {
+ const skillDir = join(skillsDir, command);
+ if (!existsSync(skillDir)) continue;
+
+ const skillMd = join(skillDir, 'SKILL.md');
+ if (!existsSync(skillMd)) continue;
+
+ // Safety: only remove if it's a pinned skill
+ const content = readFileSync(skillMd, 'utf-8');
+ if (!content.includes(PIN_MARKER)) {
+ console.log(` SKIP: ${skillDir} (not a pinned skill)`);
+ continue;
+ }
+
+ rmSync(skillDir, { recursive: true, force: true });
+ console.log(` - ${skillDir}`);
+ removed++;
+ }
+
+ if (removed > 0) {
+ console.log(`\nUnpinned '${command}' from ${removed} location(s).`);
+ console.log(`Use Impeccable's '${command}' workflow directly to access it.`);
+ } else {
+ console.log(`No pinned '${command}' shortcut found.`);
+ }
+
+ return removed > 0;
+}
+
+// --- CLI ---
+const [,, action, command] = process.argv;
+
+if (!action || !command) {
+ console.log('Usage: node pin.mjs ');
+ console.log(`\nAvailable commands: ${VALID_COMMANDS.join(', ')}`);
+ process.exit(1);
+}
+
+if (action !== 'pin' && action !== 'unpin') {
+ console.error(`Unknown action: ${action}. Use 'pin' or 'unpin'.`);
+ process.exit(1);
+}
+
+if (!VALID_COMMANDS.includes(command)) {
+ console.error(`Unknown command: ${command}`);
+ console.error(`Available commands: ${VALID_COMMANDS.join(', ')}`);
+ process.exit(1);
+}
+
+const root = findProjectRoot();
+
+if (action === 'pin') {
+ pin(command, root);
+} else {
+ unpin(command, root);
+}
diff --git a/FRAMEWORK.md b/FRAMEWORK.md
index e5b930a..0e5c3af 100644
--- a/FRAMEWORK.md
+++ b/FRAMEWORK.md
@@ -589,6 +589,7 @@ draft
proposed
materialized (Execution Graph only)
approved
+rejected
in_progress
implemented
validated
@@ -602,6 +603,10 @@ Rules:
- `draft`: artifact created, still incomplete.
- `proposed`: ready for human or audit review.
- `approved`: can feed the next stage.
+- `rejected`: a human reviewed the current content and declined approval with a
+ required rationale. It cannot feed downstream work. A human may reject an
+ approved artifact to reopen it. After revision, it may return to `draft`,
+ `proposed`, or directly to `approved` through a new, recorded human review.
- `in_progress`: being implemented.
- `implemented`: code or artifact was produced.
- `validated`: passed QA, review, Security Review when applicable, and has sufficient evidence.
@@ -615,6 +620,9 @@ Mandatory transitions:
- `validate --write-registry` preserves `parents`, `children`, `depends_on`, decisions, and delivery dependencies from structured companion `context.md` YAML. Starting-point-specific parents are additive and must not erase the existing product graph.
- `proposed`: does not require an approval record, but must not advance from an incomplete parent gate.
- `approved` and later states: require a corresponding approval record in `.product/history/`, with `artifact_id`, `path`, `content_hash`, `status_granted`, `approved_by`, `approved_at`, and `notes`. Validator and operational navigation both require that record to match the current artifact content; editing status prose alone never advances work.
+- Rejection uses the same immutable history record with `status_granted:
+ rejected`; `approved_by` identifies the rejecting human for compatibility
+ with the audit schema, and `notes` must state what requires revision.
- Human approval may be applied to one artifact with `approve` or to an explicit batch with `approve-batch`. Batch approval must preview the exact paths, IDs, hashes, ignored artifacts, blockers, and next gate first; it requires explicit scope, human identity, and `--yes`, and never includes stale or ineligible artifacts.
- `approved -> in_progress`: requires an approved task or an explicit prototype/draft exception.
- `in_progress -> implemented`: requires structured working-tree evidence in the task file: branch, base commit, changed paths, diff hash, tests, and gate results. It does not require a commit.
@@ -748,6 +756,17 @@ Installation, CLI update, product upgrade, and removal are separate. Install scr
The CLI's generated help is authoritative for command syntax. Git history records how framework boundaries evolved; skills define specialist procedure; templates define artifact structure; `BOOTSTRAP.md` defines the initial route; `context.md` defines local state and handoff.
+### Local project-status server
+
+The optional `server` command provides a local-only, browser-based status
+surface for project users. It is not the technical workspace `dashboard`, does
+not expose a remote API, and does not create approvals itself. The interface
+may present eligible approval actions only through the existing approval engine,
+which remains responsible for previews, explicit confirmation, evidence, and
+authorization boundaries. The local process binds to loopback, supports graceful
+shutdown through `Ctrl+C` or `server stop`, and stores only ephemeral connection
+metadata under `.product/`.
+
## 16. Final Rule
The framework must help agents think before they build.
diff --git a/PRODUCT.md b/PRODUCT.md
new file mode 100644
index 0000000..86347c4
--- /dev/null
+++ b/PRODUCT.md
@@ -0,0 +1,62 @@
+# Product
+
+## Register
+
+product
+
+## Platform
+
+web
+
+## Users
+
+The primary users are people authorized to approve project documentation and
+project collaborators who need to understand its current state. Approvers need
+to identify the items that block progress, inspect their context and content,
+and take a governed approval or rejection action. Collaborators need the same
+clear navigation and status visibility without gaining approval authority.
+
+## Product Purpose
+
+The project dashboard makes documentation and its delivery status understandable
+at a glance. Its primary outcome is that a user can immediately see what is
+blocking the project, navigate the relevant documentation, understand why it
+matters, and take the next permitted action.
+
+## Positioning
+
+Turn a project's documentation tree into a clear, actionable view of what is
+blocking progress and what can safely move forward.
+
+## Brand Personality
+
+Usable, clean, and pleasant. The interface should feel calm and dependable when
+someone is deciding whether to approve a project artifact.
+
+## Anti-references
+
+Avoid extravagant or decorative color. Status color must communicate a concrete
+state and always be accompanied by text or another non-color cue. Avoid dense,
+technical-first screens that expose implementation detail before the user asks
+for it.
+
+## Design Principles
+
+1. Show blockers before activity: the first screen answers what is preventing
+ progress.
+2. Reveal detail through navigation: start with a readable documentation tree
+ and disclose file content, metadata, and dependencies only for the selected
+ item.
+3. Make authority explicit: approval, rejection, and batch approval actions are
+ visible only for eligible artifacts and authorized people.
+4. Preserve decision context: every approval action makes the artifact content,
+ current status, and reason for its gate available before confirmation.
+5. Keep the visual system quiet: use restrained, purposeful color and clear
+ hierarchy rather than decorative metrics or technical noise.
+
+## Accessibility & Inclusion
+
+All primary navigation and approval workflows must be usable with a keyboard
+and understandable with screen readers. Status must never rely on color alone.
+Interactive controls need accessible names, visible focus, and predictable
+keyboard order.
diff --git a/docs/execution-runtime.md b/docs/execution-runtime.md
index e45b8ac..c469477 100644
--- a/docs/execution-runtime.md
+++ b/docs/execution-runtime.md
@@ -53,6 +53,26 @@ ACP dispatch is experimental and disabled by default. A run requires explicit en
Extensions are versioned manifests discovered without execution. A capability is usable only when that manifest declares it and the product has a matching versioned record under `.product/extensions/`; discovery itself grants no trust or authority.
+## Local project-status server
+
+`spec-framework server` is a local-only, user-facing status surface. It binds
+only to `127.0.0.1`, opens the browser by default, and does not expose a remote
+API. It is deliberately separate from `dashboard`, which is the technical
+workspace view.
+
+Run `spec-framework server start` to start it, `spec-framework server status`
+to print its local URL, and `spec-framework server stop` from another terminal
+to request graceful shutdown. The foreground process also stops on `Ctrl+C`.
+The server stores a short-lived local descriptor under `.product/server.json`;
+it is removed after normal shutdown and never contains approval data.
+
+When the status surface enables review actions, it delegates approval and
+rejection to the same lifecycle engine as the CLI. A rejection requires a
+human identity and revision rationale, writes immutable history, and moves an
+eligible artifact to `rejected`, including an approved artifact that must be
+reopened. A revised rejected artifact may then be directly approved through a
+new recorded human review; the runtime never silently edits product scope.
+
## Owning skills
- `execution-graph`: defines and validates the DAG and graph lifecycle.
diff --git a/docs/todo/compozy-inspired-improvements.md b/docs/todo/compozy-inspired-improvements.md
new file mode 100644
index 0000000..ad3cbfd
--- /dev/null
+++ b/docs/todo/compozy-inspired-improvements.md
@@ -0,0 +1,168 @@
+# Compozy-Inspired Improvement Backlog
+
+## Purpose and status
+
+This is a framework-maintenance backlog derived from a read-only comparison with [compozy/compozy](https://github.com/compozy/compozy). It records candidates; it does not approve architecture, alter Framework contracts, or authorize implementation.
+
+Every topic preserves these constraints:
+
+- Product-owned artifacts remain the source of truth.
+- Human approval and current hash-matching approval records remain mandatory.
+- Code Review, QA, and Security Review remain independent and read-only.
+- An operational runtime may produce evidence but cannot validate, release, commit, push, merge, or create approval records.
+- Upgrade must preserve adopter-owned product content.
+
+## Working agreement
+
+Before implementation, create a bounded proposal naming affected contracts, CLI surface, storage, migration, default and removal behavior, plus combination tests. Obtain an approved framework decision first whenever the topic changes architecture, an external dependency, security/privacy, or a hard-to-reverse policy.
+
+| ID | Topic | Disposition | Priority | Status |
+| --- | --- | --- | --- | --- |
+| CI-01 | Operational event ledger and replay | Adopt | P1 | Candidate |
+| CI-02 | Local status/watch surface | Adopt | P1 | Candidate |
+| CI-03 | Review-finding schema validation | Adopt | P1 | Candidate |
+| CI-04 | Governed workflow memory | Adapt | P1 | Candidate |
+| CI-05 | Normalized external-review ingestion | Adapt | P1 | Candidate |
+| CI-06 | Explicit wave worktrees and cleanup | Adapt | P2 | Candidate |
+| CI-07 | ACP runtime adapter | Adapt | P2 | Candidate |
+| CI-08 | Operational-state reconciler | Investigate | P2 | Candidate |
+| CI-09 | Extension manifest and capabilities | Investigate | P3 | Candidate |
+| CI-10 | Ambient global configuration | Reject | — | Closed |
+| CI-11 | Automatic commits and review remediation | Reject | — | Closed |
+| CI-12 | Task-frontmatter-only graph | Reject | — | Closed |
+
+## CI-01 — Operational event ledger and replay
+
+**Problem.** Workspaces have state, checkpoints, handoffs, leases, and command evidence, but no uniform timeline to reconstruct a failed run.
+
+**Proposed outcome.** Add an optional append-only ledger under the workspace runtime area, such as .product/workspaces/WORK-NNN/events. It records operational facts: lease claimed, command started/finished, checkpoint written, integration planned, and task blocked. It is not a product artifact and cannot change lifecycle state.
+
+**Modules and controls.** Event envelope, append-only writer, reader/replay API, retention policy, redaction policy, and CLI formatter. Start opt-in or only with a new runtime version; stopping or deleting the ledger must not invalidate product artifacts or approval records.
+
+**Risks.** Command-output leakage, unbounded disk growth, and treating the ledger as truth.
+
+**Done when.** Ordering is deterministic; appends survive restart; redaction is tested; replay reports corrupt gaps; an event cannot advance implemented, validated, or released.
+
+## CI-02 — Local status and watch surface
+
+**Problem.** Navigation exposes product and workspace state but lacks an operator view of a live or interrupted execution.
+
+**Proposed outcome.** Add read-only runtime status and runtime watch views over the ledger, checkpoints, leases, and command evidence. Watch should begin as local polling; a daemon is not required.
+
+**Boundary.** These views may show blockers and suggested owners, but never execute commands, recover leases, or approve artifacts.
+
+**Dependencies.** CI-01 is preferred, although an initial snapshot can read existing workspace files.
+
+**Done when.** Idle, active, expired-lease, failed-command, and stale-input fixtures render correctly; read-only mode makes no writes; JSON output is stable.
+
+## CI-03 — Schema validation for imported review findings
+
+**Problem.** Code Review and QA templates exist, but externally sourced feedback has no provider-neutral, mechanically validated format.
+
+**Proposed outcome.** Define a review-finding schema and validator with stable ID, source, external reference, observed commit/diff hash when available, severity, description, status, affected scope, evidence, and suggested owner. A finding is evidence and routing input, never approval.
+
+**Scope.** Template, validator rule, JSON output, and docs only. Do not add a provider client in this topic.
+
+**Done when.** Missing provenance and invalid severity fail; manual findings are accepted; diff mismatch is reported; a finding cannot make a task validated.
+
+## CI-04 — Governed workflow memory
+
+**Problem.** Handoffs and checkpoints preserve snapshots, but related task runs can lose concise operational learning.
+
+**Proposed outcome.** Add optional two-tier memory: task-local notes at memory/tasks/TK-NNN.md and shared cross-task context at memory/shared.md. It may contain links to approved decisions, verified discoveries, active risks, and handoff facts.
+
+**Guardrails.** It must not contain credentials, invented requirements, approval claims, or replacements for Specifications, DEC records, QA Evidence, or Code Review. Promoted shared entries need source links; compaction preserves active risks and references; canonical repository state wins on conflict.
+
+**Activation and removal.** Disabled by default and enabled per workspace through explicit runtime configuration. Disabling stops writes; removal changes no canonical product state.
+
+**Done when.** Links/provenance validate; compaction preserves active risks; contradictions are reported; memory never writes approval history.
+
+## CI-05 — Normalized ingestion of external reviews
+
+**Problem.** GitHub, CodeRabbit, CI, and AI feedback need an auditable entry path without provider authority over delivery state.
+
+**Proposed outcome.** Add an optional reviews import adapter family. It reads a named source, normalizes data into CI-03 findings, and proposes routing: behavior defect to Bug Fixer/Code Runner; coverage to QA; security to Security Review; ambiguous requirement/decision to Product Historian and a human.
+
+**Non-goals.** No automatic remote thread resolution, code edits, commits, pushes, merges, approvals, or validation. Provider failure cannot roll back product state.
+
+**Dependencies.** CI-03 and explicit decisions on credentials, network access, and data handling.
+
+**Done when.** Every imported finding remains traceable to its source; malformed payload fails closed; manual and provider findings share one schema; a fix requires new QA and Code Review over the current diff hash.
+
+## CI-06 — Explicit worktree execution by scheduler wave
+
+**Problem.** The runtime can create task worktrees and compute safe waves but does not yet join them in an explicit operator-selected execution mode.
+
+**Proposed outcome.** Add wave isolation: allocate worktrees only after a per-run choice and only where no dependency, writeScope, or sharedResources conflict exists. Plan integration in DAG order and require integrated QA afterward.
+
+**Activation and removal.** Default off. Require an explicit isolate mode plus a current approved graph. Cleanup must be bounded and preserve failed worktrees according to retention policy.
+
+**Risks.** Merge conflicts, disk growth, mistaken parallelism, and implicit auto-execution.
+
+**Done when.** Overlapping paths never run concurrently; no worktree appears without activation; conflicts stop integration; cleanup is covered for success, failure, cancellation, and restart.
+
+## CI-07 — Governed ACP runtime adapter
+
+**Problem.** The runtime deliberately does not spawn agents. ACP could offer portable execution across runtimes, but crossing that boundary is architectural.
+
+**Proposed outcome.** An experimental agent-runtime module dispatches exactly one ready, leased task to a selected ACP-compatible runtime, using isolation when necessary. It captures transcript and implementation evidence for normal QA and Code Review.
+
+**Hard limits.** It cannot approve, create approval records, alter scope, bypass writeScope, commit, push, merge, mark work validated/released, or run remote/destructive actions without the existing human gate.
+
+**Activation.** Disabled by default; explicit product/runtime configuration and per-run acknowledgement. Runtime/model selection must use manifest or flags, never ambient user configuration.
+
+**Dependencies.** CI-01/CI-02 are strongly recommended; CI-06 supports parallel execution. An approved framework decision on ACP support and distribution is mandatory first.
+
+**Done when.** It refuses unready, stale, or unleased tasks; records transcript and diff evidence; rejects scope escape; interruption resumes or yields a clear blocker; post-run state is at most implemented.
+
+## CI-08 — Operational-state reconciler
+
+**Problem.** State is distributed among task files, graph, leases, checkpoints, command evidence, worktrees, and future event records; drift needs diagnosis without automatic repair.
+
+**Proposed outcome.** A read-only runtime reconcile command reports expired leases, orphaned worktrees, stale plans, missing evidence, diff-hash mismatch, and task/graph conflicts.
+
+**Boundary.** It cannot repair approval records, change task status, delete worktrees, or invent evidence. Every corrective follow-up stays explicit and previewable.
+
+**Done when.** Fixtures cover each drift type; default execution changes no files; JSON output is deterministic; every finding names an owner.
+
+## CI-09 — Extension manifest and capability model
+
+**Problem.** Visual adapters exist, but future execution and review adapters need a uniform declaration of version, scope, dependencies, and permissions.
+
+**Proposed outcome.** Investigate a versioned extension manifest for read-only observers, controlled importers, and runtime adapters. Capabilities must map to actual boundaries such as artifacts.read, reviews.import, and runtime.dispatch; declaring a capability is not a sandbox.
+
+**Required decisions.** Trust model, signing/verification, installation source, network policy, subprocess isolation, version pinning, compatibility, and revocation. Do not build an SDK before these decisions.
+
+**Done when for a prototype.** Disabled third-party extensions do nothing; invalid capability fails; adapters cannot escape write scope; upgrade preserves adopter content when an extension is absent or incompatible.
+
+## CI-10 — Do not add ambient global configuration
+
+**Decision.** Rejected. The framework deliberately uses product manifests and explicit flags rather than inherited user configuration.
+
+**Reason.** Global precedence reduces reproducibility and weakens the relationship between a pinned runtime and observed behavior.
+
+**Allowed alternative.** An operator-local cache may hold non-semantic data such as CLI paths or event retention, but cannot alter gates, task behavior, agent selection, approvals, or external access.
+
+## CI-11 — Do not auto-commit or auto-remediate review feedback
+
+**Decision.** Rejected. Automation may propose a fix or produce implementation evidence, but cannot commit, push, merge, resolve a remote thread, or make a task validated.
+
+**Reason.** The framework requires independent QA and Code Review over the same current diff hash, followed by explicit Commit Crafter and PR Finalizer stages.
+
+**Allowed alternative.** CI-05 may route an imported finding into an approved task, which then follows the normal delivery lifecycle.
+
+## CI-12 — Do not collapse the Execution Graph into task frontmatter
+
+**Decision.** Rejected. Task-local frontmatter can hold metadata, but the canonical Execution Graph owns dependencies, writeScope, shared resources, source sections, requirements, acceptance checks, delivery level, and priority.
+
+**Reason.** A frontmatter-only graph cannot preserve the framework's traceability and conflict-aware scheduling contract.
+
+**Allowed alternative.** Improve task-file validation or derive a read-only task index, while retaining execution-graph.json as canonical.
+
+## Suggested sequencing
+
+1. CI-03 and CI-08: bounded validation work without new execution authority.
+2. CI-01 and CI-02: observability foundation.
+3. CI-04 and CI-05: controlled operational context and review ingestion.
+4. CI-06: explicit scheduler-to-worktree integration.
+5. Decide CI-07 and CI-09 only after operational boundaries and extension trust are approved.
diff --git a/examples/events/.product/artifacts.json b/examples/events/.product/artifacts.json
index b794553..e11da43 100644
--- a/examples/events/.product/artifacts.json
+++ b/examples/events/.product/artifacts.json
@@ -354,7 +354,7 @@
"ownerSkill": "engineering-system",
"parentIds": null,
"path": "engineering/engineering-system.md",
- "status": "draft",
+ "status": "approved",
"type": "engineering-system"
},
{
@@ -1016,7 +1016,7 @@
"ownerSkill": "Threat Modeler AI",
"parentIds": null,
"path": "audits/security/threat-register.md",
- "status": "draft",
+ "status": "rejected",
"type": "threat-register"
},
{
@@ -1587,6 +1587,6 @@
"type": "vision"
}
],
- "generatedAt": "2026-07-14T15:29:10.2725287Z",
+ "generatedAt": "2026-07-16T18:01:48.8218037Z",
"generator": "spec-framework (Go)"
}
diff --git a/examples/events/.product/history/approval-engsys-events-001-approved-1784222157279091500.json b/examples/events/.product/history/approval-engsys-events-001-approved-1784222157279091500.json
new file mode 100644
index 0000000..6d14010
--- /dev/null
+++ b/examples/events/.product/history/approval-engsys-events-001-approved-1784222157279091500.json
@@ -0,0 +1,9 @@
+{
+ "artifact_id": "ENGSYS-EVENTS-001",
+ "path": "engineering/engineering-system.md",
+ "content_hash": "7c76e8d3a148985a61704c5dc4399f0e64cfad3e227efb00319ef461084eaea2",
+ "status_granted": "approved",
+ "approved_by": "jonatas",
+ "approved_at": "2026-07-16T17:15:57Z",
+ "notes": ""
+}
diff --git a/examples/events/.product/history/approval-threat-register-001-approved-1784216433078634000.json b/examples/events/.product/history/approval-threat-register-001-approved-1784216433078634000.json
new file mode 100644
index 0000000..dd9dbc2
--- /dev/null
+++ b/examples/events/.product/history/approval-threat-register-001-approved-1784216433078634000.json
@@ -0,0 +1,9 @@
+{
+ "artifact_id": "THREAT-REGISTER-001",
+ "path": "audits/security/threat-register.md",
+ "content_hash": "643a0085b9d13b062b333aa69e291d0320a79faaacfc28ab655e61227b011107",
+ "status_granted": "approved",
+ "approved_by": "jonatas",
+ "approved_at": "2026-07-16T15:40:33Z",
+ "notes": ""
+}
diff --git a/examples/events/.product/history/approval-threat-register-001-approved-1784218628166918900.json b/examples/events/.product/history/approval-threat-register-001-approved-1784218628166918900.json
new file mode 100644
index 0000000..c435c17
--- /dev/null
+++ b/examples/events/.product/history/approval-threat-register-001-approved-1784218628166918900.json
@@ -0,0 +1,9 @@
+{
+ "artifact_id": "THREAT-REGISTER-001",
+ "path": "audits/security/threat-register.md",
+ "content_hash": "643a0085b9d13b062b333aa69e291d0320a79faaacfc28ab655e61227b011107",
+ "status_granted": "approved",
+ "approved_by": "jonatas",
+ "approved_at": "2026-07-16T16:17:08Z",
+ "notes": ""
+}
diff --git a/examples/events/.product/history/approval-threat-register-001-rejected-1784217749635638900.json b/examples/events/.product/history/approval-threat-register-001-rejected-1784217749635638900.json
new file mode 100644
index 0000000..684bd33
--- /dev/null
+++ b/examples/events/.product/history/approval-threat-register-001-rejected-1784217749635638900.json
@@ -0,0 +1,9 @@
+{
+ "artifact_id": "THREAT-REGISTER-001",
+ "path": "audits/security/threat-register.md",
+ "content_hash": "42ca511ebf58a29322ad5ede1e3de60897a1f6d3d5e3e02111b00c20e8dd4c83",
+ "status_granted": "rejected",
+ "approved_by": "jonatas",
+ "approved_at": "2026-07-16T16:02:29Z",
+ "notes": "asdasdsa"
+}
diff --git a/examples/events/.product/history/approval-threat-register-001-rejected-1784218645272006100.json b/examples/events/.product/history/approval-threat-register-001-rejected-1784218645272006100.json
new file mode 100644
index 0000000..aa5e12f
--- /dev/null
+++ b/examples/events/.product/history/approval-threat-register-001-rejected-1784218645272006100.json
@@ -0,0 +1,9 @@
+{
+ "artifact_id": "THREAT-REGISTER-001",
+ "path": "audits/security/threat-register.md",
+ "content_hash": "42ca511ebf58a29322ad5ede1e3de60897a1f6d3d5e3e02111b00c20e8dd4c83",
+ "status_granted": "rejected",
+ "approved_by": "ddd",
+ "approved_at": "2026-07-16T16:17:25Z",
+ "notes": "ff"
+}
diff --git a/examples/events/.product/server.json b/examples/events/.product/server.json
new file mode 100644
index 0000000..adf5742
--- /dev/null
+++ b/examples/events/.product/server.json
@@ -0,0 +1 @@
+{"url":"http://127.0.0.1:51525","token":"8609538a9b28e33d9635b543a6658a97aa370b0d5ac872a7"}
\ No newline at end of file
diff --git a/examples/events/audits/security/threat-register.md b/examples/events/audits/security/threat-register.md
index 2ea14a2..6336dce 100644
--- a/examples/events/audits/security/threat-register.md
+++ b/examples/events/audits/security/threat-register.md
@@ -5,7 +5,7 @@
| Field | Value |
| --- | --- |
| ID | `THREAT-REGISTER-001` |
-| Status | `draft` |
+| Status | `rejected` |
| Owner skill | Threat Modeler AI |
| Governed by | `FRAMEWORK.md security policy` |
| Scope | Product/framework adoption baseline |
diff --git a/examples/events/engineering/context.md b/examples/events/engineering/context.md
index df59466..216b3c5 100644
--- a/examples/events/engineering/context.md
+++ b/examples/events/engineering/context.md
@@ -2,7 +2,7 @@
id: ENGSYS-EVENTS-001
type: engineering-system
name: Events Worked Fixture Engineering System
-status: draft
+status: approved
owner_skill: engineering-system
version: 0.1.0
origin_mode: generate
diff --git a/examples/events/engineering/engineering-system.md b/examples/events/engineering/engineering-system.md
index 0ac3a42..18a4e13 100644
--- a/examples/events/engineering/engineering-system.md
+++ b/examples/events/engineering/engineering-system.md
@@ -5,7 +5,7 @@
| Field | Value |
| --- | --- |
| ID | `ENGSYS-EVENTS-001` |
-| Status | `draft` |
+| Status | `approved` |
| Version | `0.1.0` |
| Origin mode | `generate` |
| Mechanical catalog | [engineering-system.yaml](engineering-system.yaml) |
diff --git a/examples/events/engineering/engineering-system.yaml b/examples/events/engineering/engineering-system.yaml
index 3bb950f..bc62420 100644
--- a/examples/events/engineering/engineering-system.yaml
+++ b/examples/events/engineering/engineering-system.yaml
@@ -1,24 +1,24 @@
schema_version: 1
id: ENGSYS-EVENTS-001
-status: draft
+status: approved
version: 0.1.0
origin_mode: generate
scope: documentation-fixture
areas:
- system_context:
- contract: architecture/system-context.md
- maturity: baseline
- evidence: []
- modules:
- contract: architecture/modules.md
- maturity: baseline
- evidence: []
- quality:
- contract: quality/quality-system.md
- maturity: baseline
- evidence: []
+ system_context:
+ contract: architecture/system-context.md
+ maturity: baseline
+ evidence: []
+ modules:
+ contract: architecture/modules.md
+ maturity: baseline
+ evidence: []
+ quality:
+ contract: quality/quality-system.md
+ maturity: baseline
+ evidence: []
decisions:
- - DEC-001
- - DEC-002
+ - DEC-001
+ - DEC-002
standards: []
fitness_functions: []
diff --git a/examples/events/engineering/quality/quality-system.md b/examples/events/engineering/quality/quality-system.md
index be6ba59..9d066a9 100644
--- a/examples/events/engineering/quality/quality-system.md
+++ b/examples/events/engineering/quality/quality-system.md
@@ -5,7 +5,7 @@
| Field | Value |
| --- | --- |
| Engineering System | `ENGSYS-EVENTS-001 @ 0.1.0` |
-| Status | `draft` |
+| Status | `approved` |
| Mechanical catalog | [quality-system.yaml](quality-system.yaml) |
| Quality model | [quality-model.md](quality-model.md) |
| Test strategy | [test-strategy.md](test-strategy.md) |
diff --git a/examples/events/engineering/quality/quality-system.yaml b/examples/events/engineering/quality/quality-system.yaml
index 5ec8646..b07bb92 100644
--- a/examples/events/engineering/quality/quality-system.yaml
+++ b/examples/events/engineering/quality/quality-system.yaml
@@ -1,41 +1,41 @@
schema_version: 1
engineering_system: ENGSYS-EVENTS-001
version: 0.1.0
-status: draft
+status: approved
areas:
- behavioral:
- maturity: baseline
- policy: test-strategy.md
- required_evidence: []
- accessibility:
- maturity: baseline
- policy: test-strategy.md
- required_evidence: []
- security_privacy:
- maturity: baseline
- policy: test-strategy.md
- delegated_gate: security-review
- required_evidence: []
- performance_reliability:
- maturity: baseline
- policy: quality-model.md
- required_evidence: []
- observability:
- maturity: baseline
- policy: quality-model.md
- required_evidence: []
+ behavioral:
+ maturity: baseline
+ policy: test-strategy.md
+ required_evidence: []
+ accessibility:
+ maturity: baseline
+ policy: test-strategy.md
+ required_evidence: []
+ security_privacy:
+ maturity: baseline
+ policy: test-strategy.md
+ delegated_gate: security-review
+ required_evidence: []
+ performance_reliability:
+ maturity: baseline
+ policy: quality-model.md
+ required_evidence: []
+ observability:
+ maturity: baseline
+ policy: quality-model.md
+ required_evidence: []
gate_source: knowledge/conventions/gates.md
environments:
- - documentation-fixture
+ - documentation-fixture
test_data_classes:
- - synthetic-event
- - synthetic-user
- - synthetic-token
+ - synthetic-event
+ - synthetic-user
+ - synthetic-token
platforms:
- - web
- - mobile-camera
+ - web
+ - mobile-camera
exceptions:
- require_owner: true
- require_residual_risk: true
- require_expiry_or_review: true
- records: []
+ require_owner: true
+ require_residual_risk: true
+ require_expiry_or_review: true
+ records: []
diff --git a/internal/cli/app_test.go b/internal/cli/app_test.go
index d4df0cc..7b9147a 100644
--- a/internal/cli/app_test.go
+++ b/internal/cli/app_test.go
@@ -45,7 +45,7 @@ func TestUnknownCommandIsUsageError(t *testing.T) {
func TestCobraCommandTreeKeepsStableTopLevelCommands(t *testing.T) {
root := cli.New("test").NewCommand(&bytes.Buffer{}, &bytes.Buffer{})
- for _, name := range []string{"init", "validate", "graph", "runtime", "update", "uninstall", "upgrade", "version"} {
+ for _, name := range []string{"init", "validate", "graph", "runtime", "server", "update", "uninstall", "upgrade", "version"} {
command, _, err := root.Find([]string{name})
if err != nil || command == root || command.Name() != name {
t.Errorf("Cobra command %q was not registered: command=%v err=%v", name, command, err)
diff --git a/internal/cli/cobra.go b/internal/cli/cobra.go
index acbec11..d56ecd1 100644
--- a/internal/cli/cobra.go
+++ b/internal/cli/cobra.go
@@ -66,6 +66,7 @@ func (app App) NewCommand(stdout, stderr io.Writer) *cobra.Command {
app.legacyCommand("approve-stage", "Approve eligible artifacts in a stage atomically.", func(args []string, out, errout io.Writer) int { return runStage("approve-stage", args, out, errout) }, stdout, stderr),
app.legacyCommand("impact", "Inspect a decision's validity and propagation.", func(args []string, out, errout io.Writer) int { return runImpact(args, out, errout) }, stdout, stderr),
app.legacyCommand("dashboard", "Show a consolidated workflow dashboard.", func(args []string, out, errout io.Writer) int { return runDashboard(args, out, errout) }, stdout, stderr),
+ app.legacyCommand("server", "Run the local project-status server.", func(args []string, out, errout io.Writer) int { return runServer(args, out, errout) }, stdout, stderr),
app.legacyCommand("decisions", "Check or migrate product decisions.", func(args []string, out, errout io.Writer) int { return runDecisions(args, out, errout) }, stdout, stderr),
app.legacyCommand("dispatch", "Plan and supervise governed subagent assignments.", func(args []string, out, errout io.Writer) int { return runDispatch(args, out, errout) }, stdout, stderr),
)
diff --git a/internal/cli/server.go b/internal/cli/server.go
new file mode 100644
index 0000000..283b327
--- /dev/null
+++ b/internal/cli/server.go
@@ -0,0 +1,97 @@
+package cli
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "os/signal"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "syscall"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/projectserver"
+)
+
+func runServer(args []string, stdout, stderr io.Writer) int {
+ action := "start"
+ if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
+ action, args = args[0], args[1:]
+ }
+ flags := flag.NewFlagSet("server "+action, flag.ContinueOnError)
+ flags.SetOutput(stderr)
+ root := flags.String("product-root", "product", "product root")
+ port := flags.Int("port", 0, "local port; 0 selects a free port")
+ noOpen := flags.Bool("no-open", false, "do not open the browser")
+ if err := flags.Parse(args); err != nil {
+ return 2
+ }
+ cwd, err := os.Getwd()
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ productRoot := *root
+ if !filepath.IsAbs(productRoot) {
+ productRoot = filepath.Join(cwd, productRoot)
+ }
+ switch action {
+ case "start":
+ return startServer(productRoot, *port, *noOpen, stdout, stderr)
+ case "stop":
+ if err := projectserver.Stop(productRoot); err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ fmt.Fprintln(stdout, "Local project server stopped.")
+ return 0
+ case "status":
+ descriptor, err := projectserver.Healthy(productRoot)
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ fmt.Fprintf(stdout, "Local project server: running\n- URL: %s\n", descriptor.URL)
+ return 0
+ default:
+ fmt.Fprintln(stderr, "server requires start, stop, or status")
+ return 2
+ }
+}
+
+func startServer(root string, port int, noOpen bool, stdout, stderr io.Writer) int {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ running, err := projectserver.Start(ctx, projectserver.Config{ProductRoot: root, Port: port})
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ fmt.Fprintf(stdout, "Local project server running\n- URL: %s\n- Stop: Ctrl+C or spec-framework server stop --product-root %s\n", running.URL, filepath.Clean(root))
+ if !noOpen {
+ if err := openBrowser(running.URL); err != nil {
+ fmt.Fprintln(stderr, "Could not open browser:", err)
+ }
+ }
+ if err := <-running.Done; err != nil {
+ fmt.Fprintln(stderr, err)
+ return 1
+ }
+ return 0
+}
+
+func openBrowser(url string) error {
+ var command *exec.Cmd
+ switch runtime.GOOS {
+ case "windows":
+ command = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
+ case "darwin":
+ command = exec.Command("open", url)
+ default:
+ command = exec.Command("xdg-open", url)
+ }
+ return command.Start()
+}
diff --git a/internal/projectserver/api.go b/internal/projectserver/api.go
new file mode 100644
index 0000000..84848b0
--- /dev/null
+++ b/internal/projectserver/api.go
@@ -0,0 +1,138 @@
+package projectserver
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/workflow"
+)
+
+type projectStatus struct {
+ Documents []document `json:"documents"`
+ Metrics metrics `json:"metrics"`
+}
+
+type metrics struct {
+ Total int `json:"total"`
+ Approved int `json:"approved"`
+ Pending int `json:"pending"`
+ Rejected int `json:"rejected"`
+}
+
+type document struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Path string `json:"path"`
+ Folder string `json:"folder"`
+ Status string `json:"status"`
+ Updated string `json:"updated"`
+ Content string `json:"content"`
+}
+
+type transitionRequest struct {
+ ArtifactID string `json:"artifactId"`
+ Status string `json:"status"`
+ ApprovedBy string `json:"approvedBy"`
+ Notes string `json:"notes"`
+ Confirmed bool `json:"confirmed"`
+}
+
+type batchApprovalRequest struct {
+ ArtifactIDs []string `json:"artifactIds"`
+ ApprovedBy string `json:"approvedBy"`
+ Notes string `json:"notes"`
+ Confirmed bool `json:"confirmed"`
+}
+
+func readStatus(root string) (projectStatus, error) {
+ registry, err := workflow.LoadRegistry(root)
+ if err != nil {
+ return projectStatus{}, fmt.Errorf("read artifact registry: %w", err)
+ }
+ result := projectStatus{Documents: make([]document, 0, len(registry.Artifacts))}
+ for _, artifact := range registry.Artifacts {
+ path := filepath.Join(root, filepath.FromSlash(artifact.Path))
+ content, err := os.ReadFile(path)
+ if err != nil {
+ return projectStatus{}, fmt.Errorf("read %s: %w", artifact.Path, err)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ return projectStatus{}, err
+ }
+ result.Documents = append(result.Documents, document{ID: artifact.ID, Title: titleFor(artifact, content), Path: filepath.ToSlash(artifact.Path), Folder: folderFor(artifact.Path), Status: artifact.Status, Updated: info.ModTime().UTC().Format(time.RFC3339), Content: string(content)})
+ result.Metrics.Total++
+ switch artifact.Status {
+ case "approved":
+ result.Metrics.Approved++
+ case "rejected":
+ result.Metrics.Rejected++
+ default:
+ result.Metrics.Pending++
+ }
+ }
+ sort.Slice(result.Documents, func(i, j int) bool { return result.Documents[i].Path < result.Documents[j].Path })
+ return result, nil
+}
+
+func findArtifact(root, id string) (workflow.Artifact, error) {
+ registry, err := workflow.LoadRegistry(root)
+ if err != nil {
+ return workflow.Artifact{}, err
+ }
+ for _, artifact := range registry.Artifacts {
+ if artifact.ID == id {
+ return artifact, nil
+ }
+ }
+ return workflow.Artifact{}, errors.New("artifact not found")
+}
+
+func titleFor(artifact workflow.Artifact, content []byte) string {
+ for _, line := range strings.Split(string(content), "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "# ") {
+ return strings.TrimSpace(strings.TrimPrefix(line, "# "))
+ }
+ }
+ return artifact.ID
+}
+
+func folderFor(path string) string {
+ folder := filepath.ToSlash(filepath.Dir(path))
+ if folder == "." {
+ return "Raiz"
+ }
+ return folder
+}
+
+func decodeJSON(request *http.Request, target any) error {
+ defer request.Body.Close()
+ decoder := json.NewDecoder(io.LimitReader(request.Body, 1<<20))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(target); err != nil {
+ return errors.New("invalid request body")
+ }
+ return nil
+}
+
+func writeJSON(w http.ResponseWriter, status int, value any) {
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(value)
+}
+
+func writeAPIError(w http.ResponseWriter, status int, err error) {
+ writeJSON(w, status, map[string]string{"error": err.Error()})
+}
+func methodNotAllowed(w http.ResponseWriter) {
+ writeAPIError(w, http.StatusMethodNotAllowed, errors.New("method not allowed"))
+}
diff --git a/internal/projectserver/dashboard.html b/internal/projectserver/dashboard.html
new file mode 100644
index 0000000..69820b7
--- /dev/null
+++ b/internal/projectserver/dashboard.html
@@ -0,0 +1,96 @@
+
+
+
+
+
+ Status do projeto
+
+
+
+ Pular para o conteúdo
+
+ Documentação do projeto
+ Buscar documentos 3 documentos · 2 aguardando decisão
Todos Pendentes Recusados Aprovados
+
+
+
+ ! 1 pendência bloqueadora impede o progresso do projetoRevise a pendência abaixo para destravar o andamento.
Especificação de check-in Fluxo de exceção não documentado para cancelamento de reserva.
+ Especificação de check-in 04 Solução › 04.2 Arquitetura · Atualizado hoje às 09:41
BloqueadorAprovar lote (0)
+
+
+
+
+
+
+
diff --git a/internal/projectserver/server.go b/internal/projectserver/server.go
new file mode 100644
index 0000000..2b74cd1
--- /dev/null
+++ b/internal/projectserver/server.go
@@ -0,0 +1,297 @@
+package projectserver
+
+import (
+ "context"
+ "crypto/rand"
+ _ "embed"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/workflow"
+)
+
+const descriptorName = "server.json"
+
+// Config constrains the dashboard runtime to a local product directory.
+type Config struct {
+ ProductRoot string
+ Port int
+}
+
+// Descriptor is the minimal local control record used by server status and stop.
+// The token makes the stop endpoint unavailable to unrelated local processes.
+type Descriptor struct {
+ URL string `json:"url"`
+ Token string `json:"token"`
+}
+
+type Running struct {
+ URL string
+ Done <-chan error
+}
+
+func Start(ctx context.Context, config Config) (Running, error) {
+ root, err := filepath.Abs(config.ProductRoot)
+ if err != nil {
+ return Running{}, err
+ }
+ info, err := os.Stat(root)
+ if err != nil || !info.IsDir() {
+ return Running{}, fmt.Errorf("product root is not a directory: %s", root)
+ }
+ listener, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", fmt.Sprint(config.Port)))
+ if err != nil {
+ return Running{}, err
+ }
+ token, err := newToken()
+ if err != nil {
+ _ = listener.Close()
+ return Running{}, err
+ }
+ url := "http://" + listener.Addr().String()
+ if err := writeDescriptor(root, Descriptor{URL: url, Token: token}); err != nil {
+ _ = listener.Close()
+ return Running{}, err
+ }
+
+ shutdown := make(chan struct{})
+ var shutdownOnce sync.Once
+ requestShutdown := func() { shutdownOnce.Do(func() { close(shutdown) }) }
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = io.WriteString(w, dashboardHTML)
+ })
+ mux.HandleFunc("/__spec-framework/health", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"status":"ok"}`)
+ })
+ mux.HandleFunc("/__spec-framework/stop", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.Header.Get("X-Spec-Server-Token") != token {
+ http.NotFound(w, r)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ requestShutdown()
+ })
+ mux.HandleFunc("/api/status", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ methodNotAllowed(w)
+ return
+ }
+ status, err := readStatus(root)
+ if err != nil {
+ writeAPIError(w, http.StatusInternalServerError, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, status)
+ })
+ mux.HandleFunc("/api/transition", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w)
+ return
+ }
+ var request transitionRequest
+ if err := decodeJSON(r, &request); err != nil {
+ writeAPIError(w, http.StatusBadRequest, err)
+ return
+ }
+ if !request.Confirmed {
+ writeAPIError(w, http.StatusBadRequest, errors.New("confirmation is required"))
+ return
+ }
+ if strings.TrimSpace(request.ApprovedBy) == "" {
+ writeAPIError(w, http.StatusBadRequest, errors.New("approver identity is required"))
+ return
+ }
+ artifact, err := findArtifact(root, request.ArtifactID)
+ if err != nil {
+ writeAPIError(w, http.StatusNotFound, err)
+ return
+ }
+ record, err := workflow.Approve(root, filepath.Join(root, filepath.FromSlash(artifact.Path)), request.Status, request.ApprovedBy, request.Notes)
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, record)
+ })
+ mux.HandleFunc("/api/batch-approve", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w)
+ return
+ }
+ var request batchApprovalRequest
+ if err := decodeJSON(r, &request); err != nil {
+ writeAPIError(w, http.StatusBadRequest, err)
+ return
+ }
+ if !request.Confirmed {
+ writeAPIError(w, http.StatusBadRequest, errors.New("confirmation is required"))
+ return
+ }
+ if strings.TrimSpace(request.ApprovedBy) == "" {
+ writeAPIError(w, http.StatusBadRequest, errors.New("approver identity is required"))
+ return
+ }
+ plan, err := workflow.BuildBatchApprovalPlan(root, workflow.BatchScope{IDs: request.ArtifactIDs}, "approved")
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ records, err := workflow.ApproveBatch(root, plan, request.ApprovedBy, request.Notes)
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, records)
+ })
+ mux.HandleFunc("/api/batch-approval-plan", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ methodNotAllowed(w)
+ return
+ }
+ var request batchApprovalRequest
+ if err := decodeJSON(r, &request); err != nil {
+ writeAPIError(w, http.StatusBadRequest, err)
+ return
+ }
+ plan, err := workflow.BuildBatchApprovalPlan(root, workflow.BatchScope{IDs: request.ArtifactIDs}, "approved")
+ if err != nil {
+ writeAPIError(w, http.StatusUnprocessableEntity, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, plan)
+ })
+
+ httpServer := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
+ done := make(chan error, 1)
+ go func() {
+ err := httpServer.Serve(listener)
+ if !errors.Is(err, http.ErrServerClosed) {
+ done <- err
+ return
+ }
+ done <- nil
+ }()
+ go func() {
+ select {
+ case <-ctx.Done():
+ case <-shutdown:
+ }
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _ = httpServer.Shutdown(shutdownCtx)
+ _ = os.Remove(descriptorPath(root))
+ }()
+ return Running{URL: url, Done: done}, nil
+}
+
+func Stop(productRoot string) error {
+ descriptor, err := ReadDescriptor(productRoot)
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequest(http.MethodPost, descriptor.URL+"/__spec-framework/stop", nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("X-Spec-Server-Token", descriptor.Token)
+ client := &http.Client{Timeout: 3 * time.Second}
+ resp, err := client.Do(req)
+ if err != nil {
+ return fmt.Errorf("local server is not reachable: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusNoContent {
+ return fmt.Errorf("local server refused stop request: %s", resp.Status)
+ }
+ return nil
+}
+
+func Healthy(productRoot string) (Descriptor, error) {
+ descriptor, err := ReadDescriptor(productRoot)
+ if err != nil {
+ return Descriptor{}, err
+ }
+ client := &http.Client{Timeout: 3 * time.Second}
+ response, err := client.Get(descriptor.URL + "/__spec-framework/health")
+ if err != nil {
+ return Descriptor{}, fmt.Errorf("local server is not reachable: %w", err)
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ return Descriptor{}, fmt.Errorf("local server health check failed: %s", response.Status)
+ }
+ return descriptor, nil
+}
+
+func ReadDescriptor(productRoot string) (Descriptor, error) {
+ data, err := os.ReadFile(descriptorPath(productRoot))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return Descriptor{}, errors.New("no local project server is recorded for this product")
+ }
+ return Descriptor{}, err
+ }
+ var descriptor Descriptor
+ if err := json.Unmarshal(data, &descriptor); err != nil {
+ return Descriptor{}, fmt.Errorf("read local server descriptor: %w", err)
+ }
+ if !strings.HasPrefix(descriptor.URL, "http://127.0.0.1:") || descriptor.Token == "" {
+ return Descriptor{}, errors.New("local server descriptor is invalid")
+ }
+ return descriptor, nil
+}
+
+func descriptorPath(root string) string { return filepath.Join(root, ".product", descriptorName) }
+
+func writeDescriptor(root string, descriptor Descriptor) error {
+ dir := filepath.Dir(descriptorPath(root))
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ data, err := json.Marshal(descriptor)
+ if err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(dir, ".server-*.tmp")
+ if err != nil {
+ return err
+ }
+ name := tmp.Name()
+ defer os.Remove(name)
+ if _, err := tmp.Write(data); err != nil {
+ tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ return os.Rename(name, descriptorPath(root))
+}
+
+func newToken() (string, error) {
+ bytes := make([]byte, 24)
+ if _, err := rand.Read(bytes); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(bytes), nil
+}
+
+//go:embed dashboard.html
+var dashboardHTML string
diff --git a/internal/projectserver/server_test.go b/internal/projectserver/server_test.go
new file mode 100644
index 0000000..224ba93
--- /dev/null
+++ b/internal/projectserver/server_test.go
@@ -0,0 +1,133 @@
+package projectserver
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/JonatasFreireDev/spec-framework/internal/workflow"
+)
+
+func TestStartServesLocalPageAndStopRemovesDescriptor(t *testing.T) {
+ root := t.TempDir()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ running, err := Start(ctx, Config{ProductRoot: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ response, err := http.Get(running.URL + "/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("status=%s", response.Status)
+ }
+ if _, err := ReadDescriptor(root); err != nil {
+ t.Fatalf("descriptor: %v", err)
+ }
+ if _, err := Healthy(root); err != nil {
+ t.Fatalf("health: %v", err)
+ }
+ if err := Stop(root); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case err := <-running.Done:
+ if err != nil {
+ t.Fatal(err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("server did not stop")
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ _, err := os.Stat(filepath.Join(root, ".product", descriptorName))
+ if os.IsNotExist(err) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("descriptor still exists: %v", err)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func TestStatusAndRejectionEndpointsUseProductData(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := workflow.Artifact{ID: "TASK-1", Type: "task", Status: "draft", Path: "tasks/one.md"}
+ data, err := json.Marshal(workflow.Registry{Artifacts: []workflow.Artifact{artifact}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, ".product", "artifacts.json"), data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, "tasks", "one.md")
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte("status: draft\n# Tarefa de exemplo\n\nConteúdo."), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ running, err := Start(ctx, Config{ProductRoot: root})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = Stop(root); <-running.Done }()
+ response, err := http.Get(running.URL + "/api/status")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ var status projectStatus
+ if err := json.NewDecoder(response.Body).Decode(&status); err != nil {
+ t.Fatal(err)
+ }
+ if len(status.Documents) != 1 || status.Documents[0].Title != "Tarefa de exemplo" || status.Metrics.Pending != 1 {
+ t.Fatalf("status=%+v", status)
+ }
+ planRequest := bytes.NewBufferString(`{"artifactIds":["TASK-1"]}`)
+ response, err = http.Post(running.URL+"/api/batch-approval-plan", "application/json", planRequest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("batch plan status=%s", response.Status)
+ }
+ var plan workflow.BatchPlan
+ if err := json.NewDecoder(response.Body).Decode(&plan); err != nil {
+ t.Fatal(err)
+ }
+ if len(plan.ToApprove) != 1 || plan.ToApprove[0].ID != "TASK-1" {
+ t.Fatalf("batch plan=%+v", plan)
+ }
+ body := bytes.NewBufferString(`{"artifactId":"TASK-1","status":"rejected","approvedBy":"Product Owner","notes":"Falta definir os critérios.","confirmed":true}`)
+ response, err = http.Post(running.URL+"/api/transition", "application/json", body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ t.Fatalf("rejection status=%s", response.Status)
+ }
+ registry, err := workflow.LoadRegistry(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if registry.Artifacts[0].Status != "rejected" {
+ t.Fatalf("artifact status=%s", registry.Artifacts[0].Status)
+ }
+}
diff --git a/internal/workflow/rejection_test.go b/internal/workflow/rejection_test.go
new file mode 100644
index 0000000..f2589a5
--- /dev/null
+++ b/internal/workflow/rejection_test.go
@@ -0,0 +1,84 @@
+package workflow
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestRejectRequiresRationaleAndReturnsToDraft(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := Artifact{ID: "ART-1", Type: "feature", Status: "draft", Path: "artifact.md"}
+ if err := writeJSON(filepath.Join(root, ".product", "artifacts.json"), Registry{Artifacts: []Artifact{artifact}}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, artifact.Path)
+ if err := os.WriteFile(path, []byte("status: draft\n# Artifact\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Approve(root, path, "rejected", "Product Owner", ""); err == nil || !strings.Contains(err.Error(), "requires notes") {
+ t.Fatalf("empty rejection err=%v", err)
+ }
+ record, err := Approve(root, path, "rejected", "Product Owner", "Clarify the failure path before approval.")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if record.StatusGranted != "rejected" || record.Notes == "" {
+ t.Fatalf("record=%+v", record)
+ }
+ registry, err := LoadRegistry(root)
+ if err != nil || registry.Artifacts[0].Status != "rejected" {
+ t.Fatalf("registry=%+v err=%v", registry, err)
+ }
+ if _, err := Approve(root, path, "draft", "Product Owner", "Revisions started."); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestRejectCanReopenApprovedArtifact(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := Artifact{ID: "ART-1", Type: "feature", Status: "approved", Path: "artifact.md"}
+ if err := writeJSON(filepath.Join(root, ".product", "artifacts.json"), Registry{Artifacts: []Artifact{artifact}}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, artifact.Path)
+ if err := os.WriteFile(path, []byte("status: approved\n# Artifact\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Approve(root, path, "rejected", "Product Owner", "The approved version needs a correction."); err != nil {
+ t.Fatal(err)
+ }
+ registry, err := LoadRegistry(root)
+ if err != nil || registry.Artifacts[0].Status != "rejected" {
+ t.Fatalf("registry=%+v err=%v", registry, err)
+ }
+}
+
+func TestRejectedArtifactCanBeApprovedAgain(t *testing.T) {
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, ".product", "history"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ artifact := Artifact{ID: "ART-1", Type: "feature", Status: "rejected", Path: "artifact.md"}
+ if err := writeJSON(filepath.Join(root, ".product", "artifacts.json"), Registry{Artifacts: []Artifact{artifact}}); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, artifact.Path)
+ if err := os.WriteFile(path, []byte("status: rejected\n# Artifact\n"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Approve(root, path, "approved", "Product Owner", "Revised after the rejection."); err != nil {
+ t.Fatal(err)
+ }
+ registry, err := LoadRegistry(root)
+ if err != nil || registry.Artifacts[0].Status != "approved" {
+ t.Fatalf("registry=%+v err=%v", registry, err)
+ }
+}
diff --git a/internal/workflow/workflow.go b/internal/workflow/workflow.go
index e6bdef6..a26c395 100644
--- a/internal/workflow/workflow.go
+++ b/internal/workflow/workflow.go
@@ -373,10 +373,12 @@ func PreviewApproval(root, artifactPath, grant string) (ApprovalPreview, error)
return ApprovalPreview{}, fmt.Errorf("invalid status transition %s -> %s", a.Status, grant)
}
var blockers []string
- for _, pid := range a.ParentIDs {
- for _, p := range r.Artifacts {
- if p.ID == pid && (!isApproved(p.Status) || !hasCurrentApproval(root, filepath.Join(root, filepath.FromSlash(p.Path)), p.Status)) {
- blockers = append(blockers, fmt.Sprintf("parent %s lacks current approval evidence", pid))
+ if grant != "rejected" && grant != "draft" && grant != "proposed" {
+ for _, pid := range a.ParentIDs {
+ for _, p := range r.Artifacts {
+ if p.ID == pid && (!isApproved(p.Status) || !hasCurrentApproval(root, filepath.Join(root, filepath.FromSlash(p.Path)), p.Status)) {
+ blockers = append(blockers, fmt.Sprintf("parent %s lacks current approval evidence", pid))
+ }
}
}
}
@@ -388,14 +390,16 @@ func PreviewApproval(root, artifactPath, grant string) (ApprovalPreview, error)
if err != nil {
return ApprovalPreview{}, err
}
- validation, err := validator.ValidateCandidate(context.Background(), root, root, artifactPath, updated, grant)
- if err != nil {
- return ApprovalPreview{}, err
- }
validationBlockers := make([]string, 0)
- for _, diagnostic := range validation.Diagnostics {
- if filepath.ToSlash(diagnostic.File) == rel && (diagnostic.Check == "template-conformance" || diagnostic.Check == "import-provenance" || diagnostic.Check == "status-coherence" || diagnostic.Check == "qa-evidence" || diagnostic.Check == "delivery") && diagnostic.Severity == validator.Error {
- validationBlockers = append(validationBlockers, fmt.Sprintf("%s: %s", diagnostic.Check, diagnostic.Message))
+ if grant != "rejected" && grant != "draft" && grant != "proposed" {
+ validation, err := validator.ValidateCandidate(context.Background(), root, root, artifactPath, updated, grant)
+ if err != nil {
+ return ApprovalPreview{}, err
+ }
+ for _, diagnostic := range validation.Diagnostics {
+ if filepath.ToSlash(diagnostic.File) == rel && (diagnostic.Check == "template-conformance" || diagnostic.Check == "import-provenance" || diagnostic.Check == "status-coherence" || diagnostic.Check == "qa-evidence" || diagnostic.Check == "delivery") && diagnostic.Severity == validator.Error {
+ validationBlockers = append(validationBlockers, fmt.Sprintf("%s: %s", diagnostic.Check, diagnostic.Message))
+ }
}
}
updates, err := approvalUpdatesForArtifact(root, a, artifactPath, updated, grant)
@@ -736,14 +740,17 @@ func requiredContracts(contextPath string) []string {
func Approve(root, artifactPath, grant, approvedBy, notes string) (Approval, error) {
grant = strings.TrimSpace(grant)
- if !map[string]bool{"approved": true, "in_progress": true, "implemented": true, "validated": true, "released": true}[grant] {
+ if !map[string]bool{"draft": true, "proposed": true, "approved": true, "rejected": true, "in_progress": true, "implemented": true, "validated": true, "released": true}[grant] {
return Approval{}, fmt.Errorf("unsupported grant %q", grant)
}
+ if grant == "rejected" && strings.TrimSpace(notes) == "" {
+ return Approval{}, errors.New("rejection requires notes explaining what must be revised")
+ }
preview, err := PreviewApproval(root, artifactPath, grant)
if err != nil {
return Approval{}, err
}
- if len(preview.ParentBlockers) > 0 || len(preview.ValidationBlockers) > 0 {
+ if grant != "rejected" && grant != "draft" && grant != "proposed" && (len(preview.ParentBlockers) > 0 || len(preview.ValidationBlockers) > 0) {
return Approval{}, errors.New(strings.Join(append(preview.ParentBlockers, preview.ValidationBlockers...), "; "))
}
r, err := LoadRegistry(root)
@@ -766,6 +773,9 @@ func Approve(root, artifactPath, grant, approvedBy, notes string) (Approval, err
return Approval{}, fmt.Errorf("artifact is not registered: %s", rel)
}
for _, pid := range r.Artifacts[idx].ParentIDs {
+ if grant == "rejected" || grant == "draft" || grant == "proposed" {
+ break
+ }
for _, p := range r.Artifacts {
if p.ID == pid && (!isApproved(p.Status) || !hasCurrentApproval(root, filepath.Join(root, filepath.FromSlash(p.Path)), p.Status)) {
return Approval{}, fmt.Errorf("parent %s lacks current approval evidence", pid)
@@ -1282,7 +1292,7 @@ func validTransition(from, to string) bool {
if from == to {
return true
}
- allowed := map[string][]string{"draft": {"proposed", "approved"}, "proposed": {"approved"}, "materialized": {"approved"}, "approved": {"in_progress"}, "in_progress": {"implemented"}, "implemented": {"validated"}, "validated": {"released"}}
+ allowed := map[string][]string{"draft": {"proposed", "approved", "rejected"}, "proposed": {"approved", "rejected"}, "materialized": {"approved", "rejected"}, "approved": {"in_progress", "rejected"}, "in_progress": {"implemented"}, "implemented": {"validated"}, "validated": {"released"}, "rejected": {"draft", "proposed", "approved"}}
return contains(allowed[from], to)
}
func readJSON(path string, value any) error {