diff --git a/.agents/skills/impeccable/SKILL.md b/.agents/skills/impeccable/SKILL.md index 2f0241d..f000bc4 100644 --- a/.agents/skills/impeccable/SKILL.md +++ b/.agents/skills/impeccable/SKILL.md @@ -1,121 +1,53 @@ --- 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 +metadata: + version: 4.3.1 --- -Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft. +This skill gives you the tools and permission to create design that earns to be called out-of-distribution craft: Whereas before, your design work would have been safe, timid and measured, you now approach every design task as an award-winning design director with impeccable understanding for what makes exceptional design work: production-grade code, peak creativity, a clear POV, deep understanding of the needs of the client and users, and exceptional craft. + +Core principles: +- Go all out. No hedging, no shortcuts. The deliverable must be complete (except assets the user must provide). +- Dream big and bold. Distinct, beautiful, outstanding and highly inspiring work. +- Verify in bounded passes, not a loop, and the ceiling covers the whole cycle: screenshots, defect scans, micro-edits, and rebuilds alike. Build fully, inspect once with a batched round (desktop and mobile together on the web; the shipped device classes on a native platform), fix everything it shows in one batch, confirm with at most one more round, and stop polishing. Open-ended self-QA burns the user's money doing worse what the finish handoffs do better. ## Setup -You MUST do these steps before proceeding: +1. Run `/scripts/impeccable context` once per session, where `` is the directory that contains this SKILL.md (the skill folder, not a plugin root two levels above it); keep cwd at the user's project. That base directory resolves every `.agents/skills/impeccable/scripts/impeccable ` command in this skill and its references, and `.agents/skills/impeccable/scripts` is the fallback only when the runtime reports no base directory. On a Windows shell without `sh`, call `.agents/skills/impeccable/scripts/impeccable.cmd` instead. The launcher runs a self-contained binary that ships next to it or is downloaded once on first run; no Node or other runtime is required. Pass a named source file or route as `--target `. It loads PRODUCT.md, DESIGN.md, the matching surface brief, and native-platform guidance when applicable; follow its directives and do not rerun it. +2. Load the request's playbook: its Commands-table reference for an explicit/implied sub-command, or [reference/new-work.md](reference/new-work.md) for a new surface or replacement visual world. Inspect target and incumbent visual truth before editing. When the app cannot run, start with committed visual-regression goldens or screenshot fixtures; verify target and freshness against current tokens, CSS, components, or assets, resolve conflicts, and compare theme/variant captures. +3. After resolving analysis and direction, read [reference/craft-floor.md](reference/craft-floor.md) immediately before any UI edit, including small refinements. It carries the quality floor, the absolute bans, and the reflexes no detector catches. Do not load it for planning-only work. -1. Run `node .agents/skills/impeccable/scripts/context.mjs` once per session. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .agents/skills/impeccable/scripts/context.mjs --target ` instead. 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`, stop and follow `reference/init.md` before doing anything else.** 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 `reference/.md` next. 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 the project is brand-new (no existing CSS tokens / theme / committed brand colors found in step 3)**, run `node .agents/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.** +**Launcher unavailable:** On refusal or failure, send a separate message **before the next tool call**: “Context loading did not run; I’ll read the existing project context directly.” Then read existing PRODUCT.md and DESIGN.md without inventing missing context, follow applicable steps 2–3, and continue through permitted tools. This applies to planning and editing; launcher failure alone does not block either. -## Design guidance +## How to design -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). GPT is capable of extraordinary work. Don't hold back. +- **The brief wins.** Honor pinned aesthetics, eras, materials, fonts, and palettes even when they conflict with a saturated-pattern warning. Redirecting a clear brief toward your taste is failure. +- **Refinement preserves; redesign replaces.** Refinement keeps the incumbent identity, behavior, copy, and everything outside scope. Ask before replacing factual copy or adding claims. Redesign keeps product truth, content, function, native affordances, and constraints, but treats the old look as evidence and anti-reference; choose a replacement world in new-work and replace DESIGN.md. Never split the difference into polish on the discarded look. +- **Visual authority is evidence, not a filename.** Missing DESIGN.md alone does not make a project greenfield; new-work decides whether to preserve, expand, or replace the incumbent world. -### General rules +## Modes -#### Color +The mode names what the visitor's success looks like on this surface. -- **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. +- **Persuade:** the visitor decides and acts; design is the product. Landing pages, marketing, campaigns, pricing. Earn attention and action. Ship real imagery when the brief needs it; follow the committed world, not category habit. +- **Operate:** the visitor completes a task. App UI, dashboards, editors, admin, settings, tools. Scanability, consistency, native expectations, and the real usage scene outrank expression. Brand lives in precise details. +- **Read:** the visitor understands something. Docs, articles, guides, help, changelogs. Structure for comprehension, then make the reading experience worth staying in. +- **Experience:** the visitor is inside the work itself. Portfolios, galleries, showcases. Let the artifact lead from the first viewport; the interface recedes. -#### 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. - -One hard typographic ceiling you currently miss: -- Display letter-spacing ≥ -0.04em. Your default of -0.05 to -0.085em on display H1s makes the letters touch and reads as cramped. -0.02 to -0.03em is plenty for tight grotesque display; -0.04em is the floor. - -#### 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. - -**Codex-specific defects** (your most-frequent giveaways; refuse-and-rewrite): - -- **`border: 1px solid X` + `box-shadow: 0 Npx Mpx ...` with M ≥ 16px** on the same element. The "ghost-card" pattern: 1px border plus soft wide drop shadow on buttons and cards. Don't pair them. Pick one (a single solid border at the brand color, OR a defined shadow at no more than 8px blur), never both as decoration. -- **`border-radius: 32px+` on cards / sections / inputs.** You over-round. Cards top out at 12–16px; full-pill is fine for tags/buttons. Picking 24/28/32/40px on a card is the codex tell; no brand wants "insanely rounded". -- **Hand-drawn / sketchy SVG illustrations.** Class names like `loose-sketch`, `*-sketch`, `doodle`, `wavy`; `feTurbulence` / `feDisplacementMap` "paper grain" filters; 5-to-30 path crude scenes meant to depict a tangible subject (an otter, a table-and-fork, an album cover). All of these read as amateurish, not whimsical. If you can't render the scene with real assets, ship no illustration. Don't attempt sketchy SVG as a fallback. -- **`repeating-linear-gradient(...)` stripe backgrounds.** Diagonal stripes in `body:before` or section backgrounds are pure codex decoration. Don't. -- **Decorative grid backgrounds.** Two-axis CSS grid overlays built from `linear-gradient(... 1px, transparent 1px)` plus `background-size` are a Codex tell unless the surface is an actual canvas, map, blueprint, or measurement tool. Use product structure, real artifacts, or a plain surface instead. -- **Meta-criticism copy.** Naming a concept then layering an ironic modifier, or staging a strawman to "correct" it. Make the specific claim instead. - -### 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. +Choose the mode from the requested surface, not the product, and persist it only in that surface brief. A tool's landing page is still Persuade; a fashion house's documentation is still Read; a docs index is Read, not Persuade. See [new-work.md](reference/new-work.md) for new surfaces and [operate.md](reference/operate.md) for deeper Operate/Read guidance. ## Commands | Command | Category | Description | Reference | |---|---|---|---| -| `craft [feature]` | Build | Shape, then build a feature end-to-end | [reference/craft.md](reference/craft.md) | +| `craft [feature]` | Build | Deprecated alias for an ordinary new-work request | [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) | +| `init` | Build | Capture durable product context in PRODUCT.md | [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) | +| `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) | @@ -129,47 +61,24 @@ If someone could look at this interface and say "AI made that" without doubt, it | `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) | +| `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: -### Routing rules +- **No argument:** read [routing.md](reference/routing.md) and present its context-aware menu; never auto-run a command. +- **Explicit or clearly implied request to run a command:** load its reference (native variant on native platforms) and follow it. Ask once if two commands fit. +- **Workflow or command-selection question:** read [Workflow questions](reference/routing.md#workflow-questions). +- **Otherwise:** treat the request as general design work. Missing PRODUCT.md routes a new surface or replacement world through init, then new-work; a narrow refinement of existing code proceeds on the incumbent implementation as `impeccable context` directs, offering init afterward rather than blocking on it. +- `teach` aliases `init`. `craft` is a deprecated alias for ordinary new-work and adds nothing. `shape` owns task discovery, then enters new-work only for visual-world and surface-concept decisions. -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` you are already in init (setup), so finish that and skip this. Otherwise run `node .agents/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.** +After init writes PRODUCT.md, resume without rerunning `impeccable context`; init loads the native platform reference itself when the platform it recorded is `ios`, `android`, or `adaptive`. - 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`. - - 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`. +**Pin / Unpin:** `.agents/skills/impeccable/scripts/impeccable pin ` creates or removes a standalone `$` shortcut. Report the script's result concisely; relay stderr verbatim on error. - **If `scan.targets` is non-empty, run `node .agents/skills/impeccable/scripts/detect.mjs --json ` once** (the bundled detector over local files: no network, no npx). `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. +**Hooks:** `$impeccable hooks ` manages the design detector hook for this project (auto-runs the detector after UI file edits and surfaces findings). Load [reference/hooks.md](reference/hooks.md) when the user invokes it with any argument. - 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 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 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. +**Doctor:** `$impeccable doctor` reports and repairs drift between this project's Impeccable artifacts (PRODUCT.md, DESIGN.md and its sidecar, config, surface briefs, the hook) and what this version reads. Load [reference/doctor.md](reference/doctor.md) when the user invokes it, or when they ask what is out of date, stale, or needs refreshing. A `CONTEXT_STALE` directive in Setup's output is the cheap subset of the same report; act on it there per its own instructions rather than running doctor unasked. -Setup (context gathering, register) is already loaded by then; sub-commands don't re-invoke `$impeccable`. - -If the first word is `craft`, setup still runs first, but [reference/craft.md](reference/craft.md) owns the rest of the flow. 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 .agents/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 +**Never repair drift as a side effect of a design task.** A `CONTEXT_STALE` finding is reported, not acted on, unless the user asks. The one exception is a finding marked `auto`, which the next write to that file performs anyway. \ No newline at end of file diff --git a/.agents/skills/impeccable/agents/impeccable_asset_producer.toml b/.agents/skills/impeccable/agents/impeccable_asset_producer.toml index 2419f3e..30f49ab 100644 --- a/.agents/skills/impeccable/agents/impeccable_asset_producer.toml +++ b/.agents/skills/impeccable/agents/impeccable_asset_producer.toml @@ -1,92 +1,42 @@ name = "impeccable_asset_producer" description = "Produces clean reusable raster assets from approved Impeccable mock references without redesigning the direction." model_reasoning_effort = "medium" -nickname_candidates = ["Asset Plate", "Clean Plate", "Crop Cutter"] +nickname_candidates = ["Asset Plate", "Clean Plate", "Re-Render"] developer_instructions = ''' # Impeccable Asset Producer -You are the asset production agent for Impeccable craft. - -Your job is production cleanup, not new art direction. Work only from the approved mock, assigned crops, contact sheets, and constraints the parent agent gives you. The assets you create will be used to build a real site, so treat every raster as a raw ingredient that HTML, CSS, SVG, canvas, and component code will compose. +You are the asset production agent for Impeccable craft. Your job is production cleanup, not new art direction. Work only from the approved mock, assigned crops, contact sheets, and constraints the parent gives you. Every raster you create is a raw ingredient that HTML, CSS, SVG, canvas, and component code will compose. ## Core Rule -Do not redesign. Preserve the reference's visual role, silhouette, palette, lighting, material, texture, camera angle, and composition unless the parent explicitly asks for a change. Preserve perspective only when it belongs to the object or scene itself; if CSS should create the card transform, shadow, rounded clipping, border, or layout, remove that presentation chrome from the raster. +Do not redesign. Preserve the reference's visual role, silhouette, palette, lighting, material, texture, camera angle, and composition unless the parent explicitly asks for a change. Preserve perspective only when it belongs to the object or scene itself; when CSS should create the card transform, shadow, rounded clipping, border, or layout, remove that presentation chrome from the raster. + +## Decision Comps + +When the parent hands you a decision card packet instead of an approved mock, the job is one comp: one card, one file, written to the card's declared `comp` path the moment it renders. The parent runs several of you in parallel, one per card, so this card is your entire contract; generate first, plan never, because the file on disk is the deliverable and the decision page is waiting on it. Work from the card's structured fields and PRODUCT.md alone; report a card too thin to brief a comp, never pad it from imagination. Render the card's direction as a north-star comp at full fidelity: the requested surface's first viewport, prompt led by the surface's own structure (regions named in order with their scale relationships, never the world's atmosphere), fully committed in the card's own palette, type character, and material world. A native app or mobile-first surface is a portrait frame at its device viewport, never a landscape default. Every sibling renders at the same full fidelity in its own grammar, one surface, one aspect; equal commitment keeps the comparison honest. Real product name and real content only; never invent commercial claims, prices, benchmarks, or dates PRODUCT.md does not carry. Exclusions bind those claims, never a medium the card's own world has not excluded: a subject that lives in photographs keeps its photographs. Write the prompt sidecar beside the file. Return one line naming the path and any deviation, nothing more. Everything below this section is the asset-production job; none of it applies to a decision-comp run. ## Input Contract -Expect: +Expect the measured spec (`.impeccable/build/spec.json`, written by `impeccable comp-spec` from the approved comp), the approved comp path, and the skill scripts path. Optionally: a subset of region ids to produce, extra prompt notes per region, and format or transparency needs. Everything else you need is in the spec: each raster region's id, kind (plate, image, texture), pixel box, sampled palette, aspect, note, and the plate path it must land on. -- Approved mock path or screenshot reference. -- Crop paths or a contact sheet with crop ids. -- Output directory. -- Required dimensions, format, transparency needs, and avoid list. -- Notes on what should remain semantic HTML/CSS/SVG instead of raster. +If there is no spec, stop and return one line asking the parent to run `impeccable comp-spec` first. You do not inventory the comp yourself; the spec is the inventory, and a second inventory disagrees with the first. -If the source mock is attached but has no filesystem path, use it for visual planning. Ask for a path only before cropping or writing assets. +## The job -Use defaults unless contradicted: +Every region with `medium: raster` in the spec ships as a plate at its `plate` path. A plate is the region regenerated at asset resolution from the comp crop as reference: same subject, same composition, same palette, same lighting and material, with the UI text and page chrome removed, at 1.5x the comp region's pixel size or more. The page draws text, controls, radius, shadow, and layout in code; the plate carries what code cannot draw. Crops from the comp are references, never shipping pixels: a comp is reference grade and a shipped crop is how a beautiful comp becomes a blurry site. -- `.webp` for opaque photos, backgrounds, and textures. -- `.png` for transparent cutouts, seals, tickets, and illustrations. -- Target production size or at least 2x display size when dimensions are known. Do not use small full-page mock crop size as the default shipping size. -- Remove UI text, navigation, buttons, labels, and body copy by default. -- Keep physical marks only when the parent says they are part of the asset. -- Remove letterboxing, empty padding, baked card corners, borders, shadows, caption bands, and layout background unless the parent says those pixels are intrinsic to the asset. -- Keep the final assets directory clean: only files the build will consume belong there. Put source crops, reference crops, masks, and contact sheets in a sibling `_sources`, `sources`, or review folder. +Per region, in the spec's order: -Ask blockers once, globally. Missing source path/crops or output directory blocks production. Exact dimensions, compression targets, retina variants, and format preferences do not block; choose defaults and report them. +1. `.agents/skills/impeccable/scripts/impeccable comp-spec --crop ` writes the reference crop under `.impeccable/build/crops/`. +2. Choose the background from the approved region: an isolated figure, object, or line drawing on the page ground is a **transparent cutout**; a photograph, full-frame illustration, or texture stays **opaque**. Save `.agents/skills/impeccable/scripts/impeccable comp-spec --plate-prompt --background transparent` to a UTF-8 prompt file for a cutout; use `--background opaque` otherwise. The transparent prompt preserves reference placement and clear margins, white paint, fine edges, and interior holes. +3. Produce the plate at its exact spec `plate` path. Create the output directory first and choose a supported output size matching the region's aspect, at least 1.5x its pixel dimensions. Prefer the harness-native image tool with the crop as input and the saved prompt; request a transparent PNG for cutouts, then run `.agents/skills/impeccable/scripts/impeccable embed-prompt --prompt-file ` (if you refine the prompt, save and embed the exact text sent). With the API fallback, run `.agents/skills/impeccable/scripts/impeccable generate-image --ref --prompt-file --out --size --quality high --background transparent` for a cutout, or `--background opaque` otherwise. The API fallback embeds the prompt and records the background in the sidecar. The output must be PNG; the fallback requests native alpha and performs no chroma-keying. +4. Open the plate beside the crop and compare subject, placement, scale, palette, and style. For cutouts, verify a real alpha channel and inspect composites on light and dark grounds: white paint must stay solid, interior holes must clear, and fine edges must avoid halos. Inspect glass and soft shadows carefully; partial alpha alone does not ensure convincing translucency. Never chroma-key native transparent output or flatten it before saving. If a native tool returns opaque pixels or a painted checkerboard, retry with the API fallback when available; otherwise report the transparency blocker. On a visual miss, tighten the prompt and regenerate once. Two misses on one region: keep the better plate, mark it `needs_parent_review`, and name the drift. The parent runs the plates gate after all assets exist; report `unscored` until a gate score is available. -## Workflow +Codex: the imagegen skill's built-in `image_gen` path is the native tool here; prefer it for generation and editing, with the crop as the input image. -1. Inventory the full approved mock or every assigned crop. -2. Put each visual role in exactly one bucket: - - `produce`: needs generation, image editing, cleanup, cutout work, or a clean plate before it can ship. - - `direct`: can ship as a crop, format conversion, compression pass, or sourced replacement with no generative cleanup. - - `semantic`: build in HTML/CSS/SVG/canvas, no raster output. -3. Treat full-page mock crops as references, not production-resolution source assets. Put a role in `direct` only when the provided source is already a clean, sufficiently large source asset with no semantic text or presentation chrome. -4. Give the parent an execution order for the `produce` bucket. -5. For produced assets, choose the least inventive strategy: image-to-image clean plate, faithful regeneration from crop reference, transparent cutout, texture/pattern reconstruction, stock/project source, or semantic HTML/CSS/SVG recommendation if raster is wrong. -6. Treat every crop as binding reference. In Codex, use the imagegen skill and built-in `image_gen` path by default when generation or editing is needed. -7. Remove baked-in UI text, navigation, buttons, body copy, and mock chrome unless the text is part of the asset. -8. Think through the final DOM/CSS representation before generating. If CSS will own radius, clipping, shadows, borders, perspective, responsive cropping, captions, or card frames, do not bake those into the bitmap. -9. Save outputs non-destructively in the requested project directory. -10. Compare each output against its source crop. If a review/QA tool is available, run it before the final manifest, then retry each major/fatal finding once before finalizing. - -Use `direct` only for provided source assets that can already ship after crop tightening, conversion, compression, or naming. Do not ship a small crop from the full-page mock as `direct` just because it looks close. - -Use `texture/pattern extraction` only when the source region is already clean enough to sample as texture. If UI, cards, labels, headings, body copy, or footer chrome must be removed to make a reusable texture or background, classify it as crop-derived cleanup or clean-plate work. - -Use `semantic` for dashboards, charts, controls, screenshots of whole UI sections, data widgets, card chrome, app frames, icon toolbars, logos, wordmarks, and anything the final implementation can render crisply in HTML/CSS/SVG/canvas. Only ship a screenshot raster when the parent explicitly says the screenshot itself is the final asset. - -Semantic does not mean ignored. For every semantic role, write a concrete implementation handoff for the parent craft agent: name the DOM/component layers, CSS-owned visual treatment, SVG/canvas/icon-library pieces, responsive behavior, and which nearby produced raster assets it should compose with. For logos and icons, prefer inline SVG/vector or icon-library implementation unless the parent provides a production logo raster. - -For transparency, prefer true alpha output when the tool supports it. If it does not, request a flat chroma-key background in a color that cannot appear in the subject, then post-process that color to alpha before shipping a PNG/WebP. Do not ship the keyed background as the final asset. - -## Prompt Pattern - -Use this shape for image-to-image work: - -```text -Use the provided crop as the approved visual reference. -Recreate the same asset as a clean reusable production image at the target component aspect ratio and at least 2x display resolution. -Preserve silhouette, object/scene perspective, camera angle, palette, lighting, material, texture, and visual role. -Remove baked-in UI copy, navigation, buttons, labels, body text, watermarks, and mock chrome unless explicitly part of the asset. -Remove letterboxing, padding, card borders, rounded clipping, CSS shadows, perspective transforms, caption bands, and layout backgrounds that the implementation should create in code. -Do not add new objects. Do not change the concept. Do not redesign the composition. -``` - -For transparent cutouts, use the imagegen skill's built-in-first chroma-key workflow unless the parent explicitly authorizes a true native transparency fallback. +Do not redesign. Do not add objects, restyle, or reinterpret; the comp was approved as it is. Do not touch the page code, the spec, or the comp. Do not produce anything the spec does not list; a region the parent forgot goes back as a one-line note, not a plate. ## Output Contract -Return a complete manifest, grouped by `produce`, `direct`, and `semantic`. For each asset include: `id`, `source_crop`, `output_path` when applicable, `strategy`, `prompt_used` when applicable, `dimensions`, `format`, `transparency`, `deviations`, and `qa_status`. - -For each semantic row include `id`, `implementation`, `notes`, and `qa_status`. The `implementation` must be a concrete build handoff, not a short explanation that no asset was produced. It should name the likely HTML/CSS/SVG/canvas/icon/component pieces and the visual responsibilities that code owns. - -`qa_status` must be `accepted`, `needs_parent_review`, or `blocked`. Use `accepted` only after visual comparison passes. Use `needs_parent_review` for cut-off subjects, unwanted borders or rounded-card chrome, letterboxing, baked semantic text, low-resolution output, perspective that should have been CSS, missing transparency, or drift from the crop. Use `blocked` when inputs, permissions, image capability, or asset source quality prevent a credible result. - -End with `execution_order`, `blockers`, and `assumptions` sections. Keep blockers global and minimal. Do not repeat missing inputs in every row; per-asset rows should carry only asset-specific risks or decisions. - -Do not modify implementation code. Do not edit the approved mock. Do not produce final page copy. The parent craft agent owns implementation and final mock fidelity. +Return one line per raster region: ` `. Then `blockers` (missing spec, missing comp, no image capability, exhausted key) and `assumptions`, each global and minimal. Nothing else: no summary, no praise, no implementation advice. The parent runs `impeccable build-phase advance` to verify the plates against the same spec; a visual acceptance does not override a failing gate. ''' diff --git a/.agents/skills/impeccable/agents/impeccable_documenter.toml b/.agents/skills/impeccable/agents/impeccable_documenter.toml new file mode 100644 index 0000000..45203ec --- /dev/null +++ b/.agents/skills/impeccable/agents/impeccable_documenter.toml @@ -0,0 +1,27 @@ +name = "impeccable_documenter" +description = "Records DESIGN.md and its sidecar from a finished Impeccable build, deriving the design system from the shipped artifact rather than from intentions." +model_reasoning_effort = "medium" +nickname_candidates = ["System Scribe", "Token Surveyor", "Ground Truth"] +developer_instructions = ''' +# Impeccable Documenter + +You record a project's design system after the build is done. Ground truth is the shipped artifact: every token and rule you write must be evidenced by the built code, never by what was planned. Writing the system after the fact is the point; a rulebook written before the build gets defended against reality instead of describing it. + +Complete the check within your turn ceiling. Batch Reads, take `reference/document.md` and the stylesheets first, and sample components rather than walking the tree. When changes are needed, start writing by the midpoint; when the recorded system still matches, leave it untouched and report the evidence checked. + +## Input Contract + +Expect: the project root; the artifact path(s); the direction contract text (THESIS, OWN-WORLD, STORY, FIRST VIEWPORT, FORM); PRODUCT.md path; the path to the skill's `reference/document.md`; and the boundary to write at (project or app root). An existing DESIGN.md path means update, not replace: preserve confirmed incumbent decisions and reconcile them with the build. + +## Workflow + +1. Read `reference/document.md` in full; it is the operating spec for DESIGN.md's format, token schema, sidecar, and section order. Follow it exactly. +2. Scan the artifact: stylesheets, custom properties, computed values in the source, component patterns, spacing rhythm, type ramp as actually used. The direction contract's OWN-WORLD block names the world; the build shows how it landed. Where they diverge, the build wins and the prose may note the divergence. +3. For a new world or approved system change, write DESIGN.md and its sidecar from durable, reused rules in the build. Ordinary extensions preserve the incumbent system; report pre-existing drift without repairing it unasked. Do not write merely to prove this pass ran. +4. Two ways a recorded rule goes wrong, both observed live: a prohibition that bans a device the world itself uses natively, and a value recorded to legitimize a defect. Check every prohibition against the world's own materials; a value earns its place by the build and by legibility, never by making a finding disappear. +5. Never canonize a craft-floor refusal into the system: an element the floor bans (kickers and eyebrows, hard offset shadows outside a neobrutalist world, glyph icons, system display faces) is recorded in your not-canonized line as a defect the build carries, never as a design-system rule for future surfaces to inherit. A live session shipped five invented kickers and the documenter wrote their style into DESIGN.md; that is how one violation becomes the house style. + +## Output Contract + +Return: paths written, or “No changes” with the source and system files checked; a five-line system summary (palette, type ramp, named rules); and one line naming defects or drift not canonized or repaired, and why. No other prose. +''' diff --git a/.agents/skills/impeccable/agents/impeccable_finish_reviewer.toml b/.agents/skills/impeccable/agents/impeccable_finish_reviewer.toml new file mode 100644 index 0000000..cdecfe4 --- /dev/null +++ b/.agents/skills/impeccable/agents/impeccable_finish_reviewer.toml @@ -0,0 +1,41 @@ +name = "impeccable_finish_reviewer" +description = "Reviews a finished Impeccable build against its direction contract, the approved comp, and the chosen world's quality bar, returning an ordered list of material fixes." +model_reasoning_effort = "high" +nickname_candidates = ["Finishing Eye", "Contract Judge", "Ceiling Check"] +developer_instructions = ''' +# Impeccable Finish Reviewer + +You are the finishing reviewer for an Impeccable build: fresh eyes on a done artifact, outside the build thread's attention gravity. You edit nothing; the parent applies your fixes. + +You have no browser. Never render, screenshot, start a server, or open a page; review from the provided files only. When an expected input other than a capture is missing, say so in one line at the top of your return and review what is reviewable; missing captures belong to check 0 and force recapture, never a partial review. + +A hard turn ceiling ends the run without warning; a run that ends before its contracted sections are written (five, or the single recapture section) returns nothing. Treat reading as an allowance: read only the provided inputs plus the craft floor, never any other skill reference file, batch several Reads per turn, take the screenshots, the comp, the card, and the contract first, sample the artifact's primary files rather than walking the tree, and by roughly the tenth turn stop reading and write. Name whatever went unread in the line above the sections. + +## Input Contract + +Expect: the original request; the confirmed user answers; the artifact path(s); the screenshots the parent captured, in `.impeccable/review/` (web: `desktop.png` and `mobile.png`; native: device-class names such as `phone.png` and `tablet.png`, suffixed per OS on adaptive). A screenshot path the calling brief names is authoritative when the file exists; `.impeccable/review/` is where to look when the brief names none or a named path is missing, never a filename you invent. Also expect: the direction contract (THESIS, OWN-WORLD, STORY, FIRST VIEWPORT, FORM); the PRODUCT.md path; existing hook or detector findings; the chosen world's QUALITY BAR card paths; on a comp-led build the approved comp path (a code-led build has none; it passes the chosen decision comp as a separate critique-reference input, labeled as such, and nothing here that binds "the approved comp" binds it); on a comp-led build the build state (`.impeccable/build/state.json`), the measured spec (`.impeccable/build/spec.json`), and the diff directories `.impeccable/review/diff/hero/` and `.impeccable/review/diff/final/` (each holds `side-by-side.png`, `heatmap.png`, `regions/.png` paired crops, and `report.json` with per-region scores and verdicts from `impeccable comp-diff`); and the skill's `reference/craft-floor.md` path. On a native (`ios` / `android` / `adaptive`) build the packet adds the platform reference path(s) (`reference/ios.md` / `reference/android.md`) and a line saying no detector ran: read the platform reference alongside the craft floor, judge every check in the platform's own conventions, treat the screenshots as device captures, and know your floor check is the build's only slop gate. When the harness can view images, open the screenshots, the comp, and the card first, and inventory the comp's salient elements in your own words before reading the direction contract or any builder-authored summary: a review anchored on the contract inherits whatever the builder's abstraction dropped. + +## Checks, in order + +0. **Evidence.** Before any other check, verify the required captures exist and every capture is valid. Required: the platform's full viewport set (web: `desktop.png` and `mobile.png`; native: one capture per shipped device class), plus every capture the calling brief names as required, a reported user viewport (`user-.png`) included. Valid: no black or blank regions, content matching what the filename claims (a visit capture showing the About section is invalid), the document top visible where the file claims a full page, dimensions that make sense for the named viewport. A required capture that is absent fails exactly like one that is malformed: a viewport nobody captured is a viewport nobody inspected, and it cannot ship. When any capture fails, the whole review changes shape: return `disposition: recapture` as the first line, then one section, `recapture`, listing each missing or invalid file and what a valid capture of it shows, and stop. Never build a matrix on malformed evidence; a verdict derived from a broken capture launders the breakage into an approval, and the parent owes you a full re-review on valid captures, not a scoring round. +1. **Persistence.** PRODUCT.md exists. On a comp-led build, `.impeccable/build/state.json` exists and its `comps` (or `skipped` when a surface round locked the comp), `spec`, `plates`, and `hero` phases are `closed`; a comp-led config with no state file, or a state whose `comps` phase never closed, means the comp round was skipped and the build ran from a world description alone, a material finding that outranks craft; a phase closed with a `forced` record is disclosed as a material finding unless the user downgraded the comp in words the packet quotes; a state file whose `hero.gate.score` sits under 0.72, or a missing state file, means the reproduction ran unproven, a material finding, and `.impeccable/review/hero-repro.png` must exist either way. When DESIGN.md predates this build (an extension or redesign), it matches the built world; on a new world it is written after this review by the documenter, so its absence here is not a finding. When comp-round comps exist under `.impeccable/mocks/`, an approval record exists too: the surface brief naming the approved comp, or an `approved` flag in its sidecar. Comp-round comps with no recorded pick mean the approval point was skipped, a material finding. Files under `.impeccable/mocks/decision/` are exempt: they are the direction round's dealt hand, produced before any comp round, and imply no approval whatever the build path; a code-led build has no comp round at all. +2. **Fidelity.** Start from the measurement, then judge what it cannot: read `.impeccable/review/diff/final/report.json` (and hero) first; every region scored `missing` or `contradicted` is a matrix row in that state unless the paired crop under `regions/` shows the score is wrong, and you say why; a region scored `match` still gets your eye for lettering character and material, which the numbers do not measure. Then, against your own element inventory of the approved comp, never against the contract's summary of it: topology, reading order, focal scale, overlaps and z-order, density, signature geometry, the primary action's treatment (a CTA the comp physically works, dissolves, or stamps is a signature element; its plain-rectangle rendition is contradicted), navigation items and icons, headline levels and scale relationships. Classify every salient element: match, acceptable adaptation, missing, contradicted, or added without approval. Three rows are mandatory in every matrix. TYPE: the display lettering's character, compression, width, weight, contrast, terminals, against the comp's; a face of a different character is contradicted however the layout matches. MATERIAL: an element rendered as flat CSS or clean vector where the comp shows painted, textured, dimensional, or photographic material is contradicted regardless of placement; medium is part of the promise. GROUND: the page field's value and temperature against the comp's, sampled from pixels on both sides when tooling allows rather than judged from memory, and read as the net on-screen result where a texture or tile paints over the base color; a ground warmer or cooler than the comp's is contradicted however faithfully the layout matches, and drift toward the rendition prior (warm cream on light grounds, blue-black slate on dark) is the direction to hunt. With no approved comp, TYPE and MATERIAL do not lapse: judge them against the contract's OWN-WORLD and the world's real materials, and treat faked physicality (CSS bevels, embossing, stamped-metal or chalk effects imitating a material the page never renders) as contradicted on its face; imitation material is the single most reliable mark of machine-made design. GROUND narrows rather than lapses: with no comp to sample, a color OWN-WORLD names is the target and the same warmer-or-cooler judgment applies; when OWN-WORLD names none, there is no GROUND authority, and the review says so in place of a verdict, because a target the reviewer invents turns the check into taste. A critique-reference comp on such a build is provocation, not spec: no element matrix, no adaptation citations, no asset obligations; its one contribution is what the image dared that the build did not, and dares worth adopting enter material_fixes as ordinary ordered fixes. An adaptation counts as intentional only when it cites the user answer, surface brief, accessibility need, or product truth that forced it; an uncited deviation is a defect. A missing signature element, a changed topology, or content added without approval fails fidelity and outranks every craft point in material_fixes. When MATERIAL is contradicted on the focal element, or contradiction is the page rather than the exception, stop ordering repairs: make the first material fix a rebuild directive naming the comp regions to re-derive and the assets to produce; a list of patches against a rejected page launders the rejection into an approval. A fix that requires producing an asset says so explicitly ("produce: as a raster asset"), never phrased as a style adjustment the parent will answer with CSS. The comp is the spec for composition, topology, element inventory, density, lettering character, and material; it is not a pixel spec for semantics, accessibility, or responsive reflow, and that allowance covers translation, never replacement. +3. **Ceiling.** Against the QUALITY BAR card: name the world's native devices the build left unused, frame, depth, lettering treatment, ornament density, motion. The card governs commitment and finish, never composition. +4. **Contract, promise by promise.** First verify FORM carries the seed key the concept roll printed; a contract with no seed key, or one the parent cannot corroborate, means the roll was skipped, a material fix ahead of any craft point. Then, for each of the five blocks: does the render keep the promise? Apply the memory test to the first viewport. +5. **Truth.** Demonstration data authored and labeled synthetic; no invented commercial claims; unanswered claims present as marked placeholders, not omissions. Every raster region of the spec shipped as its plate (the spec names the file; the page references it; the region's diff row is not `missing`), not a gradient, an inline SVG, or a many-vertex `clip-path` standing in for it, and every produced asset visibly present in the screenshots; an asset applied at near-zero opacity or buried behind a wash is a compliance token, not a shipped material, and the detector's `buried-raster` and `organic-clip-path` findings in the packet are material fixes. +6. **Floor.** Read the craft floor's Refuse list and hold the screenshots against it: kickers and eyebrows, hard offset shadows outside a neobrutalist world, glyph icons, system display faces, gradient text, side stripes, and the rest. A banned element is a material fix even when it matches nothing in the comp: the builder loaded the same ban before writing it, and fidelity to a comp cannot authorize what the floor refuses. The parent's hook findings cover this mechanically where hooks run; this check exists because hookless harnesses reach you with none, and the last two live sessions shipped five kickers past a reviewer that never looked. + +Do not run a second detector pass; mechanical findings belong to the parent's hooks. + +## Disposition + +The first line of your return is `disposition: recapture`, `disposition: rebuild`, `disposition: fix`, or `disposition: ship`. These four words are the whole vocabulary; never invent another. The word is derived, never felt: recapture when the evidence check failed, rebuild when the rebuild-directive condition fired, fix when material_fixes is non-empty, ship only when the matrix holds no contradicted or missing row. You are the last gate before the user, not a colleague softening news for a colleague: calibrate against the approved comp and the world's quality bar, never against the effort visible in the build. A page a design director would send back is fix at best however functional it is; a page whose focal craft sits far below the comp is rebuild however complete its structure. The parent reports your disposition word verbatim and has no authority to soften it. + +## Output Contract + +Return the disposition line first, then exactly five sections: `persistence` (pass/fail with specifics), `fidelity` (the element matrix: match, adaptation, missing, contradicted, or added without approval per salient element, adaptations citing their evidence, or "faithful"), `ceiling` (unused native devices, or "reached"), `material_fixes` (ordered, most material first, fidelity failures ahead of craft, each one line tied to a check or contract promise, at most eight), and `keep` (one line naming what must not be diluted while fixing). A recapture return replaces the five sections with the single `recapture` section from check 0. Missing inputs are named in one line above the sections. No praise, no summary prose. + +## Verdict Pass + +When the parent returns with post-fix recaptures, you are scoring, not re-hunting. Three conditions take you out of scoring mode: recaptures that fail check 0 get `disposition: recapture` exactly as in the review round; a return following your rebuild directive is a new full review, because a rebuild replaces regions wholesale and scoring the directive alone would ship whatever the rebuild missed; and a packet carrying user-supplied screenshots that contradict a prior verdict is a new full review with the user's captures as primary evidence, because the user's screenshot of the real page outranks every capture the parent staged. The parent recaptures over the same screenshot files you read in the review round, so re-read those exact paths; a round-stamped filename you invent points at nothing. The parent's narration of what was fixed is not evidence; a claimed fix you cannot see in the recaptures is unresolved. For each material fix from your review, one line: resolved, partial, or unresolved, tied to what the new screenshots visibly show; a fix answered mechanically, positions moved but the quality the finding named still absent, is partial at best. Then name at most three regressions the fix batch itself introduced, judged by the same matrix rules, and nothing else; no new hunt, no new checks. Return exactly two sections: `verdict` (the scored list) and `remaining` (what stays open, or "clear"), and end with the disposition line recomputed against what remains open, in the same four-word vocabulary. Unresolved or partial material findings can never recompute to ship, and a ship earned here covers the scored fixes, not the whole surface, so state it as exactly that. +''' diff --git a/.agents/skills/impeccable/agents/impeccable_manual_edit_applier.toml b/.agents/skills/impeccable/agents/impeccable_manual_edit_applier.toml index 9ddc6f3..469dd2d 100644 --- a/.agents/skills/impeccable/agents/impeccable_manual_edit_applier.toml +++ b/.agents/skills/impeccable/agents/impeccable_manual_edit_applier.toml @@ -18,12 +18,12 @@ Expect a self-contained handoff with: - Event id. - Page URL. - Optional chunk metadata. -- Optional repair metadata. When present, fix the current source after a failed validation attempt; do not restart from the pre-Apply source. +- Optional repair metadata; when present, repair the current source (see Entry Atomicity), never the pre-Apply source. - Optional deadline. - The current event `batch`. - Optional `evidencePath`. -The user already clicked Apply. Do not ask what to do. Do not discard edits. Do not run `live-poll.mjs`, `live-commit-manual-edits.mjs`, or any live server endpoint. Do not run `live-commit-manual-edits.mjs` for a leased manual Apply event. Do not stage, commit, rebuild, push, or edit generated provider output unless the batch explicitly targets that generated file. +The user already clicked Apply. Do not ask what to do. Do not discard edits. Do not run `impeccable live-poll`, `impeccable live-commit-manual-edits`, or any live server endpoint. Do not stage, commit, rebuild, push, or edit generated provider output unless the batch explicitly targets that generated file. ## Workflow diff --git a/.agents/skills/impeccable/homepage-desktop.png b/.agents/skills/impeccable/homepage-desktop.png deleted file mode 100644 index a8d1b37..0000000 Binary files a/.agents/skills/impeccable/homepage-desktop.png and /dev/null differ diff --git a/.agents/skills/impeccable/homepage-mobile.png b/.agents/skills/impeccable/homepage-mobile.png deleted file mode 100644 index bf2f5e0..0000000 Binary files a/.agents/skills/impeccable/homepage-mobile.png and /dev/null differ diff --git a/.agents/skills/impeccable/reference/adapt.md b/.agents/skills/impeccable/reference/adapt.md index 9909edf..314d11f 100644 --- a/.agents/skills/impeccable/reference/adapt.md +++ b/.agents/skills/impeccable/reference/adapt.md @@ -2,6 +2,7 @@ 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. --- diff --git a/.agents/skills/impeccable/reference/adapt.native.md b/.agents/skills/impeccable/reference/adapt.native.md new file mode 100644 index 0000000..88975b3 --- /dev/null +++ b/.agents/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/.agents/skills/impeccable/reference/android.md b/.agents/skills/impeccable/reference/android.md new file mode 100644 index 0000000..1f67a6b --- /dev/null +++ b/.agents/skills/impeccable/reference/android.md @@ -0,0 +1,46 @@ +# Android platform + +For native Android apps: Jetpack Compose, Android Views, React Native, Expo, Flutter shipping to Android hardware. + +On native, the visitor mode narrows what expression may override. Material Design 3 governs structure, navigation, and interaction in every mode; 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. + +## Verifying the build + +- **Screenshots come from the emulator or a connected device, never a browser.** Build and install, then capture with `adb exec-out screencap -p > ` (pick a device with `adb -s ` when several are attached). Capture every device class the app ships to, at least one phone and, when tablets are a target, one tablet, and write the files where the review flow expects them. +- **Dark theme and font scale belong in the pass.** `adb shell cmd uimode night yes` flips the theme; `adb shell settings put system font_scale 1.3` (restore `1.0` after) catches the clipped labels a fixed layout hides; with several targets attached, the capture's `-s ` goes on these commands too. +- **Emulators give breadth; gestures, refresh rates, and performance need hardware.** Say which one produced the evidence. diff --git a/.agents/skills/impeccable/reference/animate.md b/.agents/skills/impeccable/reference/animate.md index 729271a..c8fb9e0 100644 --- a/.agents/skills/impeccable/reference/animate.md +++ b/.agents/skills/impeccable/reference/animate.md @@ -1,201 +1,89 @@ > **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. +Use motion to explain state, relationship, and hierarchy, or to create one authored moment the surface has earned. Decoration without purpose is animation debt. --- -## Register +## Visitor mode -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. +- **Persuade + Experience:** motion may carry the voice. Prefer one rehearsed focal sequence to repeated section reveals. +- **Operate + Read:** motion serves feedback, state, and continuity. Keep routine transitions fast and do not make users wait through page-load choreography. +- **Native (`ios` / `android` / `adaptive`):** follow the Motion section of [ios.md](ios.md) or [android.md](android.md), including the platform's Reduce Motion behavior. Do not apply the web tooling below. -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. +## Find the job ---- +Inspect the existing motion language, interaction states, target devices, and performance budget. Find only the places where motion would: -## Assess Animation Opportunities +- acknowledge an action; +- make a state change or spatial relationship legible; +- preserve continuity through navigation or layout change; +- direct attention at a meaningful moment; +- embody the selected visual world. -Analyze where motion would improve the experience: +Ask only when a material constraint cannot be inferred. Do not animate a static area merely because it exists. -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 +## Set the motion thesis -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?) +Write a short plan before implementation: -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. +- **Focal moment:** the one sequence or interaction that deserves authorship, if any. +- **Continuity:** the state, layout, or navigation changes that need explanation. +- **Feedback:** the controls and outcomes that need acknowledgment. +- **Budget:** which effects may be expensive and how often they run. -**CRITICAL**: Respect `prefers-reduced-motion`. Always provide non-animated alternatives for users who need them. +The focal moment must come from this product and surface concept. A generic fade-and-rise, hover lift, parallax layer, or scroll reveal is not a thesis. -## Plan Animation Strategy +## Choose material by meaning -Create a purposeful animation plan: +Transform and opacity are reliable foundations, not the entire palette. Choose properties for what the transition communicates: -- **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? +- **Continuity and relationship:** shared-element motion, FLIP-style transforms, view transitions, or deliberate spatial movement. +- **Focus and depth:** bounded blur, filter, backdrop, light, or shadow changes. +- **Reveal and composition:** masks, clip paths, cropping, or controlled occlusion. +- **Material and energy:** color, gradient position, texture, distortion, or shader effects when the world and runtime support them. +- **State and feedback:** the smallest change that makes cause and result unmistakable. -**IMPORTANT**: One well-orchestrated experience beats scattered animations everywhere. Focus on high-impact moments. +Do not stack techniques for spectacle. One strong material idea, carried through the focal sequence and quiet supporting states, is usually enough. -## Implement Animations +Sibling stagger is appropriate when a list appears as a list. Cap the total delay, and never reinterpret every scrolled section as a staggered list. -Add motion systematically across these categories: +## Timing and easing -### 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. +Timing should express distance and consequence: - 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. +| Duration | Typical use | +|---|---| +| 100–150 ms | immediate feedback | +| 150–300 ms | routine state change | +| 300–500 ms | layout, overlay, or view transition | +| 500–800 ms | a deliberately authored focal entrance | -### 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 +Exit faster than entrance. Use natural deceleration such as `cubic-bezier(0.16, 1, 0.3, 1)` for confident arrivals; do not use bounce or elastic curves by reflex. Long feedback feels like latency. -### 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 +## Implement to the runtime -### 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 +- Use CSS transitions and keyframes for declarative state and bounded sequences. +- Use Web Animations API or the project's existing motion library for interruption, sequencing, and dynamic values. +- Use View Transitions or shared-element techniques when continuity across states is the point. +- Use scroll-driven motion only when the scroll relationship itself carries meaning, with a robust fallback. +- Do not add a dependency for an effect the existing stack can express cleanly. -### 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 +Keep content visible in the default state so failed scripts do not hide the page. Avoid casually animating layout-driving properties such as `width`, `height`, `top`, `left`, and margins; use FLIP, transforms, or grid techniques when appropriate. Bound blur, filter, shadow, canvas, and shader work to isolated regions. Apply `will-change` only during known animation. Measure on target viewports and devices rather than assuming transform means fast. -### 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 +## Accessibility and control -## Technical Implementation +Respect autoplay and sound preferences. Any nonessential loop must stop when offscreen or hidden. -Use appropriate techniques for each animation: +Every web animation needs a `prefers-reduced-motion` path with an intentional alternative. Remove or reduce spatial movement while preserving opacity, color, and state transitions that carry meaning. Reduced motion means fewer and gentler animations, not disabling all motion; feedback that confirms an action should remain legible. -### Timing & Easing +## Verify -**Duration: the 100/300/500 rule.** Timing matters more than easing for "feels right": +- The focal motion is specific to the selected world and surface. +- Every supporting animation explains feedback, state, or relationship. +- Interruption and repeated use behave correctly. +- Desktop, mobile, and keyboard paths remain usable. +- The `prefers-reduced-motion` path reduces movement without erasing meaningful feedback or state changes. +- Expensive effects stay smooth on the target device. +- Removing an animation would lose meaning or authored character, not merely decoration. -| 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. +When motion earns its place, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/audit.md b/.agents/skills/impeccable/reference/audit.md index 10f5572..b6a0bb3 100644 --- a/.agents/skills/impeccable/reference/audit.md +++ b/.agents/skills/impeccable/reference/audit.md @@ -2,6 +2,8 @@ Run systematic **technical** quality checks and generate a comprehensive report. 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. @@ -10,6 +12,7 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the **Check for**: - **Contrast issues**: Text contrast ratios < 4.5:1 (or 7:1 for AAA) +- **Motion sensitivity**: `prefers-reduced-motion` needs an intentional alternative that preserves state change and hierarchy; flag a global `0.01ms` kill that destroys useful feedback, flashing above threshold, and motion that blocks focus, reading, or task completion - **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 @@ -23,7 +26,8 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the **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 +- **Missing optimization**: Images without lazy loading, unoptimized assets +- **will-change overuse**: `will-change` applied broadly or left on at rest (it is a targeted hint for known expensive animations, not a baseline requirement) - **Bundle size**: Unnecessary imports, unused dependencies - **Render performance**: Unnecessary re-renders, missing memoization @@ -50,11 +54,11 @@ Run comprehensive checks across 5 dimensions. Score each dimension 0-4 using the **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) +### 5. Implementation Integrity (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). +Run the bundled detector and verify each finding in context. Look for repeated implementation shortcuts, design-system drift, misleading or decorative content, and structure that is interchangeable with an unrelated product. Keep deterministic findings separate from visual judgment and call out false positives. -**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) +**Score 0-4**: 0=systemic drift, 1=major repeated failures, 2=several verified issues, 3=minor isolated issues, 4=coherent and intentional ## Generate Report @@ -66,13 +70,13 @@ Check against ALL the **DON'T** guidelines from the parent impeccable skill (alr | 2 | Performance | ? | | | 3 | Responsive Design | ? | | | 4 | Theming | ? | | -| 5 | Anti-Patterns | ? | | +| 5 | Implementation Integrity | ? | | | **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. +### Implementation Integrity Verdict +**Start here.** Pass/fail: does the implementation express a coherent product-specific system? Cite verified evidence and detector findings. ### Executive Summary - Audit Health Score: **??/20** ([rating band]) @@ -91,7 +95,7 @@ Tag every issue with **P0-P3 severity**: For each issue, document: - **[P?] Issue name** - **Location**: Component, file, line -- **Category**: Accessibility / Performance / Theming / Responsive / Anti-Pattern +- **Category**: Accessibility / Performance / Theming / Responsive / Implementation Integrity - **Impact**: How it affects users - **WCAG/Standard**: Which standard it violates (if applicable) - **Recommendation**: How to fix it @@ -130,4 +134,3 @@ After presenting the summary, tell the user: - Skip positive findings (celebrate what works) - Forget to prioritize (everything can't be P0) - Report false positives without verification - diff --git a/.agents/skills/impeccable/reference/audit.native.md b/.agents/skills/impeccable/reference/audit.native.md new file mode 100644 index 0000000..321847a --- /dev/null +++ b/.agents/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 `impeccable detect` 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 visual materials where system materials or tonal elevation are expected + +**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 +- **System drift**: repeated shortcuts or decorative patterns that conflict with the product, platform, or established design system + +**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/.agents/skills/impeccable/reference/bolder.md b/.agents/skills/impeccable/reference/bolder.md index 6326d40..0ea9bcc 100644 --- a/.agents/skills/impeccable/reference/bolder.md +++ b/.agents/skills/impeccable/reference/bolder.md @@ -1,120 +1,33 @@ -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. +> **Additional context needed**: which section is the target, and what must stay untouched. ---- +An open direction round owns the word first: "bolder" said while a direction decision is on the table is the Bolder hand register steer, a fresh deal of foreign forms (see new-work.md), not this command. This command refines a surface whose world already shipped. -## Register +"Bolder" is an amplification request, and almost always it is scoped to something that already exists. The surrounding page, its system, and its conventions are the given. Your job is to raise one part to the conviction the rest already implies, without rebuilding anything the brief did not name. The reflex answer, reaching for more effects, is the opposite of bold; reject it first. -Brand: "bolder" means distinctive. Express a stronger point of view through hierarchy, pacing, proportion, copy, evidence, and one committed visual idea. +## Scope is sovereign -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. +"Everything else stays" is a literal instruction. Touch only the named target. Do not restyle its neighbors, do not migrate the page to a new idea, do not add colors, fonts, radii, shadows, or system primitives the surface does not already own. If the existing system genuinely cannot express the direction, do not expand it on your own. STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. Name the exact addition and the job it would do. ---- +## Why it reads flat -## Assess Current State +A section usually reads flat for reasons its neighbors have already solved. Look at what the rest of the page does that this section does not: the display type at full strength, the structural devices that carry meaning, the signature motif, the density and pacing. A flat section is typically one that quietly opts out of the system's own strongest moves. The most reliable bolder pass brings the target up to the expressive level its neighbors already reach, in the system's own vocabulary rather than a new one. -Analyze what makes the design feel too safe or boring: +## The amplification -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. +- **Amplify what the system already owns.** Reuse its motif and its type scale at full strength, turned up for this section rather than invented for it. The bolder version should look more like the same brand, not less. +- **Keep content true.** Existing claims are part of the scope: preserve them unless the user supplies replacements. If real evidence is essential to the direction but absent, ask for it. +- **Commit, then clarify.** Half-measures read as noise. Make the one decisive move completely, then quiet everything around it so the move is legible. If every element got louder, the section got flatter. +- **Give it its own rhythm.** The target should read as a peak in the scroll, a shift in density or pace from what surrounds it, not simply more of the same. -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? +## The skeleton test -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. +Strip the copy out of your planned section and study the bare structure. Does the skeleton still say what this section is and why it matters, through hierarchy and the system's devices alone? If it only works once the words return, the boldness is in the text size, not the design. A placeholder for an image or artifact names a job, an anchor and a piece of evidence, not a cue to drop in a decorative photo; fill that job with whatever the subject actually has. -**CRITICAL**: "Bolder" does not mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random noise. +## Before you finish -**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." +- Everything outside the named target is unchanged. +- No new color, font, or system primitive appeared without being asked for. +- The conventions the section carried, including anything that drives an action, still work the same way. +- The section is unmistakably the same brand, only more sure of itself. -## 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. +When the target holds its own without pulling the page apart, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/brand.md b/.agents/skills/impeccable/reference/brand.md deleted file mode 100644 index a461c54..0000000 --- a/.agents/skills/impeccable/reference/brand.md +++ /dev/null @@ -1,108 +0,0 @@ -# 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/.agents/skills/impeccable/reference/clarify.md b/.agents/skills/impeccable/reference/clarify.md index 123f294..4506a31 100644 --- a/.agents/skills/impeccable/reference/clarify.md +++ b/.agents/skills/impeccable/reference/clarify.md @@ -1,288 +1,94 @@ -> **Additional context needed**: audience technical level and users' mental state in context. +> **Additional context needed**: audience knowledge and emotional state. -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. +Rewrite unclear interface text so users understand what happened, what matters, and what to do next. Preserve factual meaning, product terminology, and brand voice. +## Audit the language ---- +Read the entire interaction path, not isolated strings. Identify: -## Assess Current Copy +- ambiguous nouns, verbs, and actions; +- internal jargon or assumed knowledge; +- vague labels, outcomes, and system states; +- missing consequences, recovery, or timing; +- inconsistent terminology and capitalization; +- redundant headings, intros, helper text, and confirmations; +- text that breaks at realistic widths or in translation; +- tone that ignores stress, risk, success, or urgency. -Identify what makes the text unclear or ineffective: +Infer audience and task from product context and surrounding UI. Ask before changing factual claims, legal meaning, or a term that may be domain-specific. -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 +## Set the message hierarchy -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?) +For each state, decide: -**CRITICAL**: Clear copy helps users succeed. Unclear copy creates frustration, errors, and support tickets. +1. the one fact the user needs now; +2. the action available next; +3. supporting context that changes the decision; +4. the appropriate tone for this moment. -## Plan Copy Improvements +Say each idea once. If the heading already explains the state, the introduction should add new information or disappear. -Create a strategy for clearer communication: +## Rewrite by function -- **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 +### Actions and navigation -**IMPORTANT**: Good UX writing is invisible. Users should understand immediately without noticing the words. +Use a specific verb and object when the outcome is not already obvious. Labels should describe what will happen, not the gesture used to trigger it. Keep the same noun and verb for the same concept throughout the product. -## Improve Copy Systematically +For destructive actions, name the object and consequence. Prefer undo over confirmation when recovery is safe. When confirmation is necessary, name the action on both the message and button instead of using `Yes`, `No`, `OK`, or `Submit`. -Refine text across these common areas: +### Forms -### Error Messages -**Bad**: "Error 403: Forbidden" -**Good**: "You don't have permission to view this page. Contact your admin for access." +Use persistent labels; placeholders are examples, not labels. Put format and eligibility requirements before submission. Explain why information is requested only when it is not obvious. Required and optional treatment should be consistent. -**Bad**: "Invalid input" -**Good**: "Email addresses need an @ symbol. Try: name@example.com" +Validation says what needs attention and how to correct it without blaming the user. Keep related instructions near the field and announce errors accessibly. -**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" +### Errors and permissions -**Principles**: -- Describe the action specifically -- Use active voice (verb + noun) -- Match user's mental model -- Be specific ("Save" is better than "OK") +An actionable error answers: -### Help Text & Tooltips -**Bad**: "This is the username field" -**Good**: "Choose a username. You can change this later in Settings." +1. what failed; +2. why, when known and useful; +3. how to recover or what alternative remains. -**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 +Do not expose internal codes as the primary message. Do not promise a cause or resolution the system cannot know. Treat privacy, payment, deletion, access loss, and blocked work seriously; warmth is welcome, jokes are not. -### Empty States -**Bad**: "No items" -**Good**: "No projects yet. Create your first project to get started." +### Loading, empty, and success states -**Principles**: -- Explain why it's empty (if not obvious) -- Show next action clearly -- Make it welcoming, not dead-end +Loading text names the real operation and sets an honest expectation when the wait is meaningful. Show determinate progress when available; never invent progress. -### Success Messages -**Bad**: "Success" -**Good**: "Settings saved! Your changes will take effect immediately." +An empty state distinguishes first use, no results, filters, permissions, and failure. Explain the state and provide the next useful action. -**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") +Success confirms the completed outcome and mentions the next consequence only when it changes what the user should do. Routine success should be brief. -### Confirmation Dialogs -**Bad**: "Are you sure?" -**Good**: "Delete 'Project Alpha'? This can't be undone." +### Help and instructional text -**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) +Helper text answers an implicit question instead of restating the control. Use progressive disclosure for uncommon detail. Link text must make sense out of context; icon-only controls need accessible names. -### Navigation & Wayfinding -**Bad**: Generic labels like "Items" | "Things" | "Stuff" -**Good**: Specific labels like "Your projects" | "Team members" | "Settings" +## Voice, accessibility, and localization -**Principles**: -- Be specific and descriptive -- Use language users understand (not internal jargon) -- Make hierarchy clear -- Consider information scent (breadcrumbs, current location) +Voice stays consistent; tone adapts to the moment. Use plain language without flattening terminology the audience genuinely knows. -## Apply Clarity Principles +- Write complete translatable messages rather than concatenated fragments. +- Keep variables and numbers structured so translators can reorder them. +- Allow expansion instead of abbreviating prematurely. +- Make alt text convey the image's information; use empty alt for decoration. +- Keep screen-reader names aligned with visible labels and outcomes. +- Do not rely on punctuation, color, or iconography to carry the message alone. -Every piece of copy should follow these rules: +Maintain a short terminology glossary when inconsistency spans the product. Do not vary words for literary effect in an interface. -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) +## Verify -**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) +Read the flow in context and test: -## Verify Improvements +- comprehension without hidden product knowledge; +- actionability at errors, empty states, and decision points; +- factual accuracy and consistent terminology; +- scanability at target widths and 200% zoom; +- long names, localization expansion, pluralization, and dynamic values; +- accessible names and announced state changes; +- tone appropriate to consequence and emotional context. -Test that copy improvements work: +The final copy is as short as it can be without removing meaning or recovery. -- **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. +When the language reads cleanly, hand off to `$impeccable polish` for the final pass. diff --git a/.agents/skills/impeccable/reference/codex.md b/.agents/skills/impeccable/reference/codex.md deleted file mode 100644 index f174e1f..0000000 --- a/.agents/skills/impeccable/reference/codex.md +++ /dev/null @@ -1,105 +0,0 @@ -# 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/.agents/skills/impeccable/reference/colorize.md b/.agents/skills/impeccable/reference/colorize.md index 08a3862..02fa661 100644 --- a/.agents/skills/impeccable/reference/colorize.md +++ b/.agents/skills/impeccable/reference/colorize.md @@ -1,257 +1,86 @@ > **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. +Introduce color as hierarchy, meaning, and atmosphere. Preserve confirmed brand and semantic conventions; do not replace a visual world under the guise of colorizing it. --- -## Register +## Visitor mode -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. +- **Persuade + Experience:** color may carry the voice and own large regions when the selected world calls for it. +- **Operate + Read:** color primarily encodes action, selection, status, wayfinding, and reading hierarchy. Rarity gives an accent force. -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. +## Audit before choosing ---- +Read DESIGN.md, tokens, assets, current themes, and representative states. Identify: -## Assess Color Opportunity +- which colors are confirmed brand commitments; +- current surface, text, action, and semantic roles; +- places where grayscale obscures hierarchy or state; +- contrast failures and color-only communication; +- light/dark or data-visualization requirements; +- whether the task asks for more color or a new identity. -Analyze the current state and identify opportunities: +If a new identity is required, use [new-work.md](new-work.md). Ask only when a binding brand decision cannot be inferred. -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? +## Choose a strategy -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 +Name the intended emotional temperature, dominant relationship, contrast range, and color dosage before editing. The strategy may be restrained or immersive; it must follow the brief and selected world rather than a fixed percentage rule. -If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer. +Build roles, not a bag of swatches: -**CRITICAL**: More color ≠ better. Strategic color beats rainbow vomit every time. Every color should have a purpose. +- canvas and elevated surfaces; +- primary and secondary text; +- action, focus, and selection; +- borders and separators; +- success, warning, error, and information; +- data categories or scales when needed. -## Plan Color Strategy +Use the project's existing color space. For a new web palette, prefer OKLCH because lightness and chroma can be adjusted predictably. Choose hue from product meaning and visual direction, never from a default category association. -Create a purposeful color introduction plan: +## Apply at system scale -- **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? +- Let the strongest color own a deliberate region or role instead of scattering tiny accents. +- Keep the primary action easy to find; do not spend its color on decoration. +- Tint neutrals only when the brand hue genuinely creates cohesion. Neutral gray is valid when it serves the world. +- On colored surfaces, derive secondary text from the foreground or surface hue rather than using washed-out generic gray. +- Keep semantic meanings consistent, but respect platform and domain conventions instead of assuming fixed hues. +- For data, use distinct lightness, chroma, shape, label, or pattern so color is not the only code. +- In dark mode, design surface elevation and contrast explicitly; do not invert the light theme mechanically. +- Define primitive values and semantic tokens when the project has a token system. Theme changes should normally remap semantic roles. -**IMPORTANT**: Color should enhance hierarchy and meaning, not create chaos. Less is more when it matters more. +Decoration without a relationship to hierarchy, state, content, or the visual world is not a color strategy. -## Introduce Color Strategically +## Contrast and perception -Add color systematically across these dimensions: +Verify computed foreground/background pairs: -### 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 +| Content | WCAG AA minimum | +|---|---| +| body text | 4.5:1 | +| large text | 3:1 | +| controls, icons, focus indicators | 3:1 | -- **Status badges**: Colored backgrounds or borders for states (active, pending, completed, etc.) -- **Progress indicators**: Colored bars, rings, or charts showing completion or health +Do not rely on eyesight alone. Check interactive states, overlays, text on images, disabled content, and both themes. Simulate common vision deficiencies. Information conveyed by color also needs text, shape, iconography, or position. -### 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 +When deriving OKLCH ramps, vary lightness and reduce chroma near white and black. Do not keep high chroma at extreme lightness merely to make the math uniform. Prefer explicit colors over chains of translucent overlays when alpha would make contrast context-dependent. -### 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 +## Verify -**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? +- Every color has a stable role or a world-specific atmospheric purpose. +- Attention lands on the intended action, content, or state. +- The palette works across quiet, dense, interactive, error, and empty states. +- Light and dark themes are each composed, not mechanically inverted. +- Contrast and non-color cues pass in all relevant states. +- The result is recognizably this product, not a generic “colorful” treatment. 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. +When invoked from live mode, every variant declares a `color-amount` parameter. Author CSS against `var(--p-color-amount, 0.5)` so the user can move from neutral to the variant's full color strategy without regeneration. ```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). +Add at most two variant-specific parameters, such as palette, temperature, or tint behavior. Follow [live.md](live.md)'s parameter contract. diff --git a/.agents/skills/impeccable/reference/craft-floor.md b/.agents/skills/impeccable/reference/craft-floor.md new file mode 100644 index 0000000..ae213ce --- /dev/null +++ b/.agents/skills/impeccable/reference/craft-floor.md @@ -0,0 +1,50 @@ +# Craft floor + +Load this after the direction is settled, and build without announcing the checklist. A pinned brief or the committed visual world overrides anything here; your own habit does not. When the design hook is active it already enforces the mechanical checks below as you edit: act on its findings instead of re-auditing each rule. + +## Verify + +Each of these is a check on the built result, not an intention. Run them together in the batched inspection rounds, not as separate screenshot trips; the checks share one render. + +- **Contrast:** body and placeholder text ≥4.5:1, large text ≥3:1. On colored surfaces tint secondary text from that hue or the foreground; never gray. +- **Depth:** shadows carry an offset and a soft blur. A zero-offset colored halo is decoration. +- **Spacing:** tight groups, generous separation, more space above a heading than below it. Read the computed values. +- **Type:** body measure 65–75ch, display max 6rem, tracking floor -0.04em, balanced headings, obvious scale and weight steps. Run the real copy at every breakpoint and fix what overflows. +- **Motion:** one authored moment, not scattered effects and not one identical entrance on every section. Exponential ease-out from an already-visible default. Reach past transform and opacity: blur, backdrop-filter, clip-path, mask, and shadow belong to the palette when they stay smooth. +- **States:** hover, disabled, loading, error, empty. Plus real content, working controls, responsive composition, keyboard focus. +- **Browser surfaces:** the parts you did not draw still carry the design. Text selection, the caret, custom scrollbars, focus rings, underline offset, and the numerals in tabular data all ship with browser defaults that belong to no design system. Theme them from the palette. This is the cheapest signal that a page was built rather than assembled, and the one models skip most reliably. +- **Copy:** the product's own language. Controls name their action; errors name the problem and the recovery. +- **Coverage:** every brief requirement present and findable within seconds. + +## Refuse + +These are the category's defaults, not bans: the brief's own words can earn any of them. Reaching for one when the axis is free means you were not deciding; recognizing that means rewriting the element, not softening it. + +Page scaffolds: + +- Same-size cards of icon plus heading plus text as the page structure. Cards are the lazy container; nested cards are always wrong. +- The hero-metric template: big number, small label, supporting stats, accent. +- A kicker or eyebrow above a heading. This one is a ban, not a default: no brief earns it back. The heading carries its own weight; delete the label and let the heading speak. +- Section numbers (01 / 02 / 03) unless the sequence itself carries information the reader needs. +- A modal for a task that needs neither interruption nor protected focus. + +Surface habits: + +- Gradient text. Emphasis comes from weight or size. +- Glass and blur as decoration rather than as a specific effect. +- A colored `border-left` or `border-right` above 1px on cards, list items, callouts, or alerts. +- Hard offset shadows (`box-shadow: 4px 4px 0`) outside a world that is actually neobrutalist. The zero-blur block shadow is a costume, not a depth system; a world that did not choose it never earns it as a default. +- Sparklines, progress rings, and soft-shadowed rounded rectangles standing in for content. +- Monospace as a costume for "technical" rather than for code, data, or measurement. +- A system display face (Impact, Arial Black, the platform sans) as the display voice of an own-world page. Source and self-host a face whose character matches the approved lettering; the closest installed font is a failure, not a fallback. +- Unicode glyphs or emoji standing in for an icon system. Icons are drawn, from a real library or authored SVG, in one consistent stroke and weight. +- Geometric masks standing in for organic contours. A circle, polygon, or radial-gradient cutout approximating a photographic subject's edge is the cheap version of the effect and reads worse than omitting it. Derive an alpha matte from the actual image, or produce a cut-out asset. +- Light or dark picked by category. Pick it from the use scene: who, where, under what ambient light. + +- Tracking stops at -0.04em. -0.02 to -0.03em usually reads better. +- Declare elevation once, border or shadow. A 1px border under a wide soft shadow is the ghost card. Card radii stay at 12–16px; pills are for small controls. +- Real illustration or none. Sketch-style SVG scenes, `loose-sketch` / `doodle` class names, and `feTurbulence` grain read as amateur. This bans SVG imitating pictures, never SVG doing geometry: crisp vector shapes, diagrams, animated linework, and shader-driven effects remain first-class media. A shaded, perspectived, or figure-bearing illustration is a picture even in line-art style; geometry means shapes a session can specify exactly. +- Backgrounds are surfaces, textured only from the subject's world. `repeating-linear-gradient` stripes and two-axis grid overlays need an actual canvas, map, blueprint, or measuring tool under them. +- Claims and configuration come from supplied truth; label illustrative values honestly. Naming a concept and then ironizing it is not a claim. + +The floor holds the mechanics; it never picks the direction. With every check green, spend the page on the committed world, and when torn between refined and committed, commit. diff --git a/.agents/skills/impeccable/reference/craft.md b/.agents/skills/impeccable/reference/craft.md index 4adbc2b..dbbc940 100644 --- a/.agents/skills/impeccable/reference/craft.md +++ b/.agents/skills/impeccable/reference/craft.md @@ -1,123 +1,5 @@ -# Craft Flow +# Craft (deprecated alias) -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. +`craft` is a deprecated alias for an ordinary request to make new visual work. It adds no setup, interview, checkpoint, tool, or quality behavior. Apply SKILL.md's normal routing: create missing PRODUCT.md through [init.md](init.md), then follow [new-work.md](new-work.md) for visual authority, world and surface decisions, implementation, and finish. -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?" +Do not tell users they need to invoke `craft`. Natural requests such as “build this feature,” “make a landing page,” or “redesign this screen” use the same flow. diff --git a/.agents/skills/impeccable/reference/critique.md b/.agents/skills/impeccable/reference/critique.md index 331ea99..c1285ca 100644 --- a/.agents/skills/impeccable/reference/critique.md +++ b/.agents/skills/impeccable/reference/critique.md @@ -1,6 +1,6 @@ ### 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. +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 of that run. ### Hard Invariants @@ -8,10 +8,12 @@ Resolve one stable target, run two independent assessments, synthesize a design - 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. +- A skipped detector is a failed critique run unless `impeccable detect` 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. +- The question is the LAST thing in the response. Write the entire report out first, then ask; nothing follows the question. Prose emitted after a structured question is withheld until the user answers it, so a report written after the question reads as if the critique never ran. +- A run that ends with neither the targeted questions nor a literal `Questions skipped: ` line is an incomplete run. The report is not the finish; the close is. ### Setup @@ -19,11 +21,11 @@ Resolve one stable target, run two independent assessments, synthesize a design - "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**: +2. **Confirm the target slugs cleanly**: ```bash - node .agents/skills/impeccable/scripts/critique-storage.mjs slug "" + .agents/skills/impeccable/scripts/impeccable critique-storage slug "" ``` - Keep it. If the command exits non-zero, skip persistence and trend for this run, but continue the critique. + Every later command also accepts the resolved target directly and derives the same slug internally; never hand-write a slug. If this 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 @@ -52,13 +54,13 @@ If browser automation is available, each assessment creates its own new tab. Nev 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. +- **Design specificity**: Is the composition, interaction, and visual language grounded in this product, or could an unrelated product use it unchanged? Make this judgment before seeing detector output. - **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. +- **Nielsen heuristics**: consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below; score all 10 heuristics 0-4, marking any heuristic the mode-applicability rule allows as `n/a` instead of forcing a number. -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. +Return: design-specificity 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 @@ -66,7 +68,7 @@ Run the bundled detector and browser visualization evidence. Assessment B is man CLI scan: ```bash -node .agents/skills/impeccable/scripts/detect.mjs --json [target] +.agents/skills/impeccable/scripts/impeccable detect --json [target] ``` - Pass markup files/directories as `[target]`; do not pass CSS-only files. @@ -80,14 +82,14 @@ Browser visualization is required for a viewable target when browser automation 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 `\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 `` 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 - // `` 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. - * ``), 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/.agents/skills/impeccable/scripts/live-insert.mjs b/.agents/skills/impeccable/scripts/live-insert.mjs deleted file mode 100644 index 74cdc47..0000000 --- a/.agents/skills/impeccable/scripts/live-insert.mjs +++ /dev/null @@ -1,274 +0,0 @@ -/** - * 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] - */ -// @ts-nocheck - - -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/.agents/skills/impeccable/scripts/live-manual-edit-evidence.mjs b/.agents/skills/impeccable/scripts/live-manual-edit-evidence.mjs deleted file mode 100644 index 4f0f9dc..0000000 --- a/.agents/skills/impeccable/scripts/live-manual-edit-evidence.mjs +++ /dev/null @@ -1,364 +0,0 @@ -#!/usr/bin/env node -// @ts-nocheck -/** - * 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/.agents/skills/impeccable/scripts/live-poll.mjs b/.agents/skills/impeccable/scripts/live-poll.mjs deleted file mode 100644 index 7252fe3..0000000 --- a/.agents/skills/impeccable/scripts/live-poll.mjs +++ /dev/null @@ -1,386 +0,0 @@ -/** - * 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 - */ -// @ts-nocheck - - -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/.agents/skills/impeccable/scripts/live-resume.mjs b/.agents/skills/impeccable/scripts/live-resume.mjs deleted file mode 100644 index c0e3a1d..0000000 --- a/.agents/skills/impeccable/scripts/live-resume.mjs +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env node -// @ts-nocheck -/** - * 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/.agents/skills/impeccable/scripts/live-server.mjs b/.agents/skills/impeccable/scripts/live-server.mjs deleted file mode 100644 index 5622927..0000000 --- a/.agents/skills/impeccable/scripts/live-server.mjs +++ /dev/null @@ -1,1136 +0,0 @@ -#!/usr/bin/env node -// @ts-nocheck -/** - * 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, - 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, - 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/.agents/skills/impeccable/scripts/live-status.mjs b/.agents/skills/impeccable/scripts/live-status.mjs deleted file mode 100644 index d7d4cf8..0000000 --- a/.agents/skills/impeccable/scripts/live-status.mjs +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env node -// @ts-nocheck -/** - * 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/.agents/skills/impeccable/scripts/live-target.mjs b/.agents/skills/impeccable/scripts/live-target.mjs deleted file mode 100644 index b6c4ad4..0000000 --- a/.agents/skills/impeccable/scripts/live-target.mjs +++ /dev/null @@ -1,31 +0,0 @@ -// @ts-nocheck -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/.agents/skills/impeccable/scripts/live-wrap.mjs b/.agents/skills/impeccable/scripts/live-wrap.mjs deleted file mode 100644 index 928f2e3..0000000 --- a/.agents/skills/impeccable/scripts/live-wrap.mjs +++ /dev/null @@ -1,896 +0,0 @@ -/** - * 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. - */ -// @ts-nocheck - - -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(//gi, '') - .replace(//gi, '') - .replace(//g, '') - .replace(/<[^>]+>/g, ' ') - .replace(/\s+/g, ' ') - .trim(); - if (text.length > 0) return true; - return /<(img|svg|canvas|video|audio|picture|input|button|select|textarea)\b/i.test(markup || ''); -} - -function mergeOriginalTopLevelAttrs(markup, originalMarkup) { - const variantOpen = matchOpeningTag(markup); - const originalOpen = matchOpeningTag(originalMarkup); - if (!variantOpen || !originalOpen) return markup; - if (variantOpen.tag.toLowerCase() !== originalOpen.tag.toLowerCase()) return markup; - - const variantAttrs = parseAttrSegments(variantOpen.attrs); - const originalAttrs = parseAttrSegments(originalOpen.attrs); - const additions = []; - let attrs = variantOpen.attrs; - - const originalClass = originalAttrs.get('class'); - const variantClass = variantAttrs.get('class'); - if (originalClass && variantClass) { - const merged = mergeStaticClassAttr(originalClass, variantClass); - if (merged) { - attrs = attrs.slice(0, variantClass.start) + merged + attrs.slice(variantClass.end); - variantAttrs.set('class', { ...variantClass, raw: merged }); - } - } else if (originalClass && !variantClass) { - additions.push(originalClass.raw); - } - - for (const [name, attr] of originalAttrs) { - if (name === 'class') continue; - if (!variantAttrs.has(name)) additions.push(attr.raw); - } - - if (additions.length === 0 && attrs === variantOpen.attrs) return markup; - const nextOpen = variantOpen.prefix - + variantOpen.tag - + attrs - + additions.map((attr) => ' ' + attr.trim()).join('') - + variantOpen.close; - return markup.slice(0, variantOpen.index) + nextOpen + markup.slice(variantOpen.index + variantOpen.raw.length); -} - -function matchOpeningTag(markup) { - const match = String(markup || '').match(/^(\s*<)([A-Za-z][\w:-]*)([^>]*?)(\/?>)/); - if (!match) return null; - return { - raw: match[0], - prefix: match[1], - tag: match[2], - attrs: match[3] || '', - close: match[4], - index: match.index || 0, - }; -} - -function parseAttrSegments(attrs) { - const out = new Map(); - const re = /([A-Za-z_:][\w:.-]*)(?:\s*=\s*(?:"[^"]*"|'[^']*'|\{[^}]*\}|[^\s"'>=]+))?/g; - let match; - while ((match = re.exec(attrs))) { - const raw = match[0]; - const name = match[1]; - out.set(name, { - name, - raw, - start: match.index, - end: match.index + raw.length, - }); - } - return out; -} - -function mergeStaticClassAttr(originalClass, variantClass) { - const originalValue = originalClass.raw.match(/class\s*=\s*(["'])(.*?)\1/); - const variantValue = variantClass.raw.match(/class\s*=\s*(["'])(.*?)\1/); - if (!originalValue || !variantValue) return null; - const quote = variantValue[1]; - const classes = [ - ...variantValue[2].split(/\s+/), - ...originalValue[2].split(/\s+/), - ].filter(Boolean); - return `class=${quote}${[...new Set(classes)].join(' ')}${quote}`; -} - -export function removeSvelteComponentSession(id, cwd = process.cwd()) { - const dir = componentSessionDir(id, cwd); - try { - fs.rmSync(dir, { recursive: true, force: true }); - } catch { /* non-fatal */ } -} - -export function removeAllSvelteComponentSessions(cwd = process.cwd()) { - const root = path.join(cwd, SVELTE_COMPONENT_ROOT); - if (!fs.existsSync(root)) return; - for (const entry of fs.readdirSync(root, { withFileTypes: true })) { - if (!entry.isDirectory()) continue; - if (entry.name.startsWith('__')) continue; - try { - fs.rmSync(path.join(root, entry.name), { recursive: true, force: true }); - } catch { /* non-fatal */ } - } -} - -export function deferredAcceptsPath(cwd = process.cwd()) { - const key = createHash('sha1').update(path.resolve(cwd)).digest('hex').slice(0, 16); - return path.join(os.tmpdir(), 'impeccable-live', key, 'deferred-svelte-component-accepts.json'); -} - -export function readDeferredAccepts(cwd = process.cwd()) { - const file = deferredAcceptsPath(cwd); - try { - return JSON.parse(fs.readFileSync(file, 'utf-8')); - } catch { - return { accepts: [] }; - } -} - -export function writeDeferredAccept(entry, cwd = process.cwd()) { - const file = deferredAcceptsPath(cwd); - fs.mkdirSync(path.dirname(file), { recursive: true }); - const data = readDeferredAccepts(cwd); - data.accepts = (data.accepts || []).filter((item) => item.id !== entry.id); - data.accepts.push({ ...entry, createdAt: new Date().toISOString() }); - fs.writeFileSync(file, JSON.stringify(data, null, 2) + '\n', 'utf-8'); -} - -export function applyDeferredSvelteComponentAccepts(cwd = process.cwd()) { - const file = deferredAcceptsPath(cwd); - const data = readDeferredAccepts(cwd); - const pending = Array.isArray(data.accepts) ? data.accepts : []; - const results = []; - const remaining = []; - for (const entry of pending) { - try { - const manifest = findSvelteComponentManifest(entry.id, cwd); - if (!manifest) { - results.push({ id: entry.id, ok: false, error: 'manifest not found' }); - remaining.push(entry); - continue; - } - const result = inlineSvelteComponentAccept( - manifest, - entry.variantNum, - entry.paramValues || null, - cwd, - ); - results.push({ id: entry.id, ok: result.handled !== false, result }); - if (result.handled === false) remaining.push(entry); - } catch (err) { - results.push({ id: entry.id, ok: false, error: err.message }); - remaining.push(entry); - } - } - if (remaining.length > 0) { - fs.writeFileSync(file, JSON.stringify({ accepts: remaining }, null, 2) + '\n', 'utf-8'); - } else { - try { fs.rmSync(file, { force: true }); } catch {} - } - return { applied: results.filter((r) => r.ok).length, failed: results.filter((r) => !r.ok).length, results }; -} - -export function buildSvelteComponentCssAuthoring(count) { - const variantNumbers = Array.from({ length: count }, (_, i) => i + 1); - return { - mode: 'svelte-component', - styleTag: null, - strategy: 'component-style-block', - rulePattern: '.semantic-class { ... }', - selectorExamples: variantNumbers.map(() => '.expense-row { padding: 22px; }'), - requirements: [ - 'Write each variant as a real Svelte component file (v1.svelte, v2.svelte, ...).', - 'Keep the prop names from propContract; bind dynamic text with {propName}, not literal snapshot text.', - 'Put variant CSS in the component + + +
+ +

Novalon 官网 · Dogfood UI 审计报告

+
生成时间 ${esc(generatedAt)} · 数据源:Playwright 真实浏览器探针(多路由 × 多视口 × 浅深双主题)+ 静态硬编码色扫描
+ +

1. 审计范围与结论

+
+ + + + + + +
项目浅色主题深色主题
数据目录${esc(L?.dir || '-')}${esc(D?.dir || '-')}
路由数${L?.routeCount ?? '-'}${D?.routeCount ?? '-'}
视口desktop 1440×900 · tablet 768×1024(核心页) · mobile 390×844
探针维度对比度 · 横向溢出 · 触控目标 · 图片 alt · 标题层级 · 表单 label · 文本裁剪 · 键盘焦点 · console/网络异常 · LCP/CLS
+
+ +
+
${(L?.bySev.P1 || 0) + (D?.bySev.P1 || 0)}
P1 高危问题(浅+深)
+
${(L?.bySev.P2 || 0) + (D?.bySev.P2 || 0)}
P2 应修问题
+
${(L?.bySev.P3 || 0) + (D?.bySev.P3 || 0)}
P3 优化项
+
${(L?.bySev.INFO || 0) + (D?.bySev.INFO || 0)}
环境噪音(INFO,不计缺陷)
+
${(L?.metrics.navErrors ?? 0) + (D?.metrics.navErrors ?? 0)}
路由加载失败
+
${(L?.metrics.pageErrors ?? 0) + (D?.metrics.pageErrors ?? 0)}
未捕获 JS 异常
+
+ +${((L?.bySev.P1 || 0) + (D?.bySev.P1 || 0)) === 0 + ? '
无 P1 阻断问题。本次探针未发现加载失败、未捕获异常或致命可用性缺陷;剩余均为分级优化项。
' + : '
存在 P1 问题,优先处理。详见第 3 节共性清单。
'} + +

2. 关键指标

+
+
+

浅色主题

+ ${L ? metricTable(L) : '

无数据

'} +
+
+

深色主题

+ ${D ? metricTable(D) : '

无数据

'} +
+
+${worstContrast ? `
全局最低对比度:${esc(worstContrast.ratio)}:1(需 ${esc(worstContrast.need)}:1) + — ${esc(worstContrast.route)} ${esc(worstContrast.vp)} · 元素 ${esc(worstContrast.sel)} · 文案「${esc(worstContrast.text)}」
` : ''} + +

3. 共性问题清单(按影响面排序)

+${[L, D].map((s, i) => s ? ` +

${i === 0 ? '浅色' : '深色'}主题

+ ${SEV_ORDER.map(sev => { + const list = issuesBySev(i === 0 ? light : dark)[sev]; + if (!list.length) return ''; + const groups = groupCommon(list); + return `
+
${esc(SEV_LABEL[sev])} + ${list.length} 条 · 归为 ${groups.length} 类
+ + ${groups.map(g => ``).join('')} +
维度问题涉及路由
${esc(g.cat)}${esc(g.tpl)} + ${g.samples.length ? `
样本
    ${g.samples.slice(0, 4).map(s => `
  • ${esc(s)}
  • `).join('')}
` : ''} +
${esc(g.routes.join('
'))}
`; + }).join('')}` : '').join('')} + +

4. 深色主题专项(暗黑模式成熟度)

+
+

深色主题由 Playwright colorScheme: 'dark' 驱动,走项目三态偏好的 system 解析链路, + 与 e2e 视觉回归口径一致;不使用事后 setAttribute('data-theme')(会被挂载效果覆盖)。

+ ${newInDark.length ? ` + + + ${newInDark.slice(0, 20).map(x => ` + + + `).join('')} +
路由浅色问题数深色问题数增量
${esc(x.route)}${(x.light.P1 || 0)}+${(x.light.P2 || 0)}+${(x.light.P3 || 0)}${(x.dark.P1 || 0)}+${(x.dark.P2 || 0)}+${(x.dark.P3 || 0)}+${x.delta}
+

计数格式:P1+P2+P3。增量 > 0 表示该路由在深色下暴露了额外问题(典型为对比度不足、硬编码白底不翻转)。

` + : '
深色与浅色问题面一致,未发现深色专属回归。
'} +
+ +${notes ? `

5. 根因与修复建议(人工判定)

${notes}
` : ''} + +

6. 静态硬编码色扫描(暗黑 Phase 2 剩余)

+
+

Tailwind 原生 bg-white / bg-gray-* 是硬编码值,深色下不翻转 → 整页恒白。 + 扫描 ${esc(color?.scannedFiles ?? '-')} 个文件,命中 P0 ${esc(color?.counts?.P0 ?? '-')} / + P1 ${esc(color?.counts?.P1 ?? '-')} / INFO ${esc(color?.counts?.INFO ?? '-')} + (INFO 多为 bg-white/10 一类半透明叠加,属正确用法,非缺陷)

+ ${colorRows.length ? ` + + + ${colorRows.map(v => ` + + + + + `).join('')} +
级别文件类名原因
${esc(v.sev)}${esc(v.file)}${esc(v.ln)}${esc(v.cls)}${esc(v.why)}
+

修复映射约定:bg-bg-primary → 页面/大块骨架;bg-bg-elevated → 带边框的卡片/表单/图标盒。 + 浅色下 bg-white 与两者同值 → 改动在浅色主题零像素差异,只修深色。

` + : '
无 P0/P1 硬编码色残留。
'} +
+ +

7. 逐路由明细

+
+ + + ${routeRows.map(r => ` + + + + + `).join('')} +
路由浅色 P1/P2/P3深色 P1/P2/P3问题摘要(深色)
${esc(r.route)}${badge(r.lc)}${badge(r.dc)}${r.dIssues.length + ? `
${esc(r.dIssues.length)} 条
    ${r.dIssues.map(x => `
  • ${esc(x)}
  • `).join('')}
` + : ''}
+
+ +

8. 截图

+${renderScreenshots(light, '浅色')} +${renderScreenshots(dark, '深色')} + +

9. 复现方式

+
+
# 1) 起本地站点(URL 必须是 localhost,127.0.0.1 会被 allowedDevOrigins 拒绝 → chunk 403 → hydration 失败)
+npm run dev
+
+# 2) 浅色全站审计
+node scripts/audit/ui-audit.mjs
+
+# 3) 深色全站审计(核心页含整页长图)
+node scripts/audit/ui-audit.mjs --theme dark --full-page
+
+# 4) 静态硬编码色盘点
+node scripts/audit/hardcoded-color-audit.mjs
+
+# 5) 生成本报告
+node scripts/audit/ui-audit-report.mjs
+
+ +
+ +`; +} + +function badge(c) { + const t = (c.P1 || 0) + (c.P2 || 0) + (c.P3 || 0); + if (!t) return '0'; + return `${c.P1 || 0} ${c.P2 || 0} ${c.P3 || 0}`; +} + +function metricTable(s) { + const m = s.metrics; + return ` + + + + + + + + + + + + +
对比度违规${m.contrastTotal}
未捕获 JS 异常${m.pageErrors}
console 错误${m.consoleErrors}
请求失败${m.failedReq}
触控目标 <24px${m.touchTotal}
图片 alt 问题${m.altTotal}
表单缺 label${m.labelTotal}
键盘聚焦无指示${m.noFocusTotal}
文本被裁剪${m.clipTotal}
LCP 均值 / 最大${m.lcpAvg ?? '-'} ms / ${m.lcpMax ? m.lcpMax.v + ' ms(' + m.lcpMax.route + ' ' + m.lcpMax.vp + ')' : '-'}
CLS 最大${m.clsMax ? m.clsMax.v + '(' + m.clsMax.route + ')' : '0'}
页面平均加载${m.loadAvg ?? '-'} ms
`; +} + +// ---------------------------------------------------------------- main +const args = parseArgs(process.argv); +const lightDir = args.light || latestDir(n => !n.endsWith('-dark')); +const darkDir = args.dark || latestDir(n => n.endsWith('-dark')); +if (process.env.REPORT_DEBUG) { + console.error('[debug] ROOT =', ROOT); + console.error('[debug] AUDIT_ROOT =', AUDIT_ROOT, fs.existsSync(AUDIT_ROOT)); + console.error('[debug] lightDir =', lightDir, 'darkDir =', darkDir); +} +const colorFile = args.color || path.join(ROOT, 'dogfood-color-audit', 'color-audit.json'); + +const light = loadProbes(lightDir); +const dark = loadProbes(darkDir); +const color = fs.existsSync(colorFile) ? JSON.parse(fs.readFileSync(colorFile, 'utf8')) : null; + +if (!light && !dark) { + console.error('未找到任何探针数据(dogfood-ui-audit/ 下无 probes.json)。请先运行 ui-audit.mjs。'); + process.exit(1); +} + +const outDir = args.out || path.join(AUDIT_ROOT, 'report'); +fs.mkdirSync(outDir, { recursive: true }); +const notes = args.notes && fs.existsSync(args.notes) ? fs.readFileSync(args.notes, 'utf8') : null; +const outFile = path.join(outDir, 'index.html'); +fs.writeFileSync(outFile, buildHtml({ light, dark, color, notes })); +console.log(`✓ 报告已生成:${path.relative(ROOT, outFile)}`); +console.log(` 浅色数据:${light ? light.dir : '无'}`); +console.log(` 深色数据:${dark ? dark.dir : '无'}`); +console.log(` 颜色数据:${color ? path.relative(ROOT, colorFile) : '无'}`); diff --git a/scripts/audit/ui-audit.mjs b/scripts/audit/ui-audit.mjs new file mode 100644 index 0000000..9b55a00 --- /dev/null +++ b/scripts/audit/ui-audit.mjs @@ -0,0 +1,736 @@ +/** + * Novalon Website · UI / UX / UE Dogfood 审计采集器 + * + * 用真实浏览器访问线上等价站点(本地 dev server),对每个路由执行: + * 1. 静态探针(页面内 evaluate):对比度 / 横向溢出 / 触控目标 / alt / 标题层级 / label / 文本截断 + * 2. 动态探针(Node 层):console 与网络错误 / Tab 焦点可见性 / 性能与布局稳定性(CLS/LCP) + * 3. 多视口截图,供人工视觉审查 + * + * 用法: + * node scripts/audit/ui-audit.mjs # 默认全站 desktop+mobile,tablet 仅核心页 + * node scripts/audit/ui-audit.mjs --routes / /contact # 指定路由 + * node scripts/audit/ui-audit.mjs --viewports desktop # 指定视口 + * node scripts/audit/ui-audit.mjs --no-shot # 只跑探针不截图 + * node scripts/audit/ui-audit.mjs --theme dark # 按深色主题审计(对比度/背景翻转在此暴露) + * + * 主题驱动说明:用 Playwright context 的 colorScheme 驱动,走项目三态偏好的 system 档解析链路, + * 与 e2e 视觉回归口径一致;**不要**在页面加载后 setAttribute('data-theme'),会被挂载效果覆盖。 + * + * 输出:dogfood-ui-audit/[-]/{screenshots,probes.json,summary.md} + */ + +import { chromium } from 'playwright'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(__dirname, '../..'); + +// ---------------------------------------------------------------- 参数解析 +function parseArgs(argv) { + const args = { routes: null, viewports: null, noShot: false, fullPage: false, limit: null, theme: 'light' }; + for (let i = 2; i < argv.length; i++) { + const a = argv[i]; + if (a === '--routes') args.routes = collectUntilFlag(argv, ++i); + else if (a === '--viewports') args.viewports = collectUntilFlag(argv, ++i); + else if (a === '--limit') args.limit = Number(argv[++i]); + else if (a === '--no-shot') args.noShot = true; + else if (a === '--full-page') args.fullPage = true; + else if (a === '--theme') { args.theme = argv[i + 1] === 'dark' ? 'dark' : 'light'; i++; } + } + return args; +} +function collectUntilFlag(argv, start) { + const out = []; + for (let i = start; i < argv.length && !argv[i].startsWith('--'); i++) out.push(argv[i]); + return out; +} + +const BASE_URL = process.env.AUDIT_BASE_URL || 'http://localhost:3000'; + +const VIEWPORTS = { + desktop: { width: 1440, height: 900 }, + tablet: { width: 768, height: 1024 }, + mobile: { width: 390, height: 844 }, +}; + +/** 核心页:额外跑 tablet 视口 + 全页长图 */ +const TIER1 = new Set(['/', '/products', '/solutions', '/services', '/cases', '/contact', '/about', '/news']); + +/** 静态已知路由(列表页链接不可达的页面必须显式列出,否则审计发现不到 —— 2026-09-04 修复盲区) */ +const KNOWN_ROUTES = [ + '/', + '/about', + '/about/brand', + '/cases', + '/contact', + '/methodology', + '/news', + '/products', + '/products/erp-upgrade', + '/products/erp-upgrade-v3', + '/services', + '/solutions', + '/team', + '/privacy', + '/terms', +]; + +/** 独立产品页(/products/standalone/[id])的静态生成实例;id 来自 CMS,build 后从 .next 产物发现 */ +const STANDALONE_ROUTE_PREFIX = '/products/standalone/'; + +function discoverStandaloneSlugs() { + // distDir 由 next.config.mjs 决定(默认 'dist',可用 NEXT_DIST_DIR 覆盖) + const base = path.join(ROOT, process.env.NEXT_DIST_DIR || 'dist', 'server', 'app', 'products', 'standalone'); + if (!fs.existsSync(base)) return []; + const slugs = []; + const walk = (dir) => { + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) walk(p); + else if (/\.(html|body|meta)$/.test(e.name)) { + const rel = path.relative(base, path.dirname(p)); + if (rel && rel !== '.' && !rel.includes('[')) slugs.push(rel); + } + } + }; + walk(base); + return [...new Set(slugs)].sort(); +} + +/** 列表页 → 用于发现动态详情路由 */ +const LIST_ROUTES = ['/cases', '/news', '/products', '/services', '/solutions']; + +// ---------------------------------------------------------------- 页面内探针 +const PAGE_PROBE = `(() => { + const out = { + contrast: [], overflow: { doc: null, offenders: [] }, touch: [], images: [], + headings: [], labels: [], clipped: [], colors: {}, meta: {}, interactables: 0, + }; + + // ---- 颜色工具 ---- + function parseColor(str) { + if (!str) return null; + const s = String(str).trim(); + if (s === 'transparent' || s === 'rgba(0, 0, 0, 0)') return { r:0,g:0,b:0,a:0 }; + let m = s.match(/^rgba?\\(\\s*([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)(?:[,\\s/]+([\\d.]+))?\\s*\\)$/i); + if (m) { + return { r:+m[1], g:+m[2], b:+m[3], a: m[4] === undefined ? 1 : +m[4] }; + } + return null; + } + function composite(fg, bg) { + if (fg.a >= 1) return { r:fg.r, g:fg.g, b:fg.b, a:1 }; + return { + r: fg.r*fg.a + bg.r*(1-fg.a), + g: fg.g*fg.a + bg.g*(1-fg.a), + b: fg.b*fg.a + bg.b*(1-fg.a), + a: 1, + }; + } + function lum(c) { + const f = v => { v/=255; return v <= 0.03928 ? v/12.92 : Math.pow((v+0.055)/1.055, 2.4); }; + return 0.2126*f(c.r) + 0.7152*f(c.g) + 0.0722*f(c.b); + } + function ratio(a, b) { + const l1 = lum(a), l2 = lum(b); + const hi = Math.max(l1,l2), lo = Math.min(l1,l2); + return (hi + 0.05) / (lo + 0.05); + } + function effectiveBg(el) { + // 向上合成背景,返回不透明背景色(遇到渐变/图片则标记 unknown) + const stack = []; + let cur = el; + let guard = 0; + let unknown = false; + while (cur && cur.nodeType === 1 && guard++ < 40) { + const cs = getComputedStyle(cur); + if (cs.backgroundImage && cs.backgroundImage !== 'none') unknown = true; + const bc = parseColor(cs.backgroundColor); + if (bc && bc.a > 0) { stack.push(bc); if (bc.a >= 1) break; } + cur = cur.parentElement; + } + let base = { r:255, g:255, b:255, a:1 }; + for (let i = stack.length - 1; i >= 0; i--) base = composite(stack[i], base); + return { color: base, unknown }; + } + function isVisible(el) { + const cs = getComputedStyle(el); + if (cs.display === 'none' || cs.visibility === 'hidden') return false; + if (parseFloat(cs.opacity) === 0) return false; + const r = el.getBoundingClientRect(); + if (r.width < 1 || r.height < 1) return false; + return true; + } + function path(el) { + let s = el.tagName.toLowerCase(); + if (el.id) s += '#' + el.id; + const cls = (el.className && typeof el.className === 'string') + ? el.className.trim().split(/\\s+/).slice(0,2).join('.') : ''; + if (cls) s += '.' + cls; + return s; + } + + // ---- 1. 对比度 ---- + const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT); + let node, seen = 0, decorativeSkipped = 0; + while ((node = walker.nextNode()) && seen < 4000) { + const text = node.nodeValue && node.nodeValue.trim(); + if (!text || text.length < 1) continue; + const el = node.parentElement; + if (!el || !isVisible(el)) continue; + // 纯装饰豁免:WCAG 1.4.3 不适用于装饰性内容(元素被 aria-hidden 标记)。 + // 计入 decorativeSkipped 让豁免量可见 —— 防止用 aria-hidden 刷绿对比度数字。 + if (el.closest('[aria-hidden="true"]')) { decorativeSkipped++; continue; } + const cs = getComputedStyle(el); + const fgRaw = parseColor(cs.color); + if (!fgRaw || fgRaw.a === 0) continue; + const bgInfo = effectiveBg(el); + if (bgInfo.unknown) continue; // 渐变/图片背景:交给人工复核 + const fg = composite(fgRaw, bgInfo.color); + const size = parseFloat(cs.fontSize) || 16; + const weight = parseInt(cs.fontWeight, 10) || 400; + const isLarge = size >= 24 || (size >= 18.66 && weight >= 700); + const need = isLarge ? 3.0 : 4.5; + const r = ratio(fg, bgInfo.color); + seen++; + if (r < need) { + out.contrast.push({ + sel: path(el), + text: text.slice(0, 60), + ratio: +r.toFixed(2), + need, + fontSize: size, + weight, + fg: cs.color, + bg: 'rgb(' + Math.round(bgInfo.color.r) + ', ' + Math.round(bgInfo.color.g) + ', ' + Math.round(bgInfo.color.b) + ')', + }); + } + } + out.contrast = out.contrast.slice(0, 40); + out.decorativeSkipped = decorativeSkipped; + + // ---- 2. 横向溢出 ---- + const vw = document.documentElement.clientWidth; + const de = document.documentElement; + if (de.scrollWidth > vw + 1) { + out.overflow.doc = { scrollWidth: de.scrollWidth, clientWidth: vw, delta: de.scrollWidth - vw }; + const all = document.querySelectorAll('body *'); + const list = []; + for (const el of all) { + if (!isVisible(el)) continue; + const cs = getComputedStyle(el); + if (cs.position === 'fixed') continue; + const r = el.getBoundingClientRect(); + if (r.right > vw + 1 || r.left < -1) { + list.push({ sel: path(el), left: Math.round(r.left), right: Math.round(r.right), w: Math.round(r.width) }); + if (list.length >= 25) break; + } + } + out.overflow.offenders = list; + } + + // ---- 3. 触控目标 (WCAG 2.2 AA 2.5.8 最小 24x24) ---- + const interactive = document.querySelectorAll('a[href], button, input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])'); + out.interactables = interactive.length; + for (const el of interactive) { + if (!isVisible(el)) continue; + // aria-hidden 容器内的可聚焦元素属 ARIA 误用(隐藏内容不应能被聚焦)。 + // 单独计数上报,而不是静默跳过 —— 否则装饰标记会掩盖真实缺陷。 + if (el.closest('[aria-hidden="true"]')) { + out.ariaHiddenFocusable = (out.ariaHiddenFocusable || 0) + 1; + continue; + } + const r = el.getBoundingClientRect(); + if (r.width < 24 || r.height < 24) { + const hasName = !!(el.getAttribute('aria-label') || el.getAttribute('title') || + (el.textContent && el.textContent.trim()) || el.getAttribute('placeholder')); + out.touch.push({ + sel: path(el), w: Math.round(r.width), h: Math.round(r.height), + text: (el.textContent || '').trim().slice(0, 40) || null, + hasAccessibleName: hasName, + }); + if (out.touch.length >= 30) break; + } + } + + // ---- 4. 图片 alt ---- + for (const img of document.querySelectorAll('img')) { + if (!isVisible(img)) continue; + const alt = img.getAttribute('alt'); + if (alt === null) { + out.images.push({ sel: path(img), src: (img.getAttribute('src')||'').slice(0,110), issue: 'missing-alt' }); + } else if (alt.trim() === '' && !img.getAttribute('role') && img.getAttribute('aria-hidden') === null) { + out.images.push({ sel: path(img), src: (img.getAttribute('src')||'').slice(0,110), issue: 'empty-alt-not-marked-decorative' }); + } + } + out.images = out.images.slice(0, 20); + + // ---- 5. 标题层级 ---- + const hs = [...document.querySelectorAll('h1,h2,h3,h4,h5,h6')].filter(isVisible); + let prev = 0; + for (const h of hs) { + const lv = +h.tagName[1]; + const txt = (h.textContent || '').trim().slice(0, 60); + if (prev && lv > prev + 1) out.headings.push({ sel: path(h), level: lv, prev, text: txt, issue: 'skip-level' }); + if (lv === 1) out.headings.push({ sel: path(h), level: 1, text: txt, issue: 'h1' }); + prev = lv; + } + const h1Count = hs.filter(h => h.tagName === 'H1').length; + out.headings = out.headings.filter(x => x.issue !== 'h1').slice(0, 12); + out.headingSummary = { h1Count, total: hs.length, + sequence: hs.slice(0, 25).map(h => +h.tagName[1]) }; + + // ---- 6. 表单 label ---- + for (const f of document.querySelectorAll('input:not([type=hidden]), textarea, select')) { + if (!isVisible(f)) continue; + const id = f.id; + const hasLabel = id ? !!document.querySelector('label[for="' + CSS.escape(id) + '"]') : false; + const wrapped = !!f.closest('label'); + const aria = !!(f.getAttribute('aria-label') || f.getAttribute('aria-labelledby')); + if (!hasLabel && !wrapped && !aria) { + out.labels.push({ sel: path(f), type: f.getAttribute('type') || f.tagName.toLowerCase(), + name: f.getAttribute('name') || null, placeholder: f.getAttribute('placeholder') || null }); + } + } + out.labels = out.labels.slice(0, 20); + + // ---- 7. 文本被裁剪 (overflow hidden 且内容溢出,且非 ellipsis) ---- + let clipCount = 0; + for (const el of document.querySelectorAll('body *')) { + if (clipCount >= 15) break; + if (!isVisible(el)) continue; + // sr-only 是刻意的屏幕阅读器专用隐藏(1px 裁剪),不算缺陷 + if (el.classList.contains('sr-only')) continue; + const cs = getComputedStyle(el); + if (cs.overflow === 'visible' || cs.overflowY === 'visible') continue; + if (el.scrollHeight > el.clientHeight + 4 && el.clientHeight > 0) { + if (cs.textOverflow === 'ellipsis') continue; + // 有意的 line-clamp 多行截断不算缺陷 + if (cs.webkitLineClamp && cs.webkitLineClamp !== 'none') continue; + if (cs.display === '-webkit-box') continue; + if (el.children.length > 0 && !el.textContent.trim()) continue; + out.clipped.push({ sel: path(el), scrollH: el.scrollHeight, clientH: el.clientHeight, + text: (el.textContent||'').trim().slice(0, 50) }); + clipCount++; + } + } + + // ---- 8. 颜色使用分布(设计令牌一致性 / 品牌红触达点)---- + const freq = {}; + const bump = (k) => { if (k) freq[k] = (freq[k] || 0) + 1; }; + for (const el of document.querySelectorAll('body *')) { + if (!isVisible(el)) continue; + const cs = getComputedStyle(el); + bump(cs.color); + bump(cs.backgroundColor); + if (cs.borderTopWidth !== '0px') bump(cs.borderTopColor); + } + out.colors = Object.entries(freq).sort((a,b) => b[1]-a[1]).slice(0, 18) + .map(([c, n]) => ({ color: c, count: n })); + + // ---- 9. 元信息 ---- + out.meta = { + title: document.title, + titleLen: (document.title || '').length, + lang: document.documentElement.lang || null, + hasViewportMeta: !!document.querySelector('meta[name="viewport"]'), + h1Text: (document.querySelector('h1')?.textContent || '').trim().slice(0, 90) || null, + textNodes: seen, + scripts: document.querySelectorAll('script').length, + imgCount: document.querySelectorAll('img').length, + linkCount: document.querySelectorAll('a[href]').length, + }; + + return out; +})()`; + +// ---------------------------------------------------------------- 主流程 +async function discoverRoutes(page) { + const routes = [...KNOWN_ROUTES]; + const found = new Set(); + for (const list of LIST_ROUTES) { + try { + await page.goto(BASE_URL + list, { waitUntil: 'domcontentloaded', timeout: 45000 }); + await page.waitForTimeout(1200); + const hrefs = await page.$$eval('a[href]', as => as.map(a => a.getAttribute('href'))); + for (const h of hrefs) { + if (!h || !h.startsWith('/')) continue; + if (h.startsWith('/admin') || h === '/test-error-tracking') continue; + // 同一前缀下的详情页 + if (h.startsWith(list + '/') && h.split('/').length >= 3) found.add(h); + } + } catch (e) { + console.warn(` [discover] ${list} 失败: ${e.message.slice(0, 80)}`); + } + } + routes.push(...[...found].sort()); + return [...new Set(routes)]; +} + +async function auditRoute(page, ctx, route, viewports, args, outDir) { + const slug = route === '/' ? 'home' : route.replace(/^\//, '').replace(/\//g, '__'); + const result = { route, viewports: {} }; + + for (const vpName of viewports) { + const vp = VIEWPORTS[vpName]; + await page.setViewportSize({ width: vp.width, height: vp.height }); + + const consoleErrors = []; + const pageErrors = []; + const failedRequests = []; + const finishedUrls = new Set(); + const onConsole = m => { if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 200)); }; + const onPageErr = e => pageErrors.push(String(e.message || e).slice(0, 200)); + const onReqFail = r => { + // 请求失败时 response() 可能返回部分初始化的对象(无 status 方法),需防御 + let st = null; + try { + const resp = r.response(); + if (resp && typeof resp.status === 'function') st = resp.status(); + } catch { /* 部分初始化时忽略 */ } + let rt = null; + try { rt = r.resourceType(); } catch { /* ignore */ } + failedRequests.push({ + url: r.url().slice(0, 140), method: r.method(), + failure: r.failure()?.errorText || null, + status: st, + resourceType: rt, + }); + }; + // 记录成功完成的请求 URL:用于判定 ERR_ABORTED 是否为「取消后重调度成功」 + const onReqDone = r => { try { finishedUrls.add(r.url()); } catch { /* ignore */ } }; + page.on('console', onConsole); + page.on('pageerror', onPageErr); + page.on('requestfailed', onReqFail); + page.on('requestfinished', onReqDone); + + let navStatus = null; + let navError = null; + const t0 = Date.now(); + try { + const resp = await page.goto(BASE_URL + route, { waitUntil: 'load', timeout: 60000 }); + navStatus = resp ? resp.status() : null; + } catch (e) { + navError = e.message.slice(0, 160); + } + // 给动效与懒加载留出时间 + await page.waitForTimeout(1500); + const loadMs = Date.now() - t0; + + const vpResult = { navStatus, navError, loadMs }; + + if (!navError) { + // 静态探针 + try { + vpResult.probe = await page.evaluate(PAGE_PROBE); + } catch (e) { + vpResult.probeError = e.message.slice(0, 200); + } + + // 性能与布局稳定性 + try { + vpResult.perf = await page.evaluate(() => { + const nav = performance.getEntriesByType('navigation')[0] || {}; + const paint = {}; + for (const p of performance.getEntriesByType('paint')) paint[p.name] = Math.round(p.startTime); + return { + ttfb: nav.responseStart ? Math.round(nav.responseStart) : null, + domContentLoaded: nav.domContentLoadedEventEnd ? Math.round(nav.domContentLoadedEventEnd) : null, + load: nav.loadEventEnd ? Math.round(nav.loadEventEnd) : null, + fcp: paint['first-contentful-paint'] ?? null, + lcp: window.__audit?.lcp ? Math.round(window.__audit.lcp) : null, + cls: window.__audit?.cls ? +window.__audit.cls.toFixed(4) : 0, + transferSize: nav.transferSize ?? null, + }; + }); + } catch { /* ignore */ } + + // LCP 单次采样对系统抖动敏感:超阈值时热缓存 reload 复测一次取较优值,防假阳性 + //(2026-09-05 案例:healthcare 深色单次 2660ms,复测 3 次全 1292-1664ms) + if (vpResult.perf?.lcp && vpResult.perf.lcp > 2500) { + try { + await page.reload({ waitUntil: 'load', timeout: 60000 }); + await page.waitForTimeout(1500); + const lcp2 = await page.evaluate(() => (window.__audit?.lcp ? Math.round(window.__audit.lcp) : null)); + if (lcp2) { + vpResult.perf.lcpCold = vpResult.perf.lcp; + vpResult.perf.lcp = Math.min(vpResult.perf.lcp, lcp2); + } + } catch { /* ignore */ } + } + + // Tab 焦点可见性(UE 键盘可达性采样) + if (vpName === 'desktop') { + try { + const focusSamples = []; + for (let i = 0; i < 10; i++) { + await page.keyboard.press('Tab'); + const s = await page.evaluate(() => { + const el = document.activeElement; + if (!el || el === document.body) return null; + const cs = getComputedStyle(el); + const r = el.getBoundingClientRect(); + return { + tag: el.tagName.toLowerCase(), + text: (el.textContent || '').trim().slice(0, 30) || el.getAttribute('aria-label') || null, + outlineStyle: cs.outlineStyle, outlineWidth: cs.outlineWidth, + boxShadow: cs.boxShadow === 'none' ? null : cs.boxShadow.slice(0, 60), + inViewport: r.top >= -50 && r.bottom <= window.innerHeight + 50, + }; + }); + if (s) focusSamples.push(s); + } + vpResult.focus = focusSamples; + } catch (e) { vpResult.focusError = e.message.slice(0, 120); } + } + + // 截图 + if (!args.noShot) { + const shotDir = path.join(outDir, 'screenshots', vpName); + fs.mkdirSync(shotDir, { recursive: true }); + const file = path.join(shotDir, slug + '.png'); + await page.screenshot({ path: file, fullPage: args.fullPage && TIER1.has(route) }); + vpResult.screenshot = path.relative(ROOT, file); + } + } + + vpResult.consoleErrors = consoleErrors.slice(0, 12); + vpResult.pageErrors = pageErrors.slice(0, 8); + vpResult.failedRequests = failedRequests.slice(0, 12); + vpResult.finishedUrls = [...finishedUrls]; + + page.off('console', onConsole); + page.off('pageerror', onPageErr); + page.off('requestfailed', onReqFail); + page.off('requestfinished', onReqDone); + + result.viewports[vpName] = vpResult; + } + + return result; +} + +// 性能断言有效性(main 里按系统负载设定):load 过高时 LCP/CLS 采样不可信 +let PERF_ASSERT_VALID = true; +let PERF_LOAD_AT_START = 0; + +function scoreRoute(r) { + const issues = []; + const d = r.viewports.desktop || {}; + const m = r.viewports.mobile || {}; + const p = d.probe || {}; + const pm = m.probe || {}; + + if (d.navError) issues.push({ sev: 'P1', cat: '可用性', msg: `desktop 加载失败: ${d.navError}` }); + if (m.navError) issues.push({ sev: 'P1', cat: '可用性', msg: `mobile 加载失败: ${m.navError}` }); + if ((d.navStatus && d.navStatus >= 400) || (m.navStatus && m.navStatus >= 400)) + issues.push({ sev: 'P1', cat: '可用性', msg: `HTTP ${d.navStatus || m.navStatus}` }); + + // 第三方统计噪音(GA/gtm beacon 等):沙箱无外网时必然失败,非站点缺陷 → INFO。 + // 2026-09-04 全量终验:238 条错误 100% 为 google 系 beacon,非 GA 项 0。 + const THIRD_PARTY_NOISE_RE = /google-analytics\.com|googletagmanager\.com|google\.com\/g\/collect|doubleclick\.net|\/gtag\//i; + const cerrAll = [...(d.consoleErrors || []), ...(m.consoleErrors || [])]; + const cerr = cerrAll.filter(e => !THIRD_PARTY_NOISE_RE.test(String(e))); + const cerrNoise = cerrAll.length - cerr.length; + if (cerr.length) issues.push({ sev: 'P2', cat: 'UE/稳定性', msg: `console 错误 ${cerr.length} 条`, detail: cerr.slice(0, 3) }); + if (cerrNoise) issues.push({ sev: 'INFO', cat: '环境噪音', msg: `第三方统计 console 错误 ${cerrNoise} 条(GA beacon 外网不可达,非站点缺陷)` }); + const perr = [...(d.pageErrors || []), ...(m.pageErrors || [])]; + if (perr.length) issues.push({ sev: 'P1', cat: 'UE/稳定性', msg: `未捕获异常 ${perr.length} 条`, detail: perr.slice(0, 3) }); + const rfailAll = [...(d.failedRequests || []), ...(m.failedRequests || [])]; + const rfailNoise = rfailAll.filter(f => THIRD_PARTY_NOISE_RE.test(String(f.url || ''))); + // net::ERR_ABORTED = 客户端主动取消。结合三类证据判定是否留痕: + // ① 同 URL 后来成功(requestfinished 关联)→ 重调度,完全无害,不留痕 + // ② prefetch 资源被打断 → 本身无用户影响,不留痕 + // ③ 同源 script 被取消且该路由无未捕获异常 → 运行时自行取代的请求(App Router 静态 chunk + // 预取不带 Sec-Purpose 头,无法按头识别;后果导向:必需 chunk 被取消必然伴随 + // hydration 失败 → pageErrors 非空,届时仍会以 P1 记录)。闭环成立,不留痕。 + // ④ 其余 abort → INFO 留痕(2026-09-05 实测 /methodology 三图 abort 后 complete=true、URL 全 200) + const finishedSet = new Set([...(d.finishedUrls || []), ...(m.finishedUrls || [])]); + const noPageErr = perr.length === 0; + const abortedAndGone = f => + !THIRD_PARTY_NOISE_RE.test(String(f.url || '')) && + f.failure === 'net::ERR_ABORTED' && + (f.resourceType === 'prefetch' || finishedSet.has(f.url) || + (f.resourceType === 'script' && noPageErr)); + const rfailAbort = rfailAll.filter(f => + !THIRD_PARTY_NOISE_RE.test(String(f.url || '')) && + f.failure === 'net::ERR_ABORTED' && !abortedAndGone(f)); + const rfail = rfailAll.filter(f => !THIRD_PARTY_NOISE_RE.test(String(f.url || '')) && f.failure !== 'net::ERR_ABORTED'); + if (rfail.length) issues.push({ sev: 'P2', cat: 'UE/稳定性', msg: `请求失败 ${rfail.length} 条`, detail: rfail.slice(0, 3) }); + if (rfailAbort.length) issues.push({ sev: 'INFO', cat: '环境噪音', msg: `浏览器取消的请求 ${rfailAbort.length} 条(prefetch/懒加载调度,资源实测可服务)` }); + if (rfailNoise.length) issues.push({ sev: 'INFO', cat: '环境噪音', msg: `第三方统计请求失败 ${rfailNoise.length} 条(GA beacon 外网不可达,非站点缺陷)` }); + + const cr = [...(p.contrast || []), ...(pm.contrast || [])]; + if (cr.length) { + const worst = cr.reduce((a, b) => (b.ratio < a.ratio ? b : a), cr[0]); + issues.push({ sev: 'P1', cat: 'UI/可访问性', msg: `对比度违规 ${cr.length} 处(最低 ${worst.ratio}:1,需 ${worst.need}:1)`, + detail: cr.slice(0, 4).map(c => `${c.sel} "${c.text}" ${c.ratio}:1 (fg ${c.fg} / bg ${c.bg})`) }); + } + + const ovM = pm.overflow?.doc || m.probe?.overflow?.doc; + if (ovM) issues.push({ sev: 'P1', cat: 'UX/响应式', msg: `移动端横向溢出 ${ovM.delta}px (scrollWidth ${ovM.scrollWidth} > ${ovM.clientWidth})`, + detail: (pm.overflow?.offenders || []).slice(0, 5).map(o => `${o.sel} right=${o.right} w=${o.w}`) }); + const ovD = d.probe?.overflow?.doc; + if (ovD) issues.push({ sev: 'P2', cat: 'UX/响应式', msg: `桌面端横向溢出 ${ovD.delta}px`, + detail: (d.probe?.overflow?.offenders || []).slice(0, 5).map(o => `${o.sel} right=${o.right} w=${o.w}`) }); + + const touchM = (pm.touch || []).filter(t => t.h < 24 || t.w < 24); + if (touchM.length) issues.push({ sev: 'P2', cat: 'UE/触控', msg: `移动端触控目标 <24px ${touchM.length} 个`, + detail: touchM.slice(0, 4).map(t => `${t.sel} ${t.w}x${t.h} "${t.text || ''}"`) }); + + const imgs = [...(p.images || []), ...(pm.images || [])]; + if (imgs.length) issues.push({ sev: 'P2', cat: 'UI/可访问性', msg: `图片 alt 问题 ${imgs.length} 个`, detail: imgs.slice(0, 4).map(i => `${i.issue}: ${i.src}`) }); + + const hd = p.headingSummary || {}; + if (hd.h1Count === 0) issues.push({ sev: 'P2', cat: 'UX/信息架构', msg: '页面缺少 h1' }); + if (hd.h1Count > 1) issues.push({ sev: 'P2', cat: 'UX/信息架构', msg: `页面存在 ${hd.h1Count} 个 h1` }); + if ((p.headings || []).length) issues.push({ sev: 'P3', cat: 'UX/信息架构', msg: `标题跳级 ${p.headings.length} 处`, + detail: p.headings.slice(0, 4).map(h => `h${h.prev} → h${h.level} "${h.text}"`) }); + + const lbl = [...(p.labels || []), ...(pm.labels || [])]; + if (lbl.length) issues.push({ sev: 'P2', cat: 'UE/表单', msg: `表单控件缺 label ${lbl.length} 个`, detail: lbl.slice(0, 4).map(l => `${l.sel} name=${l.name || '-'}`) }); + + const clip = [...(p.clipped || []), ...(pm.clipped || [])]; + if (clip.length) issues.push({ sev: 'P2', cat: 'UI/排版', msg: `文本被容器裁剪 ${clip.length} 处`, detail: clip.slice(0, 4).map(c => `${c.sel} ${c.scrollH}>${c.clientH} "${c.text}"`) }); + + const noFocus = (d.focus || []).filter(f => f.outlineStyle === 'none' && !f.boxShadow); + if (noFocus.length) issues.push({ sev: 'P2', cat: 'UE/键盘可达', msg: `聚焦无可见指示 ${noFocus.length} 个`, detail: noFocus.slice(0, 4).map(f => `<${f.tag}> "${f.text || ''}"`) }); + + // 性能断言有效性门控:系统 load 过高时 LCP/CLS 采样不可信(实测 load 9.87 时整轮膨胀至 2500-3652ms + // 而 TTFB 正常),此时跳过断言而非产出假阳性。阈值取 5(单数 machine 一般 <2,共享开发机留余量)。 + if (PERF_ASSERT_VALID) { + const cls = Math.max(d.perf?.cls || 0, m.perf?.cls || 0); + if (cls > 0.1) issues.push({ sev: 'P2', cat: 'UE/性能', msg: `CLS ${cls} 超过 0.1 阈值` }); + const lcp = Math.max(d.perf?.lcp || 0, m.perf?.lcp || 0); + if (lcp > 2500) issues.push({ sev: 'P3', cat: 'UE/性能', msg: `LCP ${lcp}ms 超过 2500ms` }); + } + if (!p.meta?.lang) issues.push({ sev: 'P2', cat: 'UI/可访问性', msg: 'html 缺少 lang 属性' }); + if (p.meta?.titleLen === 0) issues.push({ sev: 'P2', cat: 'UX/SEO', msg: '页面 title 为空' }); + + return issues; +} + +function buildSummary(all, theme) { + const lines = []; + const counts = { P1: 0, P2: 0, P3: 0, INFO: 0 }; + const byCat = {}; + for (const r of all) { + for (const i of r.issues) { + counts[i.sev] = (counts[i.sev] || 0) + 1; + byCat[i.cat] = (byCat[i.cat] || 0) + 1; + } + } + lines.push(`# Dogfood UI/UX/UE 审计 · 自动探针汇总(${theme === 'dark' ? '深色主题' : '浅色主题'})`, ''); + lines.push(`生成时间:${new Date().toISOString()}`); + lines.push(`审计主题:${theme === 'dark' ? 'dark(colorScheme 驱动)' : 'light'}`); + lines.push(`审计路由:${all.length} 个`, ''); + if (!PERF_ASSERT_VALID) { + lines.push(`> ⚠ 系统负载过高(load ${PERF_LOAD_AT_START.toFixed(2)} ≥ 5),LCP/CLS 断言已跳过(采样不可信,防假阳性)。`, ''); + } + lines.push('## 问题计数', ''); + lines.push('| 等级 | 数量 |', '|---|:---:|'); + lines.push(`| P1 | ${counts.P1} |`, `| P2 | ${counts.P2} |`, `| P3 | ${counts.P3} |`, + counts.INFO ? `| INFO(环境噪音,不计缺陷) | ${counts.INFO} |` : '', ''); + lines.push('## 按维度分布', ''); + lines.push('| 维度 | 数量 |', '|---|:---:|'); + for (const [c, n] of Object.entries(byCat).sort((a, b) => b[1] - a[1])) lines.push(`| ${c} | ${n} |`); + lines.push('', '## 逐路由明细', ''); + for (const r of all) { + if (!r.issues.length) continue; + lines.push(`### ${r.route}`, ''); + for (const i of r.issues) { + lines.push(`- **[${i.sev}] ${i.cat}** — ${i.msg}`); + for (const d of (i.detail || [])) lines.push(` - \`${d}\``); + } + lines.push(''); + } + return lines.join('\n'); +} + +async function main() { + const args = parseArgs(process.argv); + console.log(`→ 审计主题:${args.theme}`); + // 性能断言门控:load ≥ 5 视为测量环境不可信(见 scoreRoute 注释) + PERF_LOAD_AT_START = os.loadavg()[0]; + PERF_ASSERT_VALID = PERF_LOAD_AT_START < 5; + console.log(`→ 系统 load:${PERF_LOAD_AT_START.toFixed(2)}(LCP/CLS 断言${PERF_ASSERT_VALID ? '启用' : '跳过'})`); + const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const outDir = path.join(ROOT, 'dogfood-ui-audit', args.theme === 'dark' ? `${stamp}-dark` : stamp); + fs.mkdirSync(outDir, { recursive: true }); + + // --no-proxy-server:本机有系统代理,Chromium 默认继承会把 localhost 请求送进隧道导致 chunk 403 + const browser = await chromium.launch({ headless: true, args: ['--no-proxy-server'] }); + const context = await browser.newContext({ + viewport: VIEWPORTS.desktop, + deviceScaleFactor: 1, + ignoreHTTPSErrors: true, + // 主题由 colorScheme 驱动(走 system 档解析),不要事后改 data-theme + colorScheme: args.theme === 'dark' ? 'dark' : 'light', + // 不加载已有登录态:审计的是访客视角 + }); + // 第三方统计噪音根治:mock 掉 GA/gtm 请求。沙箱无外网时 beacon 必然失败(console 错误 + + // failedRequests),但与 UI 审计无关。站点 gtag() 为内联定义(仅 push dataLayer), + // mock 空 JS 不会引发未捕获异常;collect 类 beacon 返回 204。 + await context.route( + /google-analytics\.com|googletagmanager\.com|google\.com\/g\/collect|doubleclick\.net/i, + route => { + const url = route.request().url(); + if (/\/gtag\/js/.test(url)) { + route.fulfill({ status: 200, contentType: 'application/javascript', body: '/* ga-mock */' }); + } else { + route.fulfill({ status: 204, body: '' }); + } + } + ); + // 注入 LCP / CLS 观察者 + await context.addInitScript(() => { + window.__audit = { lcp: 0, cls: 0 }; + try { + new PerformanceObserver(l => { for (const e of l.getEntries()) window.__audit.lcp = e.startTime; }) + .observe({ type: 'largest-contentful-paint', buffered: true }); + new PerformanceObserver(l => { for (const e of l.getEntries()) if (!e.hadRecentInput) window.__audit.cls += e.value; }) + .observe({ type: 'layout-shift', buffered: true }); + } catch { /* 老浏览器忽略 */ } + }); + const page = await context.newPage(); + + let routes = args.routes; + if (!routes) { + console.log('→ 发现路由中...'); + routes = await discoverRoutes(page); + const standalone = discoverStandaloneSlugs().map((s) => STANDALONE_ROUTE_PREFIX + s); + if (standalone.length) { + console.log(`→ 从构建产物发现独立产品页 ${standalone.length} 个:\n ${standalone.join('\n ')}`); + routes.push(...standalone); + } + } + if (args.limit) routes = routes.slice(0, args.limit); + console.log(`→ 共 ${routes.length} 个路由:\n ${routes.join('\n ')}\n`); + + const all = []; + for (let i = 0; i < routes.length; i++) { + const route = routes[i]; + const vpNames = args.viewports || (TIER1.has(route) ? ['desktop', 'tablet', 'mobile'] : ['desktop', 'mobile']); + process.stdout.write(`[${i + 1}/${routes.length}] ${route} (${vpNames.join(',')}) ... `); + try { + const r = await auditRoute(page, context, route, vpNames, args, outDir); + r.issues = scoreRoute(r); + all.push(r); + const sev = r.issues.reduce((a, x) => { a[x.sev] = (a[x.sev] || 0) + 1; return a; }, {}); + console.log(`OK ${JSON.stringify(sev)}`); + } catch (e) { + console.log(`FAILED ${e.message.slice(0, 100)}`); + all.push({ route, error: e.message.slice(0, 200), issues: [{ sev: 'P1', cat: '可用性', msg: `采集失败: ${e.message.slice(0, 120)}` }] }); + } + } + + fs.writeFileSync(path.join(outDir, 'probes.json'), JSON.stringify(all, null, 2)); + fs.writeFileSync(path.join(outDir, 'summary.md'), buildSummary(all)); + console.log(`\n✓ 输出目录:${outDir}`); + await browser.close(); +} + +main().catch(e => { console.error('FATAL', e); process.exit(1); }); diff --git a/scripts/audit/verify-tabbar.mjs b/scripts/audit/verify-tabbar.mjs new file mode 100644 index 0000000..6d881c9 --- /dev/null +++ b/scripts/audit/verify-tabbar.mjs @@ -0,0 +1,25 @@ +import { chromium } from 'playwright'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(__dirname, '../..'); +const OUT = '/Users/zhangxiang/Codes/Novalon/novalon-website/dogfood-ui-audit/2026-09-01T07-34-54/screenshots/verify'; +import fs from 'node:fs'; +fs.mkdirSync(OUT, { recursive: true }); + +const browser = await chromium.launch({ headless: true }); +for (const r of ['/', '/about', '/products/erp']) { + const ctx = await browser.newContext({ viewport: { width: 390, height: 844 } }); + const p = await ctx.newPage(); + await p.goto('http://localhost:3000' + r, { waitUntil: 'load' }); + await p.waitForTimeout(1500); + const slug = r === '/' ? 'home' : r.replace(/^\//, '').replace(/\//g, '__'); + await p.screenshot({ path: path.join(OUT, `mobile-${slug}-fullpage.png`), fullPage: true }); + // 滚到底再截首屏看底部 + await p.evaluate(() => window.scrollTo(0, document.body.scrollHeight)); + await p.waitForTimeout(500); + await p.screenshot({ path: path.join(OUT, `mobile-${slug}-bottom.png`) }); + console.log(`✓ mobile ${r} fullPage + bottom`); + await ctx.close(); +} +await browser.close(); \ No newline at end of file diff --git a/scripts/check-pr-checklist.sh b/scripts/check-pr-checklist.sh new file mode 100755 index 0000000..2a7e372 --- /dev/null +++ b/scripts/check-pr-checklist.sh @@ -0,0 +1,161 @@ +#!/usr/bin/env bash +# check-pr-checklist.sh — PR 提交门禁检查(对齐 AGENTS.md §5 质量门禁 / §6 文档同步清单) +# +# 检查 PR 描述文件中 checklist 子项的勾选完成情况,以及 PR 模板的结构完整性。 +# 规则: +# ① PR 模板必须包含「全链路检查」「测试分层检查」「质量门禁」三节 +# ② PR 描述文件中所有 checklist 子项(- [ ])必须已勾选(不适用项勾选并注明 N/A 理由) +# +# 用法: +# bash scripts/check-pr-checklist.sh # 检查模板结构 +# bash scripts/check-pr-checklist.sh # 检查 PR 描述文件 +# bash scripts/check-pr-checklist.sh --pr-dir <目录> # 扫描目录下所有 PR 文件 +# bash scripts/check-pr-checklist.sh --quiet # 仅违规时输出 +# bash scripts/check-pr-checklist.sh --help +# +# 退出码: 0=全部通过 1=发现违规 2=模板不存在/格式错误 +set -euo pipefail + +# 说明:AGENT_PROJECT_DIR 供测试与多工作树场景覆写模板根目录;默认取脚本所在仓库根, +# 因此从任意子目录调用都能定位到 .gitea/PULL_REQUEST_TEMPLATE.md。 +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TEMPLATE_FILE="${AGENT_PROJECT_DIR:-$REPO_ROOT}/.gitea/PULL_REQUEST_TEMPLATE.md" + +QUIET=0 +PR_FILE="" +SCAN_DIR="" + +# 采用 while+shift 而非 for:for arg in "$@" 里 shift 不会跳过已消费的值, +# `--pr-dir <目录>` 会把 <目录> 再当成一次位置参数误判为 PR 文件。 +while [ $# -gt 0 ]; do + case "$1" in + --help | -h) + echo "check-pr-checklist.sh — PR 提交门禁检查" + echo "" + echo "用法:" + echo " bash scripts/check-pr-checklist.sh # 检查模板结构" + echo " bash scripts/check-pr-checklist.sh # 检查 PR 描述文件" + echo " bash scripts/check-pr-checklist.sh --pr-dir <目录> # 扫描目录下所有 PR 文件" + echo " bash scripts/check-pr-checklist.sh --quiet # 仅违规时输出" + echo "" + echo "检查项:" + echo " - PR 模板结构完整性(三节必填 + checklist 子项 ≥ 20)" + echo " - PR 描述文件中所有 checklist 子项均已勾选" + exit 0 + ;; + --quiet | -q) QUIET=1 ;; + --pr-dir) + if [ $# -lt 2 ]; then + echo "❌ --pr-dir 需要一个目录参数" >&2 + exit 2 + fi + SCAN_DIR="$2" + shift + ;; + -*) + echo "❌ 未知选项: $1" >&2 + exit 2 + ;; + *) + if [ -n "$PR_FILE" ]; then + echo "❌ 只接受一个 PR 描述文件,多余参数: $1" >&2 + exit 2 + fi + PR_FILE="$1" + ;; + esac + shift +done + +violations=() + +# ── 读取 PR 描述正文:仅在文件确实以 YAML frontmatter 开头时才剥离 ── +# 若无 frontmatter 也无条件剥离,awk 的 fm 永远 <2 → 正文为空 → 三个标准节全部 +# 「未发现」→ 任何普通描述都被误判为不是 PR 描述文件。故按首行判别并加空正文兜底。 +read_pr_body() { + local file="$1" body="" + if [ "$(head -1 "$file" 2>/dev/null)" = "---" ]; then + body=$(awk 'BEGIN{fm=0} /^---$/{fm++; next} fm>=2{print}' "$file" 2>/dev/null || true) + fi + [ -n "$body" ] || body=$(cat "$file") + printf '%s\n' "$body" +} + +report_and_exit() { + local ok_msg="$1" + if [ "${#violations[@]}" -gt 0 ]; then + [ "$QUIET" -eq 0 ] && echo "❌ ${2}:" + printf '%s\n' "${violations[@]}" >&2 + exit 1 + fi + [ "$QUIET" -eq 0 ] && echo "✅ ${ok_msg}" + exit 0 +} + +# ── 模式 1: 扫描目录 ── +if [ -n "$SCAN_DIR" ]; then + if [ ! -d "$SCAN_DIR" ]; then + [ "$QUIET" -eq 0 ] && echo "⚠ PR 目录不存在: ${SCAN_DIR}(跳过)" >&2 + exit 0 + fi + while IFS= read -r f; do + [ -f "$f" ] || continue + body=$(read_pr_body "$f") + unchecked=$(printf '%s\n' "$body" | grep -c '^- \[ \]' || true) + if [ "$unchecked" -gt 0 ]; then + violations+=("$(basename "$f"): 存在 ${unchecked} 个未勾选子项——所有 checklist 子项须勾选后才可提交 PR") + fi + done < <(find "$SCAN_DIR" -name '*.md' -type f | sort) + report_and_exit "PR 描述文件门禁通过:所有文件子项均已勾选" "PR 描述文件门禁未通过" +fi + +# ── 模式 2: 检查单个 PR 描述文件 ── +if [ -n "$PR_FILE" ]; then + if [ ! -f "$PR_FILE" ]; then + echo "❌ PR 描述文件不存在: $PR_FILE" >&2 + exit 2 + fi + body=$(read_pr_body "$PR_FILE") + unchecked=$(printf '%s\n' "$body" | grep -c '^- \[ \]' || true) + + has_section1=$(printf '%s\n' "$body" | grep -c '全链路检查' || true) + has_section2=$(printf '%s\n' "$body" | grep -c '测试分层检查' || true) + has_section3=$(printf '%s\n' "$body" | grep -c '质量门禁' || true) + + if [ "$has_section1" -eq 0 ] && [ "$has_section2" -eq 0 ] && [ "$has_section3" -eq 0 ]; then + violations+=("$(basename "$PR_FILE"): 未发现 PR 模板标准节(全链路检查/测试分层检查/质量门禁)——可能不是 PR 描述文件,或模板结构被修改") + fi + + if [ "$unchecked" -gt 0 ]; then + violations+=("$(basename "$PR_FILE"): 存在 ${unchecked} 个未勾选子项——所有 checklist 子项须勾选后才可提交 PR") + fi + + report_and_exit "PR 描述文件门禁通过:所有子项均已勾选" "PR 描述文件门禁未通过" +fi + +# ── 模式 3: 检查 PR 模板结构完整性(默认模式)── +if [ ! -f "$TEMPLATE_FILE" ]; then + echo "❌ PR 模板文件不存在: $TEMPLATE_FILE" >&2 + exit 2 +fi + +required_sections=("全链路检查" "测试分层检查" "质量门禁") +missing_sections=() + +for section in "${required_sections[@]}"; do + if ! grep -q "^##.*${section}" "$TEMPLATE_FILE"; then + missing_sections+=("${section}") + fi +done + +if [ "${#missing_sections[@]}" -gt 0 ]; then + sections_str=$(IFS=, ; echo "${missing_sections[*]}") + violations+=("PR 模板缺失必要节: ${sections_str}(PR 模板须包含全链路检查/测试分层检查/质量门禁三节)") +fi + +checklist_count=$(grep -c '^- \[ \]' "$TEMPLATE_FILE" || true) +if [ "$checklist_count" -lt 20 ]; then + violations+=("PR 模板中 checklist 子项数量异常(仅 ${checklist_count} 项,预期 ≥ 20 项)——模板可能被意外修改") +fi + +report_and_exit "PR 模板结构门禁通过:${checklist_count} 项子项,三节完整" "PR 模板结构门禁未通过" diff --git a/src/app/(marketing)/about/about-content-v4.tsx b/src/app/(marketing)/about/about-content-v4.tsx index 9463628..d99c952 100644 --- a/src/app/(marketing)/about/about-content-v4.tsx +++ b/src/app/(marketing)/about/about-content-v4.tsx @@ -2,6 +2,9 @@ import { motion } from 'framer-motion'; import { CTAButton } from '@/components/ui/cta-button'; +import { MetricsBasisNote } from '@/components/ui/metrics-basis-note'; +import { weakestBasis, type MetricBasis } from '@/lib/constants/metrics-basis'; +import { ContentUnavailableState } from '@/components/ui/content-unavailable'; import { Trophy, Shield, Award, Zap, @@ -33,7 +36,7 @@ interface AboutData { promiseText?: string; coreValues?: { number: string; title: string; description: string }[]; milestones?: { year: string; title: string; description: string; highlight: string }[]; - keyMetrics?: { value: string; label: string; sub: string }[]; + keyMetrics?: { value: string; label: string; sub: string; basis?: MetricBasis }[]; certifications?: { name: string; description: string }[]; partners?: string[]; ctaTitle?: string; @@ -48,13 +51,13 @@ function HeroSection({ data }: { data: AboutData }) { const titleLines = (data.heroTitle || '').split('\n'); return ( -
-
+
+
{data.heroSubtitle || ''} @@ -63,21 +66,21 @@ function HeroSection({ data }: { data: AboutData }) { {titleLines.map((line, i) => (
0 ? 'mt-4 sm:mt-6' : ''}`}> {i === 1 ? ( - + {line} @@ -91,8 +94,8 @@ function HeroSection({ data }: { data: AboutData }) { {data.heroDescription || ''} @@ -100,13 +103,13 @@ function HeroSection({ data }: { data: AboutData }) { - + {data.heroPrimaryCtaLabel || '预约咨询'} - + {data.heroSecondaryCtaLabel || '了解更多'} @@ -134,10 +137,10 @@ function MetricsStrip({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.6, delay: i * 0.08, ease: EASE_OUT }} + transition={{ duration: 0.3, delay: i * 0.06, ease: EASE_OUT }} className="text-center lg:text-left" > -
+
{metric.value}
{metric.label}
@@ -145,6 +148,7 @@ function MetricsStrip({ data }: { data: AboutData }) { ))}
+ m.basis))} className="mt-8 text-center lg:text-left" />
); @@ -161,11 +165,11 @@ function WhoWeAreSection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} className="lg:col-span-5" >
- 01 + 01
Why We Started @@ -190,11 +194,11 @@ function WhoWeAreSection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, delay: 0.15, ease: EASE_OUT }} + transition={{ duration: 0.3, delay: 0.15, ease: EASE_OUT }} className="lg:col-span-7" >
- 02 + 02
How We Work @@ -209,11 +213,12 @@ function WhoWeAreSection({ data }: { data: AboutData }) { className="group relative border-b border-border-primary pb-6 md:pb-8 last:border-0 last:pb-0" >
-
+ {/* 纯装饰序号:与右侧 value.title 并列,无独立语义,标记 aria-hidden 豁免对比度要求 */} +
-

+

{value.title}

{value.description}

@@ -239,11 +244,11 @@ function MilestonesSection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} className="max-w-3xl mb-16 sm:mb-20 md:mb-24" >
- 03 + 03
Where We Are Heading @@ -263,7 +268,7 @@ function MilestonesSection({ data }: { data: AboutData }) { initial={{ opacity: 0, x: -20 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true, margin: '-60px' }} - transition={{ duration: 0.6, delay: idx * 0.08, ease: EASE_OUT }} + transition={{ duration: 0.3, delay: idx * 0.06, ease: EASE_OUT }} className="relative pl-8 sm:pl-12 md:pl-16 pb-10 sm:pb-12 md:pb-14 last:pb-0" >
@@ -271,7 +276,7 @@ function MilestonesSection({ data }: { data: AboutData }) {
-
+
{milestone.year}
@@ -302,7 +307,7 @@ function CertificationsSection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} className="max-w-3xl" >
@@ -335,7 +340,7 @@ function CertificationsSection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} >
Certifications @@ -369,7 +374,7 @@ function CertificationsSection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, delay: 0.15, ease: EASE_OUT }} + transition={{ duration: 0.3, delay: 0.15, ease: EASE_OUT }} >
Partners @@ -410,7 +415,7 @@ function CTASection({ data }: { data: AboutData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} className="max-w-3xl" >

@@ -420,10 +425,10 @@ function CTASection({ data }: { data: AboutData }) { {data.ctaDescription || ''}

- + {data.ctaPrimaryLabel || '预约咨询'} - + {data.ctaSecondaryLabel || '了解更多'}
@@ -438,11 +443,7 @@ export default function AboutContentV4({ data }: { data: Record // Empty state when no CMS data is available if (!data || Object.keys(data).length === 0) { - return ( -
-
内容暂未发布
-
- ); + return ; } return ( diff --git a/src/app/(marketing)/about/brand/brand-content.tsx b/src/app/(marketing)/about/brand/brand-content.tsx index ae8b7d9..0fc0d59 100644 --- a/src/app/(marketing)/about/brand/brand-content.tsx +++ b/src/app/(marketing)/about/brand/brand-content.tsx @@ -66,7 +66,7 @@ const brandStats = [ export default function BrandContent() { return ( -
+
{/* ============ L1: Hero 品牌情感入口 ============ */}
@@ -75,12 +75,12 @@ export default function BrandContent() { - + 品牌故事 @@ -90,8 +90,8 @@ export default function BrandContent() { 睿新致遠
- 以技术驱动业务增长 + 以技术驱动业务增长
{/* 数据条 */} {brandStats.map((stat, i) => (
- + {stat.value} @@ -121,12 +121,12 @@ export default function BrandContent() { ))} - {/* 副标题 */} + {/* 副标题 — alpha 0.7 仅 4.35:1 未达 WCAG AA 4.5:1,提到 0.8 → 5.74:1,视觉几乎无变化 */} 公司于 2026 年 1 月正式成立,核心团队专注企业数字化,从战略规划到系统落地,致力于陪伴每一家企业实现可衡量的业务改善。 我们相信,技术的力量在于让每一家企业都拥有数据驱动的决策能力。 @@ -143,13 +143,13 @@ export default function BrandContent() {
- + 品牌定位

做企业数字化转型的 - 长期同行者 + 长期同行者

我们不是传统的外包服务商,而是深度嵌入客户业务的战略伙伴。 @@ -162,8 +162,8 @@ export default function BrandContent() { {brandValues.map((item, i) => (

-
-
+
+

{item.title}

@@ -195,7 +195,7 @@ export default function BrandContent() {

让每一家企业
- 都拥有数据驱动的 + 都拥有数据驱动
决策能力

@@ -222,7 +222,7 @@ export default function BrandContent() {

成为中国企业
- 数字化转型的 + 数字化转型
首选伙伴

@@ -242,13 +242,13 @@ export default function BrandContent() {
- + 发展历程

新起点上,每一步都 - 脚踏实地 + 脚踏实地

@@ -265,10 +265,11 @@ export default function BrandContent() {
- + {item.year} - + {/* text-muted 在 bg-tertiary(#F1F5F9) 上仅 4.34:1;换 text-secondary → 9.45:1 */} + {item.highlight}
@@ -304,13 +305,13 @@ export default function BrandContent() {
- + 品牌实力

用实力赢得 - 每一份信任 + 每一份信任

@@ -323,7 +324,7 @@ export default function BrandContent() { ].map((item, i) => (
-
+

{item.title}

@@ -338,7 +339,7 @@ export default function BrandContent() { {/* ============ L4: CTA 品牌行动号召 ============ */}
-
+
@@ -347,7 +348,7 @@ export default function BrandContent() {

成为下一个
- 数据驱动型企业 + 数据驱动型企业

无论您处于数字化转型的哪个阶段,我们都愿意成为您的长期伙伴。 @@ -362,6 +363,6 @@ export default function BrandContent() {

-
+

); } \ No newline at end of file diff --git a/src/app/(marketing)/cases/cases-content-v3.tsx b/src/app/(marketing)/cases/cases-content-v3.tsx index 0dbe8fd..6775e7b 100644 --- a/src/app/(marketing)/cases/cases-content-v3.tsx +++ b/src/app/(marketing)/cases/cases-content-v3.tsx @@ -7,6 +7,7 @@ import { Building2, ArrowUpRight, Target, Lightbulb, Filter } from 'lucide-react import { type CaseStudy, } from '@/lib/constants/cases'; +import { EARLY_ACCESS } from '@/lib/constants/company'; import { cn } from '@/lib/utils'; const EASE_OUT = [0.22, 1, 0.36, 1] as const; @@ -25,14 +26,14 @@ function CaseCard({ caseItem, index }: { caseItem: CaseStudy; index: number }) { initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-60px' }} - transition={{ duration: 0.6, delay: index * 0.06, ease: EASE_OUT }} - className="group relative block overflow-hidden border border-border-primary hover:border-border-secondary bg-white hover:bg-bg-secondary transition-all duration-500 flex flex-col h-full" + transition={{ duration: 0.3, delay: index * 0.06, ease: EASE_OUT }} + className="group relative block overflow-hidden border border-border-primary hover:border-border-secondary bg-bg-elevated hover:bg-bg-secondary transition-all duration-150 flex flex-col h-full" > -
+
- + {caseItem.industry} @@ -40,15 +41,15 @@ function CaseCard({ caseItem, index }: { caseItem: CaseStudy; index: number }) {
-

+

{caseItem.title}

- - 挑战 + + 挑战

{caseItem.challenge} @@ -69,7 +70,7 @@ function CaseCard({ caseItem, index }: { caseItem: CaseStudy; index: number }) { {caseItem.metrics.slice(0, 2).map((m, i) => (

{m.value}
@@ -83,7 +84,7 @@ function CaseCard({ caseItem, index }: { caseItem: CaseStudy; index: number }) { {caseItem.client}
-
+
查看详情
@@ -119,16 +120,20 @@ export default function CasesContentV3({ return allCases.filter(c => c.industry === selectedIndustry); }, [selectedIndustry, casesProp]); + // critique P0(2026-09-19):CMS 零案例时「全部案例/按行业筛选成功故事」是空头承诺, + // 且空态无任何出口。整段改为共创承诺卡,文案承认现状并给出预约/方法论两条去路。 + const hasAnyCases = (casesProp ?? []).length > 0; + return ( -
+
{/* Hero Section */} -
+
Case Studies @@ -137,20 +142,20 @@ export default function CasesContentV3({
{heroTitle1}
- + {heroTitle2} @@ -160,7 +165,7 @@ export default function CasesContentV3({ {heroDescriptionLines.map((line, i) => ( @@ -174,10 +179,10 @@ export default function CasesContentV3({ - + 首批客户共创中 @@ -207,11 +212,11 @@ export default function CasesContentV3({ initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.6, delay: i * 0.08, ease: EASE_OUT }} + transition={{ duration: 0.3, delay: i * 0.06, ease: EASE_OUT }} className="text-center lg:text-left" >
{metric.value}
@@ -224,66 +229,117 @@ export default function CasesContentV3({
{/* Cases List Section */} -
+
-
- -
- All Cases -
-

- {filterTitle} -

-

- {filterDescription} -

-
+ {hasAnyCases ? ( + <> +
+ +
+ All Cases +
+

+ {filterTitle} +

+

+ {filterDescription} +

+
- -
- - {industries.map((industry) => ( + + {/* 原生 button + aria-pressed:互斥筛选 chip 的可访问语义。 + role="radio" 需 radiogroup 父级 + roving tabindex 才合法, + 此处保留按钮原生键盘行为,避免半成品 ARIA。 */} +
+ + {industries.map((industry) => ( + + ))} +
+
+
+ + {filteredCases.length > 0 ? ( +
+ {filteredCases.map((caseItem, i) => ( + + ))} +
+ ) : ( +
+

暂无该行业的案例

- ))} +
+ )} + + ) : ( + + {/* 背景纹理与出口结构沿用首页共创深色卡(home-content-v15 Cases 区) */} +
+
+
+
+
+ + Case Studies + +
+

+ {EARLY_ACCESS.label} +

+

{EARLY_ACCESS.desc}

+
+
+ + 预约咨询 + + + 查看方法论 + +
-
- - {filteredCases.length > 0 ? ( -
- {filteredCases.map((caseItem, i) => ( - - ))} -
- ) : ( -
-

暂无该行业的案例

-
)}
@@ -297,7 +353,7 @@ export default function CasesContentV3({ initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-80px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} className="max-w-3xl" >

diff --git a/src/app/(marketing)/contact/contact-content-v3.test.tsx b/src/app/(marketing)/contact/contact-content-v3.test.tsx index 3bebb3b..867d1a8 100644 --- a/src/app/(marketing)/contact/contact-content-v3.test.tsx +++ b/src/app/(marketing)/contact/contact-content-v3.test.tsx @@ -67,7 +67,7 @@ jest.mock('@/components/ui/labeled-input', () => ({ data-testid={dataTestId || 'labeled-input'} {...props} /> - {error && {error}} + {error && {error}}

), })); @@ -88,7 +88,7 @@ jest.mock('@/components/ui/labeled-textarea', () => ({ data-testid={dataTestId || 'labeled-textarea'} {...props} /> - {error && {error}} + {error && {error}}
), })); @@ -283,7 +283,7 @@ describe('ContactContentV3 - 联系表单集成测试', () => { it('should render CTA section', async () => { await renderContactContent(); expect(screen.getByText('准备好开启数字化转型了吗?')).toBeInTheDocument(); - expect(screen.getByText('预约免费咨询')).toBeInTheDocument(); + expect(screen.getByText('预约咨询')).toBeInTheDocument(); expect(screen.getByText('了解更多')).toBeInTheDocument(); }); diff --git a/src/app/(marketing)/contact/contact-content-v3.tsx b/src/app/(marketing)/contact/contact-content-v3.tsx index 8b2eb49..7918f1a 100644 --- a/src/app/(marketing)/contact/contact-content-v3.tsx +++ b/src/app/(marketing)/contact/contact-content-v3.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useState, Suspense } from 'react'; +import { useState, useEffect, Suspense } from 'react'; import { useSearchParams } from 'next/navigation'; import { z } from 'zod'; import { motion } from 'framer-motion'; @@ -9,6 +9,9 @@ import { LabeledInput as Input } from '@/components/ui/labeled-input'; import { LabeledTextarea as Textarea } from '@/components/ui/labeled-textarea'; import { Toast } from '@/components/ui/toast'; import { CTAButton } from '@/components/ui/cta-button'; +import { canonicalCtaLabel } from '@/lib/constants/cta-labels'; +import { StaticLink } from '@/components/ui/static-link'; +import { ContentUnavailableState } from '@/components/ui/content-unavailable'; import { Mail, MapPin, @@ -78,9 +81,8 @@ function ContactFormContent({ data }: { data: ContactData }) { const [toastMessage, setToastMessage] = useState( isSuccessFromRedirect ? '表单提交成功!我们会尽快与您联系。' : '' ); - const [toastType, setToastType] = useState<'success' | 'error'>( - isSuccessFromRedirect ? 'success' : 'success' - ); + // 初值仅在 ?success=true 重定向时随 showToast/isSubmitted 一同生效,故恒为 success。 + const [toastType, setToastType] = useState<'success' | 'error'>('success'); const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitted, setIsSubmitted] = useState(isSuccessFromRedirect); const [formData, setFormData] = useState({ @@ -92,6 +94,14 @@ function ContactFormContent({ data }: { data: ContactData }) { }); const [errors, setErrors] = useState({}); + // 刷新不应重放成功态:读取 ?success=true 后立即从 URL 中移除 + useEffect(() => { + if (!isSuccessFromRedirect) return; + const url = new URL(window.location.href); + url.searchParams.delete('success'); + window.history.replaceState(null, '', url.pathname + url.search + url.hash); + }, [isSuccessFromRedirect]); + const emailAddress = data.email ?? ''; const addressText = data.address ?? ''; @@ -201,52 +211,55 @@ function ContactFormContent({ data }: { data: ContactData }) { } } - const heroTitleLines = (data.heroTitle || '').split('\n'); + const heroTitleLines = (data.heroTitle || '随时欢迎\n与您聊聊需求').split('\n'); const commitmentItems = data.commitmentItems ?? []; return ( -
+
{showToast && ( setShowToast(false)} /> )} - {/* Hero Section */} -
-
+ {/* Hero Section —— critique P2(2026-09-19):80vh 巨幅把转化表单推出首屏, + 转化页按 DESIGN.md 紧凑档处理:无 min-h、py 收窄,表单回到首屏视野。 */} +
+
- - {data.heroSubtitle || ''} - + {data.heroSubtitle && ( + + {data.heroSubtitle} + + )} {heroTitleLines.map((line, i) => (
0 ? 'mt-4 sm:mt-6' : ''}`}> {i === 1 ? ( - + {line} @@ -257,14 +270,16 @@ function ContactFormContent({ data }: { data: ContactData }) { ))} - - {data.heroDescription || ''} - + {data.heroDescription && ( + + {data.heroDescription} + + )}
@@ -278,21 +293,23 @@ function ContactFormContent({ data }: { data: ContactData }) { initial={{ opacity: 0, y: 30 }} whileInView={{ opacity: 1, y: 0 }} viewport={{ once: true, margin: '-60px' }} - transition={{ duration: 0.8, ease: EASE_OUT }} + transition={{ duration: 0.3, ease: EASE_OUT }} className="lg:col-span-2 space-y-8" >
-

{data.contactTitle || ''}

+ {data.contactTitle && ( +

{data.contactTitle}

+ )}
-