Compare commits

...
Author SHA1 Message Date
Paul Bakaus f9fa46412c Bump AI SDK packages to v7 2026-07-03 19:16:38 -07:00
github-actions[bot] a20bbfc752 Sync generated provider output 2026-07-04 02:15:49 +00:00
7501e67b55 Fix live toast stale callback race (#271)
Co-authored-by: Jean-Claude <273834277+jjoanna2-debug@users.noreply.github.com>
2026-07-03 19:15:20 -07:00
dependabot[bot]andGitHub 9798bb7235 chore(deps): bump actions/cache from 5 to 6 (#325)
Bump actions/cache from v5 to v6 in CI cache steps.
2026-07-03 18:01:21 -07:00
dependabot[bot]andGitHub 67e73f47a6 chore(deps): bump the bun-minor-and-patch group with 7 updates (#320)
Bump the bun-minor-and-patch dependency group with 7 updates.
2026-07-03 18:01:06 -07:00
Paul BakausandClaude Opus 4.8 1fe9c41759 Replace Alumni Sans Pinstripe with Alumni Sans across the type system
The Pinstripe display face was single-weight, so every `font-weight` on it
was inert — the documented h1/h2 weight split never actually rendered.
Switch --ks-font-display (and --ks-font-wordmark) to plain Alumni Sans, which
honors weight, and set the display scale intentionally:

- Display / h1  -> weight 100 (thin hairline hero)
- Headline / h2 -> weight 300 via --ks-type-headline-weight (light anchor)
- Wordmark 400, body 400, title 500 unchanged

Centralize h2 weight: the eight section-title sites that hardcoded 600 now
read var(--ks-type-headline-weight), so h2 weight is a single lever.

Google Fonts now loads Alumni Sans wght@100;300;...;700 and no longer pulls
the Pinstripe family. DESIGN.md, design.json, and the token/CSS comments are
updated to match (family, weights, Two-Face and Weight-Inversion rules).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 17:32:47 -07:00
44c27a72af Fix Codex plugin hook load failure; bump skill to 3.9.1 (#333)
Codex loads bundled plugin lifecycle hooks from `hooks/hooks.json` using a
strict schema that accepts only the top-level `hooks` field. The
plugin-packaged manifest carried a top-level `description`, so Codex rejected
the whole manifest with `unknown field description, expected hooks` and the
post-edit design detector never registered (issue #330).

Drop `description` from `buildClaudePluginHooksManifest()` and regenerate
`plugin/hooks/hooks.json`. The Claude Code plugin path is unaffected (it only
reads the `hooks` object). Add a regression assertion for the plugin artifact
and bump the skill version to 3.9.1.


Claude-Session: https://claude.ai/code/session_013GTTHY6uHwESUyAgjUEm7x

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-01 11:03:55 -07:00
Paul BakausandClaude Opus 4.8 a82f02d1a1 Fix skill release tweet CTA to npx impeccable install
The generated skill-release tweet pointed at the deprecated
`npx skills add pbakaus/impeccable`; the canonical install/update path
is `npx impeccable install`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 01:58:34 -07:00
Paul BakausandClaude Opus 4.8 e83e437cdd Release prep: skill v3.9.0, CLI v3.2.0
Bump skill 3.8.0 -> 3.9.0 (plugin.json, marketplace.json, plugin/ subtree,
regenerated provider harness output) and CLI 3.1.0 -> 3.2.0 (package.json).

Changelog (site/pages/changelog.astro):
- Skill v3.9.0: codex grid-background ban, /impeccable bolder design-system
  lock, critique sub-agent independence on non-Claude/Codex harnesses,
  bundled helpers under strict-permission harnesses, Codex hook manifest fix.
- CLI v3.2.0: codex-grid-background detector rule, external skills-symlink
  preservation on first install.

Also: gitignore nested hook.cache.json/hook.pending.json copies (anchored
patterns missed the generated harness dirs), and repoint CLAUDE.md/AGENTS.md
changelog docs at changelog.astro with concise, user-facing-only tone guidance.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 01:50:04 -07:00
github-actions[bot] f604d31d54 Sync generated provider output 2026-07-01 08:30:06 +00:00
f5c1bd65ae Add codex-grid-background detector rule (#328)
* Add codex-grid-background detector rule

Detects the Codex two-axis grid-line background tell: a single background
value carrying two or more hairline `linear-gradient(... 1px, transparent
1px)` layers (one per axis), usually paired with a repeating
`background-size` cell. Gated behind --gpt like the sibling codex tells,
off by default.

Counts hairline stops within a single background declaration (not across
the page) so unrelated single-axis ruled lines don't add up to a false
flag, and matches the stop directly rather than parsing whole gradient
layers, since colors like oklch(...) carry nested parens.

Extends the gpt-tells fixture with one flag case and two pass cases
(single-axis rule, two-color blend), regenerates the browser detector
bundle, and bumps the rule count 44 -> 45.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Require tiling background-size for codex-grid-background

Address review: two hairline gradients alone draw a fixed crosshair, not a
grid. Scope detection to a single style block (CSS rule body or inline
style attr) and require both >=2 hairline stops AND a tiling
`background-size` px cell in the same block, matching the skill rule's
"plus background-size" wording. Add a crosshair-without-tiling pass case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Scope codex-grid-background hairline count to background values

Address review: count hairline stops only inside background/background-image
declaration values, not the whole style block, so a hairline in an unrelated
property (mask-image, border-image) can't stand in for the grid's second
axis. Add a bg+mask-image hairline pass case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 01:29:40 -07:00
github-actions[bot] 5844c40177 Sync generated provider output 2026-07-01 07:13:03 +00:00
Paul Bakaus 9dc97ce648 small update to our own DESIGN.md 2026-07-01 00:12:32 -07:00
Paul Bakaus b3108c1697 Clarify bolder design-system boundaries 2026-07-01 00:12:32 -07:00
Paul Bakaus 4ac0348032 Add Codex grid background slop rule 2026-07-01 00:12:32 -07:00
github-actions[bot] 7f0262f809 Sync generated provider output 2026-07-01 06:56:53 +00:00
Paul Bakaus 1a3f5d78bd Fix Codex hook manifest schema 2026-06-30 23:56:06 -07:00
github-actions[bot] c979ac37c3 Sync generated provider output 2026-06-29 07:31:56 +00:00
Paul Bakaus bcd16381cf harden critique so that it runs in sub-agents more often in harnesses other than Claude and Codex 2026-06-29 00:31:25 -07:00
Paul Bakaus 19e0174da2 update HARNESSES.md with latest updates/imfo 2026-06-29 00:31:25 -07:00
KamranandGitHub 88227f7935 Add README .gitignore snippet for ephemeral .impeccable output (#314)
* Add .gitignore seeding to init for ephemeral .impeccable output

Init now runs ensure-gitignore.mjs to write a marked block to the shared, committed .gitignore so screenshots, live session/preview/cache dirs, hook caches, and per-dev config.local.json never pollute git status across the team. Shared artifacts (config.json, live/config.json, design.json, critique/*.md) stay tracked. Unlike the existing hook/live runtime helpers, which write machine-local .git/info/exclude lazily, this targets .gitignore at init time so every clone is covered up front.

* Fix: unanchored patterns + git-aware tracking for init gitignore

Cursor Bugbot on PR #314 flagged two issues. (1) Patterns were root-anchored (/.impeccable/...) so they missed a nested monorepo .impeccable (apps/web/.impeccable/...); dropped the leading slash to match HOOK_LOCAL_IGNORE_PATTERNS / LIVE_IGNORE_PATTERNS. (2) detectTrackedArtifacts used fs.existsSync, reporting untracked/ignored files as committed; replaced with git ls-files based analyzeTracked that returns gitAvailable, tracked (confirmed shared artifacts), and needsUntrack (committed ephemeral files -> git rm --cached candidates). init Step 7 wording updated to match.

* Pivot to docs-only .gitignore snippet per maintainer feedback

Reverts the automated init Step 7 and the ensure-gitignore.mjs helper/script tests. Adds a copy-paste .gitignore block to the README instead, covering ephemeral .impeccable/ output (screenshots, live session/preview/cache dirs, hook caches, per-dev config.local.json) while keeping shared artifacts (config.json, live/config.json, design.json, critique/*.md) tracked. Patterns are unanchored so they also cover a nested monorepo .impeccable under apps/web/.
2026-06-28 21:04:09 -07:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>Paul Bakaus
3590bf9e37 chore(deps-dev): bump astro from 6.4.7 to 7.0.0 (#292)
Bumps [astro](https://github.com/withastro/astro/tree/HEAD/packages/astro) from 6.4.7 to 7.0.0.
- [Release notes](https://github.com/withastro/astro/releases)
- [Changelog](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md)
- [Commits](https://github.com/withastro/astro/commits/astro@7.0.0/packages/astro)

---
updated-dependencies:
- dependency-name: astro
  dependency-version: 7.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Paul Bakaus <paul.bakaus@gmail.com>
2026-06-25 17:51:01 -07:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
616820dcff chore(deps): bump actions/checkout from 6 to 7 in the github-actions group
Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 6 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-25 17:35:15 -07:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
a4ff58ef51 chore(deps): bump the bun-minor-and-patch group with 9 updates
Bumps the bun-minor-and-patch group with 9 updates:

| Package | From | To |
| --- | --- | --- |
| [@ai-sdk/anthropic](https://github.com/vercel/ai/tree/HEAD/packages/anthropic) | `3.0.84` | `3.0.85` |
| [@ai-sdk/google](https://github.com/vercel/ai/tree/HEAD/packages/google) | `3.0.82` | `3.0.83` |
| [@ai-sdk/openai](https://github.com/vercel/ai/tree/HEAD/packages/openai) | `3.0.71` | `3.0.74` |
| [@anthropic-ai/claude-agent-sdk](https://github.com/anthropics/claude-agent-sdk-typescript) | `0.3.178` | `0.3.185` |
| [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript) | `0.104.2` | `0.105.0` |
| [@google/genai](https://github.com/googleapis/js-genai) | `2.8.0` | `2.9.0` |
| [ai](https://github.com/vercel/ai/tree/HEAD/packages/ai) | `6.0.206` | `6.0.208` |
| [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler) | `4.100.0` | `4.103.0` |
| [puppeteer](https://github.com/puppeteer/puppeteer) | `25.1.0` | `25.2.0` |


Updates `@ai-sdk/anthropic` from 3.0.84 to 3.0.85
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/@ai-sdk/anthropic@3.0.85/packages/anthropic/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/@ai-sdk/anthropic@3.0.85/packages/anthropic)

Updates `@ai-sdk/google` from 3.0.82 to 3.0.83
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/@ai-sdk/google@3.0.83/packages/google/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/@ai-sdk/google@3.0.83/packages/google)

Updates `@ai-sdk/openai` from 3.0.71 to 3.0.74
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/@ai-sdk/openai@3.0.74/packages/openai/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/@ai-sdk/openai@3.0.74/packages/openai)

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.178 to 0.3.185
- [Release notes](https://github.com/anthropics/claude-agent-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/claude-agent-sdk-typescript/compare/v0.3.178...v0.3.185)

Updates `@anthropic-ai/sdk` from 0.104.2 to 0.105.0
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.104.2...sdk-v0.105.0)

Updates `@google/genai` from 2.8.0 to 2.9.0
- [Release notes](https://github.com/googleapis/js-genai/releases)
- [Changelog](https://github.com/googleapis/js-genai/blob/main/CHANGELOG.md)
- [Commits](https://github.com/googleapis/js-genai/compare/v2.8.0...v2.9.0)

Updates `ai` from 6.0.206 to 6.0.208
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/ai@6.0.208/packages/ai/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/ai@6.0.208/packages/ai)

Updates `wrangler` from 4.100.0 to 4.103.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.103.0/packages/wrangler)

Updates `puppeteer` from 25.1.0 to 25.2.0
- [Release notes](https://github.com/puppeteer/puppeteer/releases)
- [Changelog](https://github.com/puppeteer/puppeteer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/puppeteer/puppeteer/compare/puppeteer-v25.1.0...puppeteer-v25.2.0)

---
updated-dependencies:
- dependency-name: "@ai-sdk/anthropic"
  dependency-version: 3.0.85
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@ai-sdk/google"
  dependency-version: 3.0.83
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@ai-sdk/openai"
  dependency-version: 3.0.74
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@anthropic-ai/claude-agent-sdk"
  dependency-version: 0.3.185
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.105.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
- dependency-name: "@google/genai"
  dependency-version: 2.9.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
- dependency-name: ai
  dependency-version: 6.0.208
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: wrangler
  dependency-version: 4.103.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
- dependency-name: puppeteer
  dependency-version: 25.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-25 17:35:04 -07:00
da2cda06ed Point DESIGN.md spec links at open-source GitHub spec (#299)
* Point DESIGN.md spec links at the open-source GitHub spec.

The Stitch docs site is client-rendered and unreliable for agent fetch; the
google-labs-code/design.md repo tracks the latest machine-readable spec.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Sync plugin and harness copies after DESIGN.md spec link update.

build:release copies skill/reference into plugin/ and all harness dirs, so
refresh those generated outputs here instead of leaving plugin/ stale.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use raw GitHub URL for DESIGN.md spec in agent-facing refs.

The blob URL serves HTML; raw.githubusercontent.com returns plain markdown
that agents can fetch directly.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-25 17:21:48 -07:00
Abdul WahabandGitHub 467efe4632 Fix: preserve external ~/.claude/skills symlink on first install (#295) (#308)
* Fix: preserve external skills symlink on first install (#295)

* Fix review comments: target-based in-project link detection (#295, #308)

- isInProjectProviderLink now inspects the symlink TARGET lexically instead of comparing shared realpaths, so two providers pointing at the same external dir are no longer misflagged as in-project (cursor High / greptile P1).
- A dangling in-project cross-provider link is now correctly replaced with a real per-provider dir (cursor Medium).
- Adds regression tests for both scenarios.
2026-06-25 17:21:02 -07:00
github-actions[bot] 2520317f94 Sync generated provider output 2026-06-26 00:17:03 +00:00
Abdul WahabandGitHub b7d2ad5589 Fix: allow skill's bundled node helpers under strict-permission harnesses (#301) (#310)
The skill declared only `Bash(npx impeccable *)` in allowed-tools, but Setup and the no-arg menu shell out to `node {{scripts_path}}/*.mjs`. Under a default-deny Claude Code allowlist those calls are blocked, so Setup fails on context.mjs.

Add a provider-aware `Bash(node {{scripts_path}}/*)` entry and resolve {{scripts_path}} in the frontmatter (the build previously substituted it only in the body). Provider-aware rather than the hardcoded `.claude/...` path the issue suggested, since five providers honor allowed-tools with different script dirs.
2026-06-25 17:16:32 -07:00
Paul BakausandClaude Opus 4.8 d2ab4ddee6 Make Copilot built-in note a callout block under the Install header
Promote the inline GitHub Copilot aside to a proper note block placed
directly under "Step 1. Install", with the Copilot glyph. Full hairline
frame + faint gold ground (no side-stripe, which the detector flags as the
side-tab tell); gold icon carries the accent. Add a reusable .docs-note
style to docs-kinpaku.css so it tracks the docs theme tokens.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 16:01:16 -07:00
Paul BakausandClaude Opus 4.8 a031d5de92 Add GitHub Copilot app built-in note to setup guide
The Get started section tells Copilot-app users the skill is built in
(enable under Settings → Experimental) so they skip a needless install;
the setup guide's Step 1 only listed Copilot as an npx install target.
Add the matching note right after the install command for consistency.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 12:20:59 -07:00
Paul BakausandClaude Opus 4.8 867fab2188 Redesign Get started install block as tabbed method selector
Replace the static Install/First run/Update boxes with a tabbed "Install
via" selector (impeccable / marketplace / skills.sh). Switching a tab swaps
the install and update commands together, with a per-method note.

- impeccable tab marked recommended with a gold star; carries a Node 24+
  requirement and a collapsed "Why one command, many builds" diagram that
  animates impeccable branching per harness. The diagram foregrounds the
  model-specific slop rules compiled into the Gemini and Codex builds
  (verified against skill/SKILL.src.md provider tags).
- GitHub Copilot is built into the app, so it's a quiet de-boxed callout
  under the tabs rather than a tab, catching Copilot users before they
  install something they don't need.
- Add claude-mark.png (transparent-background Claude starburst) for the
  marketplace tab.
- Tabs baseline-align with the "INSTALL VIA" label; diagram scales and the
  tablist wraps cleanly on mobile.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 01:23:23 +09:00
Paul BakausandClaude Opus 4.8 609bbfbd5b Update GitHub star counter to 40k
Repo passed 40k stars (40,008).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 05:42:51 +09:00
Paul BakausandClaude Opus 4.8 da18929df0 Release skill v3.8.0 and CLI v3.1.0
Bump skill to 3.8.0 (GitHub Copilot design hooks, monorepo-aware
context) and CLI to 3.1.0 (inline detector ignore comments, fail-loudly
on unknown subcommands). Add changelog entries and sync generated
provider output.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 05:41:24 +09:00
github-actions[bot] a110ec5ed7 Sync generated provider output 2026-06-21 13:01:51 +00:00
8eedb150c5 Fix React hydration mismatch from live pick-cursor class on SSR roots (#286)
* Fix React hydration mismatch from live pick-cursor class on SSR roots

Entering pick mode toggled a `impeccable-live-pick-cursor` class on
`document.documentElement` (and the insert-axis cursor wrote an inline
`style.cursor` on it). `<html>`/`<body>` are server-rendered by frameworks
like Next.js App Router, so a client-only attribute the server HTML never
emitted makes React 19 log "a tree hydrated but some attributes of the server
rendered HTML didn't match" on the next Fast-Refresh re-render. It surfaced as
a console.error that flaked the nextjs-app-router live-e2e fixture's
expectConsoleClean probe.

This is the same root-cause class as the scroll-anchor lock fixed in #276
(client mutation of a hydrated SSR root), but a separate offender that fix did
not cover. Apply the same shape: drive the pick / insert cursor entirely
through the textContent of one injected `<style>` keyed by PICK_CURSOR_STYLE_ID,
never by a class or inline style on `<html>`. Same computed effect (global
`cursor` rule, reverted inside the overlay chrome), recreated on activation and
removed on teardown.

Regression guard updated to pin the new shape: no
`document.documentElement.classList.*` mutation anywhere in the overlay, the
cursor applied through the injected style, and the style removed by id on exit.

Verified end-to-end: the nextjs-app-router live-e2e fixture now passes the full
click -> Go -> cycle -> accept cycle with a clean console.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Remove now-dead pageInteractionCursorActive flag

The flag's only reader was the old inline-style cleanup branch in
syncPageInteractionCursor, which the stylesheet refactor removed. It is now
write-only, so drop the declaration and both writes (Greptile review). No
behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 22:01:17 +09:00
github-actions[bot] 55d11fb2ad Sync generated provider output 2026-06-21 12:42:04 +00:00
776c019041 Add inline, in-file ignore comments for the detector (#283) (#285)
* Add inline, in-file ignore comments for the detector (issue #283)

Complement config ignores with eslint-disable-style waivers that live where
they apply and travel with the file when it leaves the repo. The motivating
case is a generated/exported standalone document that legitimately uses a
first-party brand typeface (on the overused-font list) and is later scanned
without .impeccable/config.json present.

Marker is comment-syntax-agnostic (works in //, /* */, <!-- -->, #, {/* */}):

  impeccable-disable <rule>[, <rule>...] [-- reason | : reason]   whole file
  impeccable-disable-line <rule>...                               same line
  impeccable-disable-next-line <rule>...                          next line

Bare directive or * means every rule; reason is optional and discarded at
scan time. Behavior is suppression, for parity with config ignores.

Implementation:
- New pure module cli/engine/shared/inline-ignores.mjs (parser + filter, no
  Node deps). Static-HTML findings have no line number, so only whole-file
  directives apply there -- exactly the standalone-document case; the
  regex/text engine additionally honors the line-scoped forms.
- Wired into detectText and detectHtml, gated by options.inlineIgnores.
- detect CLI applies inline ignores by default; --no-inline-ignores skips
  just them, --no-config skips config and inline ignores together.

Docs: config.md (new section), detector.md, README. skill/reference/hooks.md
reversed its prior "inline comments are not supported" guidance and now points
the agent to inline waivers for the travels-with-the-file case. Changelog 3.x.

Tests: tests/inline-ignores.test.mjs (parser units, detectText/detectHtml
integration, CLI end-to-end), registered in the detector suite.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Reconcile design hook wording with inline ignores

Two hook-side fixes prompted by review of the new inline-ignore feature:

1. Clean-ack steer line. The old line ("Keep typography hierarchy, spacing
   rhythm, and color contrast intentional on the next change.") read as an
   odd non-sequitur after "No anti-patterns." Reworded the whole clean ack to
   say what it means: a clean scan only clears the deterministic rule set, not
   overall design quality, so keep following the design system and skill
   guidance. Now: "Design hook scanned X. No deterministic design-quality
   issues found. That does not mean the design is good: keep following the
   project design system and the impeccable skill guidance."

2. Directive footer. It still told the agent "Do not add source comments such
   as `impeccable: ignore`; those pollute the code and do not suppress hook
   findings." That is now misleading: the hook runs the same detector engine
   as the CLI, which honors inline `impeccable-disable` waivers, so they DO
   suppress hook findings (consistent with config ignores, which filterFindings
   already honors). Reworded to: don't silence a real finding to skip fixing
   it; suppress only after the user confirms intent; prefer a config ignore,
   and reach for an inline `impeccable-disable <rule>` comment only when the
   waiver must travel with a file that leaves the repo.

Added a hook test asserting an inline `impeccable-disable-line` comment makes
the hook scan the file clean (locks in the cross-cutting behavior), and updated
the clean-ack / footer assertions to the new wording.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address review on inline-ignores parser

- Case-insensitive fast-path bail-out (Cursor): the cheap substring guard was
  lowercase-only while DIRECTIVE_RE has the `i` flag, so a mixed-case marker
  like `Impeccable-Disable` skipped parsing entirely and never suppressed.
  Switched the guard to `/impeccable-disable/i.test(...)`. Added a regression
  test.
- Removed the unreachable `-->` branch from TRAILING_CLOSER_RE (Greptile):
  `--+>` already matches `-->` and any longer dash run.
- Replaced the always-truthy lazy-match + `if (sep)` reason strip with an
  explicit first-separator slice (Greptile): clearer and drops the dead branch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Align inline-ignore line numbering with the detector (CRLF/CR endings)

parseInlineIgnores split lines with /\r\n|\r|\n/, but detectText numbers lines
with split('\n'). On classic `\r`-only endings the two diverged, so a
disable-line / disable-next-line directive could key a different line than the
finding it should waive (Cursor review). Split on '\n' only, matching the
detector exactly; the directive regex already excludes '\r', so a trailing '\r'
on CRLF files is never captured into the rule list. Added a CRLF regression test
through the real detectText.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 21:41:36 +09:00
github-actions[bot] 68a15b6be4 Sync generated provider output 2026-06-20 15:00:27 +00:00
42be79eab5 Fix monorepo target-selection edge cases from #213 review (#282)
Two Cursor Bugbot Medium findings on the merged monorepo context PR:

- Excluded packages still listed: discoverTargetCandidates added every glob
  match but never applied negated workspace patterns, so an excluded package
  (e.g. "!packages/internal") showed up as a selectable target even though
  resolveWorkspaceProjectRoot sends it back to the repo root. Now filtered
  with the same isExcludedByWorkspacePattern check the resolver uses.
- Empty app list blocks root: resolveTargetSelection returned
  TARGET_SELECTION_REQUIRED whenever projectRoot === repoRoot, even with zero
  discoverable child apps (e.g. `workspaces: ["."]`), leaving an unanswerable
  prompt. It now returns null (use the repo root as the project) when there
  are no candidates.

Also documents two Greptile P2 clarity notes (the four contextSourceStatus
labels incl. the dual meaning of 'fallback', and the deliberate
isMonorepoRoot-before-hasGitBoundary ordering in findMonorepoRoot).

Adds regression tests for both behaviors.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 07:59:56 -07:00
github-actions[bot] 1e4e74793a Sync generated provider output 2026-06-20 10:50:06 +00:00
Abdul WahabandGitHub 0306b41949 Add monorepo context support (#213)
Context files (PRODUCT.md / DESIGN.md) resolve child-first then fall back to the repo root, and /impeccable live lets the user pick a child app in a monorepo. Single-app behavior is unchanged. Closes #202. Co-Authored-By: abdulwahabone
2026-06-20 19:49:37 +09:00
Abdul WahabandGitHub f1e9b3df3a Fix: fail loudly on unknown CLI subcommands (#270)
Unknown/mistyped CLI subcommands now print 'Unknown command' and exit non-zero instead of silently routing to the detector. Closes #266. Version bump and changelog entry deferred (batching). Co-Authored-By: abdulwahabone
2026-06-20 19:34:38 +09:00
2f9dc05978 Give GitHub Copilot equal prominence in harness listings (#280)
Audit of every user-facing surface that enumerates supported harnesses
found GitHub Copilot missing or buried in several. Bring it to parity with
Claude Code, Codex, Cursor, and Gemini.

Missing -> added:
- site/content/reference/hooks.md: the public /docs/hooks page (tagline,
  the post-edit list, and the manifest table) now covers GitHub Copilot,
  including the `.github/hooks/impeccable.json` surface and the
  default-branch/trust note. (Only skill/reference/hooks.md was updated in
  the feature PR; this is the website doc.)
- README.md Design hook section + the manifest surface list.
- site/content/tutorials/getting-started.md hook note.
- site/pages/faq.astro tool-specific setup list and the docs-links list.
- PRODUCT.md audience line and README.npm.md suite description.

Prominence + naming:
- README "Supported Tools" and the homepage hero logo row: move GitHub
  Copilot up to third (after Claude Code) instead of trailing.
- site/pages/designing: list GitHub Copilot earlier, full name.
- README "Supported Tools": the harness link now points at GitHub Copilot
  (github.com/features/copilot) instead of the unrelated VS Code entry.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 03:27:06 -07:00
github-actions[bot] 221064858e Sync generated provider output 2026-06-20 09:24:47 +00:00
41ff946121 Add GitHub Copilot hook support (CLI + cloud agent) (#279)
* Add GitHub Copilot hook support (CLI + cloud agent)

Wire the Impeccable design detector into GitHub Copilot's hook system so
direct file edits get the same post-edit design feedback the Claude Code,
Codex, and Cursor harnesses already receive.

GitHub Copilot's contract differs from the existing harnesses (verified
against Copilot CLI 1.0.63):
- Repo-level manifest at `.github/hooks/impeccable.json` (read by both the
  CLI, once committed to the default branch, and the cloud/app agent).
- Flat `postToolUse` entries with `bash`/`timeoutSec` and a full-match
  `matcher` regex; the file-editing tools are `edit` and `create`.
- The stdin event uses camelCase `toolName`/`toolArgs`, where `toolArgs` is
  a JSON *string* carrying the touched file under `path`.
- Context is injected via a top-level `additionalContext` string.

Changes:
- hooks.js: buildGitHubHooksManifest() + route `github` in hooksJsonFor().
- providers.js: emitHooks/hooksManifestRel for the github provider.
- hook-lib.mjs: detect the github harness, normalize the camelCase event
  (parse the JSON-string toolArgs -> tool_input.file_path), and emit the
  `additionalContext` payload shape.
- hook-admin.mjs / skills.mjs: install + idempotent-repair the
  `.github/hooks/impeccable.json` manifest (bash-aware marker stripping).
- hooks.md: document GitHub Copilot as a supported harness.
- Tests for the builder, routing, event normalization, and end-to-end run.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Cover Copilot apply_patch edits in the hook (live-verified)

The first cut matched only `edit|create`, the tool names `copilot -p` uses.
A live trace against Copilot CLI 1.0.63 in an interactive session showed it
edits files via `apply_patch`, whose toolArgs is a raw OpenAI-format patch
string (`*** Begin Patch` / `*** Add File:`), not JSON. With the narrow
matcher the hook command never ran.

- hooks.js / hook-admin.mjs: matcher -> `edit|create|apply_patch`.
- hook-lib.mjs: normalizeGitHubEvent now routes apply_patch's raw patch
  string into tool_input.command (reusing the existing parseApplyPatchPaths /
  resolveTargetFiles plumbing) and only JSON-parses toolArgs for the
  edit/create/view tools. tool_name is normalized to apply_patch so the patch
  path is extracted even if a future build relabels the tool.
- Tests: apply_patch matcher assertions, event normalization, and an
  end-to-end runHook covering the interactive/cloud path.

Verified live: a trusted interactive `apply_patch` edit fires the hook and
returns the expected `additionalContext` design reminder.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Address review feedback + add changelog entry

- hook-lib.mjs (Bugbot, low): looksLikeApplyPatch no longer misroutes an
  edit/create event whose edited *content* contains apply_patch markers. A
  real apply_patch payload is a raw string that does not parse as JSON; an
  edit payload is a JSON object, so only non-JSON-object strings are treated
  as apply_patch. Edit events keep extracting `path`. Adds a regression test.
- skills.mjs (Bugbot, medium): document why `.github` is intentionally
  excluded from hookScriptPathForProvider. Its hook manifest is committed and
  shared (read by the Copilot cloud agent and teammates), so the command must
  stay portable via `$(git rev-parse ...)`; rewriting it to a machine-local
  absolute path would break those. GitHub skills are project-scoped, so the
  project-relative path resolves.
- changelog: add an Upcoming (v3.x placeholder) entry for the Copilot hook.
  Version is not bumped yet (batching with other changes).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 02:24:18 -07:00
793feda5a0 Guard plugin/skill version drift in the build (issue #274) (#278)
* Guard plugin/skill version drift in the build (issue #274)

The Claude Code marketplace installs from the committed ./plugin subtree,
so a version disagreement between the hand-edited manifests and the
generated subtree ships stale content under a wrong version. This is the
class of bug reported in #274: a version bump that doesn't regenerate
./plugin (e.g. PR #252, where root plugin.json was 3.7.0 while
plugin/.claude-plugin/plugin.json was still 3.6.0) merges a drift window
onto main, and marketplace/Cowork installs pull the stale subtree.

Add a build-time validator that treats root .claude-plugin/plugin.json
as the source of truth and fails the build if any of these disagree:
  - .claude-plugin/marketplace.json plugins[0].version (hand-edited; the
    post-merge sync workflow never bumps versions, so it can't repair a
    mismatch here)
  - plugin/.claude-plugin/plugin.json version (generated subtree)
  - plugin/skills/impeccable/SKILL.md frontmatter version (bundled skill)

It only fires on an inconsistent bump; PRs that don't touch versions keep
every file in agreement and stay silent. The pure comparison lives in
scripts/lib/validate-plugin-versions.js with direct unit coverage; build.js
owns the logging and the non-zero exit. Documents the regenerate-on-bump
step in CLAUDE.md's Versioning section.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Harden version-drift collector against malformed/incomplete manifests

Address Greptile review on #278:

- Wrap every file read/parse in a sentinel helper (extractFromFile) so a
  half-edited manifest — the exact state during a version bump — yields a
  clean "could not parse (...)" diagnostic naming the file instead of a raw
  JSON.parse stack trace out of build().
- Report a present-but-malformed root plugin.json, or one missing its
  `version` field, as an explicit error. Previously `undefined` version
  short-circuited the build wrapper's `source == null` guard and passed
  silently. collectPluginVersions now returns an `errors` array; build.js
  fails on errors + mismatches combined, and only the genuinely-absent root
  manifest is a no-op skip.

Adds 4 unit tests: malformed checked manifest, malformed root, missing
version field, and the absent-root no-errors case.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Make SKILL.md frontmatter version read CRLF-tolerant

Address Cursor Bugbot review on #278: readSkillFrontmatterVersion only
matched `\n` delimiters, while the shared parseFrontmatter in
scripts/lib/utils.js accepts `\r?\n`. A bundled SKILL.md saved with CRLF
line endings would parse to a null version and trip a false mismatch
against root plugin.json even when the version line is correct.

Match the shared parser's `\r?\n` tolerance and drop the `$` anchor on
the version line (it would not match before a `\r`). Adds CRLF coverage
for both readSkillFrontmatterVersion and collectPluginVersions.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Re-trigger CI (no file change)

CI did not fire for 5cda9f6b; force a fresh run on the current tree.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 15:51:16 +09:00
github-actions[bot] c0d50e36da Sync generated provider output 2026-06-20 04:51:03 +00:00
67e8757401 Fix React hydration mismatch from live scroll-lock on SSR roots (#276)
* Fix React hydration mismatch from live scroll-lock on SSR roots

The live overlay's startScrollLock disabled the browser's scroll
anchoring by setting `overflow-anchor: none` as an inline style on
`<html>` and `<body>`. On frameworks that server-render those roots
(notably Next.js App Router), that client-only inline style desyncs from
the server HTML, so React 19 logs "a tree hydrated but some attributes
of the server rendered HTML didn't match" on the next Fast-Refresh
re-render. It surfaced as a flaky failure of the nextjs-app-router
live-e2e fixture's expectConsoleClean probe.

Inject the suppression as a `<style>` rule keyed by a stable id instead
of mutating inline styles on hydrated host elements. Same computed
effect, but React no longer sees a client-only attribute on `<html>` /
`<body>`. The rule is recreated on every startScrollLock and removed on
teardown, so reload survival (driven by the persisted scroll key) is
unchanged.

Adds a regression guard pinning the new shape (no inline overflowAnchor
mutation on html/body; injected <style> created and removed by id).
Verified end-to-end: the nextjs-app-router live-e2e fixture now passes
the expectConsoleClean probe deterministically.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Relax regression-guard regex spans to {0,400}

Address Greptile review: the {0,200}/{0,220}/{0,160} character-span
limits between the injected-style constructs were tight enough that an
innocent refactor or added comment inside startScrollLock could silently
break the shape-check. Widen each segment to {0,400}; the guard still
passes on the fix and still fails when the inline html/body overflowAnchor
mutation is reintroduced.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-20 13:50:32 +09:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
1fd1eb11bc chore(deps-dev): bump the bun-minor-and-patch group across 1 directory with 9 updates (#248)
Bumps the bun-minor-and-patch group with 9 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@ai-sdk/anthropic](https://github.com/vercel/ai/tree/HEAD/packages/anthropic) | `3.0.81` | `3.0.84` |
| [@ai-sdk/google](https://github.com/vercel/ai/tree/HEAD/packages/google) | `3.0.80` | `3.0.82` |
| [@ai-sdk/openai](https://github.com/vercel/ai/tree/HEAD/packages/openai) | `3.0.68` | `3.0.71` |
| [@anthropic-ai/claude-agent-sdk](https://github.com/anthropics/claude-agent-sdk-typescript) | `0.3.168` | `0.3.178` |
| [@anthropic-ai/sdk](https://github.com/anthropics/anthropic-sdk-typescript) | `0.102.0` | `0.104.2` |
| [ai](https://github.com/vercel/ai/tree/HEAD/packages/ai) | `6.0.197` | `6.0.206` |
| [astro](https://github.com/withastro/astro/tree/HEAD/packages/astro) | `6.4.4` | `6.4.7` |
| [playwright](https://github.com/microsoft/playwright) | `1.60.0` | `1.61.0` |
| [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler) | `4.98.0` | `4.100.0` |



Updates `@ai-sdk/anthropic` from 3.0.81 to 3.0.84
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/@ai-sdk/anthropic@3.0.84/packages/anthropic/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/@ai-sdk/anthropic@3.0.84/packages/anthropic)

Updates `@ai-sdk/google` from 3.0.80 to 3.0.82
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/@ai-sdk/google@3.0.82/packages/google/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/@ai-sdk/google@3.0.82/packages/google)

Updates `@ai-sdk/openai` from 3.0.68 to 3.0.71
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/@ai-sdk/openai@3.0.71/packages/openai/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/@ai-sdk/openai@3.0.71/packages/openai)

Updates `@anthropic-ai/claude-agent-sdk` from 0.3.168 to 0.3.178
- [Release notes](https://github.com/anthropics/claude-agent-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/claude-agent-sdk-typescript/compare/v0.3.168...v0.3.178)

Updates `@anthropic-ai/sdk` from 0.102.0 to 0.104.2
- [Release notes](https://github.com/anthropics/anthropic-sdk-typescript/releases)
- [Changelog](https://github.com/anthropics/anthropic-sdk-typescript/blob/main/CHANGELOG.md)
- [Commits](https://github.com/anthropics/anthropic-sdk-typescript/compare/sdk-v0.102.0...sdk-v0.104.2)

Updates `ai` from 6.0.197 to 6.0.206
- [Release notes](https://github.com/vercel/ai/releases)
- [Changelog](https://github.com/vercel/ai/blob/ai@6.0.206/packages/ai/CHANGELOG.md)
- [Commits](https://github.com/vercel/ai/commits/ai@6.0.206/packages/ai)

Updates `astro` from 6.4.4 to 6.4.7
- [Release notes](https://github.com/withastro/astro/releases)
- [Changelog](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md)
- [Commits](https://github.com/withastro/astro/commits/astro@6.4.7/packages/astro)

Updates `playwright` from 1.60.0 to 1.61.0
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.60.0...v1.61.0)

Updates `wrangler` from 4.98.0 to 4.100.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.100.0/packages/wrangler)

---
updated-dependencies:
- dependency-name: "@ai-sdk/anthropic"
  dependency-version: 3.0.84
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@ai-sdk/google"
  dependency-version: 3.0.82
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@ai-sdk/openai"
  dependency-version: 3.0.71
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@anthropic-ai/claude-agent-sdk"
  dependency-version: 0.3.177
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: "@anthropic-ai/sdk"
  dependency-version: 0.104.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
- dependency-name: ai
  dependency-version: 6.0.205
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: astro
  dependency-version: 6.4.7
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: bun-minor-and-patch
- dependency-name: playwright
  dependency-version: 1.61.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
- dependency-name: wrangler
  dependency-version: 4.100.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: bun-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-19 21:37:29 -07:00
github-actions[bot] a42d4a7060 Sync generated provider output 2026-06-20 04:29:05 +00:00
a1560fb0f5 Fix misleading npx hints in live-mode poll/wrap scripts (#275)
* Replace npx hints in live scripts with bundled-script paths

The live-mode poll/wrap scripts are invoked by the agent via
`node {{scripts_path}}/live-*.mjs`, never through the `npx impeccable`
CLI. Their help text and runtime error hints still pointed at
`npx impeccable poll|live|wrap`, which is misleading and, for the
error paths, not directly runnable.

- Docstrings/comments (never executed): switch to the
  `node <scripts_path>/...` convention already used by live-server.mjs.
- Runtime-printed error/usage strings: resolve the script's own dir via
  import.meta.url and print a real, copy-pasteable absolute path instead
  of a placeholder.

Verified by triggering the error paths from the synced bundle and by
running the live-mode E2E (vite8-react-modal) through the full cycle.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Quote script paths in runtime hints to handle spaces

Paths containing spaces (e.g. /Users/john doe/...) would otherwise
produce a non-runnable command. Addresses Greptile review feedback.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 21:28:35 -07:00
d5403f9d65 Bump extension to v1.2.1 and add consolidated changelog (#265)
Release bump covering the recent extension fixes that ship together:
toolbar badge count parity (#262), local file:// scan failure messaging
(#258), and the Kinpaku popup theme (#260).

Merge after #264, #261, and #263.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 21:51:15 -07:00
1f4021b16c Fix: make Chrome extension toolbar badge count anti-patterns (#264)
The toolbar badge counted flagged elements (state.findings.length) while
the popup and DevTools panel counted total anti-pattern findings, so the
same scan showed two numbers (e.g. 21 vs 34 on the design-system page).
Since the surfaces are labeled "anti-patterns", count total findings in
the badge too so all three agree.

Closes #262

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 21:50:36 -07:00
046a8593f5 Fix: surface scan failures in extension popup for local files (#261)
* Fix: surface scan failures in extension popup for local files

Scanning a local file:// page with "Allow access to file URLs" off left
the popup stuck on "Scanning..." because the blocked content-script
injection returned silently. ensureContentScriptInjected() now returns the
real error, and sendScanToTab() sends a scan-failed message that the popup
renders as a small line, with a permission hint shown only for file:// tabs.

Fixes #258

Co-authored-by: Cursor <cursoragent@cursor.com>

* Improve: report the actual error when a non-file scan fails

The generic "This page can't be scanned." gave no reason. Non-file failures
now read "Couldn't scan this page: <error>" so the user sees what Chrome
reported instead of a dead end.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fix: scope popup broadcasts to the active tab

The popup acted on every findings-updated / scan-failed / overlays broadcast
regardless of which tab it targeted, so a background or DevTools-driven
rescan on another tab could reset the button or show a spurious error. Cache
the active tab id and ignore broadcasts for other tabs.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 21:49:16 -07:00
Abdul WahabandGitHub e371c99f08 Update extension popup to Kinpaku theme (#263)
* Update extension popup to Kinpaku theme

* Fix popup light mode contrast
2026-06-18 21:48:37 -07:00
github-actions[bot] d949abd180 Sync generated provider output 2026-06-19 01:47:38 +00:00
Abdul WahabandGitHub 07667ed08f Add quiet mode to detect CLI (#259) 2026-06-18 18:47:02 -07:00
Paul Bakaus 1c897a09c8 Polish docs page 2026-06-17 17:49:38 +09:00
Paul Bakaus 617b3a6e5e Polish live mode and slop pages 2026-06-17 17:38:07 +09:00
Paul Bakaus c7539c867d Fix live picker sizing and divider detection 2026-06-17 13:10:53 +09:00
Paul Bakaus 4f50db2bca Fix live picker steer sizing 2026-06-17 12:36:58 +09:00
github-actions[bot] f726894373 Sync generated provider output 2026-06-17 03:00:20 +00:00
Paul BakausandGitHub 99a284a0d9 Fix live page editable focus handling (#256) 2026-06-16 19:59:48 -07:00
github-actions[bot] b86f2cc353 Sync generated provider output 2026-06-17 02:51:20 +00:00
Paul BakausandGitHub 8b0c895703 [codex] Fix CLI skill update detection (#257)
* Fix CLI skill update detection

* Preserve linked skills during install refresh

* Keep existing installs working offline

* Respect provider scope during install refresh
2026-06-16 19:50:40 -07:00
dependabot[bot]GitHubdependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
1268f10b76 chore(deps): bump actions/cache from 4 to 5 in the github-actions group (#249)
Bumps the github-actions group with 1 update: [actions/cache](https://github.com/actions/cache).


Updates `actions/cache` from 4 to 5
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-16 06:56:23 -07:00
Paul BakausandClaude Opus 4.8 795e8ed5e5 fix(skill): bundle detector config dependency so critique runs (#254)
The bundled detector's cli/main.mjs imports ../../lib/impeccable-config.mjs,
which in the source CLI resolves to cli/lib/impeccable-config.mjs. The skill
build only copies cli/engine/** into scripts/detector/**, leaving that
dependency behind, so from the bundled scripts/detector/cli/main.mjs the same
import resolved to scripts/lib/impeccable-config.mjs and failed with
"Cannot find module .../lib/impeccable-config.mjs". /impeccable critique (and
any detector-backed command) crashed on startup for every provider since #252.

Teach the detector bundler to copy out-of-bundle engine dependencies into the
skill's scripts/lib/, and add a build test that walks every bundled script and
asserts each relative import resolves to another bundled file, so a future
out-of-bundle dependency fails the test instead of the user.

Skill v3.7.1 (patch). CLI unchanged — the engine resolves fine in the CLI's
own tree; only the skill bundling was wrong.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 22:49:31 +09:00
Paul Bakaus b928fe35fb Refine CLI release changelog 2026-06-16 13:10:16 +09:00
github-actions[bot] 08f1147b69 Sync generated provider output 2026-06-16 04:06:48 +00:00
Paul BakausandGitHub 51d01e3a5f [codex] Add design-aware detector rules (#252)
* Add design-aware detector rules

* Fix design-aware detector noise

* Unify CLI and hook detector ignores

* Fix remaining design-system review findings

* Add detector ignore CLI

* Fix design detector review findings

* Fix design color source false positives

* Fix core test suite registration

* Add design-aware detector docs

* Fix font priority design-system parsing

* Fix color ignore value matching
2026-06-15 21:06:17 -07:00
c27a75ad41 fix(cli): replace extract-zip with fflate to fix silent install on Node v24.16.0+ (#253)
On Node v24.16.0 / v26.1.0+, `impeccable install` printed "Downloading
impeccable skills...", exited 0, and installed nothing. A Node streams
regression (nodejs/node#63487) made pause()/resume() no-ops on destroyed
streams, stalling extract-zip's yauzl/fd-slicer read stack partway through;
its promise never settled and the process exited clean with no error.

Swap extract-zip for fflate across both extraction call sites
(downloadAndExtractBundle, copyOrExtractLocalBundle) via a new extractZip
helper. fflate decompresses from an in-memory buffer and never touches the
fs stream path, so it is immune on every Node version. It is pure JS with
zero dependencies, so the Windows fix from #198 (no `unzip` binary) holds.
Unlike extract-zip, fflate is actively maintained.

Because extractZip writes entries itself, it guards against zip-slip (`../`
entries escaping the target dir). Tests add a many-file regression guard
(fails on partial extraction) and a zip-slip rejection test.

Verified end-to-end: the real 1,194-file universal bundle extracts and
installs completely.

Fixes #250.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-15 20:33:43 -07:00
Paul Bakaus fff712ca98 Refine release changelog copy 2026-06-15 13:57:08 +09:00
Paul Bakaus 23eae3cc5b Fix homepage polish and update stars 2026-06-15 13:46:15 +09:00
Paul Bakaus 858b9bbea6 Improve hook false-positive handling 2026-06-15 13:30:28 +09:00
github-actions[bot] a9c15481a9 Sync generated provider output 2026-06-15 04:05:09 +00:00
576 changed files with 63566 additions and 6739 deletions
+3 -1
View File
@@ -1,6 +1,7 @@
---
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
---
Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
@@ -9,7 +10,7 @@ Designs and iterates production-grade frontend interfaces. Real working code, co
You MUST do these steps before proceeding:
1. Run `node .agents/skills/impeccable/scripts/context.mjs` once per session. 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.
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 <path>` 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/<command>.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.
@@ -92,6 +93,7 @@ Match-and-refuse. If you're about to write any of these, rewrite the element wit
- **`border-radius: 32px+` on cards / sections / inputs.** You over-round. Cards top out at 1216px; 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
+66 -59
View File
@@ -1,12 +1,12 @@
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 and personality through stronger hierarchy, committed scale, and decisive type.
When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact by making the existing design language more decisive, specific, and committed.
---
## Register
Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
Brand: "bolder" means distinctive. Express a stronger point of view through hierarchy, pacing, proportion, copy, evidence, and one committed visual idea.
Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
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.
---
@@ -15,98 +15,105 @@ Product: "bolder" rarely means theatrics; those undermine trust. It means strong
Analyze what makes the design feel too safe or boring:
1. **Identify weakness sources**:
- **Generic choices**: System fonts, basic colors, standard layouts
- **Timid scale**: Everything is medium-sized with no drama
- **Low contrast**: Everything has similar visual weight
- **Static**: No motion, no energy, no life
- **Predictable**: Standard patterns with no surprises
- **Flat hierarchy**: Nothing stands out or commands attention
- **Generic choices**: The page could belong to any product in the category.
- **Timid scale**: Everything is medium-sized with no clear lead.
- **Low contrast**: Important and supporting elements have similar visual weight.
- **Static**: The surface has no meaningful moment of emphasis.
- **Predictable**: The composition follows a default pattern without a point of view.
- **Flat hierarchy**: Nothing stands out or commands attention.
2. **Understand the context**:
- What's the brand personality? (How far can we push?)
- What's the purpose? (Marketing can be bolder than financial dashboards)
- Who's the audience? (What will resonate?)
- What are the constraints? (Brand guidelines, accessibility, performance)
- What is the brand personality?
- What is the purpose of this surface?
- Who is the audience?
- What design system, tokens, components, and visual conventions already exist?
If any of these are unclear from the codebase, STOP and use Codex's structured user-input/question tool when available; if unavailable, ask directly in chat to clarify what you cannot infer.
**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
**CRITICAL**: "Bolder" does not mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random noise.
**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
## Design-System Lock
If the project has `DESIGN.md`, tokens, theme variables, or established component styles, treat that system as the boundary. Make the existing language stronger before adding new language.
Do not invent new colors, gradients, radii, shadows, fonts, decorative backgrounds, or effects just because the request says "bolder." A bolder pass should usually change emphasis, proportion, rhythm, density, contrast, copy, artifact specificity, and layout relationships while staying inside the documented system.
If the existing system is genuinely too limited to express the bolder direction, stop and ask the user before expanding it. Name the exact additions, the role each would play, and why the current system cannot do the job. If the user approves expansion, update the design system or tokens alongside the implementation.
## Plan Amplification
Create a strategy to increase impact while maintaining coherence:
- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
- **Risk budget**: How experimental can we be? Push boundaries within constraints.
- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
- **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 across these dimensions:
Systematically increase impact through intention, not a menu of effects:
### Typography Amplification
- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and the [Reference Material section of typeset.md](typeset.md#reference-material) for inspiration)
- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
- 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 Intensification
- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
- **Dominant color strategy**: Let one bold color own 60% of the design
- **Sharp accents**: High-contrast accent colors that pop
- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
### 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 Drama
- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
- **Break the grid**: Let hero elements escape containers and cross boundaries
- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
- **Overlap**: Layer elements intentionally for depth
### 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.
### Visual Effects
- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
### 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
- **Hero moment**: One signature entrance, once. Not on every visit and not on every section.
- **Micro-interactions**: Satisfying hover effects, click feedback, state changes.
- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect).
- **Bolder scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold.
- 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
- **Hero moments**: Create clear focal points with dramatic treatment
- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
- **Full-bleed elements**: Use full viewport width/height for impact
- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
- 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 effects randomly without purpose (chaos ≠ bold)
- Sacrifice readability for aesthetics (body text must be readable)
- Make everything bold (then nothing is bold; you need contrast)
- Ignore accessibility (bold design must still meet WCAG standards)
- Overwhelm with motion (animation fatigue is real)
- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
- 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?
- **Performant**: Do all these effects run smoothly?
- **Accessible**: Does it still meet accessibility standards?
- **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."
@@ -5,8 +5,9 @@ Resolve one stable target, run two independent assessments, synthesize a design
### Hard Invariants
- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
- Assessment A and B MUST run as two isolated sub-agents whenever a sub-agent/Task tool is exposed. Running them inline in this context is "possible" but is NOT permitted; it is a degraded run. Inline is allowed ONLY when no sub-agent tool exists (or the user declined, on harnesses that ask).
- If you degrade for any reason, the report's first line MUST be a banner: `⚠️ DEGRADED: single-context (<reason>)`. 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.
- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
- Viewable targets require browser inspection when available.
- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
@@ -27,14 +28,21 @@ Resolve one stable target, run two independent assessments, synthesize a design
### Assessment Orchestration
Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
Delegate Assessment A and Assessment B to separate sub-agents. They must not see each other's output. Do not show findings to the user until synthesis.
Codex sub-agent gate:
Sub-agent gate (all harnesses):
- Unless a harness-specific gate below overrides this, spawn A and B as two isolated, parallel sub-agents whenever a sub-agent/Task tool is exposed. This is the default and is mandatory; do not run them inline because it is faster.
- "Unavailable" means exactly one thing: no sub-agent/Task tool is exposed in this session (or, on harnesses that ask, the user declined). It does not mean inconvenient.
- If and only if sub-agents are unavailable, fall back sequentially: finish and record Assessment A, then run Assessment B, then synthesize, and emit the degraded banner.
- Whichever path you take, declare it in the report header (see Report header provenance). Skipping sub-agents without the banner is the most common failure of this command.
Codex sub-agent gate (overrides the default above; Codex's permission model requires asking before spawning):
- Asking is the normal path, not a degradation. Approving and spawning is the dual-agent path; do not emit the degraded banner just for asking.
- If `spawn_agent` is exposed and the user explicitly allowed sub-agents, delegation, or parallel agent work, spawn A and B immediately.
- If `spawn_agent` is exposed but the user did not explicitly allow sub-agents, ask exactly once: "Impeccable critique is designed to run two independent sub-agents for an unanchored assessment. May I use sub-agents for this critique?" Then stop until the user answers.
- If allowed, spawn A and B. If declined, run sequentially and report `Assessment independence: degraded (sub-agents declined by user)`.
- If `spawn_agent` is not exposed, do not ask; run sequentially and report `Assessment independence: degraded (spawn_agent unavailable in this session)`.
- If spawning fails after permission, run sequentially and report `Assessment independence: degraded (sub-agent spawn failed: <exact error>)`.
- If allowed, spawn A and B. If declined, run sequentially and lead the report with `⚠️ DEGRADED: single-context (sub-agents declined by user)`.
- If `spawn_agent` is not exposed, do not ask; run sequentially and lead with `⚠️ DEGRADED: single-context (spawn_agent unavailable in this session)`.
- If spawning fails after permission, run sequentially and lead with `⚠️ DEGRADED: single-context (sub-agent spawn failed: <exact error>)`.
Prefer `fork_context: false` with self-contained prompts containing cwd, target, live URL, references, product context, and output contract. If using `fork_context: true`, omit `agent_type`, `model`, and `reasoning_effort`.
If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
@@ -69,7 +77,7 @@ node .agents/skills/impeccable/scripts/detect.mjs --json [target]
Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
1. Create a fresh tab and navigate.
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 `<script>` tag. Read-only evaluate APIs do not count.
3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
4. If mutation is available, start `node .agents/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
@@ -93,6 +101,12 @@ Codex final-answer note: `$impeccable critique` produces a report artifact, so t
Structure your feedback as a design director would:
#### Report header provenance
The report's first line MUST declare how the assessments were run, so a degraded run is never silent:
- Dual-agent: `Method: dual-agent (A: <agent-id> · B: <agent-id>)`
- Degraded: `⚠️ DEGRADED: single-context (<reason, e.g. no sub-agent tool exposed>)`
#### Design Health Score
> *Consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below.*
@@ -1,6 +1,6 @@
Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
DESIGN.md follows the [official DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
## The frontmatter: token schema
+17 -9
View File
@@ -2,11 +2,13 @@
Manage the **design detector hook** for the current project.
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), Cursor (`.cursor/hooks.json` in the project), and GitHub Copilot (`.github/hooks$impeccable.json` in the project, a team-shared committed file that both the Copilot CLI and the cloud agent read). For the Copilot CLI, repo-level hooks fire once `.github/hooks$impeccable.json` is committed to the repository's default branch.
On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
@@ -46,10 +48,10 @@ The hook itself never writes ignore config. Persist an exception only after the
Prefer the narrowest exception:
- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/config.json` by default.
- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
- For value-specific findings such as `overused-font` and `bounce-easing`, use `ignore-value` when the user confirms the specific value. Do not use `ignore-rule overused-font` for a specific font.
- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
- Prefer config ignores (the commands above) by default; they keep suppressions in one reviewable place. Reach for an inline comment only when the waiver must travel with a single file that leaves the repo (a generated/exported standalone document, an emailed HTML file). The supported marker is `impeccable-disable <rule>` (whole file) or `impeccable-disable-line` / `impeccable-disable-next-line` (one line), in any comment syntax, with an optional reason after `:` or `--`. The detector honors it by default; `--no-inline-ignores` or `--no-config` bypasses it.
Example value-specific exception:
@@ -57,6 +59,12 @@ Example value-specific exception:
node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
```
Example intentional motion exception:
```bash
node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-value bounce-easing bounce-ball --shared --reason "User confirmed ball bounce animation is intentional"
```
Example whole-rule font exception:
```bash
@@ -73,8 +81,8 @@ node .agents/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Ca
- Never modify `.impeccable/config.json` or `.impeccable/config.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
- Cursor can block a proposed write when the detector finds a real issue. Claude Code, Codex, and GitHub Copilot do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, `.cursor/hooks.json`, and `.github/hooks$impeccable.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks. On GitHub Copilot, the CLI loads `.github/hooks$impeccable.json` once it is committed to the repository's default branch, and the cloud agent reads it from the repo directly.
## Failure modes
+1 -1
View File
@@ -3,7 +3,7 @@
The setup command for a project. One codebase crawl feeds everything it writes:
- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md). Answers "how it looks".
- **`.impeccable/live/config.json`** (live mode): pre-configured so `$impeccable live` boots straight into variant mode with no first-time detour.
It closes by pointing the user at the best command to run next. Every other impeccable command reads PRODUCT.md and DESIGN.md before doing any work.
+1 -1
View File
@@ -10,7 +10,7 @@ Codex: run live helper commands, the app dev server, and any dependency-installi
Execute in order. No step skipped, no step reordered.
1. `live.mjs`: boot.
1. `live.mjs`: boot. 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/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.
2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.
3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
+712 -31
View File
@@ -5,11 +5,12 @@
* init flow.
*
* Path resolution (first match wins):
* 1. cwd, if PRODUCT.md or DESIGN.md is there
* 2. .agents/context/ then docs/
* 3. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) — power-user
* 1. Active project root, if PRODUCT.md or DESIGN.md is there
* 2. Active project .agents/context/ then docs/
* 3. Monorepo root context, using the same order, as a per-file fallback
* 4. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) — power-user
* escape hatch, only consulted when defaults are empty
* 4. cwd as a "nothing found" default
* 5. Active project root as a "nothing found" default
*
* `resolveContextDir()` and `loadContext()` are also exported for the
* server-side scripts (live.mjs, live-server.mjs) that need the structured
@@ -19,15 +20,30 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseTargetOptions } from './lib/target-args.mjs';
const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
const FALLBACK_DIRS = ['.agents/context', 'docs'];
const MONOREPO_MARKER_FILES = ['pnpm-workspace.yaml', 'turbo.json', 'nx.json', 'lerna.json'];
const MONOREPO_FALLBACK_PROJECT_DIRS = ['apps', 'packages'];
const WORKSPACE_DISCOVERY_IGNORED_DIRS = new Set([
'node_modules',
'.git',
'dist',
'build',
'.next',
'.nuxt',
'.svelte-kit',
'.turbo',
'.cache',
'coverage',
]);
// ─── Update check ──────────────────────────────────────────────────────────
// Piggyback a lightweight skill-version check on the once-per-session boot.
// When a newer skill ships, append an UPDATE_AVAILABLE directive so the agent
// can offer `npx impeccable skills update`. Everything here is best-effort and
// can offer `npx impeccable update`. Everything here is best-effort and
// silent on failure: a network problem, sandbox, or missing cache must never
// block context output or print an error.
@@ -38,41 +54,623 @@ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // throttle the network poll to o
const RENOTIFY_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; // don't re-surface the same version for a week
const FETCH_TIMEOUT_MS = 1200;
export function resolveContextDir(cwd = process.cwd()) {
if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return cwd;
}
for (const rel of FALLBACK_DIRS) {
const candidate = path.resolve(cwd, rel);
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return candidate;
}
}
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
if (envDir && envDir.trim()) {
const trimmed = envDir.trim();
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
}
return cwd;
export function resolveContextDir(cwd = process.cwd(), options = {}) {
return resolveContext(cwd, options).contextDir;
}
export function loadContext(cwd = process.cwd()) {
const contextDir = resolveContextDir(cwd);
const productPath = firstExisting(contextDir, PRODUCT_NAMES);
const designPath = firstExisting(contextDir, DESIGN_NAMES);
export function loadContext(cwd = process.cwd(), options = {}) {
const resolved = resolveContext(cwd, options);
const absCwd = path.resolve(cwd);
const productPath = resolved.productPath;
const designPath = resolved.designPath;
const product = productPath ? safeRead(productPath) : null;
const design = designPath ? safeRead(designPath) : null;
return {
hasProduct: !!product,
product,
productPath: productPath ? path.relative(cwd, productPath) : null,
productPath: productPath ? path.relative(absCwd, productPath) : null,
hasDesign: !!design,
design,
designPath: designPath ? path.relative(cwd, designPath) : null,
contextDir,
designPath: designPath ? path.relative(absCwd, designPath) : null,
contextDir: resolved.contextDir,
productContextDir: productPath ? path.dirname(productPath) : null,
designContextDir: designPath ? path.dirname(designPath) : null,
projectRoot: resolved.projectRoot,
repoRoot: resolved.repoRoot,
isMonorepo: resolved.isMonorepo,
};
}
function resolveContext(cwd = process.cwd(), options = {}) {
const absCwd = path.resolve(cwd);
const project = resolveProject(absCwd, options);
const projectContextDir = resolveLocalContextDir(project.projectRoot);
const rootContextDir = project.isMonorepo && project.repoRoot !== project.projectRoot
? resolveLocalContextDir(project.repoRoot)
: null;
let productPath =
(projectContextDir ? firstExisting(projectContextDir, PRODUCT_NAMES) : null)
|| (rootContextDir ? firstExisting(rootContextDir, PRODUCT_NAMES) : null);
let designPath =
(projectContextDir ? firstExisting(projectContextDir, DESIGN_NAMES) : null)
|| (rootContextDir ? firstExisting(rootContextDir, DESIGN_NAMES) : null);
let envContextDir = null;
if (!productPath && !designPath) {
envContextDir = resolveEnvContextDir(absCwd);
if (envContextDir) {
productPath = firstExisting(envContextDir, PRODUCT_NAMES);
designPath = firstExisting(envContextDir, DESIGN_NAMES);
}
}
return {
contextDir: productPath
? path.dirname(productPath)
: designPath
? path.dirname(designPath)
: envContextDir || project.projectRoot,
productPath,
designPath,
projectRoot: project.projectRoot,
repoRoot: project.repoRoot,
isMonorepo: project.isMonorepo,
targetDir: project.targetDir,
};
}
export function resolveProjectRoot(cwd = process.cwd(), options = {}) {
return resolveProject(cwd, options).projectRoot;
}
export function resolveTargetSelection(cwd = process.cwd(), options = {}) {
if (hasTargetOption(options)) return null;
const project = resolveProject(cwd);
if (
!project.isMonorepo
|| !project.projectRoot
|| !project.repoRoot
|| path.resolve(project.projectRoot) !== path.resolve(project.repoRoot)
) {
return null;
}
const targetCandidates = discoverTargetCandidates(project.repoRoot);
// No discoverable child apps (e.g. `workspaces: ["."]`, a root-only workspace,
// or a marker file with no apps/packages children): there is nothing to choose,
// so treat the repo root as the active project rather than blocking on an empty
// selection prompt that the user cannot answer.
if (targetCandidates.length === 0) return null;
return {
targetPath: null,
projectRoot: project.projectRoot,
repoRoot: project.repoRoot,
targetCandidates,
};
}
function resolveProject(cwd = process.cwd(), options = {}) {
const absCwd = path.resolve(cwd);
const targetDir = resolveTargetDir(absCwd, options);
let repoRoot = findMonorepoRoot(targetDir);
if (!repoRoot && targetDir !== absCwd) {
const cwdRepoRoot = findMonorepoRoot(absCwd);
if (cwdRepoRoot && isPathInside(targetDir, cwdRepoRoot)) {
repoRoot = cwdRepoRoot;
}
}
if (!repoRoot) {
return {
targetDir,
projectRoot: absCwd,
repoRoot: absCwd,
isMonorepo: false,
};
}
return {
targetDir,
projectRoot: resolveWorkspaceProjectRoot(repoRoot, targetDir) || repoRoot,
repoRoot,
isMonorepo: true,
};
}
function isPathInside(candidate, root) {
const rel = path.relative(root, candidate);
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function resolveLocalContextDir(root) {
if (firstExisting(root, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return root;
}
for (const rel of FALLBACK_DIRS) {
const candidate = path.resolve(root, rel);
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return candidate;
}
}
return null;
}
function resolveEnvContextDir(cwd) {
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
if (!envDir || !envDir.trim()) return null;
const trimmed = envDir.trim();
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
}
function resolveTargetDir(cwd, options = {}) {
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
if (!targetPath || !String(targetPath).trim()) return cwd;
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
try {
const stat = fs.statSync(abs);
return stat.isDirectory() ? abs : path.dirname(abs);
} catch {
return path.extname(abs) ? path.dirname(abs) : abs;
}
}
function findMonorepoRoot(startDir) {
let dir = path.resolve(startDir);
const homeDir = path.resolve(os.homedir());
while (true) {
if (dir === homeDir) return null;
// isMonorepoRoot is checked before hasGitBoundary on purpose: a workspace
// root that also carries its own .git is still recognized. The trade-off is
// deliberate — a directory with a monorepo *marker* but no workspace patterns
// and no apps/packages children is not a monorepo root, so its .git stops
// traversal and a further-up root is not searched. The nested .git is treated
// as an independent project boundary, which is the intended isolation.
if (isMonorepoRoot(dir)) return dir;
if (hasGitBoundary(dir)) return null;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
function isMonorepoRoot(dir) {
if (readWorkspacePatterns(dir).some((pattern) => !normalizeWorkspacePattern(pattern).startsWith('!'))) return true;
if (!MONOREPO_MARKER_FILES.some((file) => fs.existsSync(path.join(dir, file)))) return false;
return hasFallbackWorkspaceChildren(dir);
}
function hasGitBoundary(dir) {
return fs.existsSync(path.join(dir, '.git'));
}
function hasFallbackWorkspaceChildren(dir) {
for (const name of MONOREPO_FALLBACK_PROJECT_DIRS) {
const base = path.join(dir, name);
let entries;
try {
entries = fs.readdirSync(base, { withFileTypes: true });
} catch {
continue;
}
if (entries.some((entry) => entry.isDirectory() && !isIgnoredWorkspaceDiscoveryDir(entry.name))) return true;
}
return false;
}
function discoverTargetCandidates(repoRoot) {
const roots = new Map();
const patterns = readWorkspacePatterns(repoRoot);
for (const pattern of patterns) {
for (const root of discoverRootsForPattern(repoRoot, pattern)) {
roots.set(path.relative(repoRoot, root).split(path.sep).join('/'), root);
}
}
if (MONOREPO_MARKER_FILES.some((file) => fs.existsSync(path.join(repoRoot, file)))) {
for (const name of MONOREPO_FALLBACK_PROJECT_DIRS) {
const base = path.join(repoRoot, name);
let entries;
try {
entries = fs.readdirSync(base, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
const root = path.join(base, entry.name);
roots.set(path.relative(repoRoot, root).split(path.sep).join('/'), root);
}
}
}
return [...roots.entries()]
.filter(([rel]) => rel && !rel.startsWith('..'))
// Honor negated workspace patterns (e.g. "!packages/internal"). resolveWorkspaceProjectRoot
// sends an excluded package back to the repo root, so an excluded folder must not appear as a
// selectable target — choosing it would silently resolve to the root instead.
.filter(([rel]) => !isExcludedByWorkspacePattern(rel.split('/').filter(Boolean), patterns))
.sort(([a], [b]) => a.localeCompare(b))
.map(([rel, root]) => {
const targetExample = findTargetExample(repoRoot, root);
return {
name: path.basename(root),
path: rel,
targetExample,
...resolveCandidateContextSummary(repoRoot, root, targetExample),
};
});
}
function resolveCandidateContextSummary(repoRoot, projectRoot, targetPath) {
const ctx = resolveContext(repoRoot, { targetPath });
return {
productStatus: contextSourceStatus(ctx.productPath, repoRoot, projectRoot),
productPath: contextSourcePath(ctx.productPath, repoRoot),
designStatus: contextSourceStatus(ctx.designPath, repoRoot, projectRoot),
designPath: contextSourcePath(ctx.designPath, repoRoot),
};
}
// Selection candidates surface one of four statuses: 'child' (a canonical
// PRODUCT.md/DESIGN.md directly in the app root), 'inherited' (resolved from the
// repo root in a monorepo), 'missing' (no file found), and 'fallback'. 'fallback'
// intentionally covers two non-canonical locations: a file inside the project
// root but in a subdirectory (FALLBACK_DIRS, e.g. `.agents/context/`), and a file
// outside both the project and repo roots (IMPECCABLE_CONTEXT_DIR override).
function contextSourceStatus(filePath, repoRoot, projectRoot) {
if (!filePath) return 'missing';
const absPath = path.resolve(filePath);
const absProjectRoot = path.resolve(projectRoot);
const absRepoRoot = path.resolve(repoRoot);
if (isPathInsideOrEqual(absPath, absProjectRoot)) {
return path.dirname(absPath) === absProjectRoot ? 'child' : 'fallback';
}
if (absProjectRoot !== absRepoRoot && isPathInsideOrEqual(absPath, absRepoRoot)) {
return 'inherited';
}
return 'fallback';
}
function contextSourcePath(filePath, repoRoot) {
if (!filePath) return null;
const rel = path.relative(repoRoot, filePath);
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
return rel.split(path.sep).join('/');
}
return filePath;
}
function discoverRootsForPattern(repoRoot, rawPattern) {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern || pattern.startsWith('!')) return [];
const segments = pattern.split('/').filter(Boolean);
if (!segments.length) return [];
const firstGlobIndex = segments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1 ? segments : segments.slice(0, firstGlobIndex);
const base = path.join(repoRoot, ...literalPrefix);
if (!fs.existsSync(base)) return [];
if (segments.includes('**')) {
const packageRoots = [];
walkDirs(base, (dir) => {
if (dir !== base && isCandidateProjectRoot(dir)) packageRoots.push(dir);
});
if (packageRoots.length) return packageRoots;
return directChildDirs(base);
}
return expandSimplePattern(repoRoot, segments);
}
function expandSimplePattern(repoRoot, patternSegments, index = 0, current = repoRoot) {
if (index >= patternSegments.length) return fs.existsSync(current) ? [current] : [];
const segment = patternSegments[index];
if (!segment.includes('*')) {
return expandSimplePattern(repoRoot, patternSegments, index + 1, path.join(current, segment));
}
let entries;
try {
entries = fs.readdirSync(current, { withFileTypes: true });
} catch {
return [];
}
const roots = [];
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
if (!segmentMatches(segment, entry.name)) continue;
roots.push(...expandSimplePattern(repoRoot, patternSegments, index + 1, path.join(current, entry.name)));
}
return roots;
}
function directChildDirs(dir) {
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !isIgnoredWorkspaceDiscoveryDir(entry.name))
.map((entry) => path.join(dir, entry.name));
} catch {
return [];
}
}
function walkDirs(root, visit) {
let entries;
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
const dir = path.join(root, entry.name);
visit(dir);
walkDirs(dir, visit);
}
}
function isCandidateProjectRoot(dir) {
return !!(
fs.existsSync(path.join(dir, 'package.json'))
|| firstExisting(dir, [...PRODUCT_NAMES, ...DESIGN_NAMES])
|| fs.existsSync(path.join(dir, 'src'))
|| fs.existsSync(path.join(dir, 'app'))
|| fs.existsSync(path.join(dir, 'pages'))
|| fs.existsSync(path.join(dir, 'public'))
);
}
function isIgnoredWorkspaceDiscoveryDir(name) {
return name.startsWith('.') || WORKSPACE_DISCOVERY_IGNORED_DIRS.has(name);
}
function findTargetExample(repoRoot, projectRoot) {
const examples = [
'src/App.jsx',
'src/App.tsx',
'src/main.jsx',
'src/main.tsx',
'src/index.jsx',
'src/index.ts',
'app/page.tsx',
'pages/index.tsx',
'public/index.html',
];
for (const rel of examples) {
const abs = path.join(projectRoot, rel);
if (fs.existsSync(abs)) return path.relative(repoRoot, abs).split(path.sep).join('/');
}
return path.relative(repoRoot, projectRoot).split(path.sep).join('/');
}
function resolveWorkspaceProjectRoot(repoRoot, targetDir) {
const rel = path.relative(repoRoot, targetDir);
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return repoRoot;
const relSegments = rel.split(path.sep).filter(Boolean);
const patterns = readWorkspacePatterns(repoRoot);
const excluded = isExcludedByWorkspacePattern(relSegments, patterns);
if (!excluded) {
for (const pattern of patterns) {
const projectRoot = projectRootFromWorkspacePattern(repoRoot, relSegments, pattern);
if (projectRoot) return projectRoot;
}
}
if (excluded) return repoRoot;
if (
relSegments.length >= 2
&& MONOREPO_FALLBACK_PROJECT_DIRS.includes(relSegments[0])
) {
return path.join(repoRoot, relSegments[0], relSegments[1]);
}
const nearest = nearestProjectLikeRoot(repoRoot, targetDir);
if (nearest) return nearest;
return repoRoot;
}
function isExcludedByWorkspacePattern(relSegments, patterns) {
return patterns.some((rawPattern) => {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern.startsWith('!')) return false;
return workspacePatternMatchesRel(pattern.slice(1), relSegments);
});
}
function nearestProjectLikeRoot(repoRoot, targetDir) {
let dir = path.resolve(targetDir);
const stop = path.resolve(repoRoot);
while (dir && dir !== stop) {
if (
firstExisting(dir, [...PRODUCT_NAMES, ...DESIGN_NAMES])
|| fs.existsSync(path.join(dir, 'package.json'))
) {
return dir;
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function nearestPackageRootBetween(repoRoot, targetDir, stopDir) {
let dir = path.resolve(targetDir);
const stop = path.resolve(stopDir || repoRoot);
const root = path.resolve(repoRoot);
while (dir && dir !== stop && isPathInsideOrEqual(dir, root)) {
if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function isPathInsideOrEqual(candidate, root) {
return path.resolve(candidate) === path.resolve(root) || isPathInside(candidate, root);
}
function workspacePatternMatchesRel(pattern, relSegments) {
const patternSegments = normalizeWorkspacePattern(pattern).split('/').filter(Boolean);
if (!patternSegments.length) return false;
if (patternSegments.includes('**')) {
const firstGlobIndex = patternSegments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1
? patternSegments
: patternSegments.slice(0, firstGlobIndex);
if (relSegments.length < literalPrefix.length + 1) return false;
for (let i = 0; i < literalPrefix.length; i++) {
if (!segmentMatches(literalPrefix[i], relSegments[i])) return false;
}
return true;
}
if (relSegments.length < patternSegments.length) return false;
for (let i = 0; i < patternSegments.length; i++) {
if (!segmentMatches(patternSegments[i], relSegments[i])) return false;
}
return true;
}
function readWorkspacePatterns(repoRoot) {
return [
...readPackageWorkspaces(repoRoot),
...readPnpmWorkspaces(repoRoot),
...readLernaWorkspaces(repoRoot),
].filter(Boolean);
}
function readPackageWorkspaces(repoRoot) {
const pkg = readJson(path.join(repoRoot, 'package.json'));
const workspaces = pkg?.workspaces;
if (Array.isArray(workspaces)) return workspaces;
if (Array.isArray(workspaces?.packages)) return workspaces.packages;
return [];
}
function readLernaWorkspaces(repoRoot) {
const lerna = readJson(path.join(repoRoot, 'lerna.json'));
return Array.isArray(lerna?.packages) ? lerna.packages : [];
}
function readPnpmWorkspaces(repoRoot) {
try {
const body = fs.readFileSync(path.join(repoRoot, 'pnpm-workspace.yaml'), 'utf-8');
const patterns = [];
let inPackages = false;
for (const line of body.split(/\r?\n/)) {
const trimmed = stripYamlInlineComment(line).trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const flowMatch = trimmed.match(/^packages:\s*\[(.*)\]\s*$/);
if (flowMatch) {
patterns.push(...parseYamlFlowList(flowMatch[1]));
inPackages = false;
continue;
}
if (/^packages:\s*$/.test(trimmed)) {
inPackages = true;
continue;
}
if (inPackages && /^[A-Za-z0-9_-]+:\s*/.test(trimmed)) break;
if (inPackages) {
const match = trimmed.match(/^-\s*(.+)$/);
if (match) patterns.push(unquoteYamlValue(match[1]));
}
}
return patterns;
} catch {
return [];
}
}
function stripYamlInlineComment(line) {
let quote = null;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if ((ch === '"' || ch === "'") && line[i - 1] !== '\\') {
quote = quote === ch ? null : quote || ch;
continue;
}
if (ch === '#' && !quote) return line.slice(0, i);
}
return line;
}
function parseYamlFlowList(body) {
const items = [];
let quote = null;
let current = '';
for (let i = 0; i < body.length; i++) {
const ch = body[i];
if ((ch === '"' || ch === "'") && body[i - 1] !== '\\') {
quote = quote === ch ? null : quote || ch;
current += ch;
continue;
}
if (ch === ',' && !quote) {
const value = unquoteYamlValue(current);
if (value) items.push(value);
current = '';
continue;
}
current += ch;
}
const value = unquoteYamlValue(current);
if (value) items.push(value);
return items;
}
function unquoteYamlValue(value) {
return String(value || '')
.trim()
.replace(/^['"]|['"]$/g, '');
}
function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return null;
}
}
function projectRootFromWorkspacePattern(repoRoot, relSegments, rawPattern) {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern || pattern.startsWith('!')) return null;
const patternSegments = pattern.split('/').filter(Boolean);
if (!patternSegments.length) return null;
if (patternSegments.includes('**')) {
return projectRootFromDoubleStarPattern(repoRoot, relSegments, patternSegments);
}
if (relSegments.length < patternSegments.length) return null;
for (let i = 0; i < patternSegments.length; i++) {
if (!segmentMatches(patternSegments[i], relSegments[i])) return null;
}
return path.join(repoRoot, ...relSegments.slice(0, patternSegments.length));
}
function projectRootFromDoubleStarPattern(repoRoot, relSegments, patternSegments) {
const firstGlobIndex = patternSegments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1
? patternSegments
: patternSegments.slice(0, firstGlobIndex);
if (relSegments.length < literalPrefix.length + 1) return null;
for (let i = 0; i < literalPrefix.length; i++) {
if (!segmentMatches(literalPrefix[i], relSegments[i])) return null;
}
const prefixDir = path.join(repoRoot, ...literalPrefix);
const targetDir = path.join(repoRoot, ...relSegments);
const packageRoot = nearestPackageRootBetween(repoRoot, targetDir, prefixDir);
if (packageRoot) return packageRoot;
return path.join(repoRoot, ...relSegments.slice(0, literalPrefix.length + 1));
}
function normalizeWorkspacePattern(pattern) {
return String(pattern || '')
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/^\.\//, '')
.replace(/\/+$/, '');
}
function segmentMatches(patternSegment, relSegment) {
if (patternSegment === '*') return true;
if (!patternSegment.includes('*')) return patternSegment === relSegment;
const re = new RegExp(`^${escapeRegExp(patternSegment).replace(/\\\*/g, '[^/]*')}$`);
return re.test(relSegment);
}
function firstExisting(dir, names) {
for (const name of names) {
const abs = path.join(dir, name);
@@ -89,6 +687,10 @@ function safeRead(p) {
}
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Pull the register (`brand` or `product`) out of PRODUCT.md by looking
* for a `## Register` section and reading the first non-empty line that
@@ -172,8 +774,8 @@ function buildUpdateDirective(localVersion, latestVersion) {
`UPDATE_AVAILABLE: A newer Impeccable skill is available ` +
`(installed v${localVersion}, latest v${latestVersion}). ` +
`Before continuing, ask the user once: "A newer Impeccable (v${latestVersion}) is available. ` +
`Update now? It runs \`npx impeccable skills update\`." ` +
`If they agree, run \`npx impeccable skills update\` (the update applies to the next session, not this one). ` +
`Update now? It runs \`npx impeccable update\`." ` +
`If they agree, run \`npx impeccable update\` (the update applies to the next session, not this one). ` +
`Either way, continue the current task without waiting, and do not raise this again.`
);
}
@@ -233,7 +835,24 @@ async function computeUpdateDirective(now = Date.now()) {
}
async function cli() {
const ctx = loadContext(process.cwd());
let cliOptions;
try {
cliOptions = parseCliOptions(process.argv.slice(2));
} catch (err) {
if (err?.name === 'TargetArgError') {
process.stderr.write(`${err.message}\n`);
process.exit(1);
}
throw err;
}
const targetProvided = hasTargetOption(cliOptions);
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
const selection = resolveTargetSelection(process.cwd(), cliOptions);
if (selection) {
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
process.exit(0);
}
const ctx = loadContext(process.cwd(), cliOptions);
const updateDirective = await computeUpdateDirective();
if (!ctx.hasProduct) {
@@ -244,6 +863,10 @@ async function cli() {
'Stop the current task, load reference/init.md, and follow its ' +
'instructions to write PRODUCT.md before resuming.',
];
parts.push(buildResolvedContextDirective(ctx, cliOptions, { targetExists }));
if (shouldWarnMissingTarget(ctx, targetProvided, targetExists)) {
parts.push(buildMissingTargetDirective());
}
if (updateDirective) parts.push(updateDirective);
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
process.exit(0);
@@ -252,6 +875,10 @@ async function cli() {
if (ctx.hasDesign) {
parts.push(`# DESIGN.md\n\n${ctx.design.trim()}`);
}
parts.push(buildResolvedContextDirective(ctx, cliOptions, { targetExists }));
if (shouldWarnMissingTarget(ctx, targetProvided, targetExists)) {
parts.push(buildMissingTargetDirective());
}
const register = extractRegister(ctx.product);
const next = register
? `NEXT STEP: This project's register is \`${register}\`. You MUST now read \`reference/${register}.md\` before producing any design output.`
@@ -261,6 +888,60 @@ async function cli() {
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
}
function parseCliOptions(args) {
return parseTargetOptions(args, { strict: true });
}
function hasTargetOption(options) {
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
}
function pathExistsForTarget(cwd, targetPath) {
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
return fs.existsSync(abs);
}
function buildResolvedContextDirective(ctx, options, { targetExists = null } = {}) {
const targetPath = hasTargetOption(options) ? options.targetPath : null;
return `RESOLVED_CONTEXT:\n${JSON.stringify({
targetPath,
...(targetPath ? { targetExists } : {}),
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
productPath: ctx.productPath,
designPath: ctx.designPath,
}, null, 2)}`;
}
function shouldWarnMissingTarget(ctx, targetProvided, targetExists = null) {
if (ctx.isMonorepo && targetProvided && targetExists === false) return true;
return !!(
ctx.isMonorepo
&& (!targetProvided || targetExists === false)
&& ctx.projectRoot
&& ctx.repoRoot
&& path.resolve(ctx.projectRoot) === path.resolve(ctx.repoRoot)
);
}
function buildMissingTargetDirective() {
const script = process.argv[1] || 'context.mjs';
return (
'MONOREPO_TARGET_REQUIRED: This is a monorepo and context.mjs ran without --target. ' +
'If the user named a file, route, or child app, do not answer from this output. ' +
`Rerun \`node ${script} --target <path>\` and answer from that run's RESOLVED_CONTEXT fields.`
);
}
function buildTargetSelectionDirective(selection) {
return (
`TARGET_SELECTION_REQUIRED:\n${JSON.stringify(selection, null, 2)}\n\n` +
'Show each app with its productStatus/productPath and designStatus/designPath so the user can see child overrides, inherited root files, fallback files, or missing files before choosing. ' +
'Ask the user which app Impeccable should use, then rerun Impeccable helper commands from that child app cwd using this same scripts directory. ' +
'Use `--target <path>` only as a fallback when changing cwd is not possible, or when the user explicitly named a file/path.'
);
}
// Run cli() only when this module is the entry point. Compare realpaths
// rather than endsWith(): a loose suffix match also fires for unrelated
// scripts like `load-context.mjs`, and realpath tolerates symlinked
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
category: ap ? ap.category : 'quality',
severity: ap?.severity || 'warning',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
description: ap ? ap.description : '',
};
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
const DESIGN_COLOR_TOLERANCE = 6;
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function normalizeBrowserFontName(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function browserPrimaryFont(stack) {
if (!stack || /var\(/i.test(stack)) return '';
return String(stack || '')
.split(',')
.map(normalizeBrowserFontName)
.find(font => font && !GENERIC_FONTS.has(font)) || '';
}
function browserDesignSystemConfig() {
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
if (!raw?.present) return null;
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
const allowedColors = (raw.allowedColors || [])
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b }));
const allowedRadii = (raw.allowedRadii || [])
.map(Number)
.filter(px => Number.isFinite(px));
return {
present: true,
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
allowedFonts,
hasColors: raw.hasColors === true && allowedColors.length > 0,
allowedColors,
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
allowedRadii,
hasPillRadius: raw.hasPillRadius === true,
};
}
function browserColorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= DESIGN_COLOR_TOLERANCE;
}
function isBrowserDesignColorAllowed(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseAnyColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
}
function isBrowserTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseAnyColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function isBrowserDesignRadiusAllowed(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
}
function browserRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function browserHasDirectText(el) {
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function browserSampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function shouldSkipDesignElement(el) {
const tag = el.tagName?.toLowerCase?.() || '';
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
}
function checkElementDesignSystemDOM(el, designSystem, seen) {
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
const findings = [];
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = getComputedStyle(el);
if (designSystem.hasFonts && browserHasDirectText(el)) {
const font = browserPrimaryFont(style.fontFamily || '');
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
ignoreValue: font,
});
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = String(raw || '').trim().replace(/\s+/g, ' ');
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seen.colors.has(key)) continue;
seen.colors.add(key);
findings.push({
type: 'design-system-color',
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
ignoreValue: label,
});
}
}
if (designSystem.hasRadii) {
for (const token of browserRadiusTokens(style.borderRadius || '')) {
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
if (seen.radii.has(token)) continue;
seen.radii.add(token);
findings.push({
type: 'design-system-radius',
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
ignoreValue: token,
});
}
}
return findings;
}
function decodeBrowserGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkBrowserDesignSystemSources(designSystem, seen) {
if (!designSystem?.hasFonts) return [];
const findings = [];
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
const href = link.getAttribute('href') || '';
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
const display = decodeBrowserGoogleFamily(match[1]);
const font = normalizeBrowserFontName(display);
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
ignoreValue: display,
});
}
}
return findings;
}
function collectBrowserFindings() {
const groupMap = new Map();
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
const designSystem = browserDesignSystemConfig();
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
// real browser env (detector page, live overlay, extension) running every
// check is free, so we always surface them; the gating is purely a CLI
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementDesignSystemDOM(el, designSystem, designSeen),
].filter(f => _ruleOk(f.type));
addBrowserFindings(groupMap, el, findings);
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
const pageLevelFindings = [];
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
.filter(f => _ruleOk(f.type));
if (designSourceFindings.length > 0) {
pageLevelFindings.push(...designSourceFindings);
addBrowserFindings(groupMap, document.body, designSourceFindings);
}
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
if (typoFindings.length > 0) {
pageLevelFindings.push(...typoFindings);
@@ -1,9 +1,15 @@
import fs from 'node:fs';
import path from 'node:path';
import { loadDesignSystemForCwd } from '../design-system.mjs';
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
import { detectHtml } from '../engines/static-html/detect-html.mjs';
import { detectText } from '../engines/regex/detect-text.mjs';
import {
filterDetectionFindings,
readDetectionConfig,
shouldIgnoreDetectionFile,
} from '../../lib/impeccable-config.mjs';
import {
HTML_EXTENSIONS,
buildImportGraph,
@@ -16,6 +22,10 @@ import {
// Output formatting
// ---------------------------------------------------------------------------
function formatFindingSummary(count) {
return `${count} anti-pattern${count === 1 ? '' : 's'} found.`;
}
function formatFindings(findings, jsonMode) {
if (jsonMode) return JSON.stringify(findings, null, 2);
@@ -33,7 +43,7 @@ function formatFindings(findings, jsonMode) {
out.push(`${item.description}`);
}
}
out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
out.push(`\n${formatFindingSummary(findings.length)}`);
return out.join('\n');
}
@@ -79,10 +89,28 @@ function printUsage() {
Scan files or URLs for UI anti-patterns and design quality issues.
Options:
--json Output results as JSON
--gpt Also report GPT-specific provider tells (off by default)
--gemini Also report Gemini-specific provider tells (off by default)
--help Show this help message
--json Output results as JSON
--quiet In text mode, only print the final findings count
--gpt Also report GPT-specific provider tells (off by default)
--gemini Also report Gemini-specific provider tells (off by default)
--no-config Do not apply project config, detector ignores, inline
ignore comments, or DESIGN.md
--no-inline-ignores Do not honor in-file impeccable-disable* ignore comments
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
--help Show this help message
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
and detector.designSystem.enabled.
Inline ignores:
In-file comments waive a finding where it lives and travel with the file:
<!-- impeccable-disable overused-font -- exported brand doc -->
.brand { font-family: Inter } /* impeccable-disable-line overused-font */
// impeccable-disable-next-line bounce-easing: intentional bounce
impeccable-disable applies to the whole file; -line / -next-line are scoped.
List one or more rule ids (comma-separated), or omit them / use * for all.
Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
@@ -93,7 +121,8 @@ Examples:
impeccable detect src/
impeccable detect index.html
impeccable detect https://example.com
impeccable detect --json .`);
impeccable detect --json .
impeccable detect --no-config src/`);
}
async function detectCli() {
@@ -104,6 +133,7 @@ async function detectCli() {
});
if (args[0] === 'detect') args = args.slice(1);
const jsonMode = args.includes('--json');
const quietMode = args.includes('--quiet');
const helpMode = args.includes('--help');
// --fast (regex-only) is deprecated: since the jsdom removal, the static
// HTML/CSS analysis is fast and covers every rule, so the regex-only path
@@ -114,10 +144,21 @@ async function detectCli() {
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
);
}
const configEnabled = !args.includes('--no-config');
const detectionConfig = configEnabled
? readDetectionConfig(process.cwd())
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
const providers = [];
if (args.includes('--gpt')) providers.push('gpt');
if (args.includes('--gemini')) providers.push('gemini');
const scanOptions = { providers };
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
// Inline `impeccable-disable*` waivers are part of the scanned file, so they
// apply by default. `--no-config` (raw scan) and the dedicated
// `--no-inline-ignores` both turn them off.
const inlineIgnoresEnabled = configEnabled && !args.includes('--no-inline-ignores');
const scanOptions = { providers, inlineIgnores: inlineIgnoresEnabled };
if (designSystem) scanOptions.designSystem = designSystem;
const targets = args.filter(a => !a.startsWith('--'));
if (helpMode) { printUsage(); process.exit(0); }
@@ -149,8 +190,8 @@ async function detectCli() {
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
if (stat.isDirectory()) {
// Check for framework dev server config (skip in JSON mode to avoid polluting output)
if (!jsonMode) {
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
if (!jsonMode && !quietMode) {
const fwConfig = detectFrameworkConfig(resolved);
if (fwConfig) {
const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
@@ -175,11 +216,12 @@ async function detectCli() {
}
}
const files = walkDir(resolved);
const files = walkDir(resolved)
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
if (files.length > 50 && process.stdin.isTTY && !jsonMode && !quietMode) {
process.stderr.write(
`\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
`Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
@@ -219,6 +261,7 @@ async function detectCli() {
allFindings.push(...fileFindings);
}
} else if (stat.isFile()) {
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
const ext = path.extname(resolved).toLowerCase();
if (HTML_EXTENSIONS.has(ext)) {
allFindings.push(...await detectHtml(resolved, scanOptions));
@@ -232,8 +275,11 @@ async function detectCli() {
}
}
allFindings = filterDetectionFindings(allFindings, detectionConfig);
if (allFindings.length > 0) {
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
else if (quietMode) process.stderr.write(formatFindingSummary(allFindings.length) + '\n');
else process.stderr.write(formatFindings(allFindings, false) + '\n');
process.exit(2);
}
@@ -0,0 +1,750 @@
import fs from 'node:fs';
import path from 'node:path';
import { finding } from './findings.mjs';
import { GENERIC_FONTS } from './shared/constants.mjs';
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
const FALLBACK_DIRS = ['.agents/context', 'docs'];
const COLOR_CHANNEL_TOLERANCE = 6;
const RADIUS_TOLERANCE_PX = 0.5;
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function firstExisting(dir, names) {
for (const name of names) {
const abs = path.join(dir, name);
if (fs.existsSync(abs)) return abs;
}
return null;
}
function resolveDesignMdPath(cwd = process.cwd()) {
const root = firstExisting(cwd, DESIGN_NAMES);
if (root) return { path: root, contextDir: cwd };
for (const rel of FALLBACK_DIRS) {
const dir = path.resolve(cwd, rel);
const found = firstExisting(dir, DESIGN_NAMES);
if (found) return { path: found, contextDir: dir };
}
return null;
}
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
const candidates = [
path.join(cwd, '.impeccable', 'design.json'),
path.join(cwd, 'DESIGN.json'),
path.join(contextDir, 'DESIGN.json'),
];
return candidates.find((candidate, index) =>
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
) || null;
}
function parseFrontmatter(md) {
const lines = String(md || '').split(/\r?\n/);
if (lines[0]?.trim() !== '---') return null;
let end = -1;
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === '---') { end = i; break; }
}
if (end === -1) return null;
try {
return parseYamlSubset(lines.slice(1, end).join('\n'));
} catch {
return null;
}
}
function parseYamlSubset(yaml) {
const root = {};
const stack = [{ indent: -1, obj: root }];
for (const raw of String(yaml || '').split(/\r?\n/)) {
if (!raw.trim() || /^\s*#/.test(raw)) continue;
const indent = raw.match(/^\s*/)[0].length;
const content = raw.slice(indent);
const colonIdx = findTopLevelColon(content);
if (colonIdx === -1) continue;
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
const parent = stack[stack.length - 1].obj;
if (rest === '') {
const obj = {};
parent[key] = obj;
stack.push({ indent, obj });
} else {
parent[key] = parseScalar(rest);
}
}
return root;
}
function findTopLevelColon(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (inQuote) {
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === ':') {
return i;
}
}
return -1;
}
function unquoteYamlKey(key) {
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
return key.slice(1, -1);
}
return key;
}
function stripInlineYamlComment(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (inQuote) {
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
return s.slice(0, i).trimEnd();
}
}
return s;
}
function parseScalar(raw) {
const s = raw.trim();
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
return s.slice(1, -1);
}
if (s === 'true') return true;
if (s === 'false') return false;
if (s === 'null' || s === '~') return null;
if (/^-?\d+$/.test(s)) return Number(s);
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
return s;
}
function safeReadJson(filePath) {
if (!filePath) return null;
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return null;
}
}
function normalizeFontName(value) {
return String(value || '')
.trim()
.replace(/\s*!important\s*$/i, '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function splitFontStack(stack) {
return String(stack || '')
.replace(/\s*!important\s*$/i, '')
.split(',')
.map(normalizeFontName)
.filter(Boolean);
}
function primaryFont(stack) {
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
}
function isLiteralFontStack(stack) {
const text = String(stack || '');
return !/[$`{}]|\s\+\s|\|\|/.test(text);
}
function cssColorLabel(raw) {
return String(raw || '').trim().replace(/\s+/g, ' ');
}
function colorKey(color) {
if (!color) return '';
return `${color.r},${color.g},${color.b}`;
}
function colorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= COLOR_CHANNEL_TOLERANCE;
}
function hslToRgb(H, S, L, alpha = 1) {
const h = (((H % 360) + 360) % 360) / 360;
const s = Math.max(0, Math.min(1, S));
const l = Math.max(0, Math.min(1, L));
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
return {
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
g: Math.round(hue2rgb(p, q, h) * 255),
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
a: alpha,
};
}
function parseDesignColor(value) {
const text = String(value || '').trim();
const parsed = parseAnyColor(text);
if (parsed) return parsed;
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
if (hsl) {
return hslToRgb(
parseFloat(hsl[1]),
parseFloat(hsl[2]) / 100,
parseFloat(hsl[3]) / 100,
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
);
}
return null;
}
function addDesignColor(out, value, label) {
const parsed = parseDesignColor(value);
if (!parsed) return;
const key = colorKey(parsed);
if (!out.allowedColorKeys.has(key)) {
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
}
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
}
function addColorObject(out, colors, prefix = 'colors') {
if (!colors || typeof colors !== 'object') return;
for (const [name, value] of Object.entries(colors)) {
if (typeof value === 'string') {
addDesignColor(out, value, `${prefix}.${name}`);
}
}
}
function addSidecarColors(out, sidecar) {
const colorMeta = sidecar?.extensions?.colorMeta;
if (!colorMeta || typeof colorMeta !== 'object') return;
for (const [name, meta] of Object.entries(colorMeta)) {
if (!meta || typeof meta !== 'object') continue;
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
if (Array.isArray(meta.tonalRamp)) {
for (const [index, value] of meta.tonalRamp.entries()) {
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
}
}
}
}
function addTypographyFonts(out, typography) {
if (!typography || typeof typography !== 'object') return;
for (const role of Object.values(typography)) {
if (!role || typeof role !== 'object') continue;
if (typeof role.fontFamily !== 'string') continue;
for (const font of splitFontStack(role.fontFamily)) {
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
}
}
}
function addRoundedScale(out, rounded) {
if (!rounded || typeof rounded !== 'object') return;
for (const [rawName, value] of Object.entries(rounded)) {
const name = unquoteYamlKey(rawName).toLowerCase();
addRoundedToken(out, name, value);
}
}
function addRoundedToken(out, name, value) {
if (typeof value !== 'string' && typeof value !== 'number') return;
const raw = String(value).trim();
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
const px = resolveLengthPx(raw, 16);
if (px == null || !Number.isFinite(px)) return;
out.allowedRadii.push({ name, value: raw, px });
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
}
function addSidecarRadii(out, sidecar) {
const roundedMeta = sidecar?.extensions?.roundedMeta;
if (!roundedMeta || typeof roundedMeta !== 'object') return;
for (const [rawName, meta] of Object.entries(roundedMeta)) {
const name = unquoteYamlKey(rawName).toLowerCase();
if (typeof meta === 'string' || typeof meta === 'number') {
addRoundedToken(out, `sidecar.${name}`, meta);
continue;
}
if (!meta || typeof meta !== 'object') continue;
for (const key of ['canonical', 'value']) {
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
}
}
for (const key of ['values', 'aliases']) {
if (!Array.isArray(meta[key])) continue;
for (const [index, value] of meta[key].entries()) {
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
}
}
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
out.hasPillRadius = true;
}
}
}
function normalizeDesignSystem(input = {}) {
const frontmatter = input.frontmatter || {};
const sidecar = input.sidecar || null;
const out = {
present: true,
sourcePath: input.sourcePath || null,
sidecarPath: input.sidecarPath || null,
mdNewerThanJson: input.mdNewerThanJson === true,
allowedFonts: new Set(),
allowedColorKeys: new Map(),
allowedRadii: [],
hasPillRadius: false,
};
addTypographyFonts(out, frontmatter.typography);
addColorObject(out, frontmatter.colors);
addSidecarColors(out, sidecar);
addRoundedScale(out, frontmatter.rounded);
addSidecarRadii(out, sidecar);
out.hasFonts = out.allowedFonts.size > 0;
out.hasColors = out.allowedColorKeys.size > 0;
out.hasRadii = out.allowedRadii.length > 0;
return out;
}
function loadDesignSystemForCwd(cwd = process.cwd()) {
const md = resolveDesignMdPath(cwd);
if (!md) return null;
let frontmatter = null;
let mdStat = null;
try {
mdStat = fs.statSync(md.path);
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
} catch {
return null;
}
if (!frontmatter || typeof frontmatter !== 'object') return null;
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
const sidecar = safeReadJson(sidecarPath);
let sidecarStat = null;
try {
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
} catch {
sidecarStat = null;
}
return normalizeDesignSystem({
frontmatter,
sidecar,
sourcePath: md.path,
sidecarPath,
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
});
}
function isAllowedFont(font, designSystem) {
if (!font || GENERIC_FONTS.has(font)) return true;
if (!designSystem?.hasFonts) return true;
return designSystem.allowedFonts.has(font);
}
function isAllowedColorRaw(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseDesignColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
for (const entry of designSystem.allowedColorKeys.values()) {
if (colorsClose(parsed, entry.color)) return true;
}
return false;
}
function isAllowedRadiusRaw(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
}
function lineLooksCommented(line) {
const trimmed = String(line || '').trim();
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
}
function isProbablyColorLiteral(line, match) {
const raw = match?.[0] || '';
const index = match.index ?? -1;
if (index < 0) return false;
if (isInsideCssAttributeSelector(line, index)) return false;
const before = line.slice(0, index);
const after = line.slice(index + raw.length);
if (raw.startsWith('#')) {
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. &#8596;
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
}
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
return styleContext || cssFunctionContext || jsColorKeyContext;
}
function isInsideCssAttributeSelector(line, index) {
if (index < 0) return false;
const before = line.slice(0, index);
const lastOpen = before.lastIndexOf('[');
if (lastOpen === -1) return false;
const lastClose = before.lastIndexOf(']');
if (lastClose > lastOpen) return false;
const after = line.slice(index);
const close = after.indexOf(']');
const block = after.indexOf('{');
return close !== -1 && (block === -1 || close < block);
}
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
return { ...finding(id, filePath, snippet, line), ...extras };
}
function decodeGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkFontStack(stack, filePath, line, designSystem, context) {
const primary = primaryFont(stack);
if (!primary || isAllowedFont(primary, designSystem)) return [];
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
return [makeDesignFinding(
'design-system-font',
filePath,
`${context}: ${display} is not declared in DESIGN.md typography`,
line,
{ ignoreValue: display },
)];
}
function extractRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function checkRadiusValue(value, filePath, line, designSystem, context) {
const findings = [];
for (const token of extractRadiusTokens(value)) {
if (isAllowedRadiusRaw(token, designSystem)) continue;
findings.push(makeDesignFinding(
'design-system-radius',
filePath,
`${context}: ${token} is outside the DESIGN.md rounded scale`,
line,
{ ignoreValue: token },
));
}
return findings;
}
function checkSourceDesignSystem(content, filePath, options = {}) {
const designSystem = options.designSystem;
if (!designSystem?.present) return [];
const findings = [];
const lines = String(content || '').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineNum = i + 1;
if (lineLooksCommented(line)) continue;
if (designSystem.hasFonts) {
for (const match of line.matchAll(FONT_DECL_RE)) {
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
}
for (const match of line.matchAll(FONT_JS_RE)) {
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
}
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
const url = match[0];
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
if (!font || isAllowedFont(font, designSystem)) continue;
const display = decodeGoogleFamily(familyMatch[1]);
findings.push(makeDesignFinding(
'design-system-font',
filePath,
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
lineNum,
{ ignoreValue: display },
));
}
}
}
if (designSystem.hasColors) {
for (const match of line.matchAll(CSS_COLOR_RE)) {
if (!isProbablyColorLiteral(line, match)) continue;
const raw = cssColorLabel(match[0]);
if (isAllowedColorRaw(raw, designSystem)) continue;
findings.push(makeDesignFinding(
'design-system-color',
filePath,
`Undocumented color ${raw} is outside DESIGN.md colors`,
lineNum,
{ ignoreValue: raw },
));
}
}
if (designSystem.hasRadii) {
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
}
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
}
}
}
return dedupeDesignFindings(findings);
}
function hasDirectText(el) {
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function sampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
if (!designSystem?.present) return [];
const findings = [];
const seenFonts = new Set();
const seenColors = new Set();
const seenRadii = new Set();
for (const el of document.querySelectorAll('*')) {
if (shouldSkipStaticDesignElement(el, window)) continue;
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = window.getComputedStyle(el);
if (designSystem.hasFonts && hasDirectText(el)) {
const font = primaryFont(style.fontFamily || '');
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
seenFonts.add(font);
findings.push(makeDesignFinding(
'design-system-font',
filePath,
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
0,
{ ignoreValue: font },
));
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = cssColorLabel(raw);
if (isAllowedColorRaw(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seenColors.has(key)) continue;
seenColors.add(key);
findings.push(makeDesignFinding(
'design-system-color',
filePath,
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
0,
{ ignoreValue: label },
));
}
}
if (designSystem.hasRadii) {
const rawRadius = String(style.borderRadius || '').trim();
if (!rawRadius) continue;
for (const token of extractRadiusTokens(rawRadius)) {
if (isAllowedRadiusRaw(token, designSystem)) continue;
if (seenRadii.has(token)) continue;
seenRadii.add(token);
findings.push(makeDesignFinding(
'design-system-radius',
filePath,
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
0,
{ ignoreValue: token },
));
}
}
}
return findings;
}
function shouldSkipStaticDesignElement(el, window) {
const tag = el.tagName?.toLowerCase?.() || '';
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
let current = el;
while (current) {
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
const style = window.getComputedStyle(current);
const display = String(style.display || '').toLowerCase();
const visibility = String(style.visibility || '').toLowerCase();
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
current = current.parentElement;
}
return false;
}
function isTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseDesignColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function canonicalDesignFindingKey(item) {
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
const value = item.ignoreValue || item.value || '';
if (item.antipattern === 'design-system-font') {
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
const font = normalizeFontName(value);
return font ? `${item.antipattern}:${context}:${font}` : null;
}
if (item.antipattern === 'design-system-color') {
const parsed = parseDesignColor(value);
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
const label = cssColorLabel(value).toLowerCase();
return label ? `${item.antipattern}:color:${label}` : null;
}
if (item.antipattern === 'design-system-radius') {
const px = resolveLengthPx(String(value || '').trim(), 16);
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
const label = String(value || '').trim().toLowerCase();
return label ? `${item.antipattern}:radius:${label}` : null;
}
return null;
}
function mergeDesignSystemFindings(...groups) {
const out = [];
const seen = new Map();
for (const group of groups) {
for (const item of group || []) {
const key = canonicalDesignFindingKey(item);
if (key) {
if (seen.has(key)) {
const existing = out[seen.get(key)];
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
continue;
}
seen.set(key, out.length);
}
out.push(item);
}
}
return out;
}
function dedupeDesignFindings(findings) {
const out = [];
const seen = new Set();
for (const item of findings) {
const key = [
item.antipattern,
item.line || 0,
normalizeFontName(item.ignoreValue || item.snippet || ''),
].join('\0');
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
export {
parseFrontmatter,
normalizeDesignSystem,
loadDesignSystemForCwd,
isAllowedFont,
isAllowedColorRaw,
isAllowedRadiusRaw,
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
mergeDesignSystemFindings,
};
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
skillSection: 'Layout & Space',
skillGuideline: 'overflow container clipping positioned children',
},
{
id: 'design-system-font',
category: 'quality',
name: 'Font outside DESIGN.md',
description:
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
skillSection: 'Typography',
skillGuideline: 'font family outside the project design system',
},
{
id: 'design-system-color',
category: 'quality',
severity: 'advisory',
name: 'Color outside DESIGN.md',
description:
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
skillSection: 'Color & Contrast',
skillGuideline: 'literal color outside the project design system',
},
{
id: 'design-system-radius',
category: 'quality',
severity: 'advisory',
name: 'Radius outside DESIGN.md',
description:
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
skillSection: 'Visual Details',
skillGuideline: 'border radius outside the project design system',
},
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
{
@@ -449,6 +478,17 @@ const ANTIPATTERNS = [
skillSection: 'Visual Details',
skillGuideline: 'repeating-gradient decorative stripes',
},
{
id: 'codex-grid-background',
category: 'slop',
severity: 'advisory',
gated: 'gpt',
name: 'Decorative grid-line background',
description:
'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
skillSection: 'Visual Details',
skillGuideline: 'two-axis grid-line gradient background',
},
{
id: 'theater-slop-phrase',
category: 'slop',
@@ -1084,9 +1124,13 @@ function checkHtmlPatterns(html) {
// --- Motion ---
// Bounce/elastic animation names
const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
if (bounceRe.test(html)) {
findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
const bounceMatch = bounceRe.exec(html);
if (bounceMatch) {
const animationToken = bounceMatch[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
}
// Overshoot cubic-bezier
@@ -1139,6 +1183,42 @@ function checkHtmlPatterns(html) {
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
}
// --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
// The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
// transparent 1px)` layers (one per axis) tiled by a repeating
// `background-size` cell. Both signals must co-occur in the SAME style block
// (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
// tiling background-size is a fixed crosshair, not a grid, and a single
// hairline is a legitimate ruled line. Scoping to one block also stops
// unrelated single-axis rules on separate elements from adding up across the
// page. Count hairlines only inside `background`/`background-image` values so
// a hairline in an unrelated property (mask-image, border-image) can't stand
// in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
// nested parens, so match the hairline stop directly rather than parsing
// whole gradient layers.
{
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
let blk;
while ((blk = blockRe.exec(html)) !== null) {
const block = blk[1] || blk[2] || blk[3] || '';
if (!gridSizeRe.test(block)) continue;
let hairlineCount = 0;
let bm;
bgDeclRe.lastIndex = 0;
while ((bm = bgDeclRe.exec(block)) !== null) {
const stops = bm[1].match(hairlineRe);
if (stops) hairlineCount += stops.length;
}
if (hairlineCount >= 2) {
findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
break;
}
}
}
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
// runs in the bundled browser path too, not just the CLI/static path.
@@ -4390,6 +4470,7 @@ if (IS_BROWSER) {
category: ap ? ap.category : 'quality',
severity: ap?.severity || 'warning',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
description: ap ? ap.description : '',
};
@@ -4426,10 +4507,203 @@ if (IS_BROWSER) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
const DESIGN_COLOR_TOLERANCE = 6;
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function normalizeBrowserFontName(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function browserPrimaryFont(stack) {
if (!stack || /var\(/i.test(stack)) return '';
return String(stack || '')
.split(',')
.map(normalizeBrowserFontName)
.find(font => font && !GENERIC_FONTS.has(font)) || '';
}
function browserDesignSystemConfig() {
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
if (!raw?.present) return null;
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
const allowedColors = (raw.allowedColors || [])
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b }));
const allowedRadii = (raw.allowedRadii || [])
.map(Number)
.filter(px => Number.isFinite(px));
return {
present: true,
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
allowedFonts,
hasColors: raw.hasColors === true && allowedColors.length > 0,
allowedColors,
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
allowedRadii,
hasPillRadius: raw.hasPillRadius === true,
};
}
function browserColorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= DESIGN_COLOR_TOLERANCE;
}
function isBrowserDesignColorAllowed(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseAnyColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
}
function isBrowserTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseAnyColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function isBrowserDesignRadiusAllowed(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
}
function browserRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function browserHasDirectText(el) {
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function browserSampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function shouldSkipDesignElement(el) {
const tag = el.tagName?.toLowerCase?.() || '';
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
}
function checkElementDesignSystemDOM(el, designSystem, seen) {
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
const findings = [];
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = getComputedStyle(el);
if (designSystem.hasFonts && browserHasDirectText(el)) {
const font = browserPrimaryFont(style.fontFamily || '');
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
ignoreValue: font,
});
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = String(raw || '').trim().replace(/\s+/g, ' ');
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seen.colors.has(key)) continue;
seen.colors.add(key);
findings.push({
type: 'design-system-color',
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
ignoreValue: label,
});
}
}
if (designSystem.hasRadii) {
for (const token of browserRadiusTokens(style.borderRadius || '')) {
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
if (seen.radii.has(token)) continue;
seen.radii.add(token);
findings.push({
type: 'design-system-radius',
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
ignoreValue: token,
});
}
}
return findings;
}
function decodeBrowserGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkBrowserDesignSystemSources(designSystem, seen) {
if (!designSystem?.hasFonts) return [];
const findings = [];
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
const href = link.getAttribute('href') || '';
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
const display = decodeBrowserGoogleFamily(match[1]);
const font = normalizeBrowserFontName(display);
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
ignoreValue: display,
});
}
}
return findings;
}
function collectBrowserFindings() {
const groupMap = new Map();
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
const designSystem = browserDesignSystemConfig();
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
// real browser env (detector page, live overlay, extension) running every
// check is free, so we always surface them; the gating is purely a CLI
@@ -4460,6 +4734,7 @@ if (IS_BROWSER) {
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementDesignSystemDOM(el, designSystem, designSeen),
].filter(f => _ruleOk(f.type));
addBrowserFindings(groupMap, el, findings);
@@ -4476,6 +4751,13 @@ if (IS_BROWSER) {
const pageLevelFindings = [];
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
.filter(f => _ruleOk(f.type));
if (designSourceFindings.length > 0) {
pageLevelFindings.push(...designSourceFindings);
addBrowserFindings(groupMap, document.body, designSourceFindings);
}
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
if (typoFindings.length > 0) {
pageLevelFindings.push(...typoFindings);
@@ -23,6 +23,13 @@ export {
checkHtmlPatterns,
} from './rules/checks.mjs';
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
export {
parseFrontmatter as parseDesignFrontmatter,
normalizeDesignSystem,
loadDesignSystemForCwd,
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
} from './design-system.mjs';
export { detectHtml } from './engines/static-html/detect-html.mjs';
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
function serializeDesignSystemForBrowser(designSystem) {
if (!designSystem?.present) return null;
return {
present: true,
hasFonts: designSystem.hasFonts === true,
allowedFonts: Array.from(designSystem.allowedFonts || []),
hasColors: designSystem.hasColors === true,
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
.map(entry => entry?.color)
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b })),
hasRadii: designSystem.hasRadii === true,
allowedRadii: (designSystem.allowedRadii || [])
.map(entry => Number(entry?.px))
.filter(px => Number.isFinite(px)),
hasPillRadius: designSystem.hasPillRadius === true,
};
}
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
if (options?.visualContrast === false) return [];
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
}
// Inject the browser detection script and collect results
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
await profileStepAsync(profile, {
engine: 'browser',
phase: 'scan',
ruleId: 'configure-pure-detect',
target: url,
}, () => page.evaluate(() => {
}, () => page.evaluate((designSystem) => {
window.__IMPECCABLE_CONFIG__ = {
...(window.__IMPECCABLE_CONFIG__ || {}),
autoScan: false,
...(designSystem ? { designSystem } : {}),
};
}));
}, browserDesignSystem));
await profileStepAsync(profile, {
engine: 'browser',
phase: 'scan',
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
return window.impeccableDetect({ decorate: false, serialize: true });
});
return serializedGroups.flatMap(({ findings }) =>
findings.map(f => ({ id: f.type, snippet: f.detail }))
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
);
});
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
}, () => browser.close());
}
}
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
return filterByProviders(results.map(f => {
const item = finding(f.id, url, f.snippet);
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
return item;
}), options.providers);
}
async function createBrowserDetector(options = {}) {
@@ -1,5 +1,8 @@
import { GENERIC_FONTS } from '../../shared/constants.mjs';
import { isNeutralColor } from '../../shared/color.mjs';
import { checkSourceDesignSystem } from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
import { finding } from '../../findings.mjs';
import { filterByProviders } from '../../registry/antipatterns.mjs';
import { profileFindings, profileStep } from '../../profile/profiler.mjs';
@@ -36,10 +39,11 @@ function shouldRunPageAnalyzers(content, filePath) {
}
function isNeutralBorderColor(str) {
const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
const m = str.match(/solid\s+((?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\([^)]*\)|#[0-9a-f]{3,8}\b|[a-z]+)/i);
if (!m) return false;
const c = m[1].toLowerCase();
if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
if (/^(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb)\(/i.test(c)) return isNeutralColor(c);
const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
if (hex) {
const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
@@ -56,10 +60,10 @@ function isNeutralBorderColor(str) {
const REGEX_MATCHERS = [
// --- Side-tab ---
{ id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 2 : n >= 4; },
fmt: (m) => m[0] },
{ id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 2 : n >= 3; },
fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
{ id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
@@ -110,9 +114,14 @@ const REGEX_MATCHERS = [
{ id: 'bounce-easing', regex: /\banimate-bounce\b/g,
test: () => true,
fmt: () => 'animate-bounce (Tailwind)' },
{ id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
{ id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi,
test: () => true,
fmt: (m) => m[0] },
fmt: (m) => {
const token = m[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
return `animation: ${token || m[1].trim()}`;
} },
{ id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
test: (m) => {
const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
@@ -498,6 +507,15 @@ function detectText(content, filePath, options = {}) {
}));
}
if (options?.designSystem) {
findings.push(...profileFindings(profile, {
engine: 'regex',
phase: 'source',
ruleId: 'design-system',
target: filePath,
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
}
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
const deduped = [];
for (const f of findings) {
@@ -532,7 +550,10 @@ function detectText(content, filePath, options = {}) {
}
}
return filterByProviders(deduped, options?.providers);
const byProvider = filterByProviders(deduped, options?.providers);
// Inline `impeccable-disable*` waivers travel with the file; honor them unless
// explicitly bypassed (`--no-config` / `--no-inline-ignores`).
return options?.inlineIgnores === false ? byProvider : applyInlineIgnores(byProvider, content);
}
export {
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
marginBottom: '0px',
marginLeft: '0px',
position: 'static',
visibility: 'visible',
top: 'auto',
right: 'auto',
bottom: 'auto',
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
'margin-bottom': 'marginBottom',
'margin-left': 'marginLeft',
'position': 'position',
'visibility': 'visibility',
'top': 'top',
'right': 'right',
'bottom': 'bottom',
@@ -2,7 +2,13 @@ import fs from 'node:fs';
import path from 'node:path';
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
import {
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
mergeDesignSystemFindings,
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
import { finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
@@ -168,6 +174,22 @@ async function detectHtml(filePath, options = {}) {
}
}
if (options?.designSystem) {
const sourceDesignFindings = profileFindings(profile, {
engine: 'static-html',
phase: 'source',
ruleId: 'design-system',
target: filePath,
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
const staticDesignFindings = profileFindings(profile, {
engine: 'static-html',
phase: 'page',
ruleId: 'design-system',
target: filePath,
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
}
if (isFullPage(html)) {
const runPageCheck = (ruleId, callback) => profile
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
@@ -202,7 +224,11 @@ async function detectHtml(filePath, options = {}) {
}
}
return filterByProviders(findings, options.providers);
const byProvider = filterByProviders(findings, options.providers);
// Static-HTML findings carry no line number, so only whole-file
// `impeccable-disable` directives apply here — exactly the standalone-document
// waiver this primitive targets. Bypassed by `--no-config` / `--no-inline-ignores`.
return options?.inlineIgnores === false ? byProvider : applyInlineIgnores(byProvider, html);
}
export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
skillSection: 'Layout & Space',
skillGuideline: 'overflow container clipping positioned children',
},
{
id: 'design-system-font',
category: 'quality',
name: 'Font outside DESIGN.md',
description:
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
skillSection: 'Typography',
skillGuideline: 'font family outside the project design system',
},
{
id: 'design-system-color',
category: 'quality',
severity: 'advisory',
name: 'Color outside DESIGN.md',
description:
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
skillSection: 'Color & Contrast',
skillGuideline: 'literal color outside the project design system',
},
{
id: 'design-system-radius',
category: 'quality',
severity: 'advisory',
name: 'Radius outside DESIGN.md',
description:
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
skillSection: 'Visual Details',
skillGuideline: 'border radius outside the project design system',
},
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
{
@@ -347,6 +376,17 @@ const ANTIPATTERNS = [
skillSection: 'Visual Details',
skillGuideline: 'repeating-gradient decorative stripes',
},
{
id: 'codex-grid-background',
category: 'slop',
severity: 'advisory',
gated: 'gpt',
name: 'Decorative grid-line background',
description:
'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
skillSection: 'Visual Details',
skillGuideline: 'two-axis grid-line gradient background',
},
{
id: 'theater-slop-phrase',
category: 'slop',
@@ -514,9 +514,13 @@ function checkHtmlPatterns(html) {
// --- Motion ---
// Bounce/elastic animation names
const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
if (bounceRe.test(html)) {
findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
const bounceMatch = bounceRe.exec(html);
if (bounceMatch) {
const animationToken = bounceMatch[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
}
// Overshoot cubic-bezier
@@ -569,6 +573,42 @@ function checkHtmlPatterns(html) {
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
}
// --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
// The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
// transparent 1px)` layers (one per axis) tiled by a repeating
// `background-size` cell. Both signals must co-occur in the SAME style block
// (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
// tiling background-size is a fixed crosshair, not a grid, and a single
// hairline is a legitimate ruled line. Scoping to one block also stops
// unrelated single-axis rules on separate elements from adding up across the
// page. Count hairlines only inside `background`/`background-image` values so
// a hairline in an unrelated property (mask-image, border-image) can't stand
// in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
// nested parens, so match the hairline stop directly rather than parsing
// whole gradient layers.
{
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
let blk;
while ((blk = blockRe.exec(html)) !== null) {
const block = blk[1] || blk[2] || blk[3] || '';
if (!gridSizeRe.test(block)) continue;
let hairlineCount = 0;
let bm;
bgDeclRe.lastIndex = 0;
while ((bm = bgDeclRe.exec(block)) !== null) {
const stops = bm[1].match(hairlineRe);
if (stops) hairlineCount += stops.length;
}
if (hairlineCount >= 2) {
findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
break;
}
}
}
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
// runs in the bundled browser path too, not just the CLI/static path.
@@ -0,0 +1,148 @@
/**
* Inline, in-file ignore directives eslint-disable-style waivers that live at
* the point they apply and travel with the artifact instead of (or alongside)
* an ignore in `.impeccable/config.json`.
*
* A config ignore is the right default for repo-wide policy. This complements it
* for the one case config can't cover: a waiver that belongs to a single file and
* needs to follow that file when it leaves the repo a generated/exported
* standalone document, an emailed HTML file, a snippet scanned out of context.
*
* Comment-syntax-agnostic: the directive is a raw token matched anywhere on a
* line, so the same marker works across every comment style impeccable scans
* `//`, `/* *\/`, `<!-- -->`, `#`, `{/* *\/}`, `{# #}`. Trailing comment closers
* are stripped before the rule list is parsed.
*
* Syntax (reason optional; eslint `--` or biome `:` separator):
*
* impeccable-disable <rule>[, <rule>...] [-- reason] whole file
* impeccable-disable-line <rule>... [-- reason] the same line
* impeccable-disable-next-line <rule>... [-- reason] the following line
* impeccable-disable bare / `*` = every rule
*
* Examples:
*
* <!-- impeccable-disable overused-font -- exported brand doc, font is first-party -->
* .brand { font-family: Inter; } /* impeccable-disable-line overused-font *\/
* // impeccable-disable-next-line bounce-easing: intentional playful affordance
*
* Behavior is suppression, for parity with config ignores: a matched directive
* drops the finding. The inline reason is self-documenting in the diff; it is not
* required and is discarded at scan time (only used here to keep reason words out
* of the parsed rule list).
*/
const DIRECTIVE_RE = /impeccable-(disable-next-line|disable-line|disable)\b[ \t]*([^\n\r]*)/gi;
// Trailing comment closers, so `*/`, `*/}`, `-->`, `*}`, `#}`, `%>`, `}}` don't
// leak into the rule list. Anchored to end-of-line; the leading `\s*` mops up the
// space before the closer. `--+>` covers `-->` and any longer dash run.
const TRAILING_CLOSER_RE = /\s*(?:\*\/\}?|--+>|\*\}|#\}|%>|\}\})\s*$/;
function normalizeRule(token) {
return String(token || '').trim().toLowerCase();
}
// Split the directive remainder into rule tokens, dropping any human reason that
// follows an eslint-style `--` or biome-style `:` separator. Rule ids only ever
// contain single hyphens (`overused-font`, `bounce-easing`), so `--` and `:`
// are unambiguous separators.
function parseRuleList(remainder) {
let text = String(remainder || '').replace(TRAILING_CLOSER_RE, '').trim();
// Cut off a human reason at the first `--` (eslint) or `:` (biome) separator.
const reasonSep = text.match(/\s*(?:--+|:)\s*/);
if (reasonSep) text = text.slice(0, reasonSep.index);
const tokens = text.split(/[\s,]+/).map(normalizeRule).filter(Boolean);
if (tokens.length === 0 || tokens.includes('*')) return ['*'];
return tokens;
}
function addRules(set, rules) {
for (const rule of rules) set.add(rule);
}
function getSet(map, key) {
let set = map.get(key);
if (!set) {
set = new Set();
map.set(key, set);
}
return set;
}
/**
* Parse every inline ignore directive in a file's raw text.
*
* Returns sets keyed by the 1-based line the directive *targets* so matching is a
* direct lookup:
* - file: rules disabled for the whole file
* - line: line -> rules disabled on that exact line (disable-line)
* - nextLine: line -> rules disabled on that line (disable-next-line on line-1)
*
* `*` in any set means "every rule".
*/
function parseInlineIgnores(content) {
const result = { file: new Set(), line: new Map(), nextLine: new Map() };
const text = typeof content === 'string' ? content : '';
// Cheap bail-out: the substring must be present for any directive to exist.
// Case-insensitive to match DIRECTIVE_RE's `i` flag (e.g. `Impeccable-Disable`).
if (!/impeccable-disable/i.test(text)) return result;
// Split on `\n` only, exactly as detectText numbers lines, so directive line
// keys line up with finding `line` values (incl. on `\r`-only line endings).
// The directive regex excludes `\r`, so a trailing `\r` on `\r\n` files is
// never captured into the rule list.
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
DIRECTIVE_RE.lastIndex = 0;
let m;
while ((m = DIRECTIVE_RE.exec(lines[i])) !== null) {
const variant = m[1].toLowerCase();
const rules = parseRuleList(m[2]);
if (variant === 'disable') {
addRules(result.file, rules);
} else if (variant === 'disable-line') {
addRules(getSet(result.line, i + 1), rules);
} else {
// disable-next-line on line i+1 targets line i+2.
addRules(getSet(result.nextLine, i + 2), rules);
}
}
}
return result;
}
function setMatches(set, rule) {
return Boolean(set) && (set.has('*') || set.has(rule));
}
function isInlineIgnored(finding, directives) {
const rule = normalizeRule(finding && finding.antipattern);
if (!rule) return false;
if (setMatches(directives.file, rule)) return true;
const line = Number(finding && finding.line) || 0;
if (line > 0) {
if (setMatches(directives.line.get(line), rule)) return true;
if (setMatches(directives.nextLine.get(line), rule)) return true;
}
return false;
}
function hasDirectives(directives) {
return directives.file.size > 0 || directives.line.size > 0 || directives.nextLine.size > 0;
}
/**
* Drop findings waived by an inline directive in the same file's source text.
* Findings without a usable line number (e.g. static-HTML page-level findings)
* are only matched by whole-file directives which is the standalone-document
* case this primitive exists for.
*/
function applyInlineIgnores(findings, content) {
if (!Array.isArray(findings) || findings.length === 0) return findings;
const directives = parseInlineIgnores(content);
if (!hasDirectives(directives)) return findings;
return findings.filter((finding) => !isInlineIgnored(finding, directives));
}
export { parseInlineIgnores, applyInlineIgnores, isInlineIgnored };
+138 -52
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env node
/**
* `/impeccable hooks <on|off|status|reset>` manage the design hook
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
* in the current project.
* `/impeccable hooks <on|off|status|reset>` manage the design hook runtime
* via the `hook` key and shared detector ignores via the `detector` key in
* .impeccable/config.json / .impeccable/config.local.json.
*
* Usage:
* node hook-admin.mjs status # print current state
@@ -75,7 +75,6 @@ const HOOK_MANIFEST_TARGETS = [
skillRel: '.agents/skills/impeccable',
destRel: '.codex/hooks.json',
manifest: () => ({
description: 'Impeccable design detector: runs after Edit/Write/apply_patch on UI files and surfaces findings as system reminders.',
hooks: {
PostToolUse: [
{
@@ -83,7 +82,7 @@ const HOOK_MANIFEST_TARGETS = [
hooks: [
{
type: 'command',
command: 'node "$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs"',
command: 'node ".agents/skills/impeccable/scripts/hook.mjs"',
timeout: TIMEOUT_SECONDS,
statusMessage: STATUS_MESSAGE,
},
@@ -109,6 +108,28 @@ const HOOK_MANIFEST_TARGETS = [
},
}),
},
{
// GitHub Copilot reads repo-level hooks from `.github/hooks/*.json`. The same
// manifest is honored by the CLI (once committed to the default branch) and
// the cloud/app agent. Schema differs: lowercase `postToolUse`, flat entries,
// `bash`/`timeoutSec`, and a `matcher` regex against the `edit`/`create` tools.
provider: '.github',
skillRel: '.github/skills/impeccable',
destRel: '.github/hooks/impeccable.json',
manifest: () => ({
version: 1,
hooks: {
postToolUse: [
{
type: 'command',
matcher: 'edit|create|apply_patch',
bash: 'node "$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/hook.mjs"',
timeoutSec: TIMEOUT_SECONDS,
},
],
},
}),
},
];
function readRawConfigFile(filePath) {
@@ -120,23 +141,48 @@ function readRawConfigFile(filePath) {
}
}
// The hook settings to edit: the unified file's `hook` subtree.
function readRawConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
return unified.hook;
}
return null;
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
function hookSection(unified) {
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
? unified.hook
: null;
}
// Write the hook config back under the `hook` key of the unified file, leaving
// any sibling keys (e.g. updateCheck) untouched.
function writeConfig(cwd, hookConfig, opts = {}) {
function detectorSection(unified) {
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
? unified.detector
: null;
}
function readRawHookConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
return hookSection(unified);
}
function readRawDetectorConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
const merged = mergeDetectorConfig(hookSection(unified));
return mergeDetectorConfig(detectorSection(unified), merged);
}
function stripDetectorKeys(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
const out = {};
for (const [key, value] of Object.entries(raw)) {
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
}
return out;
}
// Write hook runtime config under `hook`, leaving detector filters in
// `detector` and preserving sibling keys such as updateCheck.
function writeHookConfig(cwd, hookConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
if (opts.local) ensureHookGitExcludes(cwd);
const existingRaw = readRawConfigFile(filePath).raw;
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
const existingHook = stripDetectorKeys(hookSection(existing));
// Merge over the existing hook object so fields the merge helpers don't manage
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
@@ -145,15 +191,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
return filePath;
}
function mergeConfig(existing) {
// Persist the full shape so /impeccable hooks edits leave a complete file
// for the user to see, not an unhelpful `{"enabled":false}`.
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
if (opts.local) ensureHookGitExcludes(cwd);
const existingRaw = readRawConfigFile(filePath).raw;
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
const nextHook = stripDetectorKeys(hookSection(existing));
const existingDetector = mergeDetectorConfig(detectorSection(existing));
const next = {
...existing,
detector: mergeDetectorConfig(detectorConfig, existingDetector),
};
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
else delete next.hook;
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
return filePath;
}
function mergeHookConfig(existing) {
const base = existing && typeof existing === 'object' ? existing : {};
return {
enabled: base.enabled === false ? false : true,
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
limits: {
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
@@ -161,28 +220,54 @@ function mergeConfig(existing) {
};
}
function mergeLocalConfig(existing) {
function mergeDetectorConfig(existing, seed = null) {
const base = existing && typeof existing === 'object' ? existing : {};
const out = {};
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
out.enabled = base.enabled === false ? false : true;
const out = seed ? {
ignoreRules: [...seed.ignoreRules],
ignoreFiles: [...seed.ignoreFiles],
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
} : {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
};
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
out.designSystem = { ...seed.designSystem };
}
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
out.designSystem = {
...(out.designSystem || {}),
enabled: base.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(base.ignoreRules)) {
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
}
if (Array.isArray(base.ignoreFiles)) {
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
}
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
if (base.limits && typeof base.limits === 'object') {
const limits = {};
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
if (Object.keys(limits).length) out.limits = limits;
if (Array.isArray(base.ignoreValues)) {
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
}
return out;
}
function mergeIgnoreValueEntries(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(ignoreValueEntryKey(entry), entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(ignoreValueEntryKey(entry), entry);
}
return Array.from(map.values());
}
function ignoreValueEntryKey(entry) {
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
return `${entry.rule}\0${entry.value}\0${files}`;
}
function statusReport(cwd) {
const shared = readRawConfigFile(getConfigPath(cwd));
const local = readRawConfigFile(getLocalConfigPath(cwd));
@@ -216,14 +301,14 @@ function statusReport(cwd) {
}
function setEnabled(cwd, value) {
const config = mergeConfig(readRawConfig(cwd));
const config = mergeHookConfig(readRawHookConfig(cwd));
config.enabled = value;
const target = writeConfig(cwd, config);
const target = writeHookConfig(cwd, config);
if (!value) {
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
}
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
const repaired = repairHookManifests(cwd);
const parts = [
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
@@ -336,7 +421,10 @@ function valueHasImpeccableHookMarker(value) {
function stripImpeccableHookEntry(entry) {
if (!entry || typeof entry !== 'object') return entry;
if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)) {
// `command`/`args`: Claude/Codex/Cursor. `bash`/`powershell`: GitHub Copilot's
// flat entry shape, where the marker lives under the shell-command keys.
if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)
|| valueHasImpeccableHookMarker(entry.bash) || valueHasImpeccableHookMarker(entry.powershell)) {
return null;
}
if (!Array.isArray(entry.hooks)) return entry;
@@ -429,18 +517,18 @@ function addIgnoreRule(cwd, args) {
if (rule === 'overused-font' && !parsed.allValues) {
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
}
const config = mergeConfig(readRawConfig(cwd));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
writeConfig(cwd, config);
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
writeDetectorConfig(cwd, config);
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
}
function addIgnoreFile(cwd, glob) {
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
const config = mergeConfig(readRawConfig(cwd));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
writeConfig(cwd, config);
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
writeDetectorConfig(cwd, config);
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
}
function parseIgnoreValueArgs(args) {
@@ -489,9 +577,7 @@ function addIgnoreValue(cwd, args) {
}
const local = parsed.local;
const config = local
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
: mergeConfig(readRawConfig(cwd, { local: false }));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
const key = `${parsed.rule}\0${parsed.value}`;
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
@@ -507,20 +593,20 @@ function addIgnoreValue(cwd, args) {
config.ignoreValues.push(entry);
}
const target = writeConfig(cwd, config, { local });
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
const target = writeDetectorConfig(cwd, config, { local });
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
}
function reset(cwd) {
const removed = [];
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
// hook subtree and keep the rest, deleting the file only if nothing remains.
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
try {
const raw = readRawConfigFile(filePath).raw;
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
const { hook, ...rest } = raw;
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
const { hook, detector, ...rest } = raw;
if (Object.keys(rest).length === 0) {
fs.unlinkSync(filePath);
} else {
@@ -18,6 +18,8 @@ import {
EDIT_COUNT_THRESHOLD,
GENERATED_PATH,
SENSITIVE_PATH,
appendDesignSystemNote,
designSystemOptions,
filterFindings,
loadDetector,
matchesAnyGlob,
@@ -333,8 +335,8 @@ function isInsideProject(filePath, cwd) {
function cursorBlockMessage(findings, filePath, config, cwd) {
const rendered = renderTemplate(findings, filePath, config, { cwd });
const blocked = rendered.replace(
'[impeccable@1] Required design corrections',
'[impeccable@1] Impeccable design hook blocked this write before it landed. Required design corrections',
'[impeccable@1] Design hook findings requiring review',
'[impeccable@1] Impeccable design hook blocked this write before it landed. Design hook findings requiring review',
);
return blocked.length > 4000 ? `${blocked.slice(0, 3984)}\n...(truncated)` : blocked;
}
@@ -415,10 +417,11 @@ async function main() {
if (!detector || typeof detector.detectText !== 'function') {
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
}
const scanOptions = designSystemOptions(config, detector, cwd);
let findings = [];
try {
findings = await detector.detectText(content, filePath);
findings = await detector.detectText(content, filePath, scanOptions);
} catch {
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
}
@@ -433,7 +436,7 @@ async function main() {
});
}
const message = cursorBlockMessage(filtered, filePath, config, cwd);
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
const sessionId = event.session_id || event.conversation_id || 'unknown';
const cache = readCache(cwd);
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
+413 -43
View File
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
enabled: true,
quiet: false,
auditLog: null,
designSystem: { enabled: true },
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
export function readConfig(cwd) {
const config = cloneDefaultConfig();
// Hook settings live under the `hook` key of config.json (shared) and
// config.local.json (per-developer, gitignored); local wins.
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
// Hook runtime settings live under `hook`; detector filters live under
// `detector`. Back-compat: older configs stored detector filters in `hook`,
// so read those first and let canonical `detector` settings win.
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
const raw = safeReadJson(filePath);
applyConfigSource(config, hookSection(raw));
applyDetectorConfigSource(config, detectorSection(raw));
}
return config;
}
@@ -148,6 +153,11 @@ function hookSection(raw) {
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
}
function detectorSection(raw) {
if (!raw || typeof raw !== 'object') return null;
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
}
function numberOr(value, fallback) {
return Number.isFinite(value) && value > 0 ? value : fallback;
}
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { ...DEFAULT_CONFIG.designSystem },
limits: { ...DEFAULT_CONFIG.limits },
};
}
function applyDetectorConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
config.designSystem = {
...config.designSystem,
enabled: raw.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
return config;
}
function applyConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
config.auditLog = raw.auditLog.trim();
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
applyDetectorConfigSource(config, raw);
if (raw.limits && typeof raw.limits === 'object') {
config.limits = {
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function colorIgnoreKey(value) {
const color = parseIgnoreColor(value);
if (!color) return '';
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
}
function parseIgnoreColor(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return null;
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) return parseHexIgnoreColor(hex[1]);
const rgb = text.match(/^rgba?\((.*)\)$/i);
if (rgb) {
const parts = splitColorArgs(rgb[1]);
if (parts.length < 3 || parts.length > 4) return null;
const r = parseRgbChannel(parts[0]);
const g = parseRgbChannel(parts[1]);
const b = parseRgbChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([r, g, b, a].some((v) => v === null)) return null;
return { r, g, b, a };
}
const hsl = text.match(/^hsla?\((.*)\)$/i);
if (hsl) {
const parts = splitColorArgs(hsl[1]);
if (parts.length < 3 || parts.length > 4) return null;
const h = parseHueChannel(parts[0]);
const s = parsePercentChannel(parts[1]);
const l = parsePercentChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([h, s, l, a].some((v) => v === null)) return null;
return hslToRgb(h, s, l, a);
}
return null;
}
function parseHexIgnoreColor(hex) {
if (hex.length === 3 || hex.length === 4) {
const r = parseInt(hex[0] + hex[0], 16);
const g = parseInt(hex[1] + hex[1], 16);
const b = parseInt(hex[2] + hex[2], 16);
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
return { r, g, b, a };
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
return { r, g, b, a };
}
function splitColorArgs(body) {
const text = String(body || '').trim();
if (!text) return [];
if (text.includes(',')) {
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
const last = parts[parts.length - 1];
if (last && last.includes('/')) {
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
return [...parts.slice(0, -1), ...split];
}
return parts;
}
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
}
function parseRgbChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const scaled = match[2] ? value * 2.55 : value;
if (scaled < 0 || scaled > 255) return null;
return Math.round(scaled);
}
function parseAlphaChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const alpha = match[2] ? value / 100 : value;
return alpha >= 0 && alpha <= 1 ? alpha : null;
}
function parseHueChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const unit = match[2] || 'deg';
if (unit === 'turn') return value * 360;
if (unit === 'rad') return value * (180 / Math.PI);
if (unit === 'grad') return value * 0.9;
return value;
}
function parsePercentChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)%$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
return value >= 0 && value <= 100 ? value / 100 : null;
}
function hslToRgb(hue, saturation, lightness, alpha) {
const h = (((hue % 360) + 360) % 360) / 360;
if (saturation === 0) {
const gray = clampByte(Math.round(lightness * 255));
return { r: gray, g: gray, b: gray, a: alpha };
}
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const toRgb = (t) => {
let channel = t;
if (channel < 0) channel += 1;
if (channel > 1) channel -= 1;
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
if (channel < 1 / 2) return q;
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
return p;
};
return {
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
g: clampByte(Math.round(toRgb(h) * 255)),
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
a: alpha,
};
}
function clampByte(value) {
return Math.min(255, Math.max(0, value));
}
function ignoreValueMatches(rule, entryValue, findingValue) {
if (entryValue === findingValue) return true;
if (rule !== 'design-system-color') return false;
const entryColor = colorIgnoreKey(entryValue);
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
}
export function normalizeIgnoreValueEntries(entries) {
if (!Array.isArray(entries)) return [];
const out = [];
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const normalized = { rule, value };
const files = uniqueStrings([
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
]);
if (files.length > 0) normalized.files = files;
if (typeof entry.reason === 'string' && entry.reason.trim()) {
normalized.reason = entry.reason.trim();
}
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
function mergeIgnoreValues(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(`${entry.rule}\0${entry.value}`, entry);
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(`${entry.rule}\0${entry.value}`, entry);
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
return Array.from(map.values());
}
function ignoreValueFilesKey(files) {
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
}
export function readCache(cwd) {
const raw = safeReadJson(getCachePath(cwd));
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
@@ -447,22 +630,54 @@ function isIgnoredFindingValue(finding, ignoreValues) {
const rule = normalizeIgnoreRule(finding.antipattern);
const value = extractFindingIgnoreValue(finding);
if (!rule || !value) return false;
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
return ignoreValues.some((entry) => {
const wildcardValue = entry.value === '*';
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
return findingMatchesScopedIgnoreFile(finding, entry.files);
});
}
function findingMatchesScopedIgnoreFile(finding, globs) {
const filePath = String(finding?.file || '').trim();
if (!filePath) return false;
if (matchesAnyGlob(filePath, globs)) return true;
const normalized = filePath.split(path.sep).join('/');
const parts = normalized.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('/');
if (matchesAnyGlob(suffix, globs)) return true;
}
return false;
}
export function extractFindingIgnoreValue(finding) {
if (!finding || typeof finding !== 'object') return '';
const rule = normalizeIgnoreRule(finding.antipattern);
if (rule !== 'overused-font') return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
const directValueRules = new Set([
'overused-font',
'bounce-easing',
'design-system-font',
'design-system-color',
'design-system-radius',
]);
if (!directValueRules.has(rule)) return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
}
function extractFindingIgnoreValueRaw(finding) {
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
if (direct) return direct;
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
for (const text of candidates) {
if (rule === 'bounce-easing') {
const motion = extractMotionIgnoreValue(text);
if (motion) return motion;
continue;
}
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
if (primary) return cleanIgnoreValueDisplay(primary[1]);
@@ -482,6 +697,24 @@ function extractFindingIgnoreValueRaw(finding) {
return '';
}
function extractMotionIgnoreValue(text) {
const tailwind = text.match(/\banimate-bounce\b/i);
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
if (animation) {
const token = animation[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
if (token) return cleanIgnoreValueDisplay(token);
}
return '';
}
function cleanIgnoreValueDisplay(value) {
return String(value || '')
.trim()
@@ -496,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
const known = new Set(fileEntry.findings || []);
const fresh = [];
for (const f of findings) {
const key = `${f.antipattern}:${f.line || 0}`;
const key = findingCacheKey(f);
if (known.has(key)) continue;
known.add(key);
fresh.push(f);
@@ -507,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
export function rememberFindings(cache, sessionId, filePath, findings) {
const fileEntry = ensureFile(cache, sessionId, filePath);
const known = new Set(fileEntry.findings || []);
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
for (const f of findings) known.add(findingCacheKey(f));
fileEntry.findings = Array.from(known);
ensureSession(cache, sessionId).updatedAt = Date.now();
}
function findingCacheKey(finding) {
const line = finding?.line || 0;
const value = extractFindingIgnoreValue(finding);
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
if (line > 0) return `${finding.antipattern}:${line}`;
if (value) return `${finding.antipattern}:0:${value}`;
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
}
export function renderTemplate(findings, filePath, config, opts = {}) {
if (!Array.isArray(findings) || findings.length === 0) return '';
const limits = config?.limits || DEFAULT_CONFIG.limits;
@@ -524,7 +767,7 @@ export function renderTemplate(findings, filePath, config, opts = {}) {
const shown = findings.slice(0, cap);
const remaining = total - shown.length;
const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
const header = `${ENVELOPE_PREFIX} Design hook findings requiring review in ${display} (${total} issue(s)):`;
const lines = shown.map((f) => formatFindingLine(f));
const more = remaining > 0
? `... and ${remaining} more (see /impeccable audit).`
@@ -556,7 +799,7 @@ function renderGroupedTemplate(groups, config, opts = {}) {
const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
const cwd = opts.cwd || process.cwd();
const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
const header = `${ENVELOPE_PREFIX} Design hook findings requiring review across ${realGroups.length} files (${total} issue(s)):`;
const lines = [];
let shownCount = 0;
@@ -716,13 +959,114 @@ export function resolveTargetFiles(event, projectCwd) {
export function resolveHarness(env = {}, event = null) {
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
if (explicit === 'cursor') return 'cursor';
if (explicit === 'github') return 'github';
if (explicit === 'claude' || explicit === 'codex') return 'claude';
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
// has no `tool_name`/`tool_input`. That shape is the discriminator.
if (event && typeof event === 'object'
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
&& event.tool_name === undefined && event.tool_input === undefined) {
return 'github';
}
if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
return 'claude';
}
// GitHub Copilot's postToolUse payload is
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
// `toolArgs` shape depends on the tool: the `edit`/`create`/`view` tools send a
// JSON *string* (double-encoded) carrying the file under `path`, e.g.
// "{\"path\":\"/abs/app.tsx\",\"old_str\":\"...\",\"new_str\":\"...\"}",
// while `apply_patch` sends a raw OpenAI-format patch string (handled below in
// normalizeGitHubEvent). The detector reads the file from disk after the tool
// ran, so only the path (not the proposed content) is needed here.
export function parseGitHubToolArgs(toolArgs) {
if (toolArgs && typeof toolArgs === 'object' && !Array.isArray(toolArgs)) return toolArgs;
if (typeof toolArgs === 'string' && toolArgs.trim()) {
try {
const parsed = JSON.parse(toolArgs);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}
return {};
}
// Copilot's `apply_patch` tool (used by interactive sessions and the cloud
// agent) sends a raw OpenAI-format patch string in toolArgs, not JSON:
// *** Begin Patch
// *** Add File: /abs/app.css
// +body { ... }
// *** End Patch
// The `view`/`edit`/`create` tools (seen in `copilot -p` runs) instead send a
// JSON string with the path under `path`. Both must map onto the internal shape.
const APPLY_PATCH_MARKER = /\*\*\* (?:Begin Patch|Add File:|Update File:|Delete File:)/;
function looksLikeApplyPatch(rawArgs) {
if (typeof rawArgs !== 'string' || !APPLY_PATCH_MARKER.test(rawArgs)) return false;
// Guard against an edit/create payload whose edited *content* happens to
// contain patch markers: that payload is a JSON object string, whereas a real
// apply_patch payload is a raw patch string that does not parse as JSON. Only
// treat non-JSON-object strings as apply_patch so edit events still get their
// `path` extracted.
try {
const parsed = JSON.parse(rawArgs);
if (parsed && typeof parsed === 'object') return false;
} catch { /* not JSON → genuine raw patch */ }
return true;
}
function applyPatchText(rawArgs) {
if (typeof rawArgs === 'string') {
if (APPLY_PATCH_MARKER.test(rawArgs)) return rawArgs;
// Defensive: a future Copilot build might JSON-wrap the patch.
const parsed = parseGitHubToolArgs(rawArgs);
return parsed.patch || parsed.input || parsed.command || '';
}
if (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)) {
return rawArgs.patch || rawArgs.input || rawArgs.command || '';
}
return '';
}
function normalizeGitHubEvent(event, projectCwd) {
const cwd = event.cwd || envProjectDir(projectCwd) || projectCwd;
const sessionId = event.sessionId || event.session_id || 'unknown';
const toolName = event.toolName || event.tool_name || null;
const toolInput = event.tool_input && typeof event.tool_input === 'object' ? { ...event.tool_input } : {};
const rawArgs = event.toolArgs;
let normalizedToolName = toolName;
if (toolName === 'apply_patch' || looksLikeApplyPatch(rawArgs)) {
// resolveTargetFiles() reads the touched paths from tool_input.command when
// tool_name is 'apply_patch', so normalize the name even if a future build
// sends the patch under a different tool label.
const patch = applyPatchText(rawArgs);
if (patch) {
toolInput.command = patch;
normalizedToolName = 'apply_patch';
}
} else {
const args = parseGitHubToolArgs(rawArgs);
const filePath = args.path || args.file_path || args.filePath || args.target_file;
if (typeof filePath === 'string' && filePath) toolInput.file_path = filePath;
}
return {
...event,
cwd,
session_id: sessionId,
tool_name: normalizedToolName,
tool_input: toolInput,
};
}
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
if (!event || typeof event !== 'object') return event;
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
if (harness !== 'cursor') return event;
const cwd = event.cwd
|| (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
@@ -918,7 +1262,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
const found = candidates.find((c) => fs.existsSync(c));
if (!found) return null;
const mod = await import(pathToFileURL(found));
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
detectorCache = {
detectText: mod.detectText,
detectHtml: mod.detectHtml,
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
};
return detectorCache;
}
@@ -953,12 +1301,12 @@ export function setDetectorForTesting(impl) {
// session" so the model knows it's a re-mind, not a new finding.
// ────────────────────────────────────────────────────────────────────────
const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
const STEER_LINE = 'That does not mean the design is good: keep following the project design system and the impeccable skill guidance.';
export function renderCleanAck(filePath, opts = {}) {
const cwd = opts.cwd || process.cwd();
const display = relativize(filePath, cwd);
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No deterministic design-quality issues found. ${STEER_LINE}`;
}
export function renderPendingAck(filePath, knownFindings, opts = {}) {
@@ -968,37 +1316,53 @@ export function renderPendingAck(filePath, knownFindings, opts = {}) {
// `knownFindings` here are the cache strings like "side-tab:3".
const sample = knownFindings.slice(0, 3).join(', ');
const more = count > 3 ? `, +${count - 3} more` : '';
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} finding(s) flagged earlier this session (${sample}${more}). Handle them before finalizing — the previous reminder still applies.`;
}
export function shouldEmitAckForFile(filePath) {
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
}
export function designSystemOptions(config, detector, projectCwd) {
if (config?.designSystem?.enabled === false) return {};
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
try {
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
return designSystem ? { designSystem } : {};
} catch {
return {};
}
}
export function appendDesignSystemNote(text, scanOptions) {
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
}
// The directive footer is the part of the hook output that steers model
// behavior. Three intentional moves:
// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
// revising..." which the model treats as a soft suggestion it can
// override when the user asked for any kind of throwaway / demo UI.
// 2. **Explicit exception clause.** Without it, the model will try to
// "fix" intentional bad fixtures, anti-pattern examples in docs, or
// test cases. Naming the exception inline beats hoping the model
// infers it from context.
// 2. **Explicit judgment clause.** Without it, the model will try to
// "fix" intentional motion, bad fixtures, anti-pattern examples in
// docs, or test cases. Naming the judgment inline beats hoping the
// model infers it from context.
// 3. **Acknowledgement instruction.** Hook output is injected as
// developer-role context, not a chat turn, so the user never sees the
// raw envelope. Asking the model to surface the fix in its reply is
// the cheapest way to make the feedback loop visible to the user.
// raw envelope. Asking the model to surface the resolution in its
// reply is the cheapest way to make the feedback loop visible.
function directiveFooter(display, opts = {}) {
const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
const fileIgnoreGuidance = opts.grouped
? 'run `/impeccable hooks ignore-file <path>` for the specific file'
: `run \`${ignoreFileCommand}\``;
return [
'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
'Handle these before finalizing: fix findings that are real design problems, or explicitly classify contextually intentional findings as false positives. Acknowledge what you changed or why you are leaving a finding unchanged.',
'',
'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
'Use context judgment before editing. A finding is not automatically a defect; literal or domain-appropriate motion, intentional demos or fixtures, documentation of bad design, and user-confirmed choices can be valid as-is.',
'',
`Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
`Do not change intentional design just to satisfy the hook, and do not silence a real finding with an inline ignore comment to skip fixing it. Suppress a finding only after the user explicitly confirms it is intentional. Prefer a config ignore (one reviewable place, the commands below); reach for an inline \`impeccable-disable <rule>\` comment only when the waiver must travel with a file that leaves the repo, such as an exported or standalone document. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
].join('\n');
}
@@ -1062,6 +1426,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
persistCache(projectCwd, cache);
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
}
const scanOptions = designSystemOptions(config, det, projectCwd);
let pendingWinner = null;
let cleanWinner = null;
@@ -1119,9 +1484,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
let findings;
let detectorThrew = false;
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
} else {
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
}
const filtered = filterFindings(findings || [], content, ext, config);
@@ -1152,7 +1517,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
if (freshGroups.length > 0) {
const firstGroup = freshGroups[0];
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
const allFindings = freshGroups.flatMap((group) => group.findings);
return {
exitCode: 0,
@@ -1184,7 +1549,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
}
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
return {
exitCode: 0,
stdout: payload(text, 'PostToolUse', harness),
@@ -1218,7 +1583,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
}
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
return {
exitCode: 0,
stdout: payload(text, 'PostToolUse', harness),
@@ -1256,6 +1621,11 @@ export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
if (harness === 'cursor') {
return JSON.stringify({ additional_context: text });
}
// GitHub Copilot's postToolUse hook injects context via a top-level
// `additionalContext` string (alongside an optional `modifiedResult`).
if (harness === 'github') {
return JSON.stringify({ additionalContext: text });
}
return JSON.stringify({
hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
});
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
stack.pop();
}
const key = content.slice(0, colonIdx).trim();
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
const parent = stack[stack.length - 1].obj;
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
return -1;
}
function unquoteYamlKey(key) {
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
return key.slice(1, -1);
}
return key;
}
function stripInlineYamlComment(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
@@ -0,0 +1,638 @@
/**
* CLI-side reader/writer for the unified `.impeccable` config.
*
* The CLI (published to npm) and the skill scripts (bundled into the install)
* live in separate trees and cannot share runtime code, so this duplicates a
* small slice of skill/scripts/hook-lib.mjs the config-path layout, detector
* ignore semantics, and the `.git/info/exclude` handling. Keep the schema,
* ignore filtering, and exclude marker in sync if either side changes.
*
* Schema (config.json shared / config.local.json gitignored, per-developer):
* {
* "detector": { "ignoreRules": [], "ignoreFiles": [], "ignoreValues": [], "designSystem": { "enabled": true } },
* "hook": { "consent": "accepted" | "declined", ... },
* "updateCheck": bool
* }
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
import { join, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
export function getConfigPath(root) {
return join(root, '.impeccable', 'config.json');
}
export function getLocalConfigPath(root) {
return join(root, '.impeccable', 'config.local.json');
}
function safeReadJson(filePath) {
try {
const raw = JSON.parse(readFileSync(filePath, 'utf-8'));
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
} catch {
return null;
}
}
function hookSection(raw) {
return raw && raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
}
function detectorSection(raw) {
return raw && raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
}
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
const DEFAULT_DETECTION_CONFIG = Object.freeze({
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { enabled: true },
});
function cloneDetectionConfig() {
return {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { ...DEFAULT_DETECTION_CONFIG.designSystem },
};
}
function cloneRawDetectionConfig() {
return {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
};
}
function applyDetectionConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
config.designSystem = {
...config.designSystem,
enabled: raw.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
return config;
}
function uniqueStrings(values) {
return Array.from(new Set(values.map(String)));
}
/**
* Detector filters shared by `npx impeccable detect` and the design hook.
* `hook.enabled` remains hook lifecycle state; manual CLI scans still run when
* the hook is disabled, but they honor the same ignore rules and design-system
* toggle.
*/
export function readDetectionConfig(root) {
const config = cloneDetectionConfig();
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
const raw = safeReadJson(filePath);
// Back-compat: old builds stored detector filters under hook.*.
applyDetectionConfigSource(config, hookSection(raw));
applyDetectionConfigSource(config, detectorSection(raw));
}
return config;
}
export function readRawDetectionConfig(root, opts = {}) {
const raw = safeReadJson(opts.local ? getLocalConfigPath(root) : getConfigPath(root));
const config = cloneRawDetectionConfig();
applyDetectionConfigSource(config, hookSection(raw));
applyDetectionConfigSource(config, detectorSection(raw));
return config;
}
export function writeDetectionConfig(root, detectorConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(root) : getConfigPath(root);
if (opts.local) ensureConfigGitExclude(root);
const existing = safeReadJson(filePath) || {};
const existingHook = hookSection(existing);
const nextHook = stripDetectorKeys(existingHook);
const nextDetector = {
...(detectorSection(existing) || {}),
...normalizeDetectionConfigForWrite(detectorConfig),
};
const next = {
...existing,
detector: nextDetector,
};
if (nextHook && Object.keys(nextHook).length > 0) {
next.hook = nextHook;
} else {
delete next.hook;
}
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
return filePath;
}
function normalizeDetectionConfigForWrite(config) {
const out = {};
if (Array.isArray(config?.ignoreRules)) {
out.ignoreRules = uniqueStrings(config.ignoreRules.map((rule) => normalizeIgnoreRule(rule)).filter(Boolean));
}
if (Array.isArray(config?.ignoreFiles)) {
out.ignoreFiles = uniqueStrings(config.ignoreFiles.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()));
}
out.ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
if (config?.designSystem && typeof config.designSystem === 'object' && !Array.isArray(config.designSystem)) {
out.designSystem = {
enabled: config.designSystem.enabled === false ? false : true,
};
}
return out;
}
function stripDetectorKeys(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const out = {};
for (const [key, value] of Object.entries(raw)) {
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
}
return out;
}
export function normalizeIgnoreValue(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function colorIgnoreKey(value) {
const color = parseIgnoreColor(value);
if (!color) return '';
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
}
function parseIgnoreColor(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return null;
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) return parseHexIgnoreColor(hex[1]);
const rgb = text.match(/^rgba?\((.*)\)$/i);
if (rgb) {
const parts = splitColorArgs(rgb[1]);
if (parts.length < 3 || parts.length > 4) return null;
const r = parseRgbChannel(parts[0]);
const g = parseRgbChannel(parts[1]);
const b = parseRgbChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([r, g, b, a].some((v) => v === null)) return null;
return { r, g, b, a };
}
const hsl = text.match(/^hsla?\((.*)\)$/i);
if (hsl) {
const parts = splitColorArgs(hsl[1]);
if (parts.length < 3 || parts.length > 4) return null;
const h = parseHueChannel(parts[0]);
const s = parsePercentChannel(parts[1]);
const l = parsePercentChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([h, s, l, a].some((v) => v === null)) return null;
return hslToRgb(h, s, l, a);
}
return null;
}
function parseHexIgnoreColor(hex) {
if (hex.length === 3 || hex.length === 4) {
const r = parseInt(hex[0] + hex[0], 16);
const g = parseInt(hex[1] + hex[1], 16);
const b = parseInt(hex[2] + hex[2], 16);
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
return { r, g, b, a };
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
return { r, g, b, a };
}
function splitColorArgs(body) {
const text = String(body || '').trim();
if (!text) return [];
if (text.includes(',')) {
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
const last = parts[parts.length - 1];
if (last && last.includes('/')) {
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
return [...parts.slice(0, -1), ...split];
}
return parts;
}
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
}
function parseRgbChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const scaled = match[2] ? value * 2.55 : value;
if (scaled < 0 || scaled > 255) return null;
return Math.round(scaled);
}
function parseAlphaChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const alpha = match[2] ? value / 100 : value;
return alpha >= 0 && alpha <= 1 ? alpha : null;
}
function parseHueChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const unit = match[2] || 'deg';
if (unit === 'turn') return value * 360;
if (unit === 'rad') return value * (180 / Math.PI);
if (unit === 'grad') return value * 0.9;
return value;
}
function parsePercentChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)%$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
return value >= 0 && value <= 100 ? value / 100 : null;
}
function hslToRgb(hue, saturation, lightness, alpha) {
const h = (((hue % 360) + 360) % 360) / 360;
if (saturation === 0) {
const gray = clampByte(Math.round(lightness * 255));
return { r: gray, g: gray, b: gray, a: alpha };
}
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const toRgb = (t) => {
let channel = t;
if (channel < 0) channel += 1;
if (channel > 1) channel -= 1;
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
if (channel < 1 / 2) return q;
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
return p;
};
return {
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
g: clampByte(Math.round(toRgb(h) * 255)),
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
a: alpha,
};
}
function clampByte(value) {
return Math.min(255, Math.max(0, value));
}
function ignoreValueMatches(rule, entryValue, findingValue) {
if (entryValue === findingValue) return true;
if (rule !== 'design-system-color') return false;
const entryColor = colorIgnoreKey(entryValue);
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
}
export function normalizeIgnoreValueEntries(entries) {
if (!Array.isArray(entries)) return [];
const out = [];
for (const entry of entries) {
if (!entry || typeof entry !== 'object') continue;
const rule = normalizeIgnoreRule(entry.rule);
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const normalized = { rule, value };
const files = uniqueStrings([
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
]);
if (files.length > 0) normalized.files = files;
if (typeof entry.reason === 'string' && entry.reason.trim()) {
normalized.reason = entry.reason.trim();
}
if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
normalized.createdAt = entry.createdAt.trim();
}
out.push(normalized);
}
return out;
}
function mergeIgnoreValues(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
return Array.from(map.values());
}
function ignoreValueFilesKey(files) {
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
}
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
function globToRegex(glob) {
let re = '^';
let i = 0;
while (i < glob.length) {
const c = glob[i];
if (c === '*') {
if (glob[i + 1] === '*') {
re += '.*';
i += 2;
if (glob[i] === '/') i += 1;
} else {
re += '[^/]*';
i += 1;
}
} else if (c === '?') {
re += '[^/]';
i += 1;
} else if (c === '{') {
const end = glob.indexOf('}', i);
if (end === -1) { re += '\\{'; i += 1; continue; }
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
re += `(?:${parts.join('|')})`;
i = end + 1;
} else if (/[.+^$()|[\]\\]/.test(c)) {
re += `\\${c}`;
i += 1;
} else {
re += c;
i += 1;
}
}
re += '$';
return new RegExp(re);
}
export function matchesAnyGlob(filePath, globs) {
if (!Array.isArray(globs) || globs.length === 0) return false;
const normalized = String(filePath || '').split(sep).join('/');
for (const glob of globs) {
try {
const re = globToRegex(String(glob));
if (re.test(normalized)) return true;
const base = normalized.split('/').pop();
if (re.test(base)) return true;
} catch {
/* malformed glob, skip */
}
}
return false;
}
export function shouldIgnoreDetectionFile(filePath, root, config) {
const globs = config?.ignoreFiles || [];
if (!Array.isArray(globs) || globs.length === 0) return false;
const raw = String(filePath || '').trim();
if (!raw) return false;
if (matchesAnyGlob(raw, globs)) return true;
try {
const abs = isAbsolute(raw) ? raw : resolve(root, raw);
if (matchesAnyGlob(abs, globs)) return true;
const rel = relative(root, abs);
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
return matchesAnyGlob(rel, globs);
}
} catch {
/* ignore */
}
return false;
}
export function filterDetectionFindings(findings, config) {
if (!Array.isArray(findings) || findings.length === 0) return [];
const ignoreRules = new Set((config?.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
const ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
return findings.filter((finding) => {
if (!finding || typeof finding !== 'object') return false;
if (ignoreRules.has(normalizeIgnoreRule(finding.antipattern))) return false;
if (isIgnoredFindingValue(finding, ignoreValues)) return false;
return true;
});
}
function isIgnoredFindingValue(finding, ignoreValues) {
if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
const rule = normalizeIgnoreRule(finding.antipattern);
const value = extractFindingIgnoreValue(finding);
if (!rule || !value) return false;
return ignoreValues.some((entry) => {
const wildcardValue = entry.value === '*';
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
return findingMatchesScopedIgnoreFile(finding, entry.files);
});
}
function findingMatchesScopedIgnoreFile(finding, globs) {
const filePath = String(finding?.file || '').trim();
if (!filePath) return false;
if (matchesAnyGlob(filePath, globs)) return true;
const normalized = filePath.split(sep).join('/');
const parts = normalized.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('/');
if (matchesAnyGlob(suffix, globs)) return true;
}
return false;
}
export function extractFindingIgnoreValue(finding) {
if (!finding || typeof finding !== 'object') return '';
const rule = normalizeIgnoreRule(finding.antipattern);
const directValueRules = new Set([
'overused-font',
'bounce-easing',
'design-system-font',
'design-system-color',
'design-system-radius',
]);
if (!directValueRules.has(rule)) return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
}
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
if (direct) return direct;
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
for (const text of candidates) {
if (rule === 'bounce-easing') {
const motion = extractMotionIgnoreValue(text);
if (motion) return motion;
continue;
}
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
if (primary) return cleanIgnoreValueDisplay(primary[1]);
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
if (family) return cleanIgnoreValueDisplay(family[1]);
const google = text.match(/[?&]family=([^&:;\n]+)/i);
if (google) {
try {
return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
} catch {
return cleanIgnoreValueDisplay(google[1]);
}
}
}
return '';
}
function extractMotionIgnoreValue(text) {
const tailwind = text.match(/\banimate-bounce\b/i);
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
if (animation) {
const token = animation[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
if (token) return cleanIgnoreValueDisplay(token);
}
return '';
}
function cleanIgnoreValueDisplay(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ');
}
/**
* The recorded design-hook decision: 'accepted' | 'declined' | undefined.
* config.local.json (per-developer) overrides config.json.
*/
export function getHookConsent(root) {
let consent;
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
const hook = hookSection(safeReadJson(filePath));
if (hook && (hook.consent === 'accepted' || hook.consent === 'declined')) consent = hook.consent;
}
return consent;
}
/**
* Persist the per-developer decision to config.local.json, preserving any
* sibling keys, and ensure the file is gitignored.
*/
export function setHookConsent(root, value) {
const filePath = getLocalConfigPath(root);
const existing = safeReadJson(filePath) || {};
const hook = hookSection(existing) || {};
const next = { ...existing, hook: { ...hook, consent: value } };
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
ensureConfigGitExclude(root);
return filePath;
}
const EXCLUDE_OPEN = '# impeccable-config-ignore-start';
const EXCLUDE_CLOSE = '# impeccable-config-ignore-end';
const EXCLUDE_PATTERNS = ['.impeccable/config.local.json'];
/**
* Add config.local.json to `.git/info/exclude` so a developer's decision is
* never committed. Idempotent via marker comments. Best-effort; returns false
* when there is no resolvable git dir.
*/
export function ensureConfigGitExclude(root) {
try {
const gitDir = resolveGitDir(root);
if (!gitDir) return false;
const target = join(gitDir, 'info', 'exclude');
const existing = existsSync(target) ? readFileSync(target, 'utf-8') : '';
const block = [EXCLUDE_OPEN, ...EXCLUDE_PATTERNS, EXCLUDE_CLOSE].join('\n');
const markerRe = new RegExp(`${escapeRegExp(EXCLUDE_OPEN)}[\\s\\S]*?${escapeRegExp(EXCLUDE_CLOSE)}`);
let updated;
if (markerRe.test(existing)) {
updated = existing.replace(markerRe, block);
} else {
const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
updated = `${prefix}${block}\n`;
}
if (updated !== existing) {
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, updated);
}
return true;
} catch {
return false;
}
}
function resolveGitDir(root) {
const dotGit = join(root, '.git');
if (!existsSync(dotGit)) return null;
try {
if (statSync(dotGit).isDirectory()) return dotGit;
// A `.git` file (worktree/submodule) points elsewhere: "gitdir: <path>".
const match = readFileSync(dotGit, 'utf-8').match(/gitdir:\s*(.+)/);
if (match) {
const resolved = match[1].trim();
return isAbsolute(resolved) ? resolved : join(root, resolved);
}
} catch {
/* fall through */
}
return null;
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
@@ -1,50 +1,52 @@
import fs from 'node:fs';
import path from 'node:path';
import { resolveProjectRoot } from '../context.mjs';
export const IMPECCABLE_DIR = '.impeccable';
export const LIVE_DIR = 'live';
export const CRITIQUE_DIR = 'critique';
export function getImpeccableDir(cwd = process.cwd()) {
return path.join(cwd, IMPECCABLE_DIR);
export function getImpeccableDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), IMPECCABLE_DIR);
}
export function getDesignSidecarPath(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), 'design.json');
export function getDesignSidecarPath(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), 'design.json');
}
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd, options = {}) {
const projectRoot = resolveProjectRoot(cwd, options);
const candidates = [
getDesignSidecarPath(cwd),
path.join(cwd, 'DESIGN.json'),
getDesignSidecarPath(cwd, options),
path.join(projectRoot, 'DESIGN.json'),
];
const contextLegacy = path.join(contextDir, 'DESIGN.json');
if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
return candidates;
}
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd, options = {}) {
return firstExisting(getDesignSidecarCandidates(cwd, contextDir, options));
}
export function getLiveDir(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), LIVE_DIR);
export function getLiveDir(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), LIVE_DIR);
}
export function getLiveConfigPath(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'config.json');
export function getLiveConfigPath(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'config.json');
}
export function getLegacyLiveConfigPath(scriptsDir) {
return path.join(scriptsDir, 'config.json');
}
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env, targetPath } = {}) {
if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
}
const primary = getLiveConfigPath(cwd);
const primary = getLiveConfigPath(cwd, { targetPath });
if (fs.existsSync(primary)) return primary;
if (scriptsDir) {
const legacy = getLegacyLiveConfigPath(scriptsDir);
@@ -53,16 +55,16 @@ export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = p
return primary;
}
export function getLiveServerPath(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'server.json');
export function getLiveServerPath(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'server.json');
}
export function getLegacyLiveServerPath(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live.json');
export function getLegacyLiveServerPath(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live.json');
}
export function readLiveServerInfo(cwd = process.cwd()) {
for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
export function readLiveServerInfo(cwd = process.cwd(), options = {}) {
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
try {
const info = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
if (info && typeof info.pid === 'number' && !isLiveServerPidReachable(info.pid)) {
@@ -88,37 +90,37 @@ export function isLiveServerPidReachable(pid) {
}
}
export function writeLiveServerInfo(cwd = process.cwd(), info) {
const filePath = getLiveServerPath(cwd);
export function writeLiveServerInfo(cwd = process.cwd(), info, options = {}) {
const filePath = getLiveServerPath(cwd, options);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(info));
return filePath;
}
export function removeLiveServerInfo(cwd = process.cwd()) {
for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
try { fs.unlinkSync(filePath); } catch {}
}
}
export function getLiveSessionsDir(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'sessions');
export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'sessions');
}
export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live', 'sessions');
export function getLegacyLiveSessionsDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'sessions');
}
export function getLiveAnnotationsDir(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'annotations');
export function getLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'annotations');
}
export function getCritiqueDir(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
export function getCritiqueDir(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), CRITIQUE_DIR);
}
export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live', 'annotations');
export function getLegacyLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'annotations');
}
function firstExisting(paths) {
@@ -0,0 +1,42 @@
class TargetArgError extends Error {
constructor(message, code) {
super(message);
this.name = 'TargetArgError';
this.code = code;
}
}
export function parseTargetPath(args = [], { strict = false } = {}) {
let targetPath = null;
for (let i = 0; i < args.length; i++) {
const arg = String(args[i]);
if (arg === '--target' || arg === '-t') {
const next = args[i + 1];
if (next && !String(next).startsWith('-')) {
targetPath = String(next);
i++;
continue;
}
if (strict) {
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
}
continue;
}
if (arg.startsWith('--target=')) {
const value = arg.slice('--target='.length);
if (value) {
targetPath = value;
continue;
}
if (strict) {
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
}
}
}
return targetPath;
}
export function parseTargetOptions(args = [], options = {}) {
const targetPath = parseTargetPath(args, options);
return targetPath ? { targetPath } : {};
}
+175 -83
View File
@@ -57,7 +57,7 @@
const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
const PREFIX = 'impeccable-live';
const PICK_CURSOR_CLASS = PREFIX + '-pick-cursor';
const PICK_CURSOR_STYLE_ID = PREFIX + '-pick-cursor-style';
const MANUAL_APPLY_STATE_TTL_MS = 15 * 60 * 1000;
const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
prefix: PREFIX,
@@ -152,6 +152,7 @@
let scrollLockTargetY = null;
let scrollLockRaf = null;
let scrollLockAbort = null;
const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';
// Dedicated key for scroll position - SEPARATE from LS_KEY so that
// saveSession's state updates don't clobber a carefully-captured scrollY.
@@ -1915,45 +1916,45 @@
syncPageInteractionCursor();
}
let pageInteractionCursorActive = false;
function ensurePickCursorStyle() {
if (document.getElementById(PREFIX + '-pick-cursor-style')) return;
const style = document.createElement('style');
style.id = PREFIX + '-pick-cursor-style';
/**
* Drive the page-level pick / insert cursor through the textContent of one
* injected <style>, never by mutating <html> (className or inline style).
* Frameworks that server-render the <html>/<body> roots (Next.js App Router)
* report a React 19 hydration mismatch when the client adds an attribute the
* server HTML never emitted, so a `class`/inline `style` toggled on
* `document.documentElement` trips "a tree hydrated but some attributes ...
* didn't match" on the next Fast-Refresh re-render. Keying the cursor off a
* stable-id <style> keeps the effect off the hydrated host elements (same
* shape as the scroll-anchor lock). A falsy cursor clears the rule.
*/
function setPageInteractionCursor(cursor) {
let style = document.getElementById(PICK_CURSOR_STYLE_ID);
if (!cursor) {
if (style) style.textContent = '';
return;
}
if (!style) {
style = document.createElement('style');
style.id = PICK_CURSOR_STYLE_ID;
// Styles the host page, not the chrome - inside the adapter's shadow UI
// root (uiAppendStyle's target) these selectors would match nothing.
(document.head || document.documentElement).appendChild(style);
}
style.textContent =
'html.' + PICK_CURSOR_CLASS + ' * { cursor: crosshair !important; }\n'
+ 'html.' + PICK_CURSOR_CLASS + ' [id^="' + PREFIX + '"],\n'
+ 'html.' + PICK_CURSOR_CLASS + ' [id^="' + PREFIX + '"] * { cursor: revert !important; }';
// Styles the host page, not the chrome - inside the adapter's shadow UI
// root (uiAppendStyle's target) these selectors would match nothing.
document.head.appendChild(style);
'* { cursor: ' + cursor + ' !important; }\n'
+ '[id^="' + PREFIX + '"],\n'
+ '[id^="' + PREFIX + '"] * { cursor: revert !important; }';
}
/** Page-level cursor while pick or insert mode is targeting page elements. */
function syncPageInteractionCursor() {
const pickCursor = state === 'PICKING' && pickActive && !insertActive;
let axisCursor = '';
if (state === 'PICKING' && insertActive) {
axisCursor = insertHoverAnchor ? cursorForInsertAxis(insertHoverAxis || 'column') : '';
}
if (pickCursor) {
ensurePickCursorStyle();
document.documentElement.classList.add(PICK_CURSOR_CLASS);
document.documentElement.style.cursor = '';
pageInteractionCursorActive = true;
return;
}
document.documentElement.classList.remove(PICK_CURSOR_CLASS);
if (axisCursor) {
document.documentElement.style.cursor = axisCursor;
pageInteractionCursorActive = true;
} else if (pageInteractionCursorActive) {
document.documentElement.style.cursor = '';
pageInteractionCursorActive = false;
let cursor = '';
if (state === 'PICKING' && pickActive && !insertActive) {
cursor = 'crosshair';
} else if (state === 'PICKING' && insertActive && insertHoverAnchor) {
cursor = cursorForInsertAxis(insertHoverAxis || 'column');
}
setPageInteractionCursor(cursor);
}
/**
@@ -2681,12 +2682,12 @@
});
const check = el('span', {
fontSize: '15px', lineHeight: '1', flexShrink: '0',
color: 'oklch(45% 0.15 145)',
color: 'oklch(45% 0.18 145)',
});
check.textContent = '\u2713';
row.appendChild(check);
const label = el('span', {
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
});
label.textContent = 'Variant applied';
row.appendChild(label);
@@ -5815,10 +5816,22 @@
try { history.scrollRestoration = 'manual'; } catch {}
const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
const prevBodyAnchor = document.body.style.overflowAnchor;
document.documentElement.style.overflowAnchor = 'none';
document.body.style.overflowAnchor = 'none';
// Suppress the browser's scroll-anchoring on the scroll root so it can't
// fight our manual scroll correction. Apply this as a stylesheet rule, not
// as inline `style` on <html>/<body>: those elements are server-rendered by
// frameworks like Next.js App Router, and mutating their inline style makes
// React 19 report a hydration mismatch on the next Fast-Refresh re-render.
// A <style> rule has the same computed effect without touching any hydrated
// element's attributes. Like the inline version, it is recreated on every
// startScrollLock call, so reload survival (driven by the persisted scroll
// key) is unaffected.
let anchorLockStyle = document.getElementById(SCROLL_ANCHOR_LOCK_ID);
if (!anchorLockStyle) {
anchorLockStyle = document.createElement('style');
anchorLockStyle.id = SCROLL_ANCHOR_LOCK_ID;
anchorLockStyle.textContent = 'html,body{overflow-anchor:none !important;}';
(document.head || document.documentElement).appendChild(anchorLockStyle);
}
const correct = (why) => {
scrollLockRaf = null;
@@ -5853,8 +5866,7 @@
scrollLockAbort = new AbortController();
scrollLockAbort.signal.addEventListener('abort', () => {
document.documentElement.style.overflowAnchor = prevHtmlAnchor;
document.body.style.overflowAnchor = prevBodyAnchor;
document.getElementById(SCROLL_ANCHOR_LOCK_ID)?.remove();
}, { once: true });
const sig = { signal: scrollLockAbort.signal };
// Track whether the most recent scroll came from a user gesture. We
@@ -6489,10 +6501,13 @@
) {
return;
}
if (isPageEditableElement(deepActive) && !isInlineEditActive(deepActive)) {
return;
}
// While a contenteditable text-leaf is focused, let the browser handle
// all keys except Escape. Escape cancels the current edit (restores
// original text) and blurs without saving, staying in CONFIGURING.
if (e.target.isContentEditable && inlineEditRows.some((r) => r.el === e.target)) {
if (e.target.isContentEditable && isInlineEditActive(e.target)) {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
@@ -7913,7 +7928,7 @@ void main() {
const barTopFromBottom = barRect && barRect.height > 0
? Math.max(16, window.innerHeight - barRect.top + 12)
: 16;
toastEl = el('div', {
const currentToast = el('div', {
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
transform: 'translateX(-50%) translateY(8px)',
background: C.ink, color: C.white,
@@ -7923,19 +7938,24 @@ void main() {
transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
});
toastEl.id = PREFIX + '-toast';
toastEl.textContent = message;
uiAppend(toastEl);
toastEl = currentToast;
currentToast.id = PREFIX + '-toast';
currentToast.textContent = message;
uiAppend(currentToast);
requestAnimationFrame(() => {
toastEl.style.opacity = '1';
toastEl.style.transform = 'translateX(-50%) translateY(0)';
if (toastEl !== currentToast) return;
currentToast.style.opacity = '1';
currentToast.style.transform = 'translateX(-50%) translateY(0)';
});
setTimeout(() => {
if (toastEl) {
toastEl.style.opacity = '0';
toastEl.style.transform = 'translateX(-50%) translateY(8px)';
setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
}
if (toastEl !== currentToast) return;
currentToast.style.opacity = '0';
currentToast.style.transform = 'translateX(-50%) translateY(8px)';
setTimeout(() => {
if (toastEl !== currentToast) return;
currentToast.remove();
toastEl = null;
}, 250);
}, duration);
}
@@ -8186,18 +8206,18 @@ void main() {
let voiceInterimBase = '';
/** @type {{ mode: 'steer'|'configure', input: HTMLInputElement, submit: () => void, beforeStart?: () => void } | null} */
let voiceCtx = null;
const PAGE_CHAT_COLLAPSED_W = '88px';
const PAGE_CHAT_COLLAPSED_W = '104px';
const PAGE_CHAT_PROCESSING_W = '76px';
const PAGE_CHAT_PLACEHOLDER_COLLAPSED = 'Steer…';
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
const STEER_AWAIT_TIMEOUT_MS = 120000;
const AGENT_STATUS_POLL_MS = 5000;
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
const GLOBAL_BAR_SECTION_GAP = 8;
const GLOBAL_BAR_INNER_GAP = 2;
const GLOBAL_BAR_INNER_PAD_LEFT = 2;
const PAGE_CHAT_EXPANDED_W = 'min(280px, 38vw)';
const PAGE_CHAT_EXPANDED_MAX_W = 280;
const ICON_PAGE_CHAT =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
const ICON_PAGE_VOICE =
@@ -8259,8 +8279,8 @@ void main() {
// Neutral hairline for internal control borders / dividers (was a warm
// gold rule that read as muddy champagne edges on the pill / input / count).
hairline: 'oklch(92% 0 0 / 0.12)',
text: 'oklch(84% 0.035 82)',
textDim: 'oklch(63% 0.024 82)',
text: 'oklch(91% 0 0)',
textDim: 'oklch(72% 0 0)',
accent: C.brand,
accentSoft: C.brandSoft,
exitHover: 'oklch(58% 0.15 35 / 0.18)',
@@ -8277,6 +8297,52 @@ void main() {
return barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());
}
function globalBarModeToggles() {
return [
uiGetById(PREFIX + '-pick-toggle'),
uiGetById(PREFIX + '-insert-toggle'),
uiGetById(PREFIX + '-detect-toggle'),
uiGetById(PREFIX + '-design-toggle'),
].filter(Boolean);
}
function applyGlobalBarLabelState(expandInactive, forceCollapse = false) {
globalBarModeToggles().forEach((toggle) => {
if (forceCollapse) toggle._collapseLabel?.(true);
else if (expandInactive || toggle.dataset.active === 'true') toggle._expandLabel?.();
else toggle._collapseLabel?.();
});
}
function syncGlobalBarExpandedLabels(expanded = globalBarEl?.matches(':hover')) {
const expandInactive = !!(expanded && !pageChatExpanded);
applyGlobalBarLabelState(expandInactive, pageChatExpanded);
if (expandInactive && globalBarEl && globalBarEl.scrollWidth > window.innerWidth - 16) {
applyGlobalBarLabelState(false);
}
}
function pageChatCollapsedWidthPx() {
const parsed = parseFloat(PAGE_CHAT_COLLAPSED_W);
return Number.isFinite(parsed) ? parsed : 104;
}
function pageChatExpandedWidth() {
if (!pageChatEl || !globalBarEl) return PAGE_CHAT_EXPANDED_MAX_W + 'px';
const currentChatWidth = pageChatEl.getBoundingClientRect().width || pageChatCollapsedWidthPx();
const barWidth = Math.max(globalBarEl.getBoundingClientRect().width || 0, globalBarEl.scrollWidth || 0);
const nonChatWidth = Math.max(0, barWidth - currentChatWidth);
const available = window.innerWidth - 16 - nonChatWidth;
const next = Math.max(pageChatCollapsedWidthPx(), Math.min(PAGE_CHAT_EXPANDED_MAX_W, available));
return Math.round(next) + 'px';
}
function syncPageChatExpandedWidth() {
if (!pageChatEl || !pageChatExpanded) return;
pageChatEl.style.width = pageChatExpandedWidth();
}
function syncPageChatChrome() {
if (!pageChatEl) return;
const P = pageChatPalette();
@@ -8312,6 +8378,21 @@ void main() {
&& !steerLocked;
}
function isPageEditableElement(el) {
if (!el || own(el)) return false;
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName || '')) return true;
return !!el.isContentEditable;
}
function isInlineEditActive(el) {
return !!el && inlineEditRows.some((r) => r.el === el);
}
function isPageEditableActive() {
const active = activeElementDeep();
return isPageEditableElement(active) && !isInlineEditActive(active);
}
function pageHasHostTextSelection() {
const sel = window.getSelection?.();
if (!sel || sel.isCollapsed) return false;
@@ -8325,6 +8406,7 @@ void main() {
function shouldSteerAutoFocus() {
return shouldFocusSteerChat()
&& !steerFocusSuspended
&& !isPageEditableActive()
&& performance.now() >= steerFocusPauseUntil;
}
@@ -8562,7 +8644,8 @@ void main() {
if (!pageChatEl || !pageChatInput) return false;
pageChatExpanded = true;
pageChatEl.dataset.expanded = 'true';
pageChatEl.style.width = PAGE_CHAT_EXPANDED_W;
syncGlobalBarExpandedLabels(false);
pageChatEl.style.width = pageChatExpandedWidth();
pageChatEl.style.cursor = steerLocked ? 'default' : 'text';
pageChatInput.placeholder = PAGE_CHAT_PLACEHOLDER_EXPANDED;
if (pageChatHint) {
@@ -8657,7 +8740,7 @@ void main() {
pageChatEl.setAttribute('aria-label', 'Steer the page');
pageChatExpanded = keepExpanded;
pageChatEl.dataset.expanded = keepExpanded ? 'true' : 'false';
pageChatEl.style.width = keepExpanded ? PAGE_CHAT_EXPANDED_W : PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.width = keepExpanded ? pageChatExpandedWidth() : PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.cursor = 'pointer';
if (pageChatInput) {
pageChatInput.disabled = false;
@@ -8971,6 +9054,7 @@ void main() {
pageChatEl.dataset.expanded = 'false';
pageChatEl.style.width = PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.cursor = 'pointer';
syncGlobalBarExpandedLabels(globalBarEl?.matches(':hover'));
if (blur) {
pageChatInput.blur();
pageChatInput.style.pointerEvents = 'none';
@@ -9064,9 +9148,9 @@ void main() {
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
uiAppendStyle(s);
}
@@ -9270,6 +9354,7 @@ void main() {
zIndex: Z.bar + 5,
display: 'flex', alignItems: 'stretch',
gap: '0',
width: 'max-content',
background: P.surface,
border: '1px solid ' + P.border,
borderRadius: '8px',
@@ -9277,6 +9362,8 @@ void main() {
fontFamily: FONT, fontSize: '12px', lineHeight: '1',
opacity: '0',
overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
maxWidth: 'calc(100vw - 16px)',
boxSizing: 'border-box',
transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
});
globalBarEl.id = PREFIX + '-global-bar';
@@ -9306,7 +9393,7 @@ void main() {
const agentDot = el('span', {
position: 'absolute', right: '-1px', bottom: '7px',
width: '6px', height: '6px', borderRadius: '50%',
background: 'oklch(78% 0.14 75)',
background: 'oklch(77% 0.13 82)',
boxShadow: '0 0 0 2px ' + P.surface,
display: 'none', pointerEvents: 'none',
});
@@ -9325,6 +9412,7 @@ void main() {
const inner = el('div', {
display: 'flex', alignItems: 'center',
padding: '4px 5px 4px ' + GLOBAL_BAR_INNER_PAD_LEFT + 'px', gap: GLOBAL_BAR_INNER_GAP + 'px',
flex: '0 0 auto',
});
inner.id = PREFIX + '-global-bar-inner';
globalBarEl.appendChild(inner);
@@ -9333,7 +9421,10 @@ void main() {
function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
const b = el('button', {
position: 'relative',
display: 'inline-flex', alignItems: 'center',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
boxSizing: 'border-box',
flex: '0 0 auto',
minWidth: '30px',
padding: '6px 8px', borderRadius: '7px',
border: 'none', background: 'transparent',
color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
@@ -9352,8 +9443,8 @@ void main() {
if (!labelEl) return;
labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px'; labelEl.style.transform = 'translateX(0)';
};
const collapse = () => {
if (!labelEl || b.dataset.active === 'true') return;
const collapse = (force = false) => {
if (!labelEl || (!force && b.dataset.active === 'true')) return;
labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0'; labelEl.style.transform = 'translateX(-4px)';
};
// Per-button hover only changes color (no layout). The label expand/
@@ -9408,11 +9499,11 @@ void main() {
// DESIGN.md panel toggle - quartet of color squares as the mark.
const designBtn = makeIconBtn({
id: PREFIX + '-design-toggle',
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
<span style="background:oklch(84% 0.19 80.46)"></span>
<span style="background:oklch(70% 0.12 188)"></span>
<span style="background:oklch(84% 0.035 82)"></span>
<span style="background:oklch(34% 0.014 82)"></span>
<span style="background:oklch(91% 0 0)"></span>
<span style="background:oklch(34% 0 0)"></span>
</span>`,
label: 'DESIGN.md',
ariaLabel: 'Toggle DESIGN.md panel',
@@ -9604,6 +9695,7 @@ void main() {
width: '1px', height: '18px',
background: P.hairline,
margin: '0 4px 0 2px',
flexShrink: '0',
});
inner.appendChild(divider);
@@ -9620,6 +9712,7 @@ void main() {
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
padding: '0', boxSizing: 'border-box',
width: '24px', height: '24px', borderRadius: '6px',
flexShrink: '0',
border: 'none', background: 'transparent',
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
@@ -9632,16 +9725,16 @@ void main() {
exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
inner.appendChild(exitBtn);
// Bar-level hover: expand every toggle's label at once; collapse on leave.
// Bar-level hover: expand mode labels unless Steer is using the space.
// Buttons with dataset.active="true" ignore collapse (their label stays).
const toggles = [pickBtn, insertBtn, detectBtn, designBtn];
globalBarEl.addEventListener('mouseenter', () => {
toggles.forEach((t) => t._expandLabel && t._expandLabel());
syncGlobalBarExpandedLabels(true);
syncPageChatExpandedWidth();
schedulePendingDockPosition();
setTimeout(schedulePendingDockPosition, 260);
});
globalBarEl.addEventListener('mouseleave', () => {
toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
syncGlobalBarExpandedLabels(false);
schedulePendingDockPosition();
setTimeout(schedulePendingDockPosition, 260);
});
@@ -9659,6 +9752,7 @@ void main() {
pendingDockResizeObserver.observe(globalBarEl);
}
window.addEventListener('resize', positionPendingDock);
window.addEventListener('resize', syncPageChatExpandedWidth);
requestAnimationFrame(() => {
globalBarEl.style.opacity = '1';
@@ -9705,9 +9799,7 @@ void main() {
// If the bar is currently under the cursor, keep all labels expanded -
// otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
// would collapse its label while the user's mouse is still on the bar.
if (globalBarEl && globalBarEl.matches(':hover')) {
[pickToggle, insertToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
}
syncGlobalBarExpandedLabels(globalBarEl && globalBarEl.matches(':hover'));
if (detectBadge) {
detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
@@ -9896,7 +9988,7 @@ void main() {
// Remove detection overlays
window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
setLiveState('IDLE');
document.getElementById(PREFIX + '-pick-cursor-style')?.remove();
document.getElementById(PICK_CURSOR_STYLE_ID)?.remove();
window.__IMPECCABLE_LIVE_INIT__ = false;
console.log('[impeccable] Live mode exited.');
}
@@ -9996,8 +10088,8 @@ void main() {
meta: 'oklch(55% 0 0)',
hairline: 'oklch(88% 0 0)',
hairlineSoft: 'oklch(92% 0 0)',
amber: 'oklch(70% 0.13 65)', // stale-hint accent
amberBg: 'oklch(95% 0.05 80)',
amber: 'oklch(77% 0.13 82)', // stale-hint accent
amberBg: 'oklch(89% 0.055 84)',
};
function designPanelCss(BP) {
@@ -10088,7 +10180,7 @@ void main() {
}
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
.error { color: oklch(45% 0.15 25); }
.error { color: oklch(58% 0.15 35); }
/* Stale hint */
.stale {
@@ -10240,8 +10332,8 @@ void main() {
content: ''; position: absolute; left: 4px; top: 13px;
width: 8px; height: 8px; border-radius: 50%;
}
.coll .do::before { background: oklch(62% 0.16 145); }
.coll .dont::before { background: oklch(58% 0.22 25); }
.coll .do::before { background: oklch(45% 0.18 145); }
.coll .dont::before { background: oklch(58% 0.15 35); }
.coll .overview-body {
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
+16 -11
View File
@@ -2,11 +2,11 @@
* CLI client for the live variant mode poll/reply protocol.
*
* Usage:
* npx impeccable poll # Block until browser event, print JSON
* npx impeccable poll --stream # Experimental: keep polling; one JSON line per event
* npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
* npx impeccable poll --reply <id> done # Reply "done" to event <id>
* npx impeccable poll --reply <id> error "msg" # Reply with error
* node <scripts_path>/live-poll.mjs # Block until browser event, print JSON
* node <scripts_path>/live-poll.mjs --stream # Experimental: keep polling; one JSON line per event
* node <scripts_path>/live-poll.mjs --timeout=600000 # Custom timeout (ms); default is long-poll friendly
* node <scripts_path>/live-poll.mjs --reply <id> done # Reply "done" to event <id>
* node <scripts_path>/live-poll.mjs --reply <id> error "msg" # Reply with error
*/
import { execFileSync } from 'node:child_process';
@@ -15,6 +15,11 @@ 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
@@ -27,7 +32,7 @@ const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_ed
function readServerInfo() {
const record = readLiveServerInfo(process.cwd());
if (!record) {
console.error('No running live server found. Start one with: npx impeccable live');
console.error(`No running live server found. Start one with: ${scriptCmd('live.mjs')}`);
process.exit(1);
}
return record.info;
@@ -82,7 +87,7 @@ export function parseReplyArgs(args) {
}
function validateReplyArgs({ id, status }) {
const usage = "Usage: npx impeccable poll --reply <id> <status> [--file path] [--data '<json>'] [message]";
const usage = `Usage: ${scriptCmd('live-poll.mjs')} --reply <id> <status> [--file path] [--data '<json>'] [message]`;
if (!id || id.startsWith('--')) {
const err = new Error(`${usage}\nMissing event id after --reply.`);
err.code = 'INVALID_REPLY_ARGS';
@@ -283,11 +288,11 @@ export async function runPollStream(base, token, {
function handlePollError(err) {
if (err.code === 'AUTH_FAILED') {
console.error(err.message);
console.error('Try restarting: npx impeccable live stop && npx impeccable live');
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: npx impeccable live');
console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
process.exit(1);
}
if (err.code === 'ACK_TIMEOUT') {
@@ -331,7 +336,7 @@ Harness note:
const info = readServerInfo();
const base = `http://localhost:${info.port}`;
// Reply mode: npx impeccable poll --reply <id> <status> [--file path] [--data '<json>'] [message]
// Reply mode: node <scripts_path>/live-poll.mjs --reply <id> <status> [--file path] [--data '<json>'] [message]
if (args.includes('--reply')) {
let reply;
try {
@@ -345,7 +350,7 @@ Harness note:
await postReply(base, info.token, reply);
} catch (err) {
if (err.cause?.code === 'ECONNREFUSED') {
console.error('Live server not running. Start one with: npx impeccable live');
console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
} else {
console.error('Reply failed:', err.message);
}
@@ -21,7 +21,7 @@ import path from 'node:path';
import net from 'node:net';
import { fileURLToPath } from 'node:url';
import { parseDesignMd } from './lib/design-parser.mjs';
import { resolveContextDir } from './context.mjs';
import { loadContext } from './context.mjs';
import {
assembleLiveBrowserScript,
assertLiveBrowserScriptParts,
@@ -55,7 +55,11 @@ 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 CONTEXT_DIR = resolveContextDir(process.cwd());
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
@@ -371,10 +375,7 @@ 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.
try {
fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
return true;
} catch { return false; }
return !!PROJECT_CONTEXT.hasProduct;
}
function statOrNull(filePath) {
@@ -549,8 +550,8 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
const token = url.searchParams.get('token');
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
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);
@@ -0,0 +1,30 @@
import path from 'node:path';
import { resolveProjectRoot } from './context.mjs';
import { parseTargetPath } from './lib/target-args.mjs';
export function resolveLiveTarget(cwd = process.cwd(), args = []) {
const originalCwd = path.resolve(cwd);
let targetPath = null;
try {
targetPath = parseTargetPath(args, { strict: true });
} catch (err) {
if (err?.name === 'TargetArgError') {
process.stderr.write(`${err.message}\n`);
process.exit(1);
}
throw err;
}
const absoluteTargetPath = targetPath
? path.isAbsolute(targetPath) ? targetPath : path.resolve(originalCwd, targetPath)
: null;
const projectRoot = targetPath
? resolveProjectRoot(originalCwd, { targetPath: absoluteTargetPath })
: originalCwd;
return {
originalCwd,
projectRoot,
targetPath,
absoluteTargetPath,
targetOptions: absoluteTargetPath ? { targetPath: absoluteTargetPath } : {},
};
}
@@ -2,7 +2,7 @@
* CLI helper: find an element in source and wrap it in a variant container.
*
* Usage:
* npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
* node <scripts_path>/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
+72 -21
View File
@@ -21,14 +21,16 @@ import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadContext } from './context.mjs';
import { loadContext, resolveTargetSelection } from './context.mjs';
import { resolveFiles } from './live-inject.mjs';
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
import { resolveLiveTarget } from './live-target.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function liveCli() {
const args = process.argv.slice(2);
const liveTarget = resolveLiveTarget(process.cwd(), args);
if (args.includes('--help') || args.includes('-h')) {
console.log(`Usage: node live.mjs
@@ -38,37 +40,78 @@ Prepare everything for live variant mode in a single command:
- Starts (or reuses) the live server in the background
- Injects the browser script tag
- Reads PRODUCT.md / DESIGN.md for project context
- In monorepos, choose a child app first; --target <path> is the fallback/manual path
On success, prints a JSON blob with:
{ ok, serverPort, serverToken, pageFile, hasContext, context }
{ ok, serverPort, serverToken, pageFiles, projectRoot, repoRoot, targetPath, productPath, designPath }
On target_selection_required, prints:
{ ok: false, error: "target_selection_required", targetCandidates }
On config_missing, prints:
{ ok: false, error: "config_missing", configPath, hint }
The agent should then:
1. If config_missing, create the config and re-run this script
2. Optionally open the project's dev/preview URL in the browser (see reference/live.mdnot serverPort)
3. Enter the poll loop: node live-poll.mjs`);
1. If target_selection_required, ask which app to use and rerun from that child cwd
2. If config_missing, create the config and re-run this script
3. Optionally open the project's dev/preview URL in the browser (see reference/live.mdnot serverPort)
4. Enter the poll loop: node live-poll.mjs`);
process.exit(0);
}
const targetSelection = resolveTargetSelection(liveTarget.originalCwd, liveTarget.targetOptions);
if (targetSelection) {
console.log(JSON.stringify({
ok: false,
error: 'target_selection_required',
...targetSelection,
hint: 'Ask the user which app Impeccable should use, then rerun live from that child app cwd. Use --target <path> only as a fallback or explicit path diagnostic.',
}, null, 2));
process.exit(0);
}
const ctx = loadContext(liveTarget.originalCwd, liveTarget.targetOptions);
const activeCwd = ctx.projectRoot;
const outputTargetPath = liveTarget.targetPath || null;
const missingContext = missingLiveContext(ctx);
if (missingContext.length > 0) {
console.log(JSON.stringify({
ok: false,
error: 'context_missing',
missing: missingContext,
nextCommand: missingContext.includes('PRODUCT.md') ? 'init' : 'document',
targetPath: outputTargetPath,
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
productPath: ctx.productPath,
designPath: ctx.designPath,
}, null, 2));
process.exit(0);
}
// 1. Check config (fail fast if missing — no point starting anything else)
const checkOut = runScript('live-inject.mjs', ['--check']);
const checkOut = runScript('live-inject.mjs', ['--check'], { cwd: activeCwd });
const checkResult = safeParse(checkOut);
if (!checkResult || !checkResult.ok) {
console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
console.log(JSON.stringify({
...(checkResult || { ok: false, error: 'check_failed', raw: checkOut }),
targetPath: outputTargetPath,
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
}));
process.exit(0);
}
// 2. Start server (or reuse existing)
const serverInfo = ensureServerRunning();
const serverInfo = ensureServerRunning(activeCwd);
if (!serverInfo) {
console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
process.exit(1);
}
// 3. Inject the script tag at the current port
const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)], { cwd: activeCwd });
const injectResult = safeParse(injectOut);
if (!injectResult || !injectResult.ok) {
console.log(JSON.stringify({
@@ -80,22 +123,23 @@ The agent should then:
process.exit(1);
}
// 4. Load PRODUCT.md + DESIGN.md context.
const ctx = loadContext(process.cwd());
// 5. Compute drift-heal: compare resolved inject targets against the
// 4. Compute drift-heal: compare resolved inject targets against the
// project's HTML files. Orphans are HTML files not covered by config.
// Warning only — the agent decides whether to act.
const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
const resolvedFiles = resolveFiles(activeCwd, checkResult.config);
const drift = scanForDrift(activeCwd, resolvedFiles, checkResult.config);
// 6. Emit everything the agent needs
// 5. Emit everything the agent needs
console.log(JSON.stringify({
ok: true,
serverPort: serverInfo.port,
serverToken: serverInfo.token,
pageFiles: resolvedFiles,
liveConfigPath: checkResult.path,
configDrift: drift,
targetPath: outputTargetPath,
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
hasProduct: ctx.hasProduct,
product: ctx.product,
productPath: ctx.productPath,
@@ -105,6 +149,13 @@ The agent should then:
}, null, 2));
}
function missingLiveContext(ctx) {
const missing = [];
if (!ctx.hasProduct) missing.push('PRODUCT.md');
if (!ctx.hasDesign) missing.push('DESIGN.md');
return missing;
}
/**
* Drift-heal scan. Walks the project for HTML files under common
* page-source directories (public/, src/, app/, pages/) and reports any
@@ -201,11 +252,11 @@ function globToRegex(pattern) {
// Helpers
// ---------------------------------------------------------------------------
function runScript(name, args) {
function runScript(name, args, options = {}) {
const scriptPath = path.join(__dirname, name);
const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
try {
return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
return execSync(cmd, { encoding: 'utf-8', cwd: options.cwd || process.cwd(), timeout: 15_000 });
} catch (err) {
// execSync throws on non-zero exit; return stdout if any
return err.stdout || err.message || '';
@@ -219,10 +270,10 @@ function safeParse(out) {
/**
* Return { pid, port, token } for the running live server, starting one if needed.
*/
function ensureServerRunning() {
function ensureServerRunning(cwd = process.cwd()) {
// Try to reuse an existing server
try {
const existing = readLiveServerInfo(process.cwd())?.info;
const existing = readLiveServerInfo(cwd)?.info;
if (existing && existing.pid) {
try {
process.kill(existing.pid, 0); // throws if dead
@@ -232,7 +283,7 @@ function ensureServerRunning() {
} catch { /* no PID file */ }
// Start a new server
const out = runScript('live-server.mjs', ['--background']);
const out = runScript('live-server.mjs', ['--background'], { cwd });
return safeParse(out);
}
+1 -1
View File
@@ -12,7 +12,7 @@
{
"name": "impeccable",
"description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
"version": "3.6.0",
"version": "3.9.1",
"author": {
"name": "Paul Bakaus",
"email": "paul@paulbakaus.com"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "impeccable",
"description": "Design fluency for frontend development. 1 skill with 23 commands (/impeccable polish, /impeccable audit, /impeccable critique, etc.) and curated anti-pattern detection.",
"version": "3.6.0",
"version": "3.9.1",
"author": {
"name": "Paul Bakaus",
"email": "paul@paulbakaus.com"
+3 -2
View File
@@ -1,12 +1,13 @@
---
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.6.0
version: 3.9.1
user-invocable: true
argument-hint: "[craft|shape · audit|critique · animate|bolder|colorize|delight|layout|overdrive|quieter|typeset · adapt|clarify|distill · harden|onboard|optimize|polish · init|document|extract|live] [target]"
license: Apache 2.0
allowed-tools:
- Bash(npx impeccable *)
- Bash(node .claude/skills/impeccable/scripts/*)
---
Designs and iterates production-grade frontend interfaces. Real working code, committed design choices, exceptional craft.
@@ -15,7 +16,7 @@ Designs and iterates production-grade frontend interfaces. Real working code, co
You MUST do these steps before proceeding:
1. Run `node .claude/skills/impeccable/scripts/context.mjs` once per session. 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.
1. Run `node .claude/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 .claude/skills/impeccable/scripts/context.mjs --target <path>` 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/<command>.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.
+66 -59
View File
@@ -1,12 +1,12 @@
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 and personality through stronger hierarchy, committed scale, and decisive type.
When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact by making the existing design language more decisive, specific, and committed.
---
## Register
Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
Brand: "bolder" means distinctive. Express a stronger point of view through hierarchy, pacing, proportion, copy, evidence, and one committed visual idea.
Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
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.
---
@@ -15,98 +15,105 @@ Product: "bolder" rarely means theatrics; those undermine trust. It means strong
Analyze what makes the design feel too safe or boring:
1. **Identify weakness sources**:
- **Generic choices**: System fonts, basic colors, standard layouts
- **Timid scale**: Everything is medium-sized with no drama
- **Low contrast**: Everything has similar visual weight
- **Static**: No motion, no energy, no life
- **Predictable**: Standard patterns with no surprises
- **Flat hierarchy**: Nothing stands out or commands attention
- **Generic choices**: The page could belong to any product in the category.
- **Timid scale**: Everything is medium-sized with no clear lead.
- **Low contrast**: Important and supporting elements have similar visual weight.
- **Static**: The surface has no meaningful moment of emphasis.
- **Predictable**: The composition follows a default pattern without a point of view.
- **Flat hierarchy**: Nothing stands out or commands attention.
2. **Understand the context**:
- What's the brand personality? (How far can we push?)
- What's the purpose? (Marketing can be bolder than financial dashboards)
- Who's the audience? (What will resonate?)
- What are the constraints? (Brand guidelines, accessibility, performance)
- What is the brand personality?
- What is the purpose of this surface?
- Who is the audience?
- What design system, tokens, components, and visual conventions already exist?
If any of these are unclear from the codebase, STOP and call the AskUserQuestion tool to clarify.
**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
**CRITICAL**: "Bolder" does not mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random noise.
**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
## Design-System Lock
If the project has `DESIGN.md`, tokens, theme variables, or established component styles, treat that system as the boundary. Make the existing language stronger before adding new language.
Do not invent new colors, gradients, radii, shadows, fonts, decorative backgrounds, or effects just because the request says "bolder." A bolder pass should usually change emphasis, proportion, rhythm, density, contrast, copy, artifact specificity, and layout relationships while staying inside the documented system.
If the existing system is genuinely too limited to express the bolder direction, stop and ask the user before expanding it. Name the exact additions, the role each would play, and why the current system cannot do the job. If the user approves expansion, update the design system or tokens alongside the implementation.
## Plan Amplification
Create a strategy to increase impact while maintaining coherence:
- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
- **Risk budget**: How experimental can we be? Push boundaries within constraints.
- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
- **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 across these dimensions:
Systematically increase impact through intention, not a menu of effects:
### Typography Amplification
- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and the [Reference Material section of typeset.md](typeset.md#reference-material) for inspiration)
- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
- 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 Intensification
- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
- **Dominant color strategy**: Let one bold color own 60% of the design
- **Sharp accents**: High-contrast accent colors that pop
- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
### 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 Drama
- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
- **Break the grid**: Let hero elements escape containers and cross boundaries
- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
- **Overlap**: Layer elements intentionally for depth
### 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.
### Visual Effects
- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
### 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
- **Hero moment**: One signature entrance, once. Not on every visit and not on every section.
- **Micro-interactions**: Satisfying hover effects, click feedback, state changes.
- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect).
- **Bolder scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold.
- 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
- **Hero moments**: Create clear focal points with dramatic treatment
- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
- **Full-bleed elements**: Use full viewport width/height for impact
- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
- 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 effects randomly without purpose (chaos ≠ bold)
- Sacrifice readability for aesthetics (body text must be readable)
- Make everything bold (then nothing is bold; you need contrast)
- Ignore accessibility (bold design must still meet WCAG standards)
- Overwhelm with motion (animation fatigue is real)
- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
- 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?
- **Performant**: Do all these effects run smoothly?
- **Accessible**: Does it still meet accessibility standards?
- **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."
@@ -5,8 +5,9 @@ Resolve one stable target, run two independent assessments, synthesize a design
### Hard Invariants
- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
- Assessment A and B MUST run as two isolated sub-agents whenever a sub-agent/Task tool is exposed. Running them inline in this context is "possible" but is NOT permitted; it is a degraded run. Inline is allowed ONLY when no sub-agent tool exists (or the user declined, on harnesses that ask).
- If you degrade for any reason, the report's first line MUST be a banner: `⚠️ DEGRADED: single-context (<reason>)`. 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.
- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
- Viewable targets require browser inspection when available.
- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
@@ -27,7 +28,13 @@ Resolve one stable target, run two independent assessments, synthesize a design
### Assessment Orchestration
Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
Delegate Assessment A and Assessment B to separate sub-agents. They must not see each other's output. Do not show findings to the user until synthesis.
Sub-agent gate (all harnesses):
- Unless a harness-specific gate below overrides this, spawn A and B as two isolated, parallel sub-agents whenever a sub-agent/Task tool is exposed. This is the default and is mandatory; do not run them inline because it is faster.
- "Unavailable" means exactly one thing: no sub-agent/Task tool is exposed in this session (or, on harnesses that ask, the user declined). It does not mean inconvenient.
- If and only if sub-agents are unavailable, fall back sequentially: finish and record Assessment A, then run Assessment B, then synthesize, and emit the degraded banner.
- Whichever path you take, declare it in the report header (see Report header provenance). Skipping sub-agents without the banner is the most common failure of this command.
If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
@@ -61,7 +68,7 @@ node .claude/skills/impeccable/scripts/detect.mjs --json [target]
Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
1. Create a fresh tab and navigate.
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 `<script>` tag. Read-only evaluate APIs do not count.
3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
4. If mutation is available, start `node .claude/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
@@ -79,6 +86,12 @@ The chat response is the primary user-facing deliverable. Present the full struc
Structure your feedback as a design director would:
#### Report header provenance
The report's first line MUST declare how the assessments were run, so a degraded run is never silent:
- Dual-agent: `Method: dual-agent (A: <agent-id> · B: <agent-id>)`
- Degraded: `⚠️ DEGRADED: single-context (<reason, e.g. no sub-agent tool exposed>)`
#### Design Health Score
> *Consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below.*
@@ -1,6 +1,6 @@
Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
DESIGN.md follows the [official DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
## The frontmatter: token schema
+17 -9
View File
@@ -2,11 +2,13 @@
Manage the **design detector hook** for the current project.
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), Cursor (`.cursor/hooks.json` in the project), and GitHub Copilot (`.github/hooks/impeccable.json` in the project, a team-shared committed file that both the Copilot CLI and the cloud agent read). For the Copilot CLI, repo-level hooks fire once `.github/hooks/impeccable.json` is committed to the repository's default branch.
On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
@@ -46,10 +48,10 @@ The hook itself never writes ignore config. Persist an exception only after the
Prefer the narrowest exception:
- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/config.json` by default.
- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
- For value-specific findings such as `overused-font` and `bounce-easing`, use `ignore-value` when the user confirms the specific value. Do not use `ignore-rule overused-font` for a specific font.
- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
- Prefer config ignores (the commands above) by default; they keep suppressions in one reviewable place. Reach for an inline comment only when the waiver must travel with a single file that leaves the repo (a generated/exported standalone document, an emailed HTML file). The supported marker is `impeccable-disable <rule>` (whole file) or `impeccable-disable-line` / `impeccable-disable-next-line` (one line), in any comment syntax, with an optional reason after `:` or `--`. The detector honors it by default; `--no-inline-ignores` or `--no-config` bypasses it.
Example value-specific exception:
@@ -57,6 +59,12 @@ Example value-specific exception:
node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
```
Example intentional motion exception:
```bash
node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-value bounce-easing bounce-ball --shared --reason "User confirmed ball bounce animation is intentional"
```
Example whole-rule font exception:
```bash
@@ -73,8 +81,8 @@ node .claude/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Ca
- Never modify `.impeccable/config.json` or `.impeccable/config.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
- Cursor can block a proposed write when the detector finds a real issue. Claude Code, Codex, and GitHub Copilot do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, `.cursor/hooks.json`, and `.github/hooks/impeccable.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks. On GitHub Copilot, the CLI loads `.github/hooks/impeccable.json` once it is committed to the repository's default branch, and the cloud agent reads it from the repo directly.
## Failure modes
+1 -1
View File
@@ -3,7 +3,7 @@
The setup command for a project. One codebase crawl feeds everything it writes:
- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md). Answers "how it looks".
- **`.impeccable/live/config.json`** (live mode): pre-configured so `/impeccable live` boots straight into variant mode with no first-time detour.
It closes by pointing the user at the best command to run next. Every other impeccable command reads PRODUCT.md and DESIGN.md before doing any work.
+1 -1
View File
@@ -8,7 +8,7 @@ A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR
Execute in order. No step skipped, no step reordered.
1. `live.mjs`: boot.
1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .claude/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.
2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.
3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
+712 -31
View File
@@ -5,11 +5,12 @@
* init flow.
*
* Path resolution (first match wins):
* 1. cwd, if PRODUCT.md or DESIGN.md is there
* 2. .agents/context/ then docs/
* 3. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) power-user
* 1. Active project root, if PRODUCT.md or DESIGN.md is there
* 2. Active project .agents/context/ then docs/
* 3. Monorepo root context, using the same order, as a per-file fallback
* 4. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) power-user
* escape hatch, only consulted when defaults are empty
* 4. cwd as a "nothing found" default
* 5. Active project root as a "nothing found" default
*
* `resolveContextDir()` and `loadContext()` are also exported for the
* server-side scripts (live.mjs, live-server.mjs) that need the structured
@@ -19,15 +20,30 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseTargetOptions } from './lib/target-args.mjs';
const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
const FALLBACK_DIRS = ['.agents/context', 'docs'];
const MONOREPO_MARKER_FILES = ['pnpm-workspace.yaml', 'turbo.json', 'nx.json', 'lerna.json'];
const MONOREPO_FALLBACK_PROJECT_DIRS = ['apps', 'packages'];
const WORKSPACE_DISCOVERY_IGNORED_DIRS = new Set([
'node_modules',
'.git',
'dist',
'build',
'.next',
'.nuxt',
'.svelte-kit',
'.turbo',
'.cache',
'coverage',
]);
// ─── Update check ──────────────────────────────────────────────────────────
// Piggyback a lightweight skill-version check on the once-per-session boot.
// When a newer skill ships, append an UPDATE_AVAILABLE directive so the agent
// can offer `npx impeccable skills update`. Everything here is best-effort and
// can offer `npx impeccable update`. Everything here is best-effort and
// silent on failure: a network problem, sandbox, or missing cache must never
// block context output or print an error.
@@ -38,41 +54,623 @@ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // throttle the network poll to o
const RENOTIFY_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; // don't re-surface the same version for a week
const FETCH_TIMEOUT_MS = 1200;
export function resolveContextDir(cwd = process.cwd()) {
if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return cwd;
}
for (const rel of FALLBACK_DIRS) {
const candidate = path.resolve(cwd, rel);
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return candidate;
}
}
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
if (envDir && envDir.trim()) {
const trimmed = envDir.trim();
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
}
return cwd;
export function resolveContextDir(cwd = process.cwd(), options = {}) {
return resolveContext(cwd, options).contextDir;
}
export function loadContext(cwd = process.cwd()) {
const contextDir = resolveContextDir(cwd);
const productPath = firstExisting(contextDir, PRODUCT_NAMES);
const designPath = firstExisting(contextDir, DESIGN_NAMES);
export function loadContext(cwd = process.cwd(), options = {}) {
const resolved = resolveContext(cwd, options);
const absCwd = path.resolve(cwd);
const productPath = resolved.productPath;
const designPath = resolved.designPath;
const product = productPath ? safeRead(productPath) : null;
const design = designPath ? safeRead(designPath) : null;
return {
hasProduct: !!product,
product,
productPath: productPath ? path.relative(cwd, productPath) : null,
productPath: productPath ? path.relative(absCwd, productPath) : null,
hasDesign: !!design,
design,
designPath: designPath ? path.relative(cwd, designPath) : null,
contextDir,
designPath: designPath ? path.relative(absCwd, designPath) : null,
contextDir: resolved.contextDir,
productContextDir: productPath ? path.dirname(productPath) : null,
designContextDir: designPath ? path.dirname(designPath) : null,
projectRoot: resolved.projectRoot,
repoRoot: resolved.repoRoot,
isMonorepo: resolved.isMonorepo,
};
}
function resolveContext(cwd = process.cwd(), options = {}) {
const absCwd = path.resolve(cwd);
const project = resolveProject(absCwd, options);
const projectContextDir = resolveLocalContextDir(project.projectRoot);
const rootContextDir = project.isMonorepo && project.repoRoot !== project.projectRoot
? resolveLocalContextDir(project.repoRoot)
: null;
let productPath =
(projectContextDir ? firstExisting(projectContextDir, PRODUCT_NAMES) : null)
|| (rootContextDir ? firstExisting(rootContextDir, PRODUCT_NAMES) : null);
let designPath =
(projectContextDir ? firstExisting(projectContextDir, DESIGN_NAMES) : null)
|| (rootContextDir ? firstExisting(rootContextDir, DESIGN_NAMES) : null);
let envContextDir = null;
if (!productPath && !designPath) {
envContextDir = resolveEnvContextDir(absCwd);
if (envContextDir) {
productPath = firstExisting(envContextDir, PRODUCT_NAMES);
designPath = firstExisting(envContextDir, DESIGN_NAMES);
}
}
return {
contextDir: productPath
? path.dirname(productPath)
: designPath
? path.dirname(designPath)
: envContextDir || project.projectRoot,
productPath,
designPath,
projectRoot: project.projectRoot,
repoRoot: project.repoRoot,
isMonorepo: project.isMonorepo,
targetDir: project.targetDir,
};
}
export function resolveProjectRoot(cwd = process.cwd(), options = {}) {
return resolveProject(cwd, options).projectRoot;
}
export function resolveTargetSelection(cwd = process.cwd(), options = {}) {
if (hasTargetOption(options)) return null;
const project = resolveProject(cwd);
if (
!project.isMonorepo
|| !project.projectRoot
|| !project.repoRoot
|| path.resolve(project.projectRoot) !== path.resolve(project.repoRoot)
) {
return null;
}
const targetCandidates = discoverTargetCandidates(project.repoRoot);
// No discoverable child apps (e.g. `workspaces: ["."]`, a root-only workspace,
// or a marker file with no apps/packages children): there is nothing to choose,
// so treat the repo root as the active project rather than blocking on an empty
// selection prompt that the user cannot answer.
if (targetCandidates.length === 0) return null;
return {
targetPath: null,
projectRoot: project.projectRoot,
repoRoot: project.repoRoot,
targetCandidates,
};
}
function resolveProject(cwd = process.cwd(), options = {}) {
const absCwd = path.resolve(cwd);
const targetDir = resolveTargetDir(absCwd, options);
let repoRoot = findMonorepoRoot(targetDir);
if (!repoRoot && targetDir !== absCwd) {
const cwdRepoRoot = findMonorepoRoot(absCwd);
if (cwdRepoRoot && isPathInside(targetDir, cwdRepoRoot)) {
repoRoot = cwdRepoRoot;
}
}
if (!repoRoot) {
return {
targetDir,
projectRoot: absCwd,
repoRoot: absCwd,
isMonorepo: false,
};
}
return {
targetDir,
projectRoot: resolveWorkspaceProjectRoot(repoRoot, targetDir) || repoRoot,
repoRoot,
isMonorepo: true,
};
}
function isPathInside(candidate, root) {
const rel = path.relative(root, candidate);
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function resolveLocalContextDir(root) {
if (firstExisting(root, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return root;
}
for (const rel of FALLBACK_DIRS) {
const candidate = path.resolve(root, rel);
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return candidate;
}
}
return null;
}
function resolveEnvContextDir(cwd) {
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
if (!envDir || !envDir.trim()) return null;
const trimmed = envDir.trim();
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
}
function resolveTargetDir(cwd, options = {}) {
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
if (!targetPath || !String(targetPath).trim()) return cwd;
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
try {
const stat = fs.statSync(abs);
return stat.isDirectory() ? abs : path.dirname(abs);
} catch {
return path.extname(abs) ? path.dirname(abs) : abs;
}
}
function findMonorepoRoot(startDir) {
let dir = path.resolve(startDir);
const homeDir = path.resolve(os.homedir());
while (true) {
if (dir === homeDir) return null;
// isMonorepoRoot is checked before hasGitBoundary on purpose: a workspace
// root that also carries its own .git is still recognized. The trade-off is
// deliberate — a directory with a monorepo *marker* but no workspace patterns
// and no apps/packages children is not a monorepo root, so its .git stops
// traversal and a further-up root is not searched. The nested .git is treated
// as an independent project boundary, which is the intended isolation.
if (isMonorepoRoot(dir)) return dir;
if (hasGitBoundary(dir)) return null;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
function isMonorepoRoot(dir) {
if (readWorkspacePatterns(dir).some((pattern) => !normalizeWorkspacePattern(pattern).startsWith('!'))) return true;
if (!MONOREPO_MARKER_FILES.some((file) => fs.existsSync(path.join(dir, file)))) return false;
return hasFallbackWorkspaceChildren(dir);
}
function hasGitBoundary(dir) {
return fs.existsSync(path.join(dir, '.git'));
}
function hasFallbackWorkspaceChildren(dir) {
for (const name of MONOREPO_FALLBACK_PROJECT_DIRS) {
const base = path.join(dir, name);
let entries;
try {
entries = fs.readdirSync(base, { withFileTypes: true });
} catch {
continue;
}
if (entries.some((entry) => entry.isDirectory() && !isIgnoredWorkspaceDiscoveryDir(entry.name))) return true;
}
return false;
}
function discoverTargetCandidates(repoRoot) {
const roots = new Map();
const patterns = readWorkspacePatterns(repoRoot);
for (const pattern of patterns) {
for (const root of discoverRootsForPattern(repoRoot, pattern)) {
roots.set(path.relative(repoRoot, root).split(path.sep).join('/'), root);
}
}
if (MONOREPO_MARKER_FILES.some((file) => fs.existsSync(path.join(repoRoot, file)))) {
for (const name of MONOREPO_FALLBACK_PROJECT_DIRS) {
const base = path.join(repoRoot, name);
let entries;
try {
entries = fs.readdirSync(base, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
const root = path.join(base, entry.name);
roots.set(path.relative(repoRoot, root).split(path.sep).join('/'), root);
}
}
}
return [...roots.entries()]
.filter(([rel]) => rel && !rel.startsWith('..'))
// Honor negated workspace patterns (e.g. "!packages/internal"). resolveWorkspaceProjectRoot
// sends an excluded package back to the repo root, so an excluded folder must not appear as a
// selectable target — choosing it would silently resolve to the root instead.
.filter(([rel]) => !isExcludedByWorkspacePattern(rel.split('/').filter(Boolean), patterns))
.sort(([a], [b]) => a.localeCompare(b))
.map(([rel, root]) => {
const targetExample = findTargetExample(repoRoot, root);
return {
name: path.basename(root),
path: rel,
targetExample,
...resolveCandidateContextSummary(repoRoot, root, targetExample),
};
});
}
function resolveCandidateContextSummary(repoRoot, projectRoot, targetPath) {
const ctx = resolveContext(repoRoot, { targetPath });
return {
productStatus: contextSourceStatus(ctx.productPath, repoRoot, projectRoot),
productPath: contextSourcePath(ctx.productPath, repoRoot),
designStatus: contextSourceStatus(ctx.designPath, repoRoot, projectRoot),
designPath: contextSourcePath(ctx.designPath, repoRoot),
};
}
// Selection candidates surface one of four statuses: 'child' (a canonical
// PRODUCT.md/DESIGN.md directly in the app root), 'inherited' (resolved from the
// repo root in a monorepo), 'missing' (no file found), and 'fallback'. 'fallback'
// intentionally covers two non-canonical locations: a file inside the project
// root but in a subdirectory (FALLBACK_DIRS, e.g. `.agents/context/`), and a file
// outside both the project and repo roots (IMPECCABLE_CONTEXT_DIR override).
function contextSourceStatus(filePath, repoRoot, projectRoot) {
if (!filePath) return 'missing';
const absPath = path.resolve(filePath);
const absProjectRoot = path.resolve(projectRoot);
const absRepoRoot = path.resolve(repoRoot);
if (isPathInsideOrEqual(absPath, absProjectRoot)) {
return path.dirname(absPath) === absProjectRoot ? 'child' : 'fallback';
}
if (absProjectRoot !== absRepoRoot && isPathInsideOrEqual(absPath, absRepoRoot)) {
return 'inherited';
}
return 'fallback';
}
function contextSourcePath(filePath, repoRoot) {
if (!filePath) return null;
const rel = path.relative(repoRoot, filePath);
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
return rel.split(path.sep).join('/');
}
return filePath;
}
function discoverRootsForPattern(repoRoot, rawPattern) {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern || pattern.startsWith('!')) return [];
const segments = pattern.split('/').filter(Boolean);
if (!segments.length) return [];
const firstGlobIndex = segments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1 ? segments : segments.slice(0, firstGlobIndex);
const base = path.join(repoRoot, ...literalPrefix);
if (!fs.existsSync(base)) return [];
if (segments.includes('**')) {
const packageRoots = [];
walkDirs(base, (dir) => {
if (dir !== base && isCandidateProjectRoot(dir)) packageRoots.push(dir);
});
if (packageRoots.length) return packageRoots;
return directChildDirs(base);
}
return expandSimplePattern(repoRoot, segments);
}
function expandSimplePattern(repoRoot, patternSegments, index = 0, current = repoRoot) {
if (index >= patternSegments.length) return fs.existsSync(current) ? [current] : [];
const segment = patternSegments[index];
if (!segment.includes('*')) {
return expandSimplePattern(repoRoot, patternSegments, index + 1, path.join(current, segment));
}
let entries;
try {
entries = fs.readdirSync(current, { withFileTypes: true });
} catch {
return [];
}
const roots = [];
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
if (!segmentMatches(segment, entry.name)) continue;
roots.push(...expandSimplePattern(repoRoot, patternSegments, index + 1, path.join(current, entry.name)));
}
return roots;
}
function directChildDirs(dir) {
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !isIgnoredWorkspaceDiscoveryDir(entry.name))
.map((entry) => path.join(dir, entry.name));
} catch {
return [];
}
}
function walkDirs(root, visit) {
let entries;
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
const dir = path.join(root, entry.name);
visit(dir);
walkDirs(dir, visit);
}
}
function isCandidateProjectRoot(dir) {
return !!(
fs.existsSync(path.join(dir, 'package.json'))
|| firstExisting(dir, [...PRODUCT_NAMES, ...DESIGN_NAMES])
|| fs.existsSync(path.join(dir, 'src'))
|| fs.existsSync(path.join(dir, 'app'))
|| fs.existsSync(path.join(dir, 'pages'))
|| fs.existsSync(path.join(dir, 'public'))
);
}
function isIgnoredWorkspaceDiscoveryDir(name) {
return name.startsWith('.') || WORKSPACE_DISCOVERY_IGNORED_DIRS.has(name);
}
function findTargetExample(repoRoot, projectRoot) {
const examples = [
'src/App.jsx',
'src/App.tsx',
'src/main.jsx',
'src/main.tsx',
'src/index.jsx',
'src/index.ts',
'app/page.tsx',
'pages/index.tsx',
'public/index.html',
];
for (const rel of examples) {
const abs = path.join(projectRoot, rel);
if (fs.existsSync(abs)) return path.relative(repoRoot, abs).split(path.sep).join('/');
}
return path.relative(repoRoot, projectRoot).split(path.sep).join('/');
}
function resolveWorkspaceProjectRoot(repoRoot, targetDir) {
const rel = path.relative(repoRoot, targetDir);
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return repoRoot;
const relSegments = rel.split(path.sep).filter(Boolean);
const patterns = readWorkspacePatterns(repoRoot);
const excluded = isExcludedByWorkspacePattern(relSegments, patterns);
if (!excluded) {
for (const pattern of patterns) {
const projectRoot = projectRootFromWorkspacePattern(repoRoot, relSegments, pattern);
if (projectRoot) return projectRoot;
}
}
if (excluded) return repoRoot;
if (
relSegments.length >= 2
&& MONOREPO_FALLBACK_PROJECT_DIRS.includes(relSegments[0])
) {
return path.join(repoRoot, relSegments[0], relSegments[1]);
}
const nearest = nearestProjectLikeRoot(repoRoot, targetDir);
if (nearest) return nearest;
return repoRoot;
}
function isExcludedByWorkspacePattern(relSegments, patterns) {
return patterns.some((rawPattern) => {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern.startsWith('!')) return false;
return workspacePatternMatchesRel(pattern.slice(1), relSegments);
});
}
function nearestProjectLikeRoot(repoRoot, targetDir) {
let dir = path.resolve(targetDir);
const stop = path.resolve(repoRoot);
while (dir && dir !== stop) {
if (
firstExisting(dir, [...PRODUCT_NAMES, ...DESIGN_NAMES])
|| fs.existsSync(path.join(dir, 'package.json'))
) {
return dir;
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function nearestPackageRootBetween(repoRoot, targetDir, stopDir) {
let dir = path.resolve(targetDir);
const stop = path.resolve(stopDir || repoRoot);
const root = path.resolve(repoRoot);
while (dir && dir !== stop && isPathInsideOrEqual(dir, root)) {
if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function isPathInsideOrEqual(candidate, root) {
return path.resolve(candidate) === path.resolve(root) || isPathInside(candidate, root);
}
function workspacePatternMatchesRel(pattern, relSegments) {
const patternSegments = normalizeWorkspacePattern(pattern).split('/').filter(Boolean);
if (!patternSegments.length) return false;
if (patternSegments.includes('**')) {
const firstGlobIndex = patternSegments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1
? patternSegments
: patternSegments.slice(0, firstGlobIndex);
if (relSegments.length < literalPrefix.length + 1) return false;
for (let i = 0; i < literalPrefix.length; i++) {
if (!segmentMatches(literalPrefix[i], relSegments[i])) return false;
}
return true;
}
if (relSegments.length < patternSegments.length) return false;
for (let i = 0; i < patternSegments.length; i++) {
if (!segmentMatches(patternSegments[i], relSegments[i])) return false;
}
return true;
}
function readWorkspacePatterns(repoRoot) {
return [
...readPackageWorkspaces(repoRoot),
...readPnpmWorkspaces(repoRoot),
...readLernaWorkspaces(repoRoot),
].filter(Boolean);
}
function readPackageWorkspaces(repoRoot) {
const pkg = readJson(path.join(repoRoot, 'package.json'));
const workspaces = pkg?.workspaces;
if (Array.isArray(workspaces)) return workspaces;
if (Array.isArray(workspaces?.packages)) return workspaces.packages;
return [];
}
function readLernaWorkspaces(repoRoot) {
const lerna = readJson(path.join(repoRoot, 'lerna.json'));
return Array.isArray(lerna?.packages) ? lerna.packages : [];
}
function readPnpmWorkspaces(repoRoot) {
try {
const body = fs.readFileSync(path.join(repoRoot, 'pnpm-workspace.yaml'), 'utf-8');
const patterns = [];
let inPackages = false;
for (const line of body.split(/\r?\n/)) {
const trimmed = stripYamlInlineComment(line).trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const flowMatch = trimmed.match(/^packages:\s*\[(.*)\]\s*$/);
if (flowMatch) {
patterns.push(...parseYamlFlowList(flowMatch[1]));
inPackages = false;
continue;
}
if (/^packages:\s*$/.test(trimmed)) {
inPackages = true;
continue;
}
if (inPackages && /^[A-Za-z0-9_-]+:\s*/.test(trimmed)) break;
if (inPackages) {
const match = trimmed.match(/^-\s*(.+)$/);
if (match) patterns.push(unquoteYamlValue(match[1]));
}
}
return patterns;
} catch {
return [];
}
}
function stripYamlInlineComment(line) {
let quote = null;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if ((ch === '"' || ch === "'") && line[i - 1] !== '\\') {
quote = quote === ch ? null : quote || ch;
continue;
}
if (ch === '#' && !quote) return line.slice(0, i);
}
return line;
}
function parseYamlFlowList(body) {
const items = [];
let quote = null;
let current = '';
for (let i = 0; i < body.length; i++) {
const ch = body[i];
if ((ch === '"' || ch === "'") && body[i - 1] !== '\\') {
quote = quote === ch ? null : quote || ch;
current += ch;
continue;
}
if (ch === ',' && !quote) {
const value = unquoteYamlValue(current);
if (value) items.push(value);
current = '';
continue;
}
current += ch;
}
const value = unquoteYamlValue(current);
if (value) items.push(value);
return items;
}
function unquoteYamlValue(value) {
return String(value || '')
.trim()
.replace(/^['"]|['"]$/g, '');
}
function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return null;
}
}
function projectRootFromWorkspacePattern(repoRoot, relSegments, rawPattern) {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern || pattern.startsWith('!')) return null;
const patternSegments = pattern.split('/').filter(Boolean);
if (!patternSegments.length) return null;
if (patternSegments.includes('**')) {
return projectRootFromDoubleStarPattern(repoRoot, relSegments, patternSegments);
}
if (relSegments.length < patternSegments.length) return null;
for (let i = 0; i < patternSegments.length; i++) {
if (!segmentMatches(patternSegments[i], relSegments[i])) return null;
}
return path.join(repoRoot, ...relSegments.slice(0, patternSegments.length));
}
function projectRootFromDoubleStarPattern(repoRoot, relSegments, patternSegments) {
const firstGlobIndex = patternSegments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1
? patternSegments
: patternSegments.slice(0, firstGlobIndex);
if (relSegments.length < literalPrefix.length + 1) return null;
for (let i = 0; i < literalPrefix.length; i++) {
if (!segmentMatches(literalPrefix[i], relSegments[i])) return null;
}
const prefixDir = path.join(repoRoot, ...literalPrefix);
const targetDir = path.join(repoRoot, ...relSegments);
const packageRoot = nearestPackageRootBetween(repoRoot, targetDir, prefixDir);
if (packageRoot) return packageRoot;
return path.join(repoRoot, ...relSegments.slice(0, literalPrefix.length + 1));
}
function normalizeWorkspacePattern(pattern) {
return String(pattern || '')
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/^\.\//, '')
.replace(/\/+$/, '');
}
function segmentMatches(patternSegment, relSegment) {
if (patternSegment === '*') return true;
if (!patternSegment.includes('*')) return patternSegment === relSegment;
const re = new RegExp(`^${escapeRegExp(patternSegment).replace(/\\\*/g, '[^/]*')}$`);
return re.test(relSegment);
}
function firstExisting(dir, names) {
for (const name of names) {
const abs = path.join(dir, name);
@@ -89,6 +687,10 @@ function safeRead(p) {
}
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Pull the register (`brand` or `product`) out of PRODUCT.md by looking
* for a `## Register` section and reading the first non-empty line that
@@ -172,8 +774,8 @@ function buildUpdateDirective(localVersion, latestVersion) {
`UPDATE_AVAILABLE: A newer Impeccable skill is available ` +
`(installed v${localVersion}, latest v${latestVersion}). ` +
`Before continuing, ask the user once: "A newer Impeccable (v${latestVersion}) is available. ` +
`Update now? It runs \`npx impeccable skills update\`." ` +
`If they agree, run \`npx impeccable skills update\` (the update applies to the next session, not this one). ` +
`Update now? It runs \`npx impeccable update\`." ` +
`If they agree, run \`npx impeccable update\` (the update applies to the next session, not this one). ` +
`Either way, continue the current task without waiting, and do not raise this again.`
);
}
@@ -233,7 +835,24 @@ async function computeUpdateDirective(now = Date.now()) {
}
async function cli() {
const ctx = loadContext(process.cwd());
let cliOptions;
try {
cliOptions = parseCliOptions(process.argv.slice(2));
} catch (err) {
if (err?.name === 'TargetArgError') {
process.stderr.write(`${err.message}\n`);
process.exit(1);
}
throw err;
}
const targetProvided = hasTargetOption(cliOptions);
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
const selection = resolveTargetSelection(process.cwd(), cliOptions);
if (selection) {
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
process.exit(0);
}
const ctx = loadContext(process.cwd(), cliOptions);
const updateDirective = await computeUpdateDirective();
if (!ctx.hasProduct) {
@@ -244,6 +863,10 @@ async function cli() {
'Stop the current task, load reference/init.md, and follow its ' +
'instructions to write PRODUCT.md before resuming.',
];
parts.push(buildResolvedContextDirective(ctx, cliOptions, { targetExists }));
if (shouldWarnMissingTarget(ctx, targetProvided, targetExists)) {
parts.push(buildMissingTargetDirective());
}
if (updateDirective) parts.push(updateDirective);
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
process.exit(0);
@@ -252,6 +875,10 @@ async function cli() {
if (ctx.hasDesign) {
parts.push(`# DESIGN.md\n\n${ctx.design.trim()}`);
}
parts.push(buildResolvedContextDirective(ctx, cliOptions, { targetExists }));
if (shouldWarnMissingTarget(ctx, targetProvided, targetExists)) {
parts.push(buildMissingTargetDirective());
}
const register = extractRegister(ctx.product);
const next = register
? `NEXT STEP: This project's register is \`${register}\`. You MUST now read \`reference/${register}.md\` before producing any design output.`
@@ -261,6 +888,60 @@ async function cli() {
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
}
function parseCliOptions(args) {
return parseTargetOptions(args, { strict: true });
}
function hasTargetOption(options) {
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
}
function pathExistsForTarget(cwd, targetPath) {
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
return fs.existsSync(abs);
}
function buildResolvedContextDirective(ctx, options, { targetExists = null } = {}) {
const targetPath = hasTargetOption(options) ? options.targetPath : null;
return `RESOLVED_CONTEXT:\n${JSON.stringify({
targetPath,
...(targetPath ? { targetExists } : {}),
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
productPath: ctx.productPath,
designPath: ctx.designPath,
}, null, 2)}`;
}
function shouldWarnMissingTarget(ctx, targetProvided, targetExists = null) {
if (ctx.isMonorepo && targetProvided && targetExists === false) return true;
return !!(
ctx.isMonorepo
&& (!targetProvided || targetExists === false)
&& ctx.projectRoot
&& ctx.repoRoot
&& path.resolve(ctx.projectRoot) === path.resolve(ctx.repoRoot)
);
}
function buildMissingTargetDirective() {
const script = process.argv[1] || 'context.mjs';
return (
'MONOREPO_TARGET_REQUIRED: This is a monorepo and context.mjs ran without --target. ' +
'If the user named a file, route, or child app, do not answer from this output. ' +
`Rerun \`node ${script} --target <path>\` and answer from that run's RESOLVED_CONTEXT fields.`
);
}
function buildTargetSelectionDirective(selection) {
return (
`TARGET_SELECTION_REQUIRED:\n${JSON.stringify(selection, null, 2)}\n\n` +
'Show each app with its productStatus/productPath and designStatus/designPath so the user can see child overrides, inherited root files, fallback files, or missing files before choosing. ' +
'Ask the user which app Impeccable should use, then rerun Impeccable helper commands from that child app cwd using this same scripts directory. ' +
'Use `--target <path>` only as a fallback when changing cwd is not possible, or when the user explicitly named a file/path.'
);
}
// Run cli() only when this module is the entry point. Compare realpaths
// rather than endsWith(): a loose suffix match also fires for unrelated
// scripts like `load-context.mjs`, and realpath tolerates symlinked
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
category: ap ? ap.category : 'quality',
severity: ap?.severity || 'warning',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
description: ap ? ap.description : '',
};
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
const DESIGN_COLOR_TOLERANCE = 6;
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function normalizeBrowserFontName(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function browserPrimaryFont(stack) {
if (!stack || /var\(/i.test(stack)) return '';
return String(stack || '')
.split(',')
.map(normalizeBrowserFontName)
.find(font => font && !GENERIC_FONTS.has(font)) || '';
}
function browserDesignSystemConfig() {
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
if (!raw?.present) return null;
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
const allowedColors = (raw.allowedColors || [])
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b }));
const allowedRadii = (raw.allowedRadii || [])
.map(Number)
.filter(px => Number.isFinite(px));
return {
present: true,
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
allowedFonts,
hasColors: raw.hasColors === true && allowedColors.length > 0,
allowedColors,
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
allowedRadii,
hasPillRadius: raw.hasPillRadius === true,
};
}
function browserColorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= DESIGN_COLOR_TOLERANCE;
}
function isBrowserDesignColorAllowed(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseAnyColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
}
function isBrowserTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseAnyColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function isBrowserDesignRadiusAllowed(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
}
function browserRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function browserHasDirectText(el) {
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function browserSampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function shouldSkipDesignElement(el) {
const tag = el.tagName?.toLowerCase?.() || '';
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
}
function checkElementDesignSystemDOM(el, designSystem, seen) {
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
const findings = [];
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = getComputedStyle(el);
if (designSystem.hasFonts && browserHasDirectText(el)) {
const font = browserPrimaryFont(style.fontFamily || '');
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
ignoreValue: font,
});
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = String(raw || '').trim().replace(/\s+/g, ' ');
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seen.colors.has(key)) continue;
seen.colors.add(key);
findings.push({
type: 'design-system-color',
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
ignoreValue: label,
});
}
}
if (designSystem.hasRadii) {
for (const token of browserRadiusTokens(style.borderRadius || '')) {
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
if (seen.radii.has(token)) continue;
seen.radii.add(token);
findings.push({
type: 'design-system-radius',
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
ignoreValue: token,
});
}
}
return findings;
}
function decodeBrowserGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkBrowserDesignSystemSources(designSystem, seen) {
if (!designSystem?.hasFonts) return [];
const findings = [];
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
const href = link.getAttribute('href') || '';
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
const display = decodeBrowserGoogleFamily(match[1]);
const font = normalizeBrowserFontName(display);
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
ignoreValue: display,
});
}
}
return findings;
}
function collectBrowserFindings() {
const groupMap = new Map();
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
const designSystem = browserDesignSystemConfig();
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
// real browser env (detector page, live overlay, extension) running every
// check is free, so we always surface them; the gating is purely a CLI
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementDesignSystemDOM(el, designSystem, designSeen),
].filter(f => _ruleOk(f.type));
addBrowserFindings(groupMap, el, findings);
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
const pageLevelFindings = [];
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
.filter(f => _ruleOk(f.type));
if (designSourceFindings.length > 0) {
pageLevelFindings.push(...designSourceFindings);
addBrowserFindings(groupMap, document.body, designSourceFindings);
}
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
if (typoFindings.length > 0) {
pageLevelFindings.push(...typoFindings);
@@ -1,9 +1,15 @@
import fs from 'node:fs';
import path from 'node:path';
import { loadDesignSystemForCwd } from '../design-system.mjs';
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
import { detectHtml } from '../engines/static-html/detect-html.mjs';
import { detectText } from '../engines/regex/detect-text.mjs';
import {
filterDetectionFindings,
readDetectionConfig,
shouldIgnoreDetectionFile,
} from '../../lib/impeccable-config.mjs';
import {
HTML_EXTENSIONS,
buildImportGraph,
@@ -16,6 +22,10 @@ import {
// Output formatting
// ---------------------------------------------------------------------------
function formatFindingSummary(count) {
return `${count} anti-pattern${count === 1 ? '' : 's'} found.`;
}
function formatFindings(findings, jsonMode) {
if (jsonMode) return JSON.stringify(findings, null, 2);
@@ -33,7 +43,7 @@ function formatFindings(findings, jsonMode) {
out.push(`${item.description}`);
}
}
out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
out.push(`\n${formatFindingSummary(findings.length)}`);
return out.join('\n');
}
@@ -79,10 +89,28 @@ function printUsage() {
Scan files or URLs for UI anti-patterns and design quality issues.
Options:
--json Output results as JSON
--gpt Also report GPT-specific provider tells (off by default)
--gemini Also report Gemini-specific provider tells (off by default)
--help Show this help message
--json Output results as JSON
--quiet In text mode, only print the final findings count
--gpt Also report GPT-specific provider tells (off by default)
--gemini Also report Gemini-specific provider tells (off by default)
--no-config Do not apply project config, detector ignores, inline
ignore comments, or DESIGN.md
--no-inline-ignores Do not honor in-file impeccable-disable* ignore comments
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
--help Show this help message
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
and detector.designSystem.enabled.
Inline ignores:
In-file comments waive a finding where it lives and travel with the file:
<!-- impeccable-disable overused-font -- exported brand doc -->
.brand { font-family: Inter } /* impeccable-disable-line overused-font */
// impeccable-disable-next-line bounce-easing: intentional bounce
impeccable-disable applies to the whole file; -line / -next-line are scoped.
List one or more rule ids (comma-separated), or omit them / use * for all.
Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
@@ -93,7 +121,8 @@ Examples:
impeccable detect src/
impeccable detect index.html
impeccable detect https://example.com
impeccable detect --json .`);
impeccable detect --json .
impeccable detect --no-config src/`);
}
async function detectCli() {
@@ -104,6 +133,7 @@ async function detectCli() {
});
if (args[0] === 'detect') args = args.slice(1);
const jsonMode = args.includes('--json');
const quietMode = args.includes('--quiet');
const helpMode = args.includes('--help');
// --fast (regex-only) is deprecated: since the jsdom removal, the static
// HTML/CSS analysis is fast and covers every rule, so the regex-only path
@@ -114,10 +144,21 @@ async function detectCli() {
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
);
}
const configEnabled = !args.includes('--no-config');
const detectionConfig = configEnabled
? readDetectionConfig(process.cwd())
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
const providers = [];
if (args.includes('--gpt')) providers.push('gpt');
if (args.includes('--gemini')) providers.push('gemini');
const scanOptions = { providers };
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
// Inline `impeccable-disable*` waivers are part of the scanned file, so they
// apply by default. `--no-config` (raw scan) and the dedicated
// `--no-inline-ignores` both turn them off.
const inlineIgnoresEnabled = configEnabled && !args.includes('--no-inline-ignores');
const scanOptions = { providers, inlineIgnores: inlineIgnoresEnabled };
if (designSystem) scanOptions.designSystem = designSystem;
const targets = args.filter(a => !a.startsWith('--'));
if (helpMode) { printUsage(); process.exit(0); }
@@ -149,8 +190,8 @@ async function detectCli() {
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
if (stat.isDirectory()) {
// Check for framework dev server config (skip in JSON mode to avoid polluting output)
if (!jsonMode) {
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
if (!jsonMode && !quietMode) {
const fwConfig = detectFrameworkConfig(resolved);
if (fwConfig) {
const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
@@ -175,11 +216,12 @@ async function detectCli() {
}
}
const files = walkDir(resolved);
const files = walkDir(resolved)
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
if (files.length > 50 && process.stdin.isTTY && !jsonMode && !quietMode) {
process.stderr.write(
`\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
`Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
@@ -219,6 +261,7 @@ async function detectCli() {
allFindings.push(...fileFindings);
}
} else if (stat.isFile()) {
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
const ext = path.extname(resolved).toLowerCase();
if (HTML_EXTENSIONS.has(ext)) {
allFindings.push(...await detectHtml(resolved, scanOptions));
@@ -232,8 +275,11 @@ async function detectCli() {
}
}
allFindings = filterDetectionFindings(allFindings, detectionConfig);
if (allFindings.length > 0) {
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
else if (quietMode) process.stderr.write(formatFindingSummary(allFindings.length) + '\n');
else process.stderr.write(formatFindings(allFindings, false) + '\n');
process.exit(2);
}
@@ -0,0 +1,750 @@
import fs from 'node:fs';
import path from 'node:path';
import { finding } from './findings.mjs';
import { GENERIC_FONTS } from './shared/constants.mjs';
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
const FALLBACK_DIRS = ['.agents/context', 'docs'];
const COLOR_CHANNEL_TOLERANCE = 6;
const RADIUS_TOLERANCE_PX = 0.5;
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function firstExisting(dir, names) {
for (const name of names) {
const abs = path.join(dir, name);
if (fs.existsSync(abs)) return abs;
}
return null;
}
function resolveDesignMdPath(cwd = process.cwd()) {
const root = firstExisting(cwd, DESIGN_NAMES);
if (root) return { path: root, contextDir: cwd };
for (const rel of FALLBACK_DIRS) {
const dir = path.resolve(cwd, rel);
const found = firstExisting(dir, DESIGN_NAMES);
if (found) return { path: found, contextDir: dir };
}
return null;
}
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
const candidates = [
path.join(cwd, '.impeccable', 'design.json'),
path.join(cwd, 'DESIGN.json'),
path.join(contextDir, 'DESIGN.json'),
];
return candidates.find((candidate, index) =>
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
) || null;
}
function parseFrontmatter(md) {
const lines = String(md || '').split(/\r?\n/);
if (lines[0]?.trim() !== '---') return null;
let end = -1;
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === '---') { end = i; break; }
}
if (end === -1) return null;
try {
return parseYamlSubset(lines.slice(1, end).join('\n'));
} catch {
return null;
}
}
function parseYamlSubset(yaml) {
const root = {};
const stack = [{ indent: -1, obj: root }];
for (const raw of String(yaml || '').split(/\r?\n/)) {
if (!raw.trim() || /^\s*#/.test(raw)) continue;
const indent = raw.match(/^\s*/)[0].length;
const content = raw.slice(indent);
const colonIdx = findTopLevelColon(content);
if (colonIdx === -1) continue;
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
const parent = stack[stack.length - 1].obj;
if (rest === '') {
const obj = {};
parent[key] = obj;
stack.push({ indent, obj });
} else {
parent[key] = parseScalar(rest);
}
}
return root;
}
function findTopLevelColon(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (inQuote) {
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === ':') {
return i;
}
}
return -1;
}
function unquoteYamlKey(key) {
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
return key.slice(1, -1);
}
return key;
}
function stripInlineYamlComment(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (inQuote) {
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
return s.slice(0, i).trimEnd();
}
}
return s;
}
function parseScalar(raw) {
const s = raw.trim();
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
return s.slice(1, -1);
}
if (s === 'true') return true;
if (s === 'false') return false;
if (s === 'null' || s === '~') return null;
if (/^-?\d+$/.test(s)) return Number(s);
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
return s;
}
function safeReadJson(filePath) {
if (!filePath) return null;
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return null;
}
}
function normalizeFontName(value) {
return String(value || '')
.trim()
.replace(/\s*!important\s*$/i, '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function splitFontStack(stack) {
return String(stack || '')
.replace(/\s*!important\s*$/i, '')
.split(',')
.map(normalizeFontName)
.filter(Boolean);
}
function primaryFont(stack) {
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
}
function isLiteralFontStack(stack) {
const text = String(stack || '');
return !/[$`{}]|\s\+\s|\|\|/.test(text);
}
function cssColorLabel(raw) {
return String(raw || '').trim().replace(/\s+/g, ' ');
}
function colorKey(color) {
if (!color) return '';
return `${color.r},${color.g},${color.b}`;
}
function colorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= COLOR_CHANNEL_TOLERANCE;
}
function hslToRgb(H, S, L, alpha = 1) {
const h = (((H % 360) + 360) % 360) / 360;
const s = Math.max(0, Math.min(1, S));
const l = Math.max(0, Math.min(1, L));
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
return {
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
g: Math.round(hue2rgb(p, q, h) * 255),
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
a: alpha,
};
}
function parseDesignColor(value) {
const text = String(value || '').trim();
const parsed = parseAnyColor(text);
if (parsed) return parsed;
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
if (hsl) {
return hslToRgb(
parseFloat(hsl[1]),
parseFloat(hsl[2]) / 100,
parseFloat(hsl[3]) / 100,
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
);
}
return null;
}
function addDesignColor(out, value, label) {
const parsed = parseDesignColor(value);
if (!parsed) return;
const key = colorKey(parsed);
if (!out.allowedColorKeys.has(key)) {
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
}
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
}
function addColorObject(out, colors, prefix = 'colors') {
if (!colors || typeof colors !== 'object') return;
for (const [name, value] of Object.entries(colors)) {
if (typeof value === 'string') {
addDesignColor(out, value, `${prefix}.${name}`);
}
}
}
function addSidecarColors(out, sidecar) {
const colorMeta = sidecar?.extensions?.colorMeta;
if (!colorMeta || typeof colorMeta !== 'object') return;
for (const [name, meta] of Object.entries(colorMeta)) {
if (!meta || typeof meta !== 'object') continue;
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
if (Array.isArray(meta.tonalRamp)) {
for (const [index, value] of meta.tonalRamp.entries()) {
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
}
}
}
}
function addTypographyFonts(out, typography) {
if (!typography || typeof typography !== 'object') return;
for (const role of Object.values(typography)) {
if (!role || typeof role !== 'object') continue;
if (typeof role.fontFamily !== 'string') continue;
for (const font of splitFontStack(role.fontFamily)) {
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
}
}
}
function addRoundedScale(out, rounded) {
if (!rounded || typeof rounded !== 'object') return;
for (const [rawName, value] of Object.entries(rounded)) {
const name = unquoteYamlKey(rawName).toLowerCase();
addRoundedToken(out, name, value);
}
}
function addRoundedToken(out, name, value) {
if (typeof value !== 'string' && typeof value !== 'number') return;
const raw = String(value).trim();
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
const px = resolveLengthPx(raw, 16);
if (px == null || !Number.isFinite(px)) return;
out.allowedRadii.push({ name, value: raw, px });
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
}
function addSidecarRadii(out, sidecar) {
const roundedMeta = sidecar?.extensions?.roundedMeta;
if (!roundedMeta || typeof roundedMeta !== 'object') return;
for (const [rawName, meta] of Object.entries(roundedMeta)) {
const name = unquoteYamlKey(rawName).toLowerCase();
if (typeof meta === 'string' || typeof meta === 'number') {
addRoundedToken(out, `sidecar.${name}`, meta);
continue;
}
if (!meta || typeof meta !== 'object') continue;
for (const key of ['canonical', 'value']) {
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
}
}
for (const key of ['values', 'aliases']) {
if (!Array.isArray(meta[key])) continue;
for (const [index, value] of meta[key].entries()) {
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
}
}
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
out.hasPillRadius = true;
}
}
}
function normalizeDesignSystem(input = {}) {
const frontmatter = input.frontmatter || {};
const sidecar = input.sidecar || null;
const out = {
present: true,
sourcePath: input.sourcePath || null,
sidecarPath: input.sidecarPath || null,
mdNewerThanJson: input.mdNewerThanJson === true,
allowedFonts: new Set(),
allowedColorKeys: new Map(),
allowedRadii: [],
hasPillRadius: false,
};
addTypographyFonts(out, frontmatter.typography);
addColorObject(out, frontmatter.colors);
addSidecarColors(out, sidecar);
addRoundedScale(out, frontmatter.rounded);
addSidecarRadii(out, sidecar);
out.hasFonts = out.allowedFonts.size > 0;
out.hasColors = out.allowedColorKeys.size > 0;
out.hasRadii = out.allowedRadii.length > 0;
return out;
}
function loadDesignSystemForCwd(cwd = process.cwd()) {
const md = resolveDesignMdPath(cwd);
if (!md) return null;
let frontmatter = null;
let mdStat = null;
try {
mdStat = fs.statSync(md.path);
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
} catch {
return null;
}
if (!frontmatter || typeof frontmatter !== 'object') return null;
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
const sidecar = safeReadJson(sidecarPath);
let sidecarStat = null;
try {
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
} catch {
sidecarStat = null;
}
return normalizeDesignSystem({
frontmatter,
sidecar,
sourcePath: md.path,
sidecarPath,
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
});
}
function isAllowedFont(font, designSystem) {
if (!font || GENERIC_FONTS.has(font)) return true;
if (!designSystem?.hasFonts) return true;
return designSystem.allowedFonts.has(font);
}
function isAllowedColorRaw(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseDesignColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
for (const entry of designSystem.allowedColorKeys.values()) {
if (colorsClose(parsed, entry.color)) return true;
}
return false;
}
function isAllowedRadiusRaw(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
}
function lineLooksCommented(line) {
const trimmed = String(line || '').trim();
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
}
function isProbablyColorLiteral(line, match) {
const raw = match?.[0] || '';
const index = match.index ?? -1;
if (index < 0) return false;
if (isInsideCssAttributeSelector(line, index)) return false;
const before = line.slice(0, index);
const after = line.slice(index + raw.length);
if (raw.startsWith('#')) {
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. &#8596;
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
}
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
return styleContext || cssFunctionContext || jsColorKeyContext;
}
function isInsideCssAttributeSelector(line, index) {
if (index < 0) return false;
const before = line.slice(0, index);
const lastOpen = before.lastIndexOf('[');
if (lastOpen === -1) return false;
const lastClose = before.lastIndexOf(']');
if (lastClose > lastOpen) return false;
const after = line.slice(index);
const close = after.indexOf(']');
const block = after.indexOf('{');
return close !== -1 && (block === -1 || close < block);
}
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
return { ...finding(id, filePath, snippet, line), ...extras };
}
function decodeGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkFontStack(stack, filePath, line, designSystem, context) {
const primary = primaryFont(stack);
if (!primary || isAllowedFont(primary, designSystem)) return [];
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
return [makeDesignFinding(
'design-system-font',
filePath,
`${context}: ${display} is not declared in DESIGN.md typography`,
line,
{ ignoreValue: display },
)];
}
function extractRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function checkRadiusValue(value, filePath, line, designSystem, context) {
const findings = [];
for (const token of extractRadiusTokens(value)) {
if (isAllowedRadiusRaw(token, designSystem)) continue;
findings.push(makeDesignFinding(
'design-system-radius',
filePath,
`${context}: ${token} is outside the DESIGN.md rounded scale`,
line,
{ ignoreValue: token },
));
}
return findings;
}
function checkSourceDesignSystem(content, filePath, options = {}) {
const designSystem = options.designSystem;
if (!designSystem?.present) return [];
const findings = [];
const lines = String(content || '').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineNum = i + 1;
if (lineLooksCommented(line)) continue;
if (designSystem.hasFonts) {
for (const match of line.matchAll(FONT_DECL_RE)) {
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
}
for (const match of line.matchAll(FONT_JS_RE)) {
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
}
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
const url = match[0];
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
if (!font || isAllowedFont(font, designSystem)) continue;
const display = decodeGoogleFamily(familyMatch[1]);
findings.push(makeDesignFinding(
'design-system-font',
filePath,
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
lineNum,
{ ignoreValue: display },
));
}
}
}
if (designSystem.hasColors) {
for (const match of line.matchAll(CSS_COLOR_RE)) {
if (!isProbablyColorLiteral(line, match)) continue;
const raw = cssColorLabel(match[0]);
if (isAllowedColorRaw(raw, designSystem)) continue;
findings.push(makeDesignFinding(
'design-system-color',
filePath,
`Undocumented color ${raw} is outside DESIGN.md colors`,
lineNum,
{ ignoreValue: raw },
));
}
}
if (designSystem.hasRadii) {
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
}
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
}
}
}
return dedupeDesignFindings(findings);
}
function hasDirectText(el) {
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function sampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
if (!designSystem?.present) return [];
const findings = [];
const seenFonts = new Set();
const seenColors = new Set();
const seenRadii = new Set();
for (const el of document.querySelectorAll('*')) {
if (shouldSkipStaticDesignElement(el, window)) continue;
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = window.getComputedStyle(el);
if (designSystem.hasFonts && hasDirectText(el)) {
const font = primaryFont(style.fontFamily || '');
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
seenFonts.add(font);
findings.push(makeDesignFinding(
'design-system-font',
filePath,
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
0,
{ ignoreValue: font },
));
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = cssColorLabel(raw);
if (isAllowedColorRaw(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seenColors.has(key)) continue;
seenColors.add(key);
findings.push(makeDesignFinding(
'design-system-color',
filePath,
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
0,
{ ignoreValue: label },
));
}
}
if (designSystem.hasRadii) {
const rawRadius = String(style.borderRadius || '').trim();
if (!rawRadius) continue;
for (const token of extractRadiusTokens(rawRadius)) {
if (isAllowedRadiusRaw(token, designSystem)) continue;
if (seenRadii.has(token)) continue;
seenRadii.add(token);
findings.push(makeDesignFinding(
'design-system-radius',
filePath,
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
0,
{ ignoreValue: token },
));
}
}
}
return findings;
}
function shouldSkipStaticDesignElement(el, window) {
const tag = el.tagName?.toLowerCase?.() || '';
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
let current = el;
while (current) {
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
const style = window.getComputedStyle(current);
const display = String(style.display || '').toLowerCase();
const visibility = String(style.visibility || '').toLowerCase();
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
current = current.parentElement;
}
return false;
}
function isTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseDesignColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function canonicalDesignFindingKey(item) {
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
const value = item.ignoreValue || item.value || '';
if (item.antipattern === 'design-system-font') {
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
const font = normalizeFontName(value);
return font ? `${item.antipattern}:${context}:${font}` : null;
}
if (item.antipattern === 'design-system-color') {
const parsed = parseDesignColor(value);
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
const label = cssColorLabel(value).toLowerCase();
return label ? `${item.antipattern}:color:${label}` : null;
}
if (item.antipattern === 'design-system-radius') {
const px = resolveLengthPx(String(value || '').trim(), 16);
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
const label = String(value || '').trim().toLowerCase();
return label ? `${item.antipattern}:radius:${label}` : null;
}
return null;
}
function mergeDesignSystemFindings(...groups) {
const out = [];
const seen = new Map();
for (const group of groups) {
for (const item of group || []) {
const key = canonicalDesignFindingKey(item);
if (key) {
if (seen.has(key)) {
const existing = out[seen.get(key)];
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
continue;
}
seen.set(key, out.length);
}
out.push(item);
}
}
return out;
}
function dedupeDesignFindings(findings) {
const out = [];
const seen = new Set();
for (const item of findings) {
const key = [
item.antipattern,
item.line || 0,
normalizeFontName(item.ignoreValue || item.snippet || ''),
].join('\0');
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
export {
parseFrontmatter,
normalizeDesignSystem,
loadDesignSystemForCwd,
isAllowedFont,
isAllowedColorRaw,
isAllowedRadiusRaw,
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
mergeDesignSystemFindings,
};
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
skillSection: 'Layout & Space',
skillGuideline: 'overflow container clipping positioned children',
},
{
id: 'design-system-font',
category: 'quality',
name: 'Font outside DESIGN.md',
description:
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
skillSection: 'Typography',
skillGuideline: 'font family outside the project design system',
},
{
id: 'design-system-color',
category: 'quality',
severity: 'advisory',
name: 'Color outside DESIGN.md',
description:
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
skillSection: 'Color & Contrast',
skillGuideline: 'literal color outside the project design system',
},
{
id: 'design-system-radius',
category: 'quality',
severity: 'advisory',
name: 'Radius outside DESIGN.md',
description:
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
skillSection: 'Visual Details',
skillGuideline: 'border radius outside the project design system',
},
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
{
@@ -449,6 +478,17 @@ const ANTIPATTERNS = [
skillSection: 'Visual Details',
skillGuideline: 'repeating-gradient decorative stripes',
},
{
id: 'codex-grid-background',
category: 'slop',
severity: 'advisory',
gated: 'gpt',
name: 'Decorative grid-line background',
description:
'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
skillSection: 'Visual Details',
skillGuideline: 'two-axis grid-line gradient background',
},
{
id: 'theater-slop-phrase',
category: 'slop',
@@ -1084,9 +1124,13 @@ function checkHtmlPatterns(html) {
// --- Motion ---
// Bounce/elastic animation names
const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
if (bounceRe.test(html)) {
findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
const bounceMatch = bounceRe.exec(html);
if (bounceMatch) {
const animationToken = bounceMatch[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
}
// Overshoot cubic-bezier
@@ -1139,6 +1183,42 @@ function checkHtmlPatterns(html) {
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
}
// --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
// The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
// transparent 1px)` layers (one per axis) tiled by a repeating
// `background-size` cell. Both signals must co-occur in the SAME style block
// (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
// tiling background-size is a fixed crosshair, not a grid, and a single
// hairline is a legitimate ruled line. Scoping to one block also stops
// unrelated single-axis rules on separate elements from adding up across the
// page. Count hairlines only inside `background`/`background-image` values so
// a hairline in an unrelated property (mask-image, border-image) can't stand
// in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
// nested parens, so match the hairline stop directly rather than parsing
// whole gradient layers.
{
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
let blk;
while ((blk = blockRe.exec(html)) !== null) {
const block = blk[1] || blk[2] || blk[3] || '';
if (!gridSizeRe.test(block)) continue;
let hairlineCount = 0;
let bm;
bgDeclRe.lastIndex = 0;
while ((bm = bgDeclRe.exec(block)) !== null) {
const stops = bm[1].match(hairlineRe);
if (stops) hairlineCount += stops.length;
}
if (hairlineCount >= 2) {
findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
break;
}
}
}
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
// runs in the bundled browser path too, not just the CLI/static path.
@@ -4390,6 +4470,7 @@ if (IS_BROWSER) {
category: ap ? ap.category : 'quality',
severity: ap?.severity || 'warning',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
description: ap ? ap.description : '',
};
@@ -4426,10 +4507,203 @@ if (IS_BROWSER) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
const DESIGN_COLOR_TOLERANCE = 6;
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function normalizeBrowserFontName(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function browserPrimaryFont(stack) {
if (!stack || /var\(/i.test(stack)) return '';
return String(stack || '')
.split(',')
.map(normalizeBrowserFontName)
.find(font => font && !GENERIC_FONTS.has(font)) || '';
}
function browserDesignSystemConfig() {
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
if (!raw?.present) return null;
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
const allowedColors = (raw.allowedColors || [])
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b }));
const allowedRadii = (raw.allowedRadii || [])
.map(Number)
.filter(px => Number.isFinite(px));
return {
present: true,
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
allowedFonts,
hasColors: raw.hasColors === true && allowedColors.length > 0,
allowedColors,
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
allowedRadii,
hasPillRadius: raw.hasPillRadius === true,
};
}
function browserColorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= DESIGN_COLOR_TOLERANCE;
}
function isBrowserDesignColorAllowed(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseAnyColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
}
function isBrowserTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseAnyColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function isBrowserDesignRadiusAllowed(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
}
function browserRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function browserHasDirectText(el) {
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function browserSampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function shouldSkipDesignElement(el) {
const tag = el.tagName?.toLowerCase?.() || '';
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
}
function checkElementDesignSystemDOM(el, designSystem, seen) {
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
const findings = [];
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = getComputedStyle(el);
if (designSystem.hasFonts && browserHasDirectText(el)) {
const font = browserPrimaryFont(style.fontFamily || '');
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
ignoreValue: font,
});
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = String(raw || '').trim().replace(/\s+/g, ' ');
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seen.colors.has(key)) continue;
seen.colors.add(key);
findings.push({
type: 'design-system-color',
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
ignoreValue: label,
});
}
}
if (designSystem.hasRadii) {
for (const token of browserRadiusTokens(style.borderRadius || '')) {
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
if (seen.radii.has(token)) continue;
seen.radii.add(token);
findings.push({
type: 'design-system-radius',
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
ignoreValue: token,
});
}
}
return findings;
}
function decodeBrowserGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkBrowserDesignSystemSources(designSystem, seen) {
if (!designSystem?.hasFonts) return [];
const findings = [];
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
const href = link.getAttribute('href') || '';
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
const display = decodeBrowserGoogleFamily(match[1]);
const font = normalizeBrowserFontName(display);
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
ignoreValue: display,
});
}
}
return findings;
}
function collectBrowserFindings() {
const groupMap = new Map();
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
const designSystem = browserDesignSystemConfig();
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
// real browser env (detector page, live overlay, extension) running every
// check is free, so we always surface them; the gating is purely a CLI
@@ -4460,6 +4734,7 @@ if (IS_BROWSER) {
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementDesignSystemDOM(el, designSystem, designSeen),
].filter(f => _ruleOk(f.type));
addBrowserFindings(groupMap, el, findings);
@@ -4476,6 +4751,13 @@ if (IS_BROWSER) {
const pageLevelFindings = [];
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
.filter(f => _ruleOk(f.type));
if (designSourceFindings.length > 0) {
pageLevelFindings.push(...designSourceFindings);
addBrowserFindings(groupMap, document.body, designSourceFindings);
}
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
if (typoFindings.length > 0) {
pageLevelFindings.push(...typoFindings);
@@ -23,6 +23,13 @@ export {
checkHtmlPatterns,
} from './rules/checks.mjs';
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
export {
parseFrontmatter as parseDesignFrontmatter,
normalizeDesignSystem,
loadDesignSystemForCwd,
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
} from './design-system.mjs';
export { detectHtml } from './engines/static-html/detect-html.mjs';
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
function serializeDesignSystemForBrowser(designSystem) {
if (!designSystem?.present) return null;
return {
present: true,
hasFonts: designSystem.hasFonts === true,
allowedFonts: Array.from(designSystem.allowedFonts || []),
hasColors: designSystem.hasColors === true,
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
.map(entry => entry?.color)
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b })),
hasRadii: designSystem.hasRadii === true,
allowedRadii: (designSystem.allowedRadii || [])
.map(entry => Number(entry?.px))
.filter(px => Number.isFinite(px)),
hasPillRadius: designSystem.hasPillRadius === true,
};
}
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
if (options?.visualContrast === false) return [];
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
}
// Inject the browser detection script and collect results
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
await profileStepAsync(profile, {
engine: 'browser',
phase: 'scan',
ruleId: 'configure-pure-detect',
target: url,
}, () => page.evaluate(() => {
}, () => page.evaluate((designSystem) => {
window.__IMPECCABLE_CONFIG__ = {
...(window.__IMPECCABLE_CONFIG__ || {}),
autoScan: false,
...(designSystem ? { designSystem } : {}),
};
}));
}, browserDesignSystem));
await profileStepAsync(profile, {
engine: 'browser',
phase: 'scan',
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
return window.impeccableDetect({ decorate: false, serialize: true });
});
return serializedGroups.flatMap(({ findings }) =>
findings.map(f => ({ id: f.type, snippet: f.detail }))
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
);
});
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
}, () => browser.close());
}
}
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
return filterByProviders(results.map(f => {
const item = finding(f.id, url, f.snippet);
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
return item;
}), options.providers);
}
async function createBrowserDetector(options = {}) {
@@ -1,5 +1,8 @@
import { GENERIC_FONTS } from '../../shared/constants.mjs';
import { isNeutralColor } from '../../shared/color.mjs';
import { checkSourceDesignSystem } from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
import { finding } from '../../findings.mjs';
import { filterByProviders } from '../../registry/antipatterns.mjs';
import { profileFindings, profileStep } from '../../profile/profiler.mjs';
@@ -36,10 +39,11 @@ function shouldRunPageAnalyzers(content, filePath) {
}
function isNeutralBorderColor(str) {
const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
const m = str.match(/solid\s+((?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\([^)]*\)|#[0-9a-f]{3,8}\b|[a-z]+)/i);
if (!m) return false;
const c = m[1].toLowerCase();
if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
if (/^(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb)\(/i.test(c)) return isNeutralColor(c);
const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
if (hex) {
const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
@@ -56,10 +60,10 @@ function isNeutralBorderColor(str) {
const REGEX_MATCHERS = [
// --- Side-tab ---
{ id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 2 : n >= 4; },
fmt: (m) => m[0] },
{ id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 2 : n >= 3; },
fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
{ id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
@@ -110,9 +114,14 @@ const REGEX_MATCHERS = [
{ id: 'bounce-easing', regex: /\banimate-bounce\b/g,
test: () => true,
fmt: () => 'animate-bounce (Tailwind)' },
{ id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
{ id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi,
test: () => true,
fmt: (m) => m[0] },
fmt: (m) => {
const token = m[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
return `animation: ${token || m[1].trim()}`;
} },
{ id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
test: (m) => {
const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
@@ -498,6 +507,15 @@ function detectText(content, filePath, options = {}) {
}));
}
if (options?.designSystem) {
findings.push(...profileFindings(profile, {
engine: 'regex',
phase: 'source',
ruleId: 'design-system',
target: filePath,
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
}
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
const deduped = [];
for (const f of findings) {
@@ -532,7 +550,10 @@ function detectText(content, filePath, options = {}) {
}
}
return filterByProviders(deduped, options?.providers);
const byProvider = filterByProviders(deduped, options?.providers);
// Inline `impeccable-disable*` waivers travel with the file; honor them unless
// explicitly bypassed (`--no-config` / `--no-inline-ignores`).
return options?.inlineIgnores === false ? byProvider : applyInlineIgnores(byProvider, content);
}
export {
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
marginBottom: '0px',
marginLeft: '0px',
position: 'static',
visibility: 'visible',
top: 'auto',
right: 'auto',
bottom: 'auto',
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
'margin-bottom': 'marginBottom',
'margin-left': 'marginLeft',
'position': 'position',
'visibility': 'visibility',
'top': 'top',
'right': 'right',
'bottom': 'bottom',
@@ -2,7 +2,13 @@ import fs from 'node:fs';
import path from 'node:path';
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
import {
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
mergeDesignSystemFindings,
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
import { finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
@@ -168,6 +174,22 @@ async function detectHtml(filePath, options = {}) {
}
}
if (options?.designSystem) {
const sourceDesignFindings = profileFindings(profile, {
engine: 'static-html',
phase: 'source',
ruleId: 'design-system',
target: filePath,
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
const staticDesignFindings = profileFindings(profile, {
engine: 'static-html',
phase: 'page',
ruleId: 'design-system',
target: filePath,
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
}
if (isFullPage(html)) {
const runPageCheck = (ruleId, callback) => profile
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
@@ -202,7 +224,11 @@ async function detectHtml(filePath, options = {}) {
}
}
return filterByProviders(findings, options.providers);
const byProvider = filterByProviders(findings, options.providers);
// Static-HTML findings carry no line number, so only whole-file
// `impeccable-disable` directives apply here — exactly the standalone-document
// waiver this primitive targets. Bypassed by `--no-config` / `--no-inline-ignores`.
return options?.inlineIgnores === false ? byProvider : applyInlineIgnores(byProvider, html);
}
export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
skillSection: 'Layout & Space',
skillGuideline: 'overflow container clipping positioned children',
},
{
id: 'design-system-font',
category: 'quality',
name: 'Font outside DESIGN.md',
description:
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
skillSection: 'Typography',
skillGuideline: 'font family outside the project design system',
},
{
id: 'design-system-color',
category: 'quality',
severity: 'advisory',
name: 'Color outside DESIGN.md',
description:
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
skillSection: 'Color & Contrast',
skillGuideline: 'literal color outside the project design system',
},
{
id: 'design-system-radius',
category: 'quality',
severity: 'advisory',
name: 'Radius outside DESIGN.md',
description:
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
skillSection: 'Visual Details',
skillGuideline: 'border radius outside the project design system',
},
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
{
@@ -347,6 +376,17 @@ const ANTIPATTERNS = [
skillSection: 'Visual Details',
skillGuideline: 'repeating-gradient decorative stripes',
},
{
id: 'codex-grid-background',
category: 'slop',
severity: 'advisory',
gated: 'gpt',
name: 'Decorative grid-line background',
description:
'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
skillSection: 'Visual Details',
skillGuideline: 'two-axis grid-line gradient background',
},
{
id: 'theater-slop-phrase',
category: 'slop',
@@ -514,9 +514,13 @@ function checkHtmlPatterns(html) {
// --- Motion ---
// Bounce/elastic animation names
const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
if (bounceRe.test(html)) {
findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
const bounceMatch = bounceRe.exec(html);
if (bounceMatch) {
const animationToken = bounceMatch[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
}
// Overshoot cubic-bezier
@@ -569,6 +573,42 @@ function checkHtmlPatterns(html) {
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
}
// --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
// The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
// transparent 1px)` layers (one per axis) tiled by a repeating
// `background-size` cell. Both signals must co-occur in the SAME style block
// (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
// tiling background-size is a fixed crosshair, not a grid, and a single
// hairline is a legitimate ruled line. Scoping to one block also stops
// unrelated single-axis rules on separate elements from adding up across the
// page. Count hairlines only inside `background`/`background-image` values so
// a hairline in an unrelated property (mask-image, border-image) can't stand
// in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
// nested parens, so match the hairline stop directly rather than parsing
// whole gradient layers.
{
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
let blk;
while ((blk = blockRe.exec(html)) !== null) {
const block = blk[1] || blk[2] || blk[3] || '';
if (!gridSizeRe.test(block)) continue;
let hairlineCount = 0;
let bm;
bgDeclRe.lastIndex = 0;
while ((bm = bgDeclRe.exec(block)) !== null) {
const stops = bm[1].match(hairlineRe);
if (stops) hairlineCount += stops.length;
}
if (hairlineCount >= 2) {
findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
break;
}
}
}
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
// runs in the bundled browser path too, not just the CLI/static path.
@@ -0,0 +1,148 @@
/**
* Inline, in-file ignore directives eslint-disable-style waivers that live at
* the point they apply and travel with the artifact instead of (or alongside)
* an ignore in `.impeccable/config.json`.
*
* A config ignore is the right default for repo-wide policy. This complements it
* for the one case config can't cover: a waiver that belongs to a single file and
* needs to follow that file when it leaves the repo a generated/exported
* standalone document, an emailed HTML file, a snippet scanned out of context.
*
* Comment-syntax-agnostic: the directive is a raw token matched anywhere on a
* line, so the same marker works across every comment style impeccable scans
* `//`, `/* *\/`, `<!-- -->`, `#`, `{/* *\/}`, `{# #}`. Trailing comment closers
* are stripped before the rule list is parsed.
*
* Syntax (reason optional; eslint `--` or biome `:` separator):
*
* impeccable-disable <rule>[, <rule>...] [-- reason] whole file
* impeccable-disable-line <rule>... [-- reason] the same line
* impeccable-disable-next-line <rule>... [-- reason] the following line
* impeccable-disable bare / `*` = every rule
*
* Examples:
*
* <!-- impeccable-disable overused-font -- exported brand doc, font is first-party -->
* .brand { font-family: Inter; } /* impeccable-disable-line overused-font *\/
* // impeccable-disable-next-line bounce-easing: intentional playful affordance
*
* Behavior is suppression, for parity with config ignores: a matched directive
* drops the finding. The inline reason is self-documenting in the diff; it is not
* required and is discarded at scan time (only used here to keep reason words out
* of the parsed rule list).
*/
const DIRECTIVE_RE = /impeccable-(disable-next-line|disable-line|disable)\b[ \t]*([^\n\r]*)/gi;
// Trailing comment closers, so `*/`, `*/}`, `-->`, `*}`, `#}`, `%>`, `}}` don't
// leak into the rule list. Anchored to end-of-line; the leading `\s*` mops up the
// space before the closer. `--+>` covers `-->` and any longer dash run.
const TRAILING_CLOSER_RE = /\s*(?:\*\/\}?|--+>|\*\}|#\}|%>|\}\})\s*$/;
function normalizeRule(token) {
return String(token || '').trim().toLowerCase();
}
// Split the directive remainder into rule tokens, dropping any human reason that
// follows an eslint-style `--` or biome-style `:` separator. Rule ids only ever
// contain single hyphens (`overused-font`, `bounce-easing`), so `--` and `:`
// are unambiguous separators.
function parseRuleList(remainder) {
let text = String(remainder || '').replace(TRAILING_CLOSER_RE, '').trim();
// Cut off a human reason at the first `--` (eslint) or `:` (biome) separator.
const reasonSep = text.match(/\s*(?:--+|:)\s*/);
if (reasonSep) text = text.slice(0, reasonSep.index);
const tokens = text.split(/[\s,]+/).map(normalizeRule).filter(Boolean);
if (tokens.length === 0 || tokens.includes('*')) return ['*'];
return tokens;
}
function addRules(set, rules) {
for (const rule of rules) set.add(rule);
}
function getSet(map, key) {
let set = map.get(key);
if (!set) {
set = new Set();
map.set(key, set);
}
return set;
}
/**
* Parse every inline ignore directive in a file's raw text.
*
* Returns sets keyed by the 1-based line the directive *targets* so matching is a
* direct lookup:
* - file: rules disabled for the whole file
* - line: line -> rules disabled on that exact line (disable-line)
* - nextLine: line -> rules disabled on that line (disable-next-line on line-1)
*
* `*` in any set means "every rule".
*/
function parseInlineIgnores(content) {
const result = { file: new Set(), line: new Map(), nextLine: new Map() };
const text = typeof content === 'string' ? content : '';
// Cheap bail-out: the substring must be present for any directive to exist.
// Case-insensitive to match DIRECTIVE_RE's `i` flag (e.g. `Impeccable-Disable`).
if (!/impeccable-disable/i.test(text)) return result;
// Split on `\n` only, exactly as detectText numbers lines, so directive line
// keys line up with finding `line` values (incl. on `\r`-only line endings).
// The directive regex excludes `\r`, so a trailing `\r` on `\r\n` files is
// never captured into the rule list.
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
DIRECTIVE_RE.lastIndex = 0;
let m;
while ((m = DIRECTIVE_RE.exec(lines[i])) !== null) {
const variant = m[1].toLowerCase();
const rules = parseRuleList(m[2]);
if (variant === 'disable') {
addRules(result.file, rules);
} else if (variant === 'disable-line') {
addRules(getSet(result.line, i + 1), rules);
} else {
// disable-next-line on line i+1 targets line i+2.
addRules(getSet(result.nextLine, i + 2), rules);
}
}
}
return result;
}
function setMatches(set, rule) {
return Boolean(set) && (set.has('*') || set.has(rule));
}
function isInlineIgnored(finding, directives) {
const rule = normalizeRule(finding && finding.antipattern);
if (!rule) return false;
if (setMatches(directives.file, rule)) return true;
const line = Number(finding && finding.line) || 0;
if (line > 0) {
if (setMatches(directives.line.get(line), rule)) return true;
if (setMatches(directives.nextLine.get(line), rule)) return true;
}
return false;
}
function hasDirectives(directives) {
return directives.file.size > 0 || directives.line.size > 0 || directives.nextLine.size > 0;
}
/**
* Drop findings waived by an inline directive in the same file's source text.
* Findings without a usable line number (e.g. static-HTML page-level findings)
* are only matched by whole-file directives which is the standalone-document
* case this primitive exists for.
*/
function applyInlineIgnores(findings, content) {
if (!Array.isArray(findings) || findings.length === 0) return findings;
const directives = parseInlineIgnores(content);
if (!hasDirectives(directives)) return findings;
return findings.filter((finding) => !isInlineIgnored(finding, directives));
}
export { parseInlineIgnores, applyInlineIgnores, isInlineIgnored };
+138 -52
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env node
/**
* `/impeccable hooks <on|off|status|reset>` manage the design hook
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
* in the current project.
* `/impeccable hooks <on|off|status|reset>` manage the design hook runtime
* via the `hook` key and shared detector ignores via the `detector` key in
* .impeccable/config.json / .impeccable/config.local.json.
*
* Usage:
* node hook-admin.mjs status # print current state
@@ -75,7 +75,6 @@ const HOOK_MANIFEST_TARGETS = [
skillRel: '.agents/skills/impeccable',
destRel: '.codex/hooks.json',
manifest: () => ({
description: 'Impeccable design detector: runs after Edit/Write/apply_patch on UI files and surfaces findings as system reminders.',
hooks: {
PostToolUse: [
{
@@ -83,7 +82,7 @@ const HOOK_MANIFEST_TARGETS = [
hooks: [
{
type: 'command',
command: 'node "$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs"',
command: 'node ".agents/skills/impeccable/scripts/hook.mjs"',
timeout: TIMEOUT_SECONDS,
statusMessage: STATUS_MESSAGE,
},
@@ -109,6 +108,28 @@ const HOOK_MANIFEST_TARGETS = [
},
}),
},
{
// GitHub Copilot reads repo-level hooks from `.github/hooks/*.json`. The same
// manifest is honored by the CLI (once committed to the default branch) and
// the cloud/app agent. Schema differs: lowercase `postToolUse`, flat entries,
// `bash`/`timeoutSec`, and a `matcher` regex against the `edit`/`create` tools.
provider: '.github',
skillRel: '.github/skills/impeccable',
destRel: '.github/hooks/impeccable.json',
manifest: () => ({
version: 1,
hooks: {
postToolUse: [
{
type: 'command',
matcher: 'edit|create|apply_patch',
bash: 'node "$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/hook.mjs"',
timeoutSec: TIMEOUT_SECONDS,
},
],
},
}),
},
];
function readRawConfigFile(filePath) {
@@ -120,23 +141,48 @@ function readRawConfigFile(filePath) {
}
}
// The hook settings to edit: the unified file's `hook` subtree.
function readRawConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
return unified.hook;
}
return null;
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
function hookSection(unified) {
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
? unified.hook
: null;
}
// Write the hook config back under the `hook` key of the unified file, leaving
// any sibling keys (e.g. updateCheck) untouched.
function writeConfig(cwd, hookConfig, opts = {}) {
function detectorSection(unified) {
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
? unified.detector
: null;
}
function readRawHookConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
return hookSection(unified);
}
function readRawDetectorConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
const merged = mergeDetectorConfig(hookSection(unified));
return mergeDetectorConfig(detectorSection(unified), merged);
}
function stripDetectorKeys(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
const out = {};
for (const [key, value] of Object.entries(raw)) {
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
}
return out;
}
// Write hook runtime config under `hook`, leaving detector filters in
// `detector` and preserving sibling keys such as updateCheck.
function writeHookConfig(cwd, hookConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
if (opts.local) ensureHookGitExcludes(cwd);
const existingRaw = readRawConfigFile(filePath).raw;
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
const existingHook = stripDetectorKeys(hookSection(existing));
// Merge over the existing hook object so fields the merge helpers don't manage
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
@@ -145,15 +191,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
return filePath;
}
function mergeConfig(existing) {
// Persist the full shape so /impeccable hooks edits leave a complete file
// for the user to see, not an unhelpful `{"enabled":false}`.
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
if (opts.local) ensureHookGitExcludes(cwd);
const existingRaw = readRawConfigFile(filePath).raw;
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
const nextHook = stripDetectorKeys(hookSection(existing));
const existingDetector = mergeDetectorConfig(detectorSection(existing));
const next = {
...existing,
detector: mergeDetectorConfig(detectorConfig, existingDetector),
};
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
else delete next.hook;
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
return filePath;
}
function mergeHookConfig(existing) {
const base = existing && typeof existing === 'object' ? existing : {};
return {
enabled: base.enabled === false ? false : true,
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
limits: {
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
@@ -161,28 +220,54 @@ function mergeConfig(existing) {
};
}
function mergeLocalConfig(existing) {
function mergeDetectorConfig(existing, seed = null) {
const base = existing && typeof existing === 'object' ? existing : {};
const out = {};
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
out.enabled = base.enabled === false ? false : true;
const out = seed ? {
ignoreRules: [...seed.ignoreRules],
ignoreFiles: [...seed.ignoreFiles],
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
} : {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
};
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
out.designSystem = { ...seed.designSystem };
}
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
out.designSystem = {
...(out.designSystem || {}),
enabled: base.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(base.ignoreRules)) {
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
}
if (Array.isArray(base.ignoreFiles)) {
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
}
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
if (base.limits && typeof base.limits === 'object') {
const limits = {};
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
if (Object.keys(limits).length) out.limits = limits;
if (Array.isArray(base.ignoreValues)) {
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
}
return out;
}
function mergeIgnoreValueEntries(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(ignoreValueEntryKey(entry), entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(ignoreValueEntryKey(entry), entry);
}
return Array.from(map.values());
}
function ignoreValueEntryKey(entry) {
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
return `${entry.rule}\0${entry.value}\0${files}`;
}
function statusReport(cwd) {
const shared = readRawConfigFile(getConfigPath(cwd));
const local = readRawConfigFile(getLocalConfigPath(cwd));
@@ -216,14 +301,14 @@ function statusReport(cwd) {
}
function setEnabled(cwd, value) {
const config = mergeConfig(readRawConfig(cwd));
const config = mergeHookConfig(readRawHookConfig(cwd));
config.enabled = value;
const target = writeConfig(cwd, config);
const target = writeHookConfig(cwd, config);
if (!value) {
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
}
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
const repaired = repairHookManifests(cwd);
const parts = [
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
@@ -336,7 +421,10 @@ function valueHasImpeccableHookMarker(value) {
function stripImpeccableHookEntry(entry) {
if (!entry || typeof entry !== 'object') return entry;
if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)) {
// `command`/`args`: Claude/Codex/Cursor. `bash`/`powershell`: GitHub Copilot's
// flat entry shape, where the marker lives under the shell-command keys.
if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)
|| valueHasImpeccableHookMarker(entry.bash) || valueHasImpeccableHookMarker(entry.powershell)) {
return null;
}
if (!Array.isArray(entry.hooks)) return entry;
@@ -429,18 +517,18 @@ function addIgnoreRule(cwd, args) {
if (rule === 'overused-font' && !parsed.allValues) {
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
}
const config = mergeConfig(readRawConfig(cwd));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
writeConfig(cwd, config);
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
writeDetectorConfig(cwd, config);
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
}
function addIgnoreFile(cwd, glob) {
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
const config = mergeConfig(readRawConfig(cwd));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
writeConfig(cwd, config);
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
writeDetectorConfig(cwd, config);
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
}
function parseIgnoreValueArgs(args) {
@@ -489,9 +577,7 @@ function addIgnoreValue(cwd, args) {
}
const local = parsed.local;
const config = local
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
: mergeConfig(readRawConfig(cwd, { local: false }));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
const key = `${parsed.rule}\0${parsed.value}`;
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
@@ -507,20 +593,20 @@ function addIgnoreValue(cwd, args) {
config.ignoreValues.push(entry);
}
const target = writeConfig(cwd, config, { local });
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
const target = writeDetectorConfig(cwd, config, { local });
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
}
function reset(cwd) {
const removed = [];
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
// hook subtree and keep the rest, deleting the file only if nothing remains.
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
try {
const raw = readRawConfigFile(filePath).raw;
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
const { hook, ...rest } = raw;
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
const { hook, detector, ...rest } = raw;
if (Object.keys(rest).length === 0) {
fs.unlinkSync(filePath);
} else {
@@ -18,6 +18,8 @@ import {
EDIT_COUNT_THRESHOLD,
GENERATED_PATH,
SENSITIVE_PATH,
appendDesignSystemNote,
designSystemOptions,
filterFindings,
loadDetector,
matchesAnyGlob,
@@ -333,8 +335,8 @@ function isInsideProject(filePath, cwd) {
function cursorBlockMessage(findings, filePath, config, cwd) {
const rendered = renderTemplate(findings, filePath, config, { cwd });
const blocked = rendered.replace(
'[impeccable@1] Required design corrections',
'[impeccable@1] Impeccable design hook blocked this write before it landed. Required design corrections',
'[impeccable@1] Design hook findings requiring review',
'[impeccable@1] Impeccable design hook blocked this write before it landed. Design hook findings requiring review',
);
return blocked.length > 4000 ? `${blocked.slice(0, 3984)}\n...(truncated)` : blocked;
}
@@ -415,10 +417,11 @@ async function main() {
if (!detector || typeof detector.detectText !== 'function') {
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
}
const scanOptions = designSystemOptions(config, detector, cwd);
let findings = [];
try {
findings = await detector.detectText(content, filePath);
findings = await detector.detectText(content, filePath, scanOptions);
} catch {
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
}
@@ -433,7 +436,7 @@ async function main() {
});
}
const message = cursorBlockMessage(filtered, filePath, config, cwd);
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
const sessionId = event.session_id || event.conversation_id || 'unknown';
const cache = readCache(cwd);
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
+413 -43
View File
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
enabled: true,
quiet: false,
auditLog: null,
designSystem: { enabled: true },
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
export function readConfig(cwd) {
const config = cloneDefaultConfig();
// Hook settings live under the `hook` key of config.json (shared) and
// config.local.json (per-developer, gitignored); local wins.
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
// Hook runtime settings live under `hook`; detector filters live under
// `detector`. Back-compat: older configs stored detector filters in `hook`,
// so read those first and let canonical `detector` settings win.
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
const raw = safeReadJson(filePath);
applyConfigSource(config, hookSection(raw));
applyDetectorConfigSource(config, detectorSection(raw));
}
return config;
}
@@ -148,6 +153,11 @@ function hookSection(raw) {
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
}
function detectorSection(raw) {
if (!raw || typeof raw !== 'object') return null;
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
}
function numberOr(value, fallback) {
return Number.isFinite(value) && value > 0 ? value : fallback;
}
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { ...DEFAULT_CONFIG.designSystem },
limits: { ...DEFAULT_CONFIG.limits },
};
}
function applyDetectorConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
config.designSystem = {
...config.designSystem,
enabled: raw.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
return config;
}
function applyConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
config.auditLog = raw.auditLog.trim();
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
applyDetectorConfigSource(config, raw);
if (raw.limits && typeof raw.limits === 'object') {
config.limits = {
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function colorIgnoreKey(value) {
const color = parseIgnoreColor(value);
if (!color) return '';
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
}
function parseIgnoreColor(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return null;
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) return parseHexIgnoreColor(hex[1]);
const rgb = text.match(/^rgba?\((.*)\)$/i);
if (rgb) {
const parts = splitColorArgs(rgb[1]);
if (parts.length < 3 || parts.length > 4) return null;
const r = parseRgbChannel(parts[0]);
const g = parseRgbChannel(parts[1]);
const b = parseRgbChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([r, g, b, a].some((v) => v === null)) return null;
return { r, g, b, a };
}
const hsl = text.match(/^hsla?\((.*)\)$/i);
if (hsl) {
const parts = splitColorArgs(hsl[1]);
if (parts.length < 3 || parts.length > 4) return null;
const h = parseHueChannel(parts[0]);
const s = parsePercentChannel(parts[1]);
const l = parsePercentChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([h, s, l, a].some((v) => v === null)) return null;
return hslToRgb(h, s, l, a);
}
return null;
}
function parseHexIgnoreColor(hex) {
if (hex.length === 3 || hex.length === 4) {
const r = parseInt(hex[0] + hex[0], 16);
const g = parseInt(hex[1] + hex[1], 16);
const b = parseInt(hex[2] + hex[2], 16);
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
return { r, g, b, a };
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
return { r, g, b, a };
}
function splitColorArgs(body) {
const text = String(body || '').trim();
if (!text) return [];
if (text.includes(',')) {
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
const last = parts[parts.length - 1];
if (last && last.includes('/')) {
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
return [...parts.slice(0, -1), ...split];
}
return parts;
}
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
}
function parseRgbChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const scaled = match[2] ? value * 2.55 : value;
if (scaled < 0 || scaled > 255) return null;
return Math.round(scaled);
}
function parseAlphaChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const alpha = match[2] ? value / 100 : value;
return alpha >= 0 && alpha <= 1 ? alpha : null;
}
function parseHueChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const unit = match[2] || 'deg';
if (unit === 'turn') return value * 360;
if (unit === 'rad') return value * (180 / Math.PI);
if (unit === 'grad') return value * 0.9;
return value;
}
function parsePercentChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)%$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
return value >= 0 && value <= 100 ? value / 100 : null;
}
function hslToRgb(hue, saturation, lightness, alpha) {
const h = (((hue % 360) + 360) % 360) / 360;
if (saturation === 0) {
const gray = clampByte(Math.round(lightness * 255));
return { r: gray, g: gray, b: gray, a: alpha };
}
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const toRgb = (t) => {
let channel = t;
if (channel < 0) channel += 1;
if (channel > 1) channel -= 1;
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
if (channel < 1 / 2) return q;
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
return p;
};
return {
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
g: clampByte(Math.round(toRgb(h) * 255)),
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
a: alpha,
};
}
function clampByte(value) {
return Math.min(255, Math.max(0, value));
}
function ignoreValueMatches(rule, entryValue, findingValue) {
if (entryValue === findingValue) return true;
if (rule !== 'design-system-color') return false;
const entryColor = colorIgnoreKey(entryValue);
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
}
export function normalizeIgnoreValueEntries(entries) {
if (!Array.isArray(entries)) return [];
const out = [];
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const normalized = { rule, value };
const files = uniqueStrings([
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
]);
if (files.length > 0) normalized.files = files;
if (typeof entry.reason === 'string' && entry.reason.trim()) {
normalized.reason = entry.reason.trim();
}
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
function mergeIgnoreValues(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(`${entry.rule}\0${entry.value}`, entry);
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(`${entry.rule}\0${entry.value}`, entry);
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
return Array.from(map.values());
}
function ignoreValueFilesKey(files) {
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
}
export function readCache(cwd) {
const raw = safeReadJson(getCachePath(cwd));
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
@@ -447,22 +630,54 @@ function isIgnoredFindingValue(finding, ignoreValues) {
const rule = normalizeIgnoreRule(finding.antipattern);
const value = extractFindingIgnoreValue(finding);
if (!rule || !value) return false;
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
return ignoreValues.some((entry) => {
const wildcardValue = entry.value === '*';
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
return findingMatchesScopedIgnoreFile(finding, entry.files);
});
}
function findingMatchesScopedIgnoreFile(finding, globs) {
const filePath = String(finding?.file || '').trim();
if (!filePath) return false;
if (matchesAnyGlob(filePath, globs)) return true;
const normalized = filePath.split(path.sep).join('/');
const parts = normalized.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('/');
if (matchesAnyGlob(suffix, globs)) return true;
}
return false;
}
export function extractFindingIgnoreValue(finding) {
if (!finding || typeof finding !== 'object') return '';
const rule = normalizeIgnoreRule(finding.antipattern);
if (rule !== 'overused-font') return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
const directValueRules = new Set([
'overused-font',
'bounce-easing',
'design-system-font',
'design-system-color',
'design-system-radius',
]);
if (!directValueRules.has(rule)) return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
}
function extractFindingIgnoreValueRaw(finding) {
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
if (direct) return direct;
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
for (const text of candidates) {
if (rule === 'bounce-easing') {
const motion = extractMotionIgnoreValue(text);
if (motion) return motion;
continue;
}
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
if (primary) return cleanIgnoreValueDisplay(primary[1]);
@@ -482,6 +697,24 @@ function extractFindingIgnoreValueRaw(finding) {
return '';
}
function extractMotionIgnoreValue(text) {
const tailwind = text.match(/\banimate-bounce\b/i);
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
if (animation) {
const token = animation[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
if (token) return cleanIgnoreValueDisplay(token);
}
return '';
}
function cleanIgnoreValueDisplay(value) {
return String(value || '')
.trim()
@@ -496,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
const known = new Set(fileEntry.findings || []);
const fresh = [];
for (const f of findings) {
const key = `${f.antipattern}:${f.line || 0}`;
const key = findingCacheKey(f);
if (known.has(key)) continue;
known.add(key);
fresh.push(f);
@@ -507,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
export function rememberFindings(cache, sessionId, filePath, findings) {
const fileEntry = ensureFile(cache, sessionId, filePath);
const known = new Set(fileEntry.findings || []);
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
for (const f of findings) known.add(findingCacheKey(f));
fileEntry.findings = Array.from(known);
ensureSession(cache, sessionId).updatedAt = Date.now();
}
function findingCacheKey(finding) {
const line = finding?.line || 0;
const value = extractFindingIgnoreValue(finding);
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
if (line > 0) return `${finding.antipattern}:${line}`;
if (value) return `${finding.antipattern}:0:${value}`;
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
}
export function renderTemplate(findings, filePath, config, opts = {}) {
if (!Array.isArray(findings) || findings.length === 0) return '';
const limits = config?.limits || DEFAULT_CONFIG.limits;
@@ -524,7 +767,7 @@ export function renderTemplate(findings, filePath, config, opts = {}) {
const shown = findings.slice(0, cap);
const remaining = total - shown.length;
const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
const header = `${ENVELOPE_PREFIX} Design hook findings requiring review in ${display} (${total} issue(s)):`;
const lines = shown.map((f) => formatFindingLine(f));
const more = remaining > 0
? `... and ${remaining} more (see /impeccable audit).`
@@ -556,7 +799,7 @@ function renderGroupedTemplate(groups, config, opts = {}) {
const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
const cwd = opts.cwd || process.cwd();
const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
const header = `${ENVELOPE_PREFIX} Design hook findings requiring review across ${realGroups.length} files (${total} issue(s)):`;
const lines = [];
let shownCount = 0;
@@ -716,13 +959,114 @@ export function resolveTargetFiles(event, projectCwd) {
export function resolveHarness(env = {}, event = null) {
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
if (explicit === 'cursor') return 'cursor';
if (explicit === 'github') return 'github';
if (explicit === 'claude' || explicit === 'codex') return 'claude';
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
// has no `tool_name`/`tool_input`. That shape is the discriminator.
if (event && typeof event === 'object'
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
&& event.tool_name === undefined && event.tool_input === undefined) {
return 'github';
}
if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
return 'claude';
}
// GitHub Copilot's postToolUse payload is
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
// `toolArgs` shape depends on the tool: the `edit`/`create`/`view` tools send a
// JSON *string* (double-encoded) carrying the file under `path`, e.g.
// "{\"path\":\"/abs/app.tsx\",\"old_str\":\"...\",\"new_str\":\"...\"}",
// while `apply_patch` sends a raw OpenAI-format patch string (handled below in
// normalizeGitHubEvent). The detector reads the file from disk after the tool
// ran, so only the path (not the proposed content) is needed here.
export function parseGitHubToolArgs(toolArgs) {
if (toolArgs && typeof toolArgs === 'object' && !Array.isArray(toolArgs)) return toolArgs;
if (typeof toolArgs === 'string' && toolArgs.trim()) {
try {
const parsed = JSON.parse(toolArgs);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}
return {};
}
// Copilot's `apply_patch` tool (used by interactive sessions and the cloud
// agent) sends a raw OpenAI-format patch string in toolArgs, not JSON:
// *** Begin Patch
// *** Add File: /abs/app.css
// +body { ... }
// *** End Patch
// The `view`/`edit`/`create` tools (seen in `copilot -p` runs) instead send a
// JSON string with the path under `path`. Both must map onto the internal shape.
const APPLY_PATCH_MARKER = /\*\*\* (?:Begin Patch|Add File:|Update File:|Delete File:)/;
function looksLikeApplyPatch(rawArgs) {
if (typeof rawArgs !== 'string' || !APPLY_PATCH_MARKER.test(rawArgs)) return false;
// Guard against an edit/create payload whose edited *content* happens to
// contain patch markers: that payload is a JSON object string, whereas a real
// apply_patch payload is a raw patch string that does not parse as JSON. Only
// treat non-JSON-object strings as apply_patch so edit events still get their
// `path` extracted.
try {
const parsed = JSON.parse(rawArgs);
if (parsed && typeof parsed === 'object') return false;
} catch { /* not JSON → genuine raw patch */ }
return true;
}
function applyPatchText(rawArgs) {
if (typeof rawArgs === 'string') {
if (APPLY_PATCH_MARKER.test(rawArgs)) return rawArgs;
// Defensive: a future Copilot build might JSON-wrap the patch.
const parsed = parseGitHubToolArgs(rawArgs);
return parsed.patch || parsed.input || parsed.command || '';
}
if (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)) {
return rawArgs.patch || rawArgs.input || rawArgs.command || '';
}
return '';
}
function normalizeGitHubEvent(event, projectCwd) {
const cwd = event.cwd || envProjectDir(projectCwd) || projectCwd;
const sessionId = event.sessionId || event.session_id || 'unknown';
const toolName = event.toolName || event.tool_name || null;
const toolInput = event.tool_input && typeof event.tool_input === 'object' ? { ...event.tool_input } : {};
const rawArgs = event.toolArgs;
let normalizedToolName = toolName;
if (toolName === 'apply_patch' || looksLikeApplyPatch(rawArgs)) {
// resolveTargetFiles() reads the touched paths from tool_input.command when
// tool_name is 'apply_patch', so normalize the name even if a future build
// sends the patch under a different tool label.
const patch = applyPatchText(rawArgs);
if (patch) {
toolInput.command = patch;
normalizedToolName = 'apply_patch';
}
} else {
const args = parseGitHubToolArgs(rawArgs);
const filePath = args.path || args.file_path || args.filePath || args.target_file;
if (typeof filePath === 'string' && filePath) toolInput.file_path = filePath;
}
return {
...event,
cwd,
session_id: sessionId,
tool_name: normalizedToolName,
tool_input: toolInput,
};
}
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
if (!event || typeof event !== 'object') return event;
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
if (harness !== 'cursor') return event;
const cwd = event.cwd
|| (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
@@ -918,7 +1262,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
const found = candidates.find((c) => fs.existsSync(c));
if (!found) return null;
const mod = await import(pathToFileURL(found));
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
detectorCache = {
detectText: mod.detectText,
detectHtml: mod.detectHtml,
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
};
return detectorCache;
}
@@ -953,12 +1301,12 @@ export function setDetectorForTesting(impl) {
// session" so the model knows it's a re-mind, not a new finding.
// ────────────────────────────────────────────────────────────────────────
const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
const STEER_LINE = 'That does not mean the design is good: keep following the project design system and the impeccable skill guidance.';
export function renderCleanAck(filePath, opts = {}) {
const cwd = opts.cwd || process.cwd();
const display = relativize(filePath, cwd);
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No deterministic design-quality issues found. ${STEER_LINE}`;
}
export function renderPendingAck(filePath, knownFindings, opts = {}) {
@@ -968,37 +1316,53 @@ export function renderPendingAck(filePath, knownFindings, opts = {}) {
// `knownFindings` here are the cache strings like "side-tab:3".
const sample = knownFindings.slice(0, 3).join(', ');
const more = count > 3 ? `, +${count - 3} more` : '';
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} finding(s) flagged earlier this session (${sample}${more}). Handle them before finalizing — the previous reminder still applies.`;
}
export function shouldEmitAckForFile(filePath) {
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
}
export function designSystemOptions(config, detector, projectCwd) {
if (config?.designSystem?.enabled === false) return {};
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
try {
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
return designSystem ? { designSystem } : {};
} catch {
return {};
}
}
export function appendDesignSystemNote(text, scanOptions) {
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
}
// The directive footer is the part of the hook output that steers model
// behavior. Three intentional moves:
// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
// revising..." which the model treats as a soft suggestion it can
// override when the user asked for any kind of throwaway / demo UI.
// 2. **Explicit exception clause.** Without it, the model will try to
// "fix" intentional bad fixtures, anti-pattern examples in docs, or
// test cases. Naming the exception inline beats hoping the model
// infers it from context.
// 2. **Explicit judgment clause.** Without it, the model will try to
// "fix" intentional motion, bad fixtures, anti-pattern examples in
// docs, or test cases. Naming the judgment inline beats hoping the
// model infers it from context.
// 3. **Acknowledgement instruction.** Hook output is injected as
// developer-role context, not a chat turn, so the user never sees the
// raw envelope. Asking the model to surface the fix in its reply is
// the cheapest way to make the feedback loop visible to the user.
// raw envelope. Asking the model to surface the resolution in its
// reply is the cheapest way to make the feedback loop visible.
function directiveFooter(display, opts = {}) {
const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
const fileIgnoreGuidance = opts.grouped
? 'run `/impeccable hooks ignore-file <path>` for the specific file'
: `run \`${ignoreFileCommand}\``;
return [
'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
'Handle these before finalizing: fix findings that are real design problems, or explicitly classify contextually intentional findings as false positives. Acknowledge what you changed or why you are leaving a finding unchanged.',
'',
'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
'Use context judgment before editing. A finding is not automatically a defect; literal or domain-appropriate motion, intentional demos or fixtures, documentation of bad design, and user-confirmed choices can be valid as-is.',
'',
`Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
`Do not change intentional design just to satisfy the hook, and do not silence a real finding with an inline ignore comment to skip fixing it. Suppress a finding only after the user explicitly confirms it is intentional. Prefer a config ignore (one reviewable place, the commands below); reach for an inline \`impeccable-disable <rule>\` comment only when the waiver must travel with a file that leaves the repo, such as an exported or standalone document. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
].join('\n');
}
@@ -1062,6 +1426,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
persistCache(projectCwd, cache);
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
}
const scanOptions = designSystemOptions(config, det, projectCwd);
let pendingWinner = null;
let cleanWinner = null;
@@ -1119,9 +1484,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
let findings;
let detectorThrew = false;
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
} else {
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
}
const filtered = filterFindings(findings || [], content, ext, config);
@@ -1152,7 +1517,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
if (freshGroups.length > 0) {
const firstGroup = freshGroups[0];
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
const allFindings = freshGroups.flatMap((group) => group.findings);
return {
exitCode: 0,
@@ -1184,7 +1549,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
}
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
return {
exitCode: 0,
stdout: payload(text, 'PostToolUse', harness),
@@ -1218,7 +1583,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
}
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
return {
exitCode: 0,
stdout: payload(text, 'PostToolUse', harness),
@@ -1256,6 +1621,11 @@ export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
if (harness === 'cursor') {
return JSON.stringify({ additional_context: text });
}
// GitHub Copilot's postToolUse hook injects context via a top-level
// `additionalContext` string (alongside an optional `modifiedResult`).
if (harness === 'github') {
return JSON.stringify({ additionalContext: text });
}
return JSON.stringify({
hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
});
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
stack.pop();
}
const key = content.slice(0, colonIdx).trim();
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
const parent = stack[stack.length - 1].obj;
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
return -1;
}
function unquoteYamlKey(key) {
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
return key.slice(1, -1);
}
return key;
}
function stripInlineYamlComment(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
@@ -0,0 +1,638 @@
/**
* CLI-side reader/writer for the unified `.impeccable` config.
*
* The CLI (published to npm) and the skill scripts (bundled into the install)
* live in separate trees and cannot share runtime code, so this duplicates a
* small slice of skill/scripts/hook-lib.mjs the config-path layout, detector
* ignore semantics, and the `.git/info/exclude` handling. Keep the schema,
* ignore filtering, and exclude marker in sync if either side changes.
*
* Schema (config.json shared / config.local.json gitignored, per-developer):
* {
* "detector": { "ignoreRules": [], "ignoreFiles": [], "ignoreValues": [], "designSystem": { "enabled": true } },
* "hook": { "consent": "accepted" | "declined", ... },
* "updateCheck": bool
* }
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
import { join, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
export function getConfigPath(root) {
return join(root, '.impeccable', 'config.json');
}
export function getLocalConfigPath(root) {
return join(root, '.impeccable', 'config.local.json');
}
function safeReadJson(filePath) {
try {
const raw = JSON.parse(readFileSync(filePath, 'utf-8'));
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
} catch {
return null;
}
}
function hookSection(raw) {
return raw && raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
}
function detectorSection(raw) {
return raw && raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
}
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
const DEFAULT_DETECTION_CONFIG = Object.freeze({
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { enabled: true },
});
function cloneDetectionConfig() {
return {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { ...DEFAULT_DETECTION_CONFIG.designSystem },
};
}
function cloneRawDetectionConfig() {
return {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
};
}
function applyDetectionConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
config.designSystem = {
...config.designSystem,
enabled: raw.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
return config;
}
function uniqueStrings(values) {
return Array.from(new Set(values.map(String)));
}
/**
* Detector filters shared by `npx impeccable detect` and the design hook.
* `hook.enabled` remains hook lifecycle state; manual CLI scans still run when
* the hook is disabled, but they honor the same ignore rules and design-system
* toggle.
*/
export function readDetectionConfig(root) {
const config = cloneDetectionConfig();
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
const raw = safeReadJson(filePath);
// Back-compat: old builds stored detector filters under hook.*.
applyDetectionConfigSource(config, hookSection(raw));
applyDetectionConfigSource(config, detectorSection(raw));
}
return config;
}
export function readRawDetectionConfig(root, opts = {}) {
const raw = safeReadJson(opts.local ? getLocalConfigPath(root) : getConfigPath(root));
const config = cloneRawDetectionConfig();
applyDetectionConfigSource(config, hookSection(raw));
applyDetectionConfigSource(config, detectorSection(raw));
return config;
}
export function writeDetectionConfig(root, detectorConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(root) : getConfigPath(root);
if (opts.local) ensureConfigGitExclude(root);
const existing = safeReadJson(filePath) || {};
const existingHook = hookSection(existing);
const nextHook = stripDetectorKeys(existingHook);
const nextDetector = {
...(detectorSection(existing) || {}),
...normalizeDetectionConfigForWrite(detectorConfig),
};
const next = {
...existing,
detector: nextDetector,
};
if (nextHook && Object.keys(nextHook).length > 0) {
next.hook = nextHook;
} else {
delete next.hook;
}
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
return filePath;
}
function normalizeDetectionConfigForWrite(config) {
const out = {};
if (Array.isArray(config?.ignoreRules)) {
out.ignoreRules = uniqueStrings(config.ignoreRules.map((rule) => normalizeIgnoreRule(rule)).filter(Boolean));
}
if (Array.isArray(config?.ignoreFiles)) {
out.ignoreFiles = uniqueStrings(config.ignoreFiles.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()));
}
out.ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
if (config?.designSystem && typeof config.designSystem === 'object' && !Array.isArray(config.designSystem)) {
out.designSystem = {
enabled: config.designSystem.enabled === false ? false : true,
};
}
return out;
}
function stripDetectorKeys(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const out = {};
for (const [key, value] of Object.entries(raw)) {
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
}
return out;
}
export function normalizeIgnoreValue(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function colorIgnoreKey(value) {
const color = parseIgnoreColor(value);
if (!color) return '';
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
}
function parseIgnoreColor(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return null;
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) return parseHexIgnoreColor(hex[1]);
const rgb = text.match(/^rgba?\((.*)\)$/i);
if (rgb) {
const parts = splitColorArgs(rgb[1]);
if (parts.length < 3 || parts.length > 4) return null;
const r = parseRgbChannel(parts[0]);
const g = parseRgbChannel(parts[1]);
const b = parseRgbChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([r, g, b, a].some((v) => v === null)) return null;
return { r, g, b, a };
}
const hsl = text.match(/^hsla?\((.*)\)$/i);
if (hsl) {
const parts = splitColorArgs(hsl[1]);
if (parts.length < 3 || parts.length > 4) return null;
const h = parseHueChannel(parts[0]);
const s = parsePercentChannel(parts[1]);
const l = parsePercentChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([h, s, l, a].some((v) => v === null)) return null;
return hslToRgb(h, s, l, a);
}
return null;
}
function parseHexIgnoreColor(hex) {
if (hex.length === 3 || hex.length === 4) {
const r = parseInt(hex[0] + hex[0], 16);
const g = parseInt(hex[1] + hex[1], 16);
const b = parseInt(hex[2] + hex[2], 16);
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
return { r, g, b, a };
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
return { r, g, b, a };
}
function splitColorArgs(body) {
const text = String(body || '').trim();
if (!text) return [];
if (text.includes(',')) {
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
const last = parts[parts.length - 1];
if (last && last.includes('/')) {
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
return [...parts.slice(0, -1), ...split];
}
return parts;
}
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
}
function parseRgbChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const scaled = match[2] ? value * 2.55 : value;
if (scaled < 0 || scaled > 255) return null;
return Math.round(scaled);
}
function parseAlphaChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const alpha = match[2] ? value / 100 : value;
return alpha >= 0 && alpha <= 1 ? alpha : null;
}
function parseHueChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const unit = match[2] || 'deg';
if (unit === 'turn') return value * 360;
if (unit === 'rad') return value * (180 / Math.PI);
if (unit === 'grad') return value * 0.9;
return value;
}
function parsePercentChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)%$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
return value >= 0 && value <= 100 ? value / 100 : null;
}
function hslToRgb(hue, saturation, lightness, alpha) {
const h = (((hue % 360) + 360) % 360) / 360;
if (saturation === 0) {
const gray = clampByte(Math.round(lightness * 255));
return { r: gray, g: gray, b: gray, a: alpha };
}
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const toRgb = (t) => {
let channel = t;
if (channel < 0) channel += 1;
if (channel > 1) channel -= 1;
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
if (channel < 1 / 2) return q;
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
return p;
};
return {
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
g: clampByte(Math.round(toRgb(h) * 255)),
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
a: alpha,
};
}
function clampByte(value) {
return Math.min(255, Math.max(0, value));
}
function ignoreValueMatches(rule, entryValue, findingValue) {
if (entryValue === findingValue) return true;
if (rule !== 'design-system-color') return false;
const entryColor = colorIgnoreKey(entryValue);
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
}
export function normalizeIgnoreValueEntries(entries) {
if (!Array.isArray(entries)) return [];
const out = [];
for (const entry of entries) {
if (!entry || typeof entry !== 'object') continue;
const rule = normalizeIgnoreRule(entry.rule);
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const normalized = { rule, value };
const files = uniqueStrings([
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
]);
if (files.length > 0) normalized.files = files;
if (typeof entry.reason === 'string' && entry.reason.trim()) {
normalized.reason = entry.reason.trim();
}
if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
normalized.createdAt = entry.createdAt.trim();
}
out.push(normalized);
}
return out;
}
function mergeIgnoreValues(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
return Array.from(map.values());
}
function ignoreValueFilesKey(files) {
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
}
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
function globToRegex(glob) {
let re = '^';
let i = 0;
while (i < glob.length) {
const c = glob[i];
if (c === '*') {
if (glob[i + 1] === '*') {
re += '.*';
i += 2;
if (glob[i] === '/') i += 1;
} else {
re += '[^/]*';
i += 1;
}
} else if (c === '?') {
re += '[^/]';
i += 1;
} else if (c === '{') {
const end = glob.indexOf('}', i);
if (end === -1) { re += '\\{'; i += 1; continue; }
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
re += `(?:${parts.join('|')})`;
i = end + 1;
} else if (/[.+^$()|[\]\\]/.test(c)) {
re += `\\${c}`;
i += 1;
} else {
re += c;
i += 1;
}
}
re += '$';
return new RegExp(re);
}
export function matchesAnyGlob(filePath, globs) {
if (!Array.isArray(globs) || globs.length === 0) return false;
const normalized = String(filePath || '').split(sep).join('/');
for (const glob of globs) {
try {
const re = globToRegex(String(glob));
if (re.test(normalized)) return true;
const base = normalized.split('/').pop();
if (re.test(base)) return true;
} catch {
/* malformed glob, skip */
}
}
return false;
}
export function shouldIgnoreDetectionFile(filePath, root, config) {
const globs = config?.ignoreFiles || [];
if (!Array.isArray(globs) || globs.length === 0) return false;
const raw = String(filePath || '').trim();
if (!raw) return false;
if (matchesAnyGlob(raw, globs)) return true;
try {
const abs = isAbsolute(raw) ? raw : resolve(root, raw);
if (matchesAnyGlob(abs, globs)) return true;
const rel = relative(root, abs);
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
return matchesAnyGlob(rel, globs);
}
} catch {
/* ignore */
}
return false;
}
export function filterDetectionFindings(findings, config) {
if (!Array.isArray(findings) || findings.length === 0) return [];
const ignoreRules = new Set((config?.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
const ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
return findings.filter((finding) => {
if (!finding || typeof finding !== 'object') return false;
if (ignoreRules.has(normalizeIgnoreRule(finding.antipattern))) return false;
if (isIgnoredFindingValue(finding, ignoreValues)) return false;
return true;
});
}
function isIgnoredFindingValue(finding, ignoreValues) {
if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
const rule = normalizeIgnoreRule(finding.antipattern);
const value = extractFindingIgnoreValue(finding);
if (!rule || !value) return false;
return ignoreValues.some((entry) => {
const wildcardValue = entry.value === '*';
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
return findingMatchesScopedIgnoreFile(finding, entry.files);
});
}
function findingMatchesScopedIgnoreFile(finding, globs) {
const filePath = String(finding?.file || '').trim();
if (!filePath) return false;
if (matchesAnyGlob(filePath, globs)) return true;
const normalized = filePath.split(sep).join('/');
const parts = normalized.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('/');
if (matchesAnyGlob(suffix, globs)) return true;
}
return false;
}
export function extractFindingIgnoreValue(finding) {
if (!finding || typeof finding !== 'object') return '';
const rule = normalizeIgnoreRule(finding.antipattern);
const directValueRules = new Set([
'overused-font',
'bounce-easing',
'design-system-font',
'design-system-color',
'design-system-radius',
]);
if (!directValueRules.has(rule)) return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
}
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
if (direct) return direct;
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
for (const text of candidates) {
if (rule === 'bounce-easing') {
const motion = extractMotionIgnoreValue(text);
if (motion) return motion;
continue;
}
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
if (primary) return cleanIgnoreValueDisplay(primary[1]);
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
if (family) return cleanIgnoreValueDisplay(family[1]);
const google = text.match(/[?&]family=([^&:;\n]+)/i);
if (google) {
try {
return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
} catch {
return cleanIgnoreValueDisplay(google[1]);
}
}
}
return '';
}
function extractMotionIgnoreValue(text) {
const tailwind = text.match(/\banimate-bounce\b/i);
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
if (animation) {
const token = animation[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
if (token) return cleanIgnoreValueDisplay(token);
}
return '';
}
function cleanIgnoreValueDisplay(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ');
}
/**
* The recorded design-hook decision: 'accepted' | 'declined' | undefined.
* config.local.json (per-developer) overrides config.json.
*/
export function getHookConsent(root) {
let consent;
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
const hook = hookSection(safeReadJson(filePath));
if (hook && (hook.consent === 'accepted' || hook.consent === 'declined')) consent = hook.consent;
}
return consent;
}
/**
* Persist the per-developer decision to config.local.json, preserving any
* sibling keys, and ensure the file is gitignored.
*/
export function setHookConsent(root, value) {
const filePath = getLocalConfigPath(root);
const existing = safeReadJson(filePath) || {};
const hook = hookSection(existing) || {};
const next = { ...existing, hook: { ...hook, consent: value } };
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
ensureConfigGitExclude(root);
return filePath;
}
const EXCLUDE_OPEN = '# impeccable-config-ignore-start';
const EXCLUDE_CLOSE = '# impeccable-config-ignore-end';
const EXCLUDE_PATTERNS = ['.impeccable/config.local.json'];
/**
* Add config.local.json to `.git/info/exclude` so a developer's decision is
* never committed. Idempotent via marker comments. Best-effort; returns false
* when there is no resolvable git dir.
*/
export function ensureConfigGitExclude(root) {
try {
const gitDir = resolveGitDir(root);
if (!gitDir) return false;
const target = join(gitDir, 'info', 'exclude');
const existing = existsSync(target) ? readFileSync(target, 'utf-8') : '';
const block = [EXCLUDE_OPEN, ...EXCLUDE_PATTERNS, EXCLUDE_CLOSE].join('\n');
const markerRe = new RegExp(`${escapeRegExp(EXCLUDE_OPEN)}[\\s\\S]*?${escapeRegExp(EXCLUDE_CLOSE)}`);
let updated;
if (markerRe.test(existing)) {
updated = existing.replace(markerRe, block);
} else {
const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
updated = `${prefix}${block}\n`;
}
if (updated !== existing) {
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, updated);
}
return true;
} catch {
return false;
}
}
function resolveGitDir(root) {
const dotGit = join(root, '.git');
if (!existsSync(dotGit)) return null;
try {
if (statSync(dotGit).isDirectory()) return dotGit;
// A `.git` file (worktree/submodule) points elsewhere: "gitdir: <path>".
const match = readFileSync(dotGit, 'utf-8').match(/gitdir:\s*(.+)/);
if (match) {
const resolved = match[1].trim();
return isAbsolute(resolved) ? resolved : join(root, resolved);
}
} catch {
/* fall through */
}
return null;
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
@@ -1,50 +1,52 @@
import fs from 'node:fs';
import path from 'node:path';
import { resolveProjectRoot } from '../context.mjs';
export const IMPECCABLE_DIR = '.impeccable';
export const LIVE_DIR = 'live';
export const CRITIQUE_DIR = 'critique';
export function getImpeccableDir(cwd = process.cwd()) {
return path.join(cwd, IMPECCABLE_DIR);
export function getImpeccableDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), IMPECCABLE_DIR);
}
export function getDesignSidecarPath(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), 'design.json');
export function getDesignSidecarPath(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), 'design.json');
}
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd, options = {}) {
const projectRoot = resolveProjectRoot(cwd, options);
const candidates = [
getDesignSidecarPath(cwd),
path.join(cwd, 'DESIGN.json'),
getDesignSidecarPath(cwd, options),
path.join(projectRoot, 'DESIGN.json'),
];
const contextLegacy = path.join(contextDir, 'DESIGN.json');
if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
return candidates;
}
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd, options = {}) {
return firstExisting(getDesignSidecarCandidates(cwd, contextDir, options));
}
export function getLiveDir(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), LIVE_DIR);
export function getLiveDir(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), LIVE_DIR);
}
export function getLiveConfigPath(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'config.json');
export function getLiveConfigPath(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'config.json');
}
export function getLegacyLiveConfigPath(scriptsDir) {
return path.join(scriptsDir, 'config.json');
}
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env, targetPath } = {}) {
if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
}
const primary = getLiveConfigPath(cwd);
const primary = getLiveConfigPath(cwd, { targetPath });
if (fs.existsSync(primary)) return primary;
if (scriptsDir) {
const legacy = getLegacyLiveConfigPath(scriptsDir);
@@ -53,16 +55,16 @@ export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = p
return primary;
}
export function getLiveServerPath(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'server.json');
export function getLiveServerPath(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'server.json');
}
export function getLegacyLiveServerPath(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live.json');
export function getLegacyLiveServerPath(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live.json');
}
export function readLiveServerInfo(cwd = process.cwd()) {
for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
export function readLiveServerInfo(cwd = process.cwd(), options = {}) {
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
try {
const info = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
if (info && typeof info.pid === 'number' && !isLiveServerPidReachable(info.pid)) {
@@ -88,37 +90,37 @@ export function isLiveServerPidReachable(pid) {
}
}
export function writeLiveServerInfo(cwd = process.cwd(), info) {
const filePath = getLiveServerPath(cwd);
export function writeLiveServerInfo(cwd = process.cwd(), info, options = {}) {
const filePath = getLiveServerPath(cwd, options);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(info));
return filePath;
}
export function removeLiveServerInfo(cwd = process.cwd()) {
for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
try { fs.unlinkSync(filePath); } catch {}
}
}
export function getLiveSessionsDir(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'sessions');
export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'sessions');
}
export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live', 'sessions');
export function getLegacyLiveSessionsDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'sessions');
}
export function getLiveAnnotationsDir(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'annotations');
export function getLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'annotations');
}
export function getCritiqueDir(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
export function getCritiqueDir(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), CRITIQUE_DIR);
}
export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live', 'annotations');
export function getLegacyLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'annotations');
}
function firstExisting(paths) {
@@ -0,0 +1,42 @@
class TargetArgError extends Error {
constructor(message, code) {
super(message);
this.name = 'TargetArgError';
this.code = code;
}
}
export function parseTargetPath(args = [], { strict = false } = {}) {
let targetPath = null;
for (let i = 0; i < args.length; i++) {
const arg = String(args[i]);
if (arg === '--target' || arg === '-t') {
const next = args[i + 1];
if (next && !String(next).startsWith('-')) {
targetPath = String(next);
i++;
continue;
}
if (strict) {
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
}
continue;
}
if (arg.startsWith('--target=')) {
const value = arg.slice('--target='.length);
if (value) {
targetPath = value;
continue;
}
if (strict) {
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
}
}
}
return targetPath;
}
export function parseTargetOptions(args = [], options = {}) {
const targetPath = parseTargetPath(args, options);
return targetPath ? { targetPath } : {};
}
+175 -83
View File
@@ -57,7 +57,7 @@
const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
const PREFIX = 'impeccable-live';
const PICK_CURSOR_CLASS = PREFIX + '-pick-cursor';
const PICK_CURSOR_STYLE_ID = PREFIX + '-pick-cursor-style';
const MANUAL_APPLY_STATE_TTL_MS = 15 * 60 * 1000;
const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
prefix: PREFIX,
@@ -152,6 +152,7 @@
let scrollLockTargetY = null;
let scrollLockRaf = null;
let scrollLockAbort = null;
const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';
// Dedicated key for scroll position - SEPARATE from LS_KEY so that
// saveSession's state updates don't clobber a carefully-captured scrollY.
@@ -1915,45 +1916,45 @@
syncPageInteractionCursor();
}
let pageInteractionCursorActive = false;
function ensurePickCursorStyle() {
if (document.getElementById(PREFIX + '-pick-cursor-style')) return;
const style = document.createElement('style');
style.id = PREFIX + '-pick-cursor-style';
/**
* Drive the page-level pick / insert cursor through the textContent of one
* injected <style>, never by mutating <html> (className or inline style).
* Frameworks that server-render the <html>/<body> roots (Next.js App Router)
* report a React 19 hydration mismatch when the client adds an attribute the
* server HTML never emitted, so a `class`/inline `style` toggled on
* `document.documentElement` trips "a tree hydrated but some attributes ...
* didn't match" on the next Fast-Refresh re-render. Keying the cursor off a
* stable-id <style> keeps the effect off the hydrated host elements (same
* shape as the scroll-anchor lock). A falsy cursor clears the rule.
*/
function setPageInteractionCursor(cursor) {
let style = document.getElementById(PICK_CURSOR_STYLE_ID);
if (!cursor) {
if (style) style.textContent = '';
return;
}
if (!style) {
style = document.createElement('style');
style.id = PICK_CURSOR_STYLE_ID;
// Styles the host page, not the chrome - inside the adapter's shadow UI
// root (uiAppendStyle's target) these selectors would match nothing.
(document.head || document.documentElement).appendChild(style);
}
style.textContent =
'html.' + PICK_CURSOR_CLASS + ' * { cursor: crosshair !important; }\n'
+ 'html.' + PICK_CURSOR_CLASS + ' [id^="' + PREFIX + '"],\n'
+ 'html.' + PICK_CURSOR_CLASS + ' [id^="' + PREFIX + '"] * { cursor: revert !important; }';
// Styles the host page, not the chrome - inside the adapter's shadow UI
// root (uiAppendStyle's target) these selectors would match nothing.
document.head.appendChild(style);
'* { cursor: ' + cursor + ' !important; }\n'
+ '[id^="' + PREFIX + '"],\n'
+ '[id^="' + PREFIX + '"] * { cursor: revert !important; }';
}
/** Page-level cursor while pick or insert mode is targeting page elements. */
function syncPageInteractionCursor() {
const pickCursor = state === 'PICKING' && pickActive && !insertActive;
let axisCursor = '';
if (state === 'PICKING' && insertActive) {
axisCursor = insertHoverAnchor ? cursorForInsertAxis(insertHoverAxis || 'column') : '';
}
if (pickCursor) {
ensurePickCursorStyle();
document.documentElement.classList.add(PICK_CURSOR_CLASS);
document.documentElement.style.cursor = '';
pageInteractionCursorActive = true;
return;
}
document.documentElement.classList.remove(PICK_CURSOR_CLASS);
if (axisCursor) {
document.documentElement.style.cursor = axisCursor;
pageInteractionCursorActive = true;
} else if (pageInteractionCursorActive) {
document.documentElement.style.cursor = '';
pageInteractionCursorActive = false;
let cursor = '';
if (state === 'PICKING' && pickActive && !insertActive) {
cursor = 'crosshair';
} else if (state === 'PICKING' && insertActive && insertHoverAnchor) {
cursor = cursorForInsertAxis(insertHoverAxis || 'column');
}
setPageInteractionCursor(cursor);
}
/**
@@ -2681,12 +2682,12 @@
});
const check = el('span', {
fontSize: '15px', lineHeight: '1', flexShrink: '0',
color: 'oklch(45% 0.15 145)',
color: 'oklch(45% 0.18 145)',
});
check.textContent = '\u2713';
row.appendChild(check);
const label = el('span', {
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
});
label.textContent = 'Variant applied';
row.appendChild(label);
@@ -5815,10 +5816,22 @@
try { history.scrollRestoration = 'manual'; } catch {}
const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
const prevBodyAnchor = document.body.style.overflowAnchor;
document.documentElement.style.overflowAnchor = 'none';
document.body.style.overflowAnchor = 'none';
// Suppress the browser's scroll-anchoring on the scroll root so it can't
// fight our manual scroll correction. Apply this as a stylesheet rule, not
// as inline `style` on <html>/<body>: those elements are server-rendered by
// frameworks like Next.js App Router, and mutating their inline style makes
// React 19 report a hydration mismatch on the next Fast-Refresh re-render.
// A <style> rule has the same computed effect without touching any hydrated
// element's attributes. Like the inline version, it is recreated on every
// startScrollLock call, so reload survival (driven by the persisted scroll
// key) is unaffected.
let anchorLockStyle = document.getElementById(SCROLL_ANCHOR_LOCK_ID);
if (!anchorLockStyle) {
anchorLockStyle = document.createElement('style');
anchorLockStyle.id = SCROLL_ANCHOR_LOCK_ID;
anchorLockStyle.textContent = 'html,body{overflow-anchor:none !important;}';
(document.head || document.documentElement).appendChild(anchorLockStyle);
}
const correct = (why) => {
scrollLockRaf = null;
@@ -5853,8 +5866,7 @@
scrollLockAbort = new AbortController();
scrollLockAbort.signal.addEventListener('abort', () => {
document.documentElement.style.overflowAnchor = prevHtmlAnchor;
document.body.style.overflowAnchor = prevBodyAnchor;
document.getElementById(SCROLL_ANCHOR_LOCK_ID)?.remove();
}, { once: true });
const sig = { signal: scrollLockAbort.signal };
// Track whether the most recent scroll came from a user gesture. We
@@ -6489,10 +6501,13 @@
) {
return;
}
if (isPageEditableElement(deepActive) && !isInlineEditActive(deepActive)) {
return;
}
// While a contenteditable text-leaf is focused, let the browser handle
// all keys except Escape. Escape cancels the current edit (restores
// original text) and blurs without saving, staying in CONFIGURING.
if (e.target.isContentEditable && inlineEditRows.some((r) => r.el === e.target)) {
if (e.target.isContentEditable && isInlineEditActive(e.target)) {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
@@ -7913,7 +7928,7 @@ void main() {
const barTopFromBottom = barRect && barRect.height > 0
? Math.max(16, window.innerHeight - barRect.top + 12)
: 16;
toastEl = el('div', {
const currentToast = el('div', {
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
transform: 'translateX(-50%) translateY(8px)',
background: C.ink, color: C.white,
@@ -7923,19 +7938,24 @@ void main() {
transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
});
toastEl.id = PREFIX + '-toast';
toastEl.textContent = message;
uiAppend(toastEl);
toastEl = currentToast;
currentToast.id = PREFIX + '-toast';
currentToast.textContent = message;
uiAppend(currentToast);
requestAnimationFrame(() => {
toastEl.style.opacity = '1';
toastEl.style.transform = 'translateX(-50%) translateY(0)';
if (toastEl !== currentToast) return;
currentToast.style.opacity = '1';
currentToast.style.transform = 'translateX(-50%) translateY(0)';
});
setTimeout(() => {
if (toastEl) {
toastEl.style.opacity = '0';
toastEl.style.transform = 'translateX(-50%) translateY(8px)';
setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
}
if (toastEl !== currentToast) return;
currentToast.style.opacity = '0';
currentToast.style.transform = 'translateX(-50%) translateY(8px)';
setTimeout(() => {
if (toastEl !== currentToast) return;
currentToast.remove();
toastEl = null;
}, 250);
}, duration);
}
@@ -8186,18 +8206,18 @@ void main() {
let voiceInterimBase = '';
/** @type {{ mode: 'steer'|'configure', input: HTMLInputElement, submit: () => void, beforeStart?: () => void } | null} */
let voiceCtx = null;
const PAGE_CHAT_COLLAPSED_W = '88px';
const PAGE_CHAT_COLLAPSED_W = '104px';
const PAGE_CHAT_PROCESSING_W = '76px';
const PAGE_CHAT_PLACEHOLDER_COLLAPSED = 'Steer…';
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
const STEER_AWAIT_TIMEOUT_MS = 120000;
const AGENT_STATUS_POLL_MS = 5000;
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
const GLOBAL_BAR_SECTION_GAP = 8;
const GLOBAL_BAR_INNER_GAP = 2;
const GLOBAL_BAR_INNER_PAD_LEFT = 2;
const PAGE_CHAT_EXPANDED_W = 'min(280px, 38vw)';
const PAGE_CHAT_EXPANDED_MAX_W = 280;
const ICON_PAGE_CHAT =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
const ICON_PAGE_VOICE =
@@ -8259,8 +8279,8 @@ void main() {
// Neutral hairline for internal control borders / dividers (was a warm
// gold rule that read as muddy champagne edges on the pill / input / count).
hairline: 'oklch(92% 0 0 / 0.12)',
text: 'oklch(84% 0.035 82)',
textDim: 'oklch(63% 0.024 82)',
text: 'oklch(91% 0 0)',
textDim: 'oklch(72% 0 0)',
accent: C.brand,
accentSoft: C.brandSoft,
exitHover: 'oklch(58% 0.15 35 / 0.18)',
@@ -8277,6 +8297,52 @@ void main() {
return barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());
}
function globalBarModeToggles() {
return [
uiGetById(PREFIX + '-pick-toggle'),
uiGetById(PREFIX + '-insert-toggle'),
uiGetById(PREFIX + '-detect-toggle'),
uiGetById(PREFIX + '-design-toggle'),
].filter(Boolean);
}
function applyGlobalBarLabelState(expandInactive, forceCollapse = false) {
globalBarModeToggles().forEach((toggle) => {
if (forceCollapse) toggle._collapseLabel?.(true);
else if (expandInactive || toggle.dataset.active === 'true') toggle._expandLabel?.();
else toggle._collapseLabel?.();
});
}
function syncGlobalBarExpandedLabels(expanded = globalBarEl?.matches(':hover')) {
const expandInactive = !!(expanded && !pageChatExpanded);
applyGlobalBarLabelState(expandInactive, pageChatExpanded);
if (expandInactive && globalBarEl && globalBarEl.scrollWidth > window.innerWidth - 16) {
applyGlobalBarLabelState(false);
}
}
function pageChatCollapsedWidthPx() {
const parsed = parseFloat(PAGE_CHAT_COLLAPSED_W);
return Number.isFinite(parsed) ? parsed : 104;
}
function pageChatExpandedWidth() {
if (!pageChatEl || !globalBarEl) return PAGE_CHAT_EXPANDED_MAX_W + 'px';
const currentChatWidth = pageChatEl.getBoundingClientRect().width || pageChatCollapsedWidthPx();
const barWidth = Math.max(globalBarEl.getBoundingClientRect().width || 0, globalBarEl.scrollWidth || 0);
const nonChatWidth = Math.max(0, barWidth - currentChatWidth);
const available = window.innerWidth - 16 - nonChatWidth;
const next = Math.max(pageChatCollapsedWidthPx(), Math.min(PAGE_CHAT_EXPANDED_MAX_W, available));
return Math.round(next) + 'px';
}
function syncPageChatExpandedWidth() {
if (!pageChatEl || !pageChatExpanded) return;
pageChatEl.style.width = pageChatExpandedWidth();
}
function syncPageChatChrome() {
if (!pageChatEl) return;
const P = pageChatPalette();
@@ -8312,6 +8378,21 @@ void main() {
&& !steerLocked;
}
function isPageEditableElement(el) {
if (!el || own(el)) return false;
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName || '')) return true;
return !!el.isContentEditable;
}
function isInlineEditActive(el) {
return !!el && inlineEditRows.some((r) => r.el === el);
}
function isPageEditableActive() {
const active = activeElementDeep();
return isPageEditableElement(active) && !isInlineEditActive(active);
}
function pageHasHostTextSelection() {
const sel = window.getSelection?.();
if (!sel || sel.isCollapsed) return false;
@@ -8325,6 +8406,7 @@ void main() {
function shouldSteerAutoFocus() {
return shouldFocusSteerChat()
&& !steerFocusSuspended
&& !isPageEditableActive()
&& performance.now() >= steerFocusPauseUntil;
}
@@ -8562,7 +8644,8 @@ void main() {
if (!pageChatEl || !pageChatInput) return false;
pageChatExpanded = true;
pageChatEl.dataset.expanded = 'true';
pageChatEl.style.width = PAGE_CHAT_EXPANDED_W;
syncGlobalBarExpandedLabels(false);
pageChatEl.style.width = pageChatExpandedWidth();
pageChatEl.style.cursor = steerLocked ? 'default' : 'text';
pageChatInput.placeholder = PAGE_CHAT_PLACEHOLDER_EXPANDED;
if (pageChatHint) {
@@ -8657,7 +8740,7 @@ void main() {
pageChatEl.setAttribute('aria-label', 'Steer the page');
pageChatExpanded = keepExpanded;
pageChatEl.dataset.expanded = keepExpanded ? 'true' : 'false';
pageChatEl.style.width = keepExpanded ? PAGE_CHAT_EXPANDED_W : PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.width = keepExpanded ? pageChatExpandedWidth() : PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.cursor = 'pointer';
if (pageChatInput) {
pageChatInput.disabled = false;
@@ -8971,6 +9054,7 @@ void main() {
pageChatEl.dataset.expanded = 'false';
pageChatEl.style.width = PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.cursor = 'pointer';
syncGlobalBarExpandedLabels(globalBarEl?.matches(':hover'));
if (blur) {
pageChatInput.blur();
pageChatInput.style.pointerEvents = 'none';
@@ -9064,9 +9148,9 @@ void main() {
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
uiAppendStyle(s);
}
@@ -9270,6 +9354,7 @@ void main() {
zIndex: Z.bar + 5,
display: 'flex', alignItems: 'stretch',
gap: '0',
width: 'max-content',
background: P.surface,
border: '1px solid ' + P.border,
borderRadius: '8px',
@@ -9277,6 +9362,8 @@ void main() {
fontFamily: FONT, fontSize: '12px', lineHeight: '1',
opacity: '0',
overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
maxWidth: 'calc(100vw - 16px)',
boxSizing: 'border-box',
transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
});
globalBarEl.id = PREFIX + '-global-bar';
@@ -9306,7 +9393,7 @@ void main() {
const agentDot = el('span', {
position: 'absolute', right: '-1px', bottom: '7px',
width: '6px', height: '6px', borderRadius: '50%',
background: 'oklch(78% 0.14 75)',
background: 'oklch(77% 0.13 82)',
boxShadow: '0 0 0 2px ' + P.surface,
display: 'none', pointerEvents: 'none',
});
@@ -9325,6 +9412,7 @@ void main() {
const inner = el('div', {
display: 'flex', alignItems: 'center',
padding: '4px 5px 4px ' + GLOBAL_BAR_INNER_PAD_LEFT + 'px', gap: GLOBAL_BAR_INNER_GAP + 'px',
flex: '0 0 auto',
});
inner.id = PREFIX + '-global-bar-inner';
globalBarEl.appendChild(inner);
@@ -9333,7 +9421,10 @@ void main() {
function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
const b = el('button', {
position: 'relative',
display: 'inline-flex', alignItems: 'center',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
boxSizing: 'border-box',
flex: '0 0 auto',
minWidth: '30px',
padding: '6px 8px', borderRadius: '7px',
border: 'none', background: 'transparent',
color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
@@ -9352,8 +9443,8 @@ void main() {
if (!labelEl) return;
labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px'; labelEl.style.transform = 'translateX(0)';
};
const collapse = () => {
if (!labelEl || b.dataset.active === 'true') return;
const collapse = (force = false) => {
if (!labelEl || (!force && b.dataset.active === 'true')) return;
labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0'; labelEl.style.transform = 'translateX(-4px)';
};
// Per-button hover only changes color (no layout). The label expand/
@@ -9408,11 +9499,11 @@ void main() {
// DESIGN.md panel toggle - quartet of color squares as the mark.
const designBtn = makeIconBtn({
id: PREFIX + '-design-toggle',
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
<span style="background:oklch(84% 0.19 80.46)"></span>
<span style="background:oklch(70% 0.12 188)"></span>
<span style="background:oklch(84% 0.035 82)"></span>
<span style="background:oklch(34% 0.014 82)"></span>
<span style="background:oklch(91% 0 0)"></span>
<span style="background:oklch(34% 0 0)"></span>
</span>`,
label: 'DESIGN.md',
ariaLabel: 'Toggle DESIGN.md panel',
@@ -9604,6 +9695,7 @@ void main() {
width: '1px', height: '18px',
background: P.hairline,
margin: '0 4px 0 2px',
flexShrink: '0',
});
inner.appendChild(divider);
@@ -9620,6 +9712,7 @@ void main() {
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
padding: '0', boxSizing: 'border-box',
width: '24px', height: '24px', borderRadius: '6px',
flexShrink: '0',
border: 'none', background: 'transparent',
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
@@ -9632,16 +9725,16 @@ void main() {
exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
inner.appendChild(exitBtn);
// Bar-level hover: expand every toggle's label at once; collapse on leave.
// Bar-level hover: expand mode labels unless Steer is using the space.
// Buttons with dataset.active="true" ignore collapse (their label stays).
const toggles = [pickBtn, insertBtn, detectBtn, designBtn];
globalBarEl.addEventListener('mouseenter', () => {
toggles.forEach((t) => t._expandLabel && t._expandLabel());
syncGlobalBarExpandedLabels(true);
syncPageChatExpandedWidth();
schedulePendingDockPosition();
setTimeout(schedulePendingDockPosition, 260);
});
globalBarEl.addEventListener('mouseleave', () => {
toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
syncGlobalBarExpandedLabels(false);
schedulePendingDockPosition();
setTimeout(schedulePendingDockPosition, 260);
});
@@ -9659,6 +9752,7 @@ void main() {
pendingDockResizeObserver.observe(globalBarEl);
}
window.addEventListener('resize', positionPendingDock);
window.addEventListener('resize', syncPageChatExpandedWidth);
requestAnimationFrame(() => {
globalBarEl.style.opacity = '1';
@@ -9705,9 +9799,7 @@ void main() {
// If the bar is currently under the cursor, keep all labels expanded -
// otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
// would collapse its label while the user's mouse is still on the bar.
if (globalBarEl && globalBarEl.matches(':hover')) {
[pickToggle, insertToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
}
syncGlobalBarExpandedLabels(globalBarEl && globalBarEl.matches(':hover'));
if (detectBadge) {
detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
@@ -9896,7 +9988,7 @@ void main() {
// Remove detection overlays
window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
setLiveState('IDLE');
document.getElementById(PREFIX + '-pick-cursor-style')?.remove();
document.getElementById(PICK_CURSOR_STYLE_ID)?.remove();
window.__IMPECCABLE_LIVE_INIT__ = false;
console.log('[impeccable] Live mode exited.');
}
@@ -9996,8 +10088,8 @@ void main() {
meta: 'oklch(55% 0 0)',
hairline: 'oklch(88% 0 0)',
hairlineSoft: 'oklch(92% 0 0)',
amber: 'oklch(70% 0.13 65)', // stale-hint accent
amberBg: 'oklch(95% 0.05 80)',
amber: 'oklch(77% 0.13 82)', // stale-hint accent
amberBg: 'oklch(89% 0.055 84)',
};
function designPanelCss(BP) {
@@ -10088,7 +10180,7 @@ void main() {
}
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
.error { color: oklch(45% 0.15 25); }
.error { color: oklch(58% 0.15 35); }
/* Stale hint */
.stale {
@@ -10240,8 +10332,8 @@ void main() {
content: ''; position: absolute; left: 4px; top: 13px;
width: 8px; height: 8px; border-radius: 50%;
}
.coll .do::before { background: oklch(62% 0.16 145); }
.coll .dont::before { background: oklch(58% 0.22 25); }
.coll .do::before { background: oklch(45% 0.18 145); }
.coll .dont::before { background: oklch(58% 0.15 35); }
.coll .overview-body {
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
+16 -11
View File
@@ -2,11 +2,11 @@
* CLI client for the live variant mode poll/reply protocol.
*
* Usage:
* npx impeccable poll # Block until browser event, print JSON
* npx impeccable poll --stream # Experimental: keep polling; one JSON line per event
* npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
* npx impeccable poll --reply <id> done # Reply "done" to event <id>
* npx impeccable poll --reply <id> error "msg" # Reply with error
* node <scripts_path>/live-poll.mjs # Block until browser event, print JSON
* node <scripts_path>/live-poll.mjs --stream # Experimental: keep polling; one JSON line per event
* node <scripts_path>/live-poll.mjs --timeout=600000 # Custom timeout (ms); default is long-poll friendly
* node <scripts_path>/live-poll.mjs --reply <id> done # Reply "done" to event <id>
* node <scripts_path>/live-poll.mjs --reply <id> error "msg" # Reply with error
*/
import { execFileSync } from 'node:child_process';
@@ -15,6 +15,11 @@ 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
@@ -27,7 +32,7 @@ const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_ed
function readServerInfo() {
const record = readLiveServerInfo(process.cwd());
if (!record) {
console.error('No running live server found. Start one with: npx impeccable live');
console.error(`No running live server found. Start one with: ${scriptCmd('live.mjs')}`);
process.exit(1);
}
return record.info;
@@ -82,7 +87,7 @@ export function parseReplyArgs(args) {
}
function validateReplyArgs({ id, status }) {
const usage = "Usage: npx impeccable poll --reply <id> <status> [--file path] [--data '<json>'] [message]";
const usage = `Usage: ${scriptCmd('live-poll.mjs')} --reply <id> <status> [--file path] [--data '<json>'] [message]`;
if (!id || id.startsWith('--')) {
const err = new Error(`${usage}\nMissing event id after --reply.`);
err.code = 'INVALID_REPLY_ARGS';
@@ -283,11 +288,11 @@ export async function runPollStream(base, token, {
function handlePollError(err) {
if (err.code === 'AUTH_FAILED') {
console.error(err.message);
console.error('Try restarting: npx impeccable live stop && npx impeccable live');
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: npx impeccable live');
console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
process.exit(1);
}
if (err.code === 'ACK_TIMEOUT') {
@@ -331,7 +336,7 @@ Harness note:
const info = readServerInfo();
const base = `http://localhost:${info.port}`;
// Reply mode: npx impeccable poll --reply <id> <status> [--file path] [--data '<json>'] [message]
// Reply mode: node <scripts_path>/live-poll.mjs --reply <id> <status> [--file path] [--data '<json>'] [message]
if (args.includes('--reply')) {
let reply;
try {
@@ -345,7 +350,7 @@ Harness note:
await postReply(base, info.token, reply);
} catch (err) {
if (err.cause?.code === 'ECONNREFUSED') {
console.error('Live server not running. Start one with: npx impeccable live');
console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
} else {
console.error('Reply failed:', err.message);
}
@@ -21,7 +21,7 @@ import path from 'node:path';
import net from 'node:net';
import { fileURLToPath } from 'node:url';
import { parseDesignMd } from './lib/design-parser.mjs';
import { resolveContextDir } from './context.mjs';
import { loadContext } from './context.mjs';
import {
assembleLiveBrowserScript,
assertLiveBrowserScriptParts,
@@ -55,7 +55,11 @@ 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 CONTEXT_DIR = resolveContextDir(process.cwd());
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
@@ -371,10 +375,7 @@ 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.
try {
fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
return true;
} catch { return false; }
return !!PROJECT_CONTEXT.hasProduct;
}
function statOrNull(filePath) {
@@ -549,8 +550,8 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
const token = url.searchParams.get('token');
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
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);
@@ -0,0 +1,30 @@
import path from 'node:path';
import { resolveProjectRoot } from './context.mjs';
import { parseTargetPath } from './lib/target-args.mjs';
export function resolveLiveTarget(cwd = process.cwd(), args = []) {
const originalCwd = path.resolve(cwd);
let targetPath = null;
try {
targetPath = parseTargetPath(args, { strict: true });
} catch (err) {
if (err?.name === 'TargetArgError') {
process.stderr.write(`${err.message}\n`);
process.exit(1);
}
throw err;
}
const absoluteTargetPath = targetPath
? path.isAbsolute(targetPath) ? targetPath : path.resolve(originalCwd, targetPath)
: null;
const projectRoot = targetPath
? resolveProjectRoot(originalCwd, { targetPath: absoluteTargetPath })
: originalCwd;
return {
originalCwd,
projectRoot,
targetPath,
absoluteTargetPath,
targetOptions: absoluteTargetPath ? { targetPath: absoluteTargetPath } : {},
};
}
@@ -2,7 +2,7 @@
* CLI helper: find an element in source and wrap it in a variant container.
*
* Usage:
* npx impeccable wrap --id SESSION_ID --count N --query "hero-combined-left" [--file path]
* node <scripts_path>/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
+72 -21
View File
@@ -21,14 +21,16 @@ import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { loadContext } from './context.mjs';
import { loadContext, resolveTargetSelection } from './context.mjs';
import { resolveFiles } from './live-inject.mjs';
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
import { resolveLiveTarget } from './live-target.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function liveCli() {
const args = process.argv.slice(2);
const liveTarget = resolveLiveTarget(process.cwd(), args);
if (args.includes('--help') || args.includes('-h')) {
console.log(`Usage: node live.mjs
@@ -38,37 +40,78 @@ Prepare everything for live variant mode in a single command:
- Starts (or reuses) the live server in the background
- Injects the browser script tag
- Reads PRODUCT.md / DESIGN.md for project context
- In monorepos, choose a child app first; --target <path> is the fallback/manual path
On success, prints a JSON blob with:
{ ok, serverPort, serverToken, pageFile, hasContext, context }
{ ok, serverPort, serverToken, pageFiles, projectRoot, repoRoot, targetPath, productPath, designPath }
On target_selection_required, prints:
{ ok: false, error: "target_selection_required", targetCandidates }
On config_missing, prints:
{ ok: false, error: "config_missing", configPath, hint }
The agent should then:
1. If config_missing, create the config and re-run this script
2. Optionally open the project's dev/preview URL in the browser (see reference/live.mdnot serverPort)
3. Enter the poll loop: node live-poll.mjs`);
1. If target_selection_required, ask which app to use and rerun from that child cwd
2. If config_missing, create the config and re-run this script
3. Optionally open the project's dev/preview URL in the browser (see reference/live.mdnot serverPort)
4. Enter the poll loop: node live-poll.mjs`);
process.exit(0);
}
const targetSelection = resolveTargetSelection(liveTarget.originalCwd, liveTarget.targetOptions);
if (targetSelection) {
console.log(JSON.stringify({
ok: false,
error: 'target_selection_required',
...targetSelection,
hint: 'Ask the user which app Impeccable should use, then rerun live from that child app cwd. Use --target <path> only as a fallback or explicit path diagnostic.',
}, null, 2));
process.exit(0);
}
const ctx = loadContext(liveTarget.originalCwd, liveTarget.targetOptions);
const activeCwd = ctx.projectRoot;
const outputTargetPath = liveTarget.targetPath || null;
const missingContext = missingLiveContext(ctx);
if (missingContext.length > 0) {
console.log(JSON.stringify({
ok: false,
error: 'context_missing',
missing: missingContext,
nextCommand: missingContext.includes('PRODUCT.md') ? 'init' : 'document',
targetPath: outputTargetPath,
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
productPath: ctx.productPath,
designPath: ctx.designPath,
}, null, 2));
process.exit(0);
}
// 1. Check config (fail fast if missing — no point starting anything else)
const checkOut = runScript('live-inject.mjs', ['--check']);
const checkOut = runScript('live-inject.mjs', ['--check'], { cwd: activeCwd });
const checkResult = safeParse(checkOut);
if (!checkResult || !checkResult.ok) {
console.log(JSON.stringify(checkResult || { ok: false, error: 'check_failed', raw: checkOut }));
console.log(JSON.stringify({
...(checkResult || { ok: false, error: 'check_failed', raw: checkOut }),
targetPath: outputTargetPath,
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
}));
process.exit(0);
}
// 2. Start server (or reuse existing)
const serverInfo = ensureServerRunning();
const serverInfo = ensureServerRunning(activeCwd);
if (!serverInfo) {
console.log(JSON.stringify({ ok: false, error: 'server_start_failed' }));
process.exit(1);
}
// 3. Inject the script tag at the current port
const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)]);
const injectOut = runScript('live-inject.mjs', ['--port', String(serverInfo.port)], { cwd: activeCwd });
const injectResult = safeParse(injectOut);
if (!injectResult || !injectResult.ok) {
console.log(JSON.stringify({
@@ -80,22 +123,23 @@ The agent should then:
process.exit(1);
}
// 4. Load PRODUCT.md + DESIGN.md context.
const ctx = loadContext(process.cwd());
// 5. Compute drift-heal: compare resolved inject targets against the
// 4. Compute drift-heal: compare resolved inject targets against the
// project's HTML files. Orphans are HTML files not covered by config.
// Warning only — the agent decides whether to act.
const resolvedFiles = resolveFiles(process.cwd(), checkResult.config);
const drift = scanForDrift(process.cwd(), resolvedFiles, checkResult.config);
const resolvedFiles = resolveFiles(activeCwd, checkResult.config);
const drift = scanForDrift(activeCwd, resolvedFiles, checkResult.config);
// 6. Emit everything the agent needs
// 5. Emit everything the agent needs
console.log(JSON.stringify({
ok: true,
serverPort: serverInfo.port,
serverToken: serverInfo.token,
pageFiles: resolvedFiles,
liveConfigPath: checkResult.path,
configDrift: drift,
targetPath: outputTargetPath,
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
hasProduct: ctx.hasProduct,
product: ctx.product,
productPath: ctx.productPath,
@@ -105,6 +149,13 @@ The agent should then:
}, null, 2));
}
function missingLiveContext(ctx) {
const missing = [];
if (!ctx.hasProduct) missing.push('PRODUCT.md');
if (!ctx.hasDesign) missing.push('DESIGN.md');
return missing;
}
/**
* Drift-heal scan. Walks the project for HTML files under common
* page-source directories (public/, src/, app/, pages/) and reports any
@@ -201,11 +252,11 @@ function globToRegex(pattern) {
// Helpers
// ---------------------------------------------------------------------------
function runScript(name, args) {
function runScript(name, args, options = {}) {
const scriptPath = path.join(__dirname, name);
const cmd = `node "${scriptPath}" ${args.map(a => `"${a}"`).join(' ')}`;
try {
return execSync(cmd, { encoding: 'utf-8', cwd: process.cwd(), timeout: 15_000 });
return execSync(cmd, { encoding: 'utf-8', cwd: options.cwd || process.cwd(), timeout: 15_000 });
} catch (err) {
// execSync throws on non-zero exit; return stdout if any
return err.stdout || err.message || '';
@@ -219,10 +270,10 @@ function safeParse(out) {
/**
* Return { pid, port, token } for the running live server, starting one if needed.
*/
function ensureServerRunning() {
function ensureServerRunning(cwd = process.cwd()) {
// Try to reuse an existing server
try {
const existing = readLiveServerInfo(process.cwd())?.info;
const existing = readLiveServerInfo(cwd)?.info;
if (existing && existing.pid) {
try {
process.kill(existing.pid, 0); // throws if dead
@@ -232,7 +283,7 @@ function ensureServerRunning() {
} catch { /* no PID file */ }
// Start a new server
const out = runScript('live-server.mjs', ['--background']);
const out = runScript('live-server.mjs', ['--background'], { cwd });
return safeParse(out);
}
+1 -2
View File
@@ -1,5 +1,4 @@
{
"description": "Impeccable design detector: runs after Edit/Write/apply_patch on UI files and surfaces findings as system reminders.",
"hooks": {
"PostToolUse": [
{
@@ -7,7 +6,7 @@
"hooks": [
{
"type": "command",
"command": "node \"$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs\"",
"command": "node \".agents/skills/impeccable/scripts/hook.mjs\"",
"timeout": 5,
"statusMessage": "Checking UI changes"
}
+2 -2
View File
@@ -1,7 +1,7 @@
---
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.6.0
version: 3.9.1
license: Apache 2.0
---
@@ -11,7 +11,7 @@ Designs and iterates production-grade frontend interfaces. Real working code, co
You MUST do these steps before proceeding:
1. Run `node .cursor/skills/impeccable/scripts/context.mjs` once per session. 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.
1. Run `node .cursor/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 .cursor/skills/impeccable/scripts/context.mjs --target <path>` 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/<command>.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.
+66 -59
View File
@@ -1,12 +1,12 @@
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 and personality through stronger hierarchy, committed scale, and decisive type.
When asked for "bolder," AI defaults to the same tired tricks: cyan/purple gradients, glassmorphism, neon accents on dark backgrounds, gradient text on metrics. These are the opposite of bold. Reject them first, then increase visual impact by making the existing design language more decisive, specific, and committed.
---
## Register
Brand: "bolder" means distinctive. Extreme scale, unexpected color, typographic risk, committed POV.
Brand: "bolder" means distinctive. Express a stronger point of view through hierarchy, pacing, proportion, copy, evidence, and one committed visual idea.
Product: "bolder" rarely means theatrics; those undermine trust. It means stronger hierarchy, clearer weight contrast, one sharper accent, more committed density. The amplification is in clarity, not drama.
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.
---
@@ -15,98 +15,105 @@ Product: "bolder" rarely means theatrics; those undermine trust. It means strong
Analyze what makes the design feel too safe or boring:
1. **Identify weakness sources**:
- **Generic choices**: System fonts, basic colors, standard layouts
- **Timid scale**: Everything is medium-sized with no drama
- **Low contrast**: Everything has similar visual weight
- **Static**: No motion, no energy, no life
- **Predictable**: Standard patterns with no surprises
- **Flat hierarchy**: Nothing stands out or commands attention
- **Generic choices**: The page could belong to any product in the category.
- **Timid scale**: Everything is medium-sized with no clear lead.
- **Low contrast**: Important and supporting elements have similar visual weight.
- **Static**: The surface has no meaningful moment of emphasis.
- **Predictable**: The composition follows a default pattern without a point of view.
- **Flat hierarchy**: Nothing stands out or commands attention.
2. **Understand the context**:
- What's the brand personality? (How far can we push?)
- What's the purpose? (Marketing can be bolder than financial dashboards)
- Who's the audience? (What will resonate?)
- What are the constraints? (Brand guidelines, accessibility, performance)
- What is the brand personality?
- What is the purpose of this surface?
- Who is the audience?
- What design system, tokens, components, and visual conventions already exist?
If any of these are unclear from the codebase, ask the user directly to clarify what you cannot infer.
**CRITICAL**: "Bolder" doesn't mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random chaos.
**CRITICAL**: "Bolder" does not mean chaotic or garish. It means distinctive, memorable, and confident. Think intentional drama, not random noise.
**WARNING - AI SLOP TRAP**: Review ALL the DON'T guidelines from the parent impeccable skill (already loaded in this context) before proceeding. Bold means distinctive, not "more effects."
## Design-System Lock
If the project has `DESIGN.md`, tokens, theme variables, or established component styles, treat that system as the boundary. Make the existing language stronger before adding new language.
Do not invent new colors, gradients, radii, shadows, fonts, decorative backgrounds, or effects just because the request says "bolder." A bolder pass should usually change emphasis, proportion, rhythm, density, contrast, copy, artifact specificity, and layout relationships while staying inside the documented system.
If the existing system is genuinely too limited to express the bolder direction, stop and ask the user before expanding it. Name the exact additions, the role each would play, and why the current system cannot do the job. If the user approves expansion, update the design system or tokens alongside the implementation.
## Plan Amplification
Create a strategy to increase impact while maintaining coherence:
- **Focal point**: What should be the hero moment? (Pick ONE, make it amazing)
- **Personality direction**: Maximalist chaos? Elegant drama? Playful energy? Dark moody? Choose a lane.
- **Risk budget**: How experimental can we be? Push boundaries within constraints.
- **Hierarchy amplification**: Make big things BIGGER, small things smaller (increase contrast)
- **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 across these dimensions:
Systematically increase impact through intention, not a menu of effects:
### Typography Amplification
- **Replace generic fonts**: Swap system fonts for distinctive choices (see the parent skill's typography guidelines and the [Reference Material section of typeset.md](typeset.md#reference-material) for inspiration)
- **Extreme scale**: Create dramatic size jumps (3x-5x differences, not 1.5x)
- **Weight contrast**: Pair 900 weights with 200 weights, not 600 with 400
- **Unexpected choices**: Variable fonts, display fonts for headlines, condensed/extended widths, monospace as intentional accent (not as lazy "dev tool" default)
- 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 Intensification
- **Increase saturation**: Shift to more vibrant, energetic colors (but not neon)
- **Bold palette**: Introduce unexpected color combinations. Avoid the purple-blue gradient AI slop
- **Dominant color strategy**: Let one bold color own 60% of the design
- **Sharp accents**: High-contrast accent colors that pop
- **Tinted neutrals**: Replace pure grays with tinted grays that harmonize with your palette
- **Rich gradients**: Intentional multi-stop gradients (not generic purple-to-blue)
### 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 Drama
- **Extreme scale jumps**: Make important elements 3-5x larger than surroundings
- **Break the grid**: Let hero elements escape containers and cross boundaries
- **Asymmetric layouts**: Replace centered, balanced layouts with tension-filled asymmetry
- **Generous space**: Use white space dramatically (100-200px gaps, not 20-40px)
- **Overlap**: Layer elements intentionally for depth
### 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.
### Visual Effects
- **Dramatic shadows**: Large, soft shadows for elevation (but not generic drop shadows on rounded rectangles)
- **Background treatments**: Mesh patterns, noise textures, geometric patterns, intentional gradients (not purple-to-blue)
- **Texture & depth**: Grain, halftone, duotone, layered elements. NOT glassmorphism (it's overused AI slop)
- **Borders & frames**: Thick borders, decorative frames, custom shapes (not rounded rectangles with colored border on one side)
- **Custom elements**: Illustrative elements, custom icons, decorative details that reinforce brand
### 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
- **Hero moment**: One signature entrance, once. Not on every visit and not on every section.
- **Micro-interactions**: Satisfying hover effects, click feedback, state changes.
- **Transitions**: Smooth, noticeable transitions using ease-out-quart/quint/expo (not bounce or elastic, which cheapen the effect).
- **Bolder scroll-fade-rise on every section.** That's the saturated AI default, the opposite of bold.
- 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
- **Hero moments**: Create clear focal points with dramatic treatment
- **Diagonal flows**: Escape horizontal/vertical rigidity with diagonal arrangements
- **Full-bleed elements**: Use full viewport width/height for impact
- **Unexpected proportions**: Golden ratio? Throw it out. Try 70/30, 80/20 splits
- 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 effects randomly without purpose (chaos ≠ bold)
- Sacrifice readability for aesthetics (body text must be readable)
- Make everything bold (then nothing is bold; you need contrast)
- Ignore accessibility (bold design must still meet WCAG standards)
- Overwhelm with motion (animation fatigue is real)
- Copy trendy aesthetics blindly (bold means distinctive, not derivative)
- 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?
- **Performant**: Do all these effects run smoothly?
- **Accessible**: Does it still meet accessibility standards?
- **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."
@@ -5,8 +5,9 @@ Resolve one stable target, run two independent assessments, synthesize a design
### Hard Invariants
- Assessment A (design review) and Assessment B (detector/browser evidence) are both required.
- Assessment A and B MUST run as two isolated sub-agents whenever a sub-agent/Task tool is exposed. Running them inline in this context is "possible" but is NOT permitted; it is a degraded run. Inline is allowed ONLY when no sub-agent tool exists (or the user declined, on harnesses that ask).
- If you degrade for any reason, the report's first line MUST be a banner: `⚠️ DEGRADED: single-context (<reason>)`. 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.
- If sub-agents are unavailable, fall back sequentially: finish and record Assessment A first, then run Assessment B, then synthesize.
- A skipped detector is a failed critique run unless `detect.mjs` is missing or crashes after a real attempt.
- Viewable targets require browser inspection when available.
- Any local server started only for critique visualization must run in the background, have a recorded stop method, and be stopped before final reporting unless the user asks to keep it.
@@ -27,7 +28,13 @@ Resolve one stable target, run two independent assessments, synthesize a design
### Assessment Orchestration
Delegate Assessment A and Assessment B to separate sub-agents when possible. They must not see each other's output. Do not show findings to the user until synthesis.
Delegate Assessment A and Assessment B to separate sub-agents. They must not see each other's output. Do not show findings to the user until synthesis.
Sub-agent gate (all harnesses):
- Unless a harness-specific gate below overrides this, spawn A and B as two isolated, parallel sub-agents whenever a sub-agent/Task tool is exposed. This is the default and is mandatory; do not run them inline because it is faster.
- "Unavailable" means exactly one thing: no sub-agent/Task tool is exposed in this session (or, on harnesses that ask, the user declined). It does not mean inconvenient.
- If and only if sub-agents are unavailable, fall back sequentially: finish and record Assessment A, then run Assessment B, then synthesize, and emit the degraded banner.
- Whichever path you take, declare it in the report header (see Report header provenance). Skipping sub-agents without the banner is the most common failure of this command.
If browser automation is available, each assessment creates its own new tab. Never reuse an existing tab, even if it is already at the right URL.
@@ -61,7 +68,7 @@ node .cursor/skills/impeccable/scripts/detect.mjs --json [target]
Browser visualization is required for a viewable target when browser automation is available. Use a localhost dev/static URL for local files; avoid `file://` unless the available browser explicitly supports this workflow. Overlay flow:
1. Create a fresh tab and navigate.
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 `<script>` tag. Read-only evaluate APIs do not count.
3. If mutation is unavailable, skip live server, browser presentation, and injection; report fallback signal.
4. If mutation is available, start `node .cursor/skills/impeccable/scripts/live-server.mjs --background`, present the browser if supported, label `[Human]`, scroll top, inject `http://localhost:PORT/detect.js`, wait 2-3 seconds, read `impeccable` console messages, then stop the live server.
@@ -79,6 +86,12 @@ The chat response is the primary user-facing deliverable. Present the full struc
Structure your feedback as a design director would:
#### Report header provenance
The report's first line MUST declare how the assessments were run, so a degraded run is never silent:
- Dual-agent: `Method: dual-agent (A: <agent-id> · B: <agent-id>)`
- Degraded: `⚠️ DEGRADED: single-context (<reason, e.g. no sub-agent tool exposed>)`
#### Design Health Score
> *Consult the [Heuristics Scoring Guide](#heuristics-scoring-guide) section below.*
@@ -1,6 +1,6 @@
Generate a `DESIGN.md` file at the project root that captures the current visual design system, so AI agents generating new screens stay on-brand.
DESIGN.md follows the [official Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
DESIGN.md follows the [official DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md): YAML frontmatter carrying machine-readable design tokens, followed by a markdown body with exactly six sections in a fixed order. **Tokens are normative; prose provides context for how to apply them.** Sections may be omitted when not relevant, but **do not reorder them and do not rename them**. Section headers must match the spec character-for-character so the file stays parseable by other DESIGN.md-aware tools (Stitch itself, awesome-design-md, skill-rest, etc.).
## The frontmatter: token schema
+17 -9
View File
@@ -2,11 +2,13 @@
Manage the **design detector hook** for the current project.
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code and Codex use `PostToolUse` and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
The hook runs the impeccable design detector on direct file edits to design-relevant files (`.tsx`, `.jsx`, `.html`, `.vue`, `.svelte`, `.astro`, `.css`, `.scss`, `.sass`, `.less`, `.ts`, `.js`). Claude Code, Codex, and GitHub Copilot use a post-tool-use hook and push a short system reminder into the agent's context after the edit; findings get a correction prompt, pending issues get a re-nudge, and clean UI-ish files get a short ack unless quiet mode is on (`hook.quiet` in config). Plain `.ts` and `.js` files are still scanned, but stay quiet unless the detector finds something. Cursor uses `preToolUse` to block bad proposed writes before they land and stays silent when it allows a clean write.
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook settings live under its `hook` key). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
This command toggles the hook **per project** by editing `.impeccable/config.json` (the unified Impeccable config; hook runtime settings live under its `hook` key, and shared detector ignores live under `detector`). Per-developer overrides, including the install consent decision (`hook.consent`) the CLI records, live in the gitignored `.impeccable/config.local.json`. Set `hook.enabled: false` to turn the hook off, `hook.quiet: true` to silence the clean/pending acks, or `hook.auditLog` to a file path for an NDJSON log. The legacy `IMPECCABLE_HOOK_DISABLED`, `IMPECCABLE_HOOK_QUIET`, and `IMPECCABLE_HOOK_LOG` env vars are still honored and override these config values when set.
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), and Cursor (`.cursor/hooks.json` in the project).
Manual `npx impeccable detect` scans use the same project filter config by default: `detector.ignoreRules`, `detector.ignoreFiles`, `detector.ignoreValues`, and `detector.designSystem.enabled`. `hook.enabled` only controls automatic hook execution, not manual CLI scans. Use `npx impeccable detect --no-config ...` for a raw detector run that ignores project config/context. Use `npx impeccable ignores ...` for direct CLI CRUD on the same detector ignores.
Supported harnesses: Claude Code (`.claude/settings.local.json` in the project, which is gitignored so the hook stays machine-local; a hook you move into the shared `settings.json` is honored in place too), Codex (`.codex/hooks.json` in the project), Cursor (`.cursor/hooks.json` in the project), and GitHub Copilot (`.github/hooks/impeccable.json` in the project, a team-shared committed file that both the Copilot CLI and the cloud agent read). For the Copilot CLI, repo-level hooks fire once `.github/hooks/impeccable.json` is committed to the repository's default branch.
On **Cursor**, `preToolUse` checks proposed Write/Edit/Shell write content and denies only when the real detector finds an issue. The denial message is visible to the agent as the tool error, so the agent can reconsider before the bad write lands.
@@ -19,8 +21,8 @@ The first argument is the action. Defaults to `status`.
| `status` | Print current state, shared/local config paths, ignored rules / files / values, env override. |
| `on` | Set `enabled: true` in `.impeccable/config.json`, record local hook consent as accepted, and install/repair provider hook manifests when the skill is installed. |
| `off` | Set `enabled: false` in `.impeccable/config.json`. |
| `ignore-rule <id>` | Append `<id>` to `ignoreRules`; for `overused-font`, requires `--all-values`. |
| `ignore-file <glob>` | Append `<glob>` to `ignoreFiles`. |
| `ignore-rule <id>` | Append `<id>` to `detector.ignoreRules`; for `overused-font`, requires `--all-values`. |
| `ignore-file <glob>` | Append `<glob>` to `detector.ignoreFiles`. |
| `ignore-value <id> <value> [--shared] [--reason "..."]` | Append a rule/value suppression to shared `.impeccable/config.json`. |
| `ignore-value <id> <value> --local [--reason "..."]` | Append a private rule/value suppression to `.impeccable/config.local.json`. |
| `reset` | Delete the project config, dedup cache, and Cursor pending queue. |
@@ -46,10 +48,10 @@ The hook itself never writes ignore config. Persist an exception only after the
Prefer the narrowest exception:
- If the finding line shows an exact `ignore-value` command, run that command. This writes shared `.impeccable/config.json` by default.
- For `overused-font`, use `ignore-value` when the user confirms a specific font. Do not use `ignore-rule overused-font` for a specific font.
- For value-specific findings such as `overused-font` and `bounce-easing`, use `ignore-value` when the user confirms the specific value. Do not use `ignore-rule overused-font` for a specific font.
- If the finding has no value-specific command, such as `side-tab`, prefer `ignore-file <path>` for the current file.
- Use `ignore-rule <id>` only when the user asks to suppress that whole rule across the project. For broad overused-font suppression, use `ignore-rule overused-font --all-values` only when the user asks to ignore overused fonts generally.
- Do not add source comments such as `impeccable: ignore`; inline comments pollute code and are not a supported suppression mechanism.
- Prefer config ignores (the commands above) by default; they keep suppressions in one reviewable place. Reach for an inline comment only when the waiver must travel with a single file that leaves the repo (a generated/exported standalone document, an emailed HTML file). The supported marker is `impeccable-disable <rule>` (whole file) or `impeccable-disable-line` / `impeccable-disable-next-line` (one line), in any comment syntax, with an optional reason after `:` or `--`. The detector honors it by default; `--no-inline-ignores` or `--no-config` bypasses it.
Example value-specific exception:
@@ -57,6 +59,12 @@ Example value-specific exception:
node .cursor/skills/impeccable/scripts/hook-admin.mjs ignore-value overused-font Inter --shared --reason "User confirmed Inter is intentional"
```
Example intentional motion exception:
```bash
node .cursor/skills/impeccable/scripts/hook-admin.mjs ignore-value bounce-easing bounce-ball --shared --reason "User confirmed ball bounce animation is intentional"
```
Example whole-rule font exception:
```bash
@@ -73,8 +81,8 @@ node .cursor/skills/impeccable/scripts/hook-admin.mjs ignore-file "src/legacy/Ca
- Never modify `.impeccable/config.json` or `.impeccable/config.local.json` by hand from this command. Always go through `hook-admin.mjs` so writes stay validated and the file shape stays consistent.
- Do not edit the hook scripts themselves (`hook.mjs`, `hook-lib.mjs`, `hook-before-edit.mjs`) from this flow. Those are skill plumbing.
- Cursor can block a proposed write when the detector finds a real issue. Claude Code and Codex do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, and `.cursor/hooks.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks.
- Cursor can block a proposed write when the detector finds a real issue. Claude Code, Codex, and GitHub Copilot do not block the edit; they emit a post-edit reminder instead. Disabling stops both blocking and reminders.
- The hook is bundled with the Impeccable skill and installed through project-local manifests: `.claude/settings.local.json`, `.codex/hooks.json`, `.cursor/hooks.json`, and `.github/hooks/impeccable.json`. On Codex, the user must approve the hook via `/hooks` the first time. On Cursor, confirm hooks are enabled under Settings -> Hooks. On GitHub Copilot, the CLI loads `.github/hooks/impeccable.json` once it is committed to the repository's default branch, and the cloud agent reads it from the repo directly.
## Failure modes
+1 -1
View File
@@ -3,7 +3,7 @@
The setup command for a project. One codebase crawl feeds everything it writes:
- **PRODUCT.md** (strategic): root project file for register, target users, product purpose, brand personality, anti-references, strategic design principles. Answers "who/what/why".
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [Google Stitch DESIGN.md format](https://stitch.withgoogle.com/docs/design-md/format/). Answers "how it looks".
- **DESIGN.md** (visual): root project file for visual theme, color palette, typography, components, layout. Follows the [DESIGN.md format spec](https://raw.githubusercontent.com/google-labs-code/design.md/main/docs/spec.md). Answers "how it looks".
- **`.impeccable/live/config.json`** (live mode): pre-configured so `/impeccable live` boots straight into variant mode with no first-time detour.
It closes by pointing the user at the best command to run next. Every other impeccable command reads PRODUCT.md and DESIGN.md before doing any work.
+1 -1
View File
@@ -8,7 +8,7 @@ A running dev server with hot module replacement (Vite, Next.js, Bun, etc.), OR
Execute in order. No step skipped, no step reordered.
1. `live.mjs`: boot.
1. `live.mjs`: boot. If the request names or implies a file, route, or app inside a monorepo, infer the concrete path and run `node .cursor/skills/impeccable/scripts/live.mjs --target <path>` instead; then run the rest of this live session from the returned `projectRoot`.
2. Open the app URL that serves `pageFile` (infer from `package.json`, docs, terminal output, or an open tab). Never use `serverPort`; it's the helper, not the app. **Cursor:** `browser_navigate` to that URL before polling; do not skip. **Other harnesses:** use the available browser tool; if the URL is uncertain, ask the user once.
3. Poll loop with the default long timeout (600000 ms). After every event or `--reply`, run `live-poll.mjs` again immediately. Never pass a short `--timeout=`.
+712 -31
View File
@@ -5,11 +5,12 @@
* init flow.
*
* Path resolution (first match wins):
* 1. cwd, if PRODUCT.md or DESIGN.md is there
* 2. .agents/context/ then docs/
* 3. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) power-user
* 1. Active project root, if PRODUCT.md or DESIGN.md is there
* 2. Active project .agents/context/ then docs/
* 3. Monorepo root context, using the same order, as a per-file fallback
* 4. $IMPECCABLE_CONTEXT_DIR (absolute or cwd-relative) power-user
* escape hatch, only consulted when defaults are empty
* 4. cwd as a "nothing found" default
* 5. Active project root as a "nothing found" default
*
* `resolveContextDir()` and `loadContext()` are also exported for the
* server-side scripts (live.mjs, live-server.mjs) that need the structured
@@ -19,15 +20,30 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseTargetOptions } from './lib/target-args.mjs';
const PRODUCT_NAMES = ['PRODUCT.md', 'Product.md', 'product.md'];
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
const FALLBACK_DIRS = ['.agents/context', 'docs'];
const MONOREPO_MARKER_FILES = ['pnpm-workspace.yaml', 'turbo.json', 'nx.json', 'lerna.json'];
const MONOREPO_FALLBACK_PROJECT_DIRS = ['apps', 'packages'];
const WORKSPACE_DISCOVERY_IGNORED_DIRS = new Set([
'node_modules',
'.git',
'dist',
'build',
'.next',
'.nuxt',
'.svelte-kit',
'.turbo',
'.cache',
'coverage',
]);
// ─── Update check ──────────────────────────────────────────────────────────
// Piggyback a lightweight skill-version check on the once-per-session boot.
// When a newer skill ships, append an UPDATE_AVAILABLE directive so the agent
// can offer `npx impeccable skills update`. Everything here is best-effort and
// can offer `npx impeccable update`. Everything here is best-effort and
// silent on failure: a network problem, sandbox, or missing cache must never
// block context output or print an error.
@@ -38,41 +54,623 @@ const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // throttle the network poll to o
const RENOTIFY_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; // don't re-surface the same version for a week
const FETCH_TIMEOUT_MS = 1200;
export function resolveContextDir(cwd = process.cwd()) {
if (firstExisting(cwd, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return cwd;
}
for (const rel of FALLBACK_DIRS) {
const candidate = path.resolve(cwd, rel);
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return candidate;
}
}
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
if (envDir && envDir.trim()) {
const trimmed = envDir.trim();
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
}
return cwd;
export function resolveContextDir(cwd = process.cwd(), options = {}) {
return resolveContext(cwd, options).contextDir;
}
export function loadContext(cwd = process.cwd()) {
const contextDir = resolveContextDir(cwd);
const productPath = firstExisting(contextDir, PRODUCT_NAMES);
const designPath = firstExisting(contextDir, DESIGN_NAMES);
export function loadContext(cwd = process.cwd(), options = {}) {
const resolved = resolveContext(cwd, options);
const absCwd = path.resolve(cwd);
const productPath = resolved.productPath;
const designPath = resolved.designPath;
const product = productPath ? safeRead(productPath) : null;
const design = designPath ? safeRead(designPath) : null;
return {
hasProduct: !!product,
product,
productPath: productPath ? path.relative(cwd, productPath) : null,
productPath: productPath ? path.relative(absCwd, productPath) : null,
hasDesign: !!design,
design,
designPath: designPath ? path.relative(cwd, designPath) : null,
contextDir,
designPath: designPath ? path.relative(absCwd, designPath) : null,
contextDir: resolved.contextDir,
productContextDir: productPath ? path.dirname(productPath) : null,
designContextDir: designPath ? path.dirname(designPath) : null,
projectRoot: resolved.projectRoot,
repoRoot: resolved.repoRoot,
isMonorepo: resolved.isMonorepo,
};
}
function resolveContext(cwd = process.cwd(), options = {}) {
const absCwd = path.resolve(cwd);
const project = resolveProject(absCwd, options);
const projectContextDir = resolveLocalContextDir(project.projectRoot);
const rootContextDir = project.isMonorepo && project.repoRoot !== project.projectRoot
? resolveLocalContextDir(project.repoRoot)
: null;
let productPath =
(projectContextDir ? firstExisting(projectContextDir, PRODUCT_NAMES) : null)
|| (rootContextDir ? firstExisting(rootContextDir, PRODUCT_NAMES) : null);
let designPath =
(projectContextDir ? firstExisting(projectContextDir, DESIGN_NAMES) : null)
|| (rootContextDir ? firstExisting(rootContextDir, DESIGN_NAMES) : null);
let envContextDir = null;
if (!productPath && !designPath) {
envContextDir = resolveEnvContextDir(absCwd);
if (envContextDir) {
productPath = firstExisting(envContextDir, PRODUCT_NAMES);
designPath = firstExisting(envContextDir, DESIGN_NAMES);
}
}
return {
contextDir: productPath
? path.dirname(productPath)
: designPath
? path.dirname(designPath)
: envContextDir || project.projectRoot,
productPath,
designPath,
projectRoot: project.projectRoot,
repoRoot: project.repoRoot,
isMonorepo: project.isMonorepo,
targetDir: project.targetDir,
};
}
export function resolveProjectRoot(cwd = process.cwd(), options = {}) {
return resolveProject(cwd, options).projectRoot;
}
export function resolveTargetSelection(cwd = process.cwd(), options = {}) {
if (hasTargetOption(options)) return null;
const project = resolveProject(cwd);
if (
!project.isMonorepo
|| !project.projectRoot
|| !project.repoRoot
|| path.resolve(project.projectRoot) !== path.resolve(project.repoRoot)
) {
return null;
}
const targetCandidates = discoverTargetCandidates(project.repoRoot);
// No discoverable child apps (e.g. `workspaces: ["."]`, a root-only workspace,
// or a marker file with no apps/packages children): there is nothing to choose,
// so treat the repo root as the active project rather than blocking on an empty
// selection prompt that the user cannot answer.
if (targetCandidates.length === 0) return null;
return {
targetPath: null,
projectRoot: project.projectRoot,
repoRoot: project.repoRoot,
targetCandidates,
};
}
function resolveProject(cwd = process.cwd(), options = {}) {
const absCwd = path.resolve(cwd);
const targetDir = resolveTargetDir(absCwd, options);
let repoRoot = findMonorepoRoot(targetDir);
if (!repoRoot && targetDir !== absCwd) {
const cwdRepoRoot = findMonorepoRoot(absCwd);
if (cwdRepoRoot && isPathInside(targetDir, cwdRepoRoot)) {
repoRoot = cwdRepoRoot;
}
}
if (!repoRoot) {
return {
targetDir,
projectRoot: absCwd,
repoRoot: absCwd,
isMonorepo: false,
};
}
return {
targetDir,
projectRoot: resolveWorkspaceProjectRoot(repoRoot, targetDir) || repoRoot,
repoRoot,
isMonorepo: true,
};
}
function isPathInside(candidate, root) {
const rel = path.relative(root, candidate);
return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
}
function resolveLocalContextDir(root) {
if (firstExisting(root, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return root;
}
for (const rel of FALLBACK_DIRS) {
const candidate = path.resolve(root, rel);
if (firstExisting(candidate, [...PRODUCT_NAMES, ...DESIGN_NAMES])) {
return candidate;
}
}
return null;
}
function resolveEnvContextDir(cwd) {
const envDir = process.env.IMPECCABLE_CONTEXT_DIR;
if (!envDir || !envDir.trim()) return null;
const trimmed = envDir.trim();
return path.isAbsolute(trimmed) ? trimmed : path.resolve(cwd, trimmed);
}
function resolveTargetDir(cwd, options = {}) {
const targetPath = options && typeof options === 'object' ? options.targetPath : null;
if (!targetPath || !String(targetPath).trim()) return cwd;
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
try {
const stat = fs.statSync(abs);
return stat.isDirectory() ? abs : path.dirname(abs);
} catch {
return path.extname(abs) ? path.dirname(abs) : abs;
}
}
function findMonorepoRoot(startDir) {
let dir = path.resolve(startDir);
const homeDir = path.resolve(os.homedir());
while (true) {
if (dir === homeDir) return null;
// isMonorepoRoot is checked before hasGitBoundary on purpose: a workspace
// root that also carries its own .git is still recognized. The trade-off is
// deliberate — a directory with a monorepo *marker* but no workspace patterns
// and no apps/packages children is not a monorepo root, so its .git stops
// traversal and a further-up root is not searched. The nested .git is treated
// as an independent project boundary, which is the intended isolation.
if (isMonorepoRoot(dir)) return dir;
if (hasGitBoundary(dir)) return null;
const parent = path.dirname(dir);
if (parent === dir) return null;
dir = parent;
}
}
function isMonorepoRoot(dir) {
if (readWorkspacePatterns(dir).some((pattern) => !normalizeWorkspacePattern(pattern).startsWith('!'))) return true;
if (!MONOREPO_MARKER_FILES.some((file) => fs.existsSync(path.join(dir, file)))) return false;
return hasFallbackWorkspaceChildren(dir);
}
function hasGitBoundary(dir) {
return fs.existsSync(path.join(dir, '.git'));
}
function hasFallbackWorkspaceChildren(dir) {
for (const name of MONOREPO_FALLBACK_PROJECT_DIRS) {
const base = path.join(dir, name);
let entries;
try {
entries = fs.readdirSync(base, { withFileTypes: true });
} catch {
continue;
}
if (entries.some((entry) => entry.isDirectory() && !isIgnoredWorkspaceDiscoveryDir(entry.name))) return true;
}
return false;
}
function discoverTargetCandidates(repoRoot) {
const roots = new Map();
const patterns = readWorkspacePatterns(repoRoot);
for (const pattern of patterns) {
for (const root of discoverRootsForPattern(repoRoot, pattern)) {
roots.set(path.relative(repoRoot, root).split(path.sep).join('/'), root);
}
}
if (MONOREPO_MARKER_FILES.some((file) => fs.existsSync(path.join(repoRoot, file)))) {
for (const name of MONOREPO_FALLBACK_PROJECT_DIRS) {
const base = path.join(repoRoot, name);
let entries;
try {
entries = fs.readdirSync(base, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
const root = path.join(base, entry.name);
roots.set(path.relative(repoRoot, root).split(path.sep).join('/'), root);
}
}
}
return [...roots.entries()]
.filter(([rel]) => rel && !rel.startsWith('..'))
// Honor negated workspace patterns (e.g. "!packages/internal"). resolveWorkspaceProjectRoot
// sends an excluded package back to the repo root, so an excluded folder must not appear as a
// selectable target — choosing it would silently resolve to the root instead.
.filter(([rel]) => !isExcludedByWorkspacePattern(rel.split('/').filter(Boolean), patterns))
.sort(([a], [b]) => a.localeCompare(b))
.map(([rel, root]) => {
const targetExample = findTargetExample(repoRoot, root);
return {
name: path.basename(root),
path: rel,
targetExample,
...resolveCandidateContextSummary(repoRoot, root, targetExample),
};
});
}
function resolveCandidateContextSummary(repoRoot, projectRoot, targetPath) {
const ctx = resolveContext(repoRoot, { targetPath });
return {
productStatus: contextSourceStatus(ctx.productPath, repoRoot, projectRoot),
productPath: contextSourcePath(ctx.productPath, repoRoot),
designStatus: contextSourceStatus(ctx.designPath, repoRoot, projectRoot),
designPath: contextSourcePath(ctx.designPath, repoRoot),
};
}
// Selection candidates surface one of four statuses: 'child' (a canonical
// PRODUCT.md/DESIGN.md directly in the app root), 'inherited' (resolved from the
// repo root in a monorepo), 'missing' (no file found), and 'fallback'. 'fallback'
// intentionally covers two non-canonical locations: a file inside the project
// root but in a subdirectory (FALLBACK_DIRS, e.g. `.agents/context/`), and a file
// outside both the project and repo roots (IMPECCABLE_CONTEXT_DIR override).
function contextSourceStatus(filePath, repoRoot, projectRoot) {
if (!filePath) return 'missing';
const absPath = path.resolve(filePath);
const absProjectRoot = path.resolve(projectRoot);
const absRepoRoot = path.resolve(repoRoot);
if (isPathInsideOrEqual(absPath, absProjectRoot)) {
return path.dirname(absPath) === absProjectRoot ? 'child' : 'fallback';
}
if (absProjectRoot !== absRepoRoot && isPathInsideOrEqual(absPath, absRepoRoot)) {
return 'inherited';
}
return 'fallback';
}
function contextSourcePath(filePath, repoRoot) {
if (!filePath) return null;
const rel = path.relative(repoRoot, filePath);
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
return rel.split(path.sep).join('/');
}
return filePath;
}
function discoverRootsForPattern(repoRoot, rawPattern) {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern || pattern.startsWith('!')) return [];
const segments = pattern.split('/').filter(Boolean);
if (!segments.length) return [];
const firstGlobIndex = segments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1 ? segments : segments.slice(0, firstGlobIndex);
const base = path.join(repoRoot, ...literalPrefix);
if (!fs.existsSync(base)) return [];
if (segments.includes('**')) {
const packageRoots = [];
walkDirs(base, (dir) => {
if (dir !== base && isCandidateProjectRoot(dir)) packageRoots.push(dir);
});
if (packageRoots.length) return packageRoots;
return directChildDirs(base);
}
return expandSimplePattern(repoRoot, segments);
}
function expandSimplePattern(repoRoot, patternSegments, index = 0, current = repoRoot) {
if (index >= patternSegments.length) return fs.existsSync(current) ? [current] : [];
const segment = patternSegments[index];
if (!segment.includes('*')) {
return expandSimplePattern(repoRoot, patternSegments, index + 1, path.join(current, segment));
}
let entries;
try {
entries = fs.readdirSync(current, { withFileTypes: true });
} catch {
return [];
}
const roots = [];
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
if (!segmentMatches(segment, entry.name)) continue;
roots.push(...expandSimplePattern(repoRoot, patternSegments, index + 1, path.join(current, entry.name)));
}
return roots;
}
function directChildDirs(dir) {
try {
return fs.readdirSync(dir, { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !isIgnoredWorkspaceDiscoveryDir(entry.name))
.map((entry) => path.join(dir, entry.name));
} catch {
return [];
}
}
function walkDirs(root, visit) {
let entries;
try {
entries = fs.readdirSync(root, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (!entry.isDirectory() || isIgnoredWorkspaceDiscoveryDir(entry.name)) continue;
const dir = path.join(root, entry.name);
visit(dir);
walkDirs(dir, visit);
}
}
function isCandidateProjectRoot(dir) {
return !!(
fs.existsSync(path.join(dir, 'package.json'))
|| firstExisting(dir, [...PRODUCT_NAMES, ...DESIGN_NAMES])
|| fs.existsSync(path.join(dir, 'src'))
|| fs.existsSync(path.join(dir, 'app'))
|| fs.existsSync(path.join(dir, 'pages'))
|| fs.existsSync(path.join(dir, 'public'))
);
}
function isIgnoredWorkspaceDiscoveryDir(name) {
return name.startsWith('.') || WORKSPACE_DISCOVERY_IGNORED_DIRS.has(name);
}
function findTargetExample(repoRoot, projectRoot) {
const examples = [
'src/App.jsx',
'src/App.tsx',
'src/main.jsx',
'src/main.tsx',
'src/index.jsx',
'src/index.ts',
'app/page.tsx',
'pages/index.tsx',
'public/index.html',
];
for (const rel of examples) {
const abs = path.join(projectRoot, rel);
if (fs.existsSync(abs)) return path.relative(repoRoot, abs).split(path.sep).join('/');
}
return path.relative(repoRoot, projectRoot).split(path.sep).join('/');
}
function resolveWorkspaceProjectRoot(repoRoot, targetDir) {
const rel = path.relative(repoRoot, targetDir);
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return repoRoot;
const relSegments = rel.split(path.sep).filter(Boolean);
const patterns = readWorkspacePatterns(repoRoot);
const excluded = isExcludedByWorkspacePattern(relSegments, patterns);
if (!excluded) {
for (const pattern of patterns) {
const projectRoot = projectRootFromWorkspacePattern(repoRoot, relSegments, pattern);
if (projectRoot) return projectRoot;
}
}
if (excluded) return repoRoot;
if (
relSegments.length >= 2
&& MONOREPO_FALLBACK_PROJECT_DIRS.includes(relSegments[0])
) {
return path.join(repoRoot, relSegments[0], relSegments[1]);
}
const nearest = nearestProjectLikeRoot(repoRoot, targetDir);
if (nearest) return nearest;
return repoRoot;
}
function isExcludedByWorkspacePattern(relSegments, patterns) {
return patterns.some((rawPattern) => {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern.startsWith('!')) return false;
return workspacePatternMatchesRel(pattern.slice(1), relSegments);
});
}
function nearestProjectLikeRoot(repoRoot, targetDir) {
let dir = path.resolve(targetDir);
const stop = path.resolve(repoRoot);
while (dir && dir !== stop) {
if (
firstExisting(dir, [...PRODUCT_NAMES, ...DESIGN_NAMES])
|| fs.existsSync(path.join(dir, 'package.json'))
) {
return dir;
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function nearestPackageRootBetween(repoRoot, targetDir, stopDir) {
let dir = path.resolve(targetDir);
const stop = path.resolve(stopDir || repoRoot);
const root = path.resolve(repoRoot);
while (dir && dir !== stop && isPathInsideOrEqual(dir, root)) {
if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function isPathInsideOrEqual(candidate, root) {
return path.resolve(candidate) === path.resolve(root) || isPathInside(candidate, root);
}
function workspacePatternMatchesRel(pattern, relSegments) {
const patternSegments = normalizeWorkspacePattern(pattern).split('/').filter(Boolean);
if (!patternSegments.length) return false;
if (patternSegments.includes('**')) {
const firstGlobIndex = patternSegments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1
? patternSegments
: patternSegments.slice(0, firstGlobIndex);
if (relSegments.length < literalPrefix.length + 1) return false;
for (let i = 0; i < literalPrefix.length; i++) {
if (!segmentMatches(literalPrefix[i], relSegments[i])) return false;
}
return true;
}
if (relSegments.length < patternSegments.length) return false;
for (let i = 0; i < patternSegments.length; i++) {
if (!segmentMatches(patternSegments[i], relSegments[i])) return false;
}
return true;
}
function readWorkspacePatterns(repoRoot) {
return [
...readPackageWorkspaces(repoRoot),
...readPnpmWorkspaces(repoRoot),
...readLernaWorkspaces(repoRoot),
].filter(Boolean);
}
function readPackageWorkspaces(repoRoot) {
const pkg = readJson(path.join(repoRoot, 'package.json'));
const workspaces = pkg?.workspaces;
if (Array.isArray(workspaces)) return workspaces;
if (Array.isArray(workspaces?.packages)) return workspaces.packages;
return [];
}
function readLernaWorkspaces(repoRoot) {
const lerna = readJson(path.join(repoRoot, 'lerna.json'));
return Array.isArray(lerna?.packages) ? lerna.packages : [];
}
function readPnpmWorkspaces(repoRoot) {
try {
const body = fs.readFileSync(path.join(repoRoot, 'pnpm-workspace.yaml'), 'utf-8');
const patterns = [];
let inPackages = false;
for (const line of body.split(/\r?\n/)) {
const trimmed = stripYamlInlineComment(line).trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const flowMatch = trimmed.match(/^packages:\s*\[(.*)\]\s*$/);
if (flowMatch) {
patterns.push(...parseYamlFlowList(flowMatch[1]));
inPackages = false;
continue;
}
if (/^packages:\s*$/.test(trimmed)) {
inPackages = true;
continue;
}
if (inPackages && /^[A-Za-z0-9_-]+:\s*/.test(trimmed)) break;
if (inPackages) {
const match = trimmed.match(/^-\s*(.+)$/);
if (match) patterns.push(unquoteYamlValue(match[1]));
}
}
return patterns;
} catch {
return [];
}
}
function stripYamlInlineComment(line) {
let quote = null;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if ((ch === '"' || ch === "'") && line[i - 1] !== '\\') {
quote = quote === ch ? null : quote || ch;
continue;
}
if (ch === '#' && !quote) return line.slice(0, i);
}
return line;
}
function parseYamlFlowList(body) {
const items = [];
let quote = null;
let current = '';
for (let i = 0; i < body.length; i++) {
const ch = body[i];
if ((ch === '"' || ch === "'") && body[i - 1] !== '\\') {
quote = quote === ch ? null : quote || ch;
current += ch;
continue;
}
if (ch === ',' && !quote) {
const value = unquoteYamlValue(current);
if (value) items.push(value);
current = '';
continue;
}
current += ch;
}
const value = unquoteYamlValue(current);
if (value) items.push(value);
return items;
}
function unquoteYamlValue(value) {
return String(value || '')
.trim()
.replace(/^['"]|['"]$/g, '');
}
function readJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return null;
}
}
function projectRootFromWorkspacePattern(repoRoot, relSegments, rawPattern) {
const pattern = normalizeWorkspacePattern(rawPattern);
if (!pattern || pattern.startsWith('!')) return null;
const patternSegments = pattern.split('/').filter(Boolean);
if (!patternSegments.length) return null;
if (patternSegments.includes('**')) {
return projectRootFromDoubleStarPattern(repoRoot, relSegments, patternSegments);
}
if (relSegments.length < patternSegments.length) return null;
for (let i = 0; i < patternSegments.length; i++) {
if (!segmentMatches(patternSegments[i], relSegments[i])) return null;
}
return path.join(repoRoot, ...relSegments.slice(0, patternSegments.length));
}
function projectRootFromDoubleStarPattern(repoRoot, relSegments, patternSegments) {
const firstGlobIndex = patternSegments.findIndex((segment) => segment.includes('*'));
const literalPrefix = firstGlobIndex === -1
? patternSegments
: patternSegments.slice(0, firstGlobIndex);
if (relSegments.length < literalPrefix.length + 1) return null;
for (let i = 0; i < literalPrefix.length; i++) {
if (!segmentMatches(literalPrefix[i], relSegments[i])) return null;
}
const prefixDir = path.join(repoRoot, ...literalPrefix);
const targetDir = path.join(repoRoot, ...relSegments);
const packageRoot = nearestPackageRootBetween(repoRoot, targetDir, prefixDir);
if (packageRoot) return packageRoot;
return path.join(repoRoot, ...relSegments.slice(0, literalPrefix.length + 1));
}
function normalizeWorkspacePattern(pattern) {
return String(pattern || '')
.trim()
.replace(/^['"]|['"]$/g, '')
.replace(/^\.\//, '')
.replace(/\/+$/, '');
}
function segmentMatches(patternSegment, relSegment) {
if (patternSegment === '*') return true;
if (!patternSegment.includes('*')) return patternSegment === relSegment;
const re = new RegExp(`^${escapeRegExp(patternSegment).replace(/\\\*/g, '[^/]*')}$`);
return re.test(relSegment);
}
function firstExisting(dir, names) {
for (const name of names) {
const abs = path.join(dir, name);
@@ -89,6 +687,10 @@ function safeRead(p) {
}
}
function escapeRegExp(value) {
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
/**
* Pull the register (`brand` or `product`) out of PRODUCT.md by looking
* for a `## Register` section and reading the first non-empty line that
@@ -172,8 +774,8 @@ function buildUpdateDirective(localVersion, latestVersion) {
`UPDATE_AVAILABLE: A newer Impeccable skill is available ` +
`(installed v${localVersion}, latest v${latestVersion}). ` +
`Before continuing, ask the user once: "A newer Impeccable (v${latestVersion}) is available. ` +
`Update now? It runs \`npx impeccable skills update\`." ` +
`If they agree, run \`npx impeccable skills update\` (the update applies to the next session, not this one). ` +
`Update now? It runs \`npx impeccable update\`." ` +
`If they agree, run \`npx impeccable update\` (the update applies to the next session, not this one). ` +
`Either way, continue the current task without waiting, and do not raise this again.`
);
}
@@ -233,7 +835,24 @@ async function computeUpdateDirective(now = Date.now()) {
}
async function cli() {
const ctx = loadContext(process.cwd());
let cliOptions;
try {
cliOptions = parseCliOptions(process.argv.slice(2));
} catch (err) {
if (err?.name === 'TargetArgError') {
process.stderr.write(`${err.message}\n`);
process.exit(1);
}
throw err;
}
const targetProvided = hasTargetOption(cliOptions);
const targetExists = targetProvided ? pathExistsForTarget(process.cwd(), cliOptions.targetPath) : null;
const selection = resolveTargetSelection(process.cwd(), cliOptions);
if (selection) {
process.stdout.write(buildTargetSelectionDirective(selection) + '\n');
process.exit(0);
}
const ctx = loadContext(process.cwd(), cliOptions);
const updateDirective = await computeUpdateDirective();
if (!ctx.hasProduct) {
@@ -244,6 +863,10 @@ async function cli() {
'Stop the current task, load reference/init.md, and follow its ' +
'instructions to write PRODUCT.md before resuming.',
];
parts.push(buildResolvedContextDirective(ctx, cliOptions, { targetExists }));
if (shouldWarnMissingTarget(ctx, targetProvided, targetExists)) {
parts.push(buildMissingTargetDirective());
}
if (updateDirective) parts.push(updateDirective);
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
process.exit(0);
@@ -252,6 +875,10 @@ async function cli() {
if (ctx.hasDesign) {
parts.push(`# DESIGN.md\n\n${ctx.design.trim()}`);
}
parts.push(buildResolvedContextDirective(ctx, cliOptions, { targetExists }));
if (shouldWarnMissingTarget(ctx, targetProvided, targetExists)) {
parts.push(buildMissingTargetDirective());
}
const register = extractRegister(ctx.product);
const next = register
? `NEXT STEP: This project's register is \`${register}\`. You MUST now read \`reference/${register}.md\` before producing any design output.`
@@ -261,6 +888,60 @@ async function cli() {
process.stdout.write(parts.join('\n\n---\n\n') + '\n');
}
function parseCliOptions(args) {
return parseTargetOptions(args, { strict: true });
}
function hasTargetOption(options) {
return !!(options && typeof options.targetPath === 'string' && options.targetPath.trim());
}
function pathExistsForTarget(cwd, targetPath) {
const abs = path.isAbsolute(targetPath) ? targetPath : path.resolve(cwd, targetPath);
return fs.existsSync(abs);
}
function buildResolvedContextDirective(ctx, options, { targetExists = null } = {}) {
const targetPath = hasTargetOption(options) ? options.targetPath : null;
return `RESOLVED_CONTEXT:\n${JSON.stringify({
targetPath,
...(targetPath ? { targetExists } : {}),
projectRoot: ctx.projectRoot,
repoRoot: ctx.repoRoot,
productPath: ctx.productPath,
designPath: ctx.designPath,
}, null, 2)}`;
}
function shouldWarnMissingTarget(ctx, targetProvided, targetExists = null) {
if (ctx.isMonorepo && targetProvided && targetExists === false) return true;
return !!(
ctx.isMonorepo
&& (!targetProvided || targetExists === false)
&& ctx.projectRoot
&& ctx.repoRoot
&& path.resolve(ctx.projectRoot) === path.resolve(ctx.repoRoot)
);
}
function buildMissingTargetDirective() {
const script = process.argv[1] || 'context.mjs';
return (
'MONOREPO_TARGET_REQUIRED: This is a monorepo and context.mjs ran without --target. ' +
'If the user named a file, route, or child app, do not answer from this output. ' +
`Rerun \`node ${script} --target <path>\` and answer from that run's RESOLVED_CONTEXT fields.`
);
}
function buildTargetSelectionDirective(selection) {
return (
`TARGET_SELECTION_REQUIRED:\n${JSON.stringify(selection, null, 2)}\n\n` +
'Show each app with its productStatus/productPath and designStatus/designPath so the user can see child overrides, inherited root files, fallback files, or missing files before choosing. ' +
'Ask the user which app Impeccable should use, then rerun Impeccable helper commands from that child app cwd using this same scripts directory. ' +
'Use `--target <path>` only as a fallback when changing cwd is not possible, or when the user explicitly named a file/path.'
);
}
// Run cli() only when this module is the entry point. Compare realpaths
// rather than endsWith(): a loose suffix match also fires for unrelated
// scripts like `load-context.mjs`, and realpath tolerates symlinked
@@ -1224,6 +1224,7 @@ if (IS_BROWSER) {
category: ap ? ap.category : 'quality',
severity: ap?.severity || 'warning',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
description: ap ? ap.description : '',
};
@@ -1260,10 +1261,203 @@ if (IS_BROWSER) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
const DESIGN_COLOR_TOLERANCE = 6;
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function normalizeBrowserFontName(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function browserPrimaryFont(stack) {
if (!stack || /var\(/i.test(stack)) return '';
return String(stack || '')
.split(',')
.map(normalizeBrowserFontName)
.find(font => font && !GENERIC_FONTS.has(font)) || '';
}
function browserDesignSystemConfig() {
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
if (!raw?.present) return null;
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
const allowedColors = (raw.allowedColors || [])
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b }));
const allowedRadii = (raw.allowedRadii || [])
.map(Number)
.filter(px => Number.isFinite(px));
return {
present: true,
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
allowedFonts,
hasColors: raw.hasColors === true && allowedColors.length > 0,
allowedColors,
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
allowedRadii,
hasPillRadius: raw.hasPillRadius === true,
};
}
function browserColorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= DESIGN_COLOR_TOLERANCE;
}
function isBrowserDesignColorAllowed(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseAnyColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
}
function isBrowserTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseAnyColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function isBrowserDesignRadiusAllowed(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
}
function browserRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function browserHasDirectText(el) {
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function browserSampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function shouldSkipDesignElement(el) {
const tag = el.tagName?.toLowerCase?.() || '';
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
}
function checkElementDesignSystemDOM(el, designSystem, seen) {
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
const findings = [];
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = getComputedStyle(el);
if (designSystem.hasFonts && browserHasDirectText(el)) {
const font = browserPrimaryFont(style.fontFamily || '');
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
ignoreValue: font,
});
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = String(raw || '').trim().replace(/\s+/g, ' ');
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seen.colors.has(key)) continue;
seen.colors.add(key);
findings.push({
type: 'design-system-color',
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
ignoreValue: label,
});
}
}
if (designSystem.hasRadii) {
for (const token of browserRadiusTokens(style.borderRadius || '')) {
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
if (seen.radii.has(token)) continue;
seen.radii.add(token);
findings.push({
type: 'design-system-radius',
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
ignoreValue: token,
});
}
}
return findings;
}
function decodeBrowserGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkBrowserDesignSystemSources(designSystem, seen) {
if (!designSystem?.hasFonts) return [];
const findings = [];
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
const href = link.getAttribute('href') || '';
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
const display = decodeBrowserGoogleFamily(match[1]);
const font = normalizeBrowserFontName(display);
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
ignoreValue: display,
});
}
}
return findings;
}
function collectBrowserFindings() {
const groupMap = new Map();
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
const designSystem = browserDesignSystemConfig();
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
// real browser env (detector page, live overlay, extension) running every
// check is free, so we always surface them; the gating is purely a CLI
@@ -1294,6 +1488,7 @@ if (IS_BROWSER) {
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementDesignSystemDOM(el, designSystem, designSeen),
].filter(f => _ruleOk(f.type));
addBrowserFindings(groupMap, el, findings);
@@ -1310,6 +1505,13 @@ if (IS_BROWSER) {
const pageLevelFindings = [];
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
.filter(f => _ruleOk(f.type));
if (designSourceFindings.length > 0) {
pageLevelFindings.push(...designSourceFindings);
addBrowserFindings(groupMap, document.body, designSourceFindings);
}
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
if (typoFindings.length > 0) {
pageLevelFindings.push(...typoFindings);
@@ -1,9 +1,15 @@
import fs from 'node:fs';
import path from 'node:path';
import { loadDesignSystemForCwd } from '../design-system.mjs';
import { createBrowserDetector, detectUrl } from '../engines/browser/detect-url.mjs';
import { detectHtml } from '../engines/static-html/detect-html.mjs';
import { detectText } from '../engines/regex/detect-text.mjs';
import {
filterDetectionFindings,
readDetectionConfig,
shouldIgnoreDetectionFile,
} from '../../lib/impeccable-config.mjs';
import {
HTML_EXTENSIONS,
buildImportGraph,
@@ -16,6 +22,10 @@ import {
// Output formatting
// ---------------------------------------------------------------------------
function formatFindingSummary(count) {
return `${count} anti-pattern${count === 1 ? '' : 's'} found.`;
}
function formatFindings(findings, jsonMode) {
if (jsonMode) return JSON.stringify(findings, null, 2);
@@ -33,7 +43,7 @@ function formatFindings(findings, jsonMode) {
out.push(`${item.description}`);
}
}
out.push(`\n${findings.length} anti-pattern${findings.length === 1 ? '' : 's'} found.`);
out.push(`\n${formatFindingSummary(findings.length)}`);
return out.join('\n');
}
@@ -79,10 +89,28 @@ function printUsage() {
Scan files or URLs for UI anti-patterns and design quality issues.
Options:
--json Output results as JSON
--gpt Also report GPT-specific provider tells (off by default)
--gemini Also report Gemini-specific provider tells (off by default)
--help Show this help message
--json Output results as JSON
--quiet In text mode, only print the final findings count
--gpt Also report GPT-specific provider tells (off by default)
--gemini Also report Gemini-specific provider tells (off by default)
--no-config Do not apply project config, detector ignores, inline
ignore comments, or DESIGN.md
--no-inline-ignores Do not honor in-file impeccable-disable* ignore comments
--no-design-system Do not load local DESIGN.md / .impeccable/design.json context
--help Show this help message
Project config:
Respects .impeccable/config.json and .impeccable/config.local.json detector
settings: detector.ignoreRules, detector.ignoreFiles, detector.ignoreValues,
and detector.designSystem.enabled.
Inline ignores:
In-file comments waive a finding where it lives and travel with the file:
<!-- impeccable-disable overused-font -- exported brand doc -->
.brand { font-family: Inter } /* impeccable-disable-line overused-font */
// impeccable-disable-next-line bounce-easing: intentional bounce
impeccable-disable applies to the whole file; -line / -next-line are scoped.
List one or more rule ids (comma-separated), or omit them / use * for all.
Detection modes:
HTML files Static HTML/CSS analysis (default, catches linked CSS)
@@ -93,7 +121,8 @@ Examples:
impeccable detect src/
impeccable detect index.html
impeccable detect https://example.com
impeccable detect --json .`);
impeccable detect --json .
impeccable detect --no-config src/`);
}
async function detectCli() {
@@ -104,6 +133,7 @@ async function detectCli() {
});
if (args[0] === 'detect') args = args.slice(1);
const jsonMode = args.includes('--json');
const quietMode = args.includes('--quiet');
const helpMode = args.includes('--help');
// --fast (regex-only) is deprecated: since the jsdom removal, the static
// HTML/CSS analysis is fast and covers every rule, so the regex-only path
@@ -114,10 +144,21 @@ async function detectCli() {
'Note: --fast is deprecated and ignored. The full scan is fast now and runs every rule.\n',
);
}
const configEnabled = !args.includes('--no-config');
const detectionConfig = configEnabled
? readDetectionConfig(process.cwd())
: { ignoreRules: [], ignoreFiles: [], ignoreValues: [] };
const providers = [];
if (args.includes('--gpt')) providers.push('gpt');
if (args.includes('--gemini')) providers.push('gemini');
const scanOptions = { providers };
const designSystemEnabled = configEnabled && !args.includes('--no-design-system') && detectionConfig.designSystem?.enabled !== false;
const designSystem = designSystemEnabled ? loadDesignSystemForCwd(process.cwd()) : null;
// Inline `impeccable-disable*` waivers are part of the scanned file, so they
// apply by default. `--no-config` (raw scan) and the dedicated
// `--no-inline-ignores` both turn them off.
const inlineIgnoresEnabled = configEnabled && !args.includes('--no-inline-ignores');
const scanOptions = { providers, inlineIgnores: inlineIgnoresEnabled };
if (designSystem) scanOptions.designSystem = designSystem;
const targets = args.filter(a => !a.startsWith('--'));
if (helpMode) { printUsage(); process.exit(0); }
@@ -149,8 +190,8 @@ async function detectCli() {
catch { process.stderr.write(`Warning: cannot access ${target}\n`); continue; }
if (stat.isDirectory()) {
// Check for framework dev server config (skip in JSON mode to avoid polluting output)
if (!jsonMode) {
// Check for framework dev server config (skip in JSON/quiet modes to avoid polluting output)
if (!jsonMode && !quietMode) {
const fwConfig = detectFrameworkConfig(resolved);
if (fwConfig) {
const probe = await isPortListening(fwConfig.port, fwConfig.fingerprint);
@@ -175,11 +216,12 @@ async function detectCli() {
}
}
const files = walkDir(resolved);
const files = walkDir(resolved)
.filter(file => !shouldIgnoreDetectionFile(file, process.cwd(), detectionConfig));
const htmlCount = files.filter(f => HTML_EXTENSIONS.has(path.extname(f).toLowerCase())).length;
// Warn and confirm if scanning many files (static HTML/CSS processes each HTML file)
if (files.length > 50 && process.stdin.isTTY && !jsonMode) {
if (files.length > 50 && process.stdin.isTTY && !jsonMode && !quietMode) {
process.stderr.write(
`\nFound ${files.length} files (${htmlCount} HTML) in ${target}.\n` +
`Scanning may take a while${htmlCount > 10 ? ' (static HTML/CSS processes each HTML file individually)' : ''}.\n` +
@@ -219,6 +261,7 @@ async function detectCli() {
allFindings.push(...fileFindings);
}
} else if (stat.isFile()) {
if (shouldIgnoreDetectionFile(resolved, process.cwd(), detectionConfig)) continue;
const ext = path.extname(resolved).toLowerCase();
if (HTML_EXTENSIONS.has(ext)) {
allFindings.push(...await detectHtml(resolved, scanOptions));
@@ -232,8 +275,11 @@ async function detectCli() {
}
}
allFindings = filterDetectionFindings(allFindings, detectionConfig);
if (allFindings.length > 0) {
if (jsonMode) process.stdout.write(formatFindings(allFindings, true) + '\n');
else if (quietMode) process.stderr.write(formatFindingSummary(allFindings.length) + '\n');
else process.stderr.write(formatFindings(allFindings, false) + '\n');
process.exit(2);
}
@@ -0,0 +1,750 @@
import fs from 'node:fs';
import path from 'node:path';
import { finding } from './findings.mjs';
import { GENERIC_FONTS } from './shared/constants.mjs';
import { parseAnyColor, resolveLengthPx } from './rules/checks.mjs';
const DESIGN_NAMES = ['DESIGN.md', 'Design.md', 'design.md'];
const FALLBACK_DIRS = ['.agents/context', 'docs'];
const COLOR_CHANNEL_TOLERANCE = 6;
const RADIUS_TOLERANCE_PX = 0.5;
const CSS_COLOR_RE = /#[0-9a-f]{3,8}\b|rgba?\([^)]+\)|oklch\([^)]+\)|hsla?\([^)]+\)/gi;
const FONT_DECL_RE = /font-family\s*:\s*([^;}\n]+)/gi;
const FONT_JS_RE = /fontFamily\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
const GOOGLE_FONT_RE = /fonts\.googleapis\.com\/css2?\?[^"'\s)<>]*/gi;
const BORDER_RADIUS_RE = /border-radius\s*:\s*([^;}\n]+)/gi;
const BORDER_RADIUS_JS_RE = /borderRadius\s*[:=]\s*["'`]([^"'`]+)["'`]/g;
const STATIC_DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function firstExisting(dir, names) {
for (const name of names) {
const abs = path.join(dir, name);
if (fs.existsSync(abs)) return abs;
}
return null;
}
function resolveDesignMdPath(cwd = process.cwd()) {
const root = firstExisting(cwd, DESIGN_NAMES);
if (root) return { path: root, contextDir: cwd };
for (const rel of FALLBACK_DIRS) {
const dir = path.resolve(cwd, rel);
const found = firstExisting(dir, DESIGN_NAMES);
if (found) return { path: found, contextDir: dir };
}
return null;
}
function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
const candidates = [
path.join(cwd, '.impeccable', 'design.json'),
path.join(cwd, 'DESIGN.json'),
path.join(contextDir, 'DESIGN.json'),
];
return candidates.find((candidate, index) =>
candidates.indexOf(candidate) === index && fs.existsSync(candidate)
) || null;
}
function parseFrontmatter(md) {
const lines = String(md || '').split(/\r?\n/);
if (lines[0]?.trim() !== '---') return null;
let end = -1;
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === '---') { end = i; break; }
}
if (end === -1) return null;
try {
return parseYamlSubset(lines.slice(1, end).join('\n'));
} catch {
return null;
}
}
function parseYamlSubset(yaml) {
const root = {};
const stack = [{ indent: -1, obj: root }];
for (const raw of String(yaml || '').split(/\r?\n/)) {
if (!raw.trim() || /^\s*#/.test(raw)) continue;
const indent = raw.match(/^\s*/)[0].length;
const content = raw.slice(indent);
const colonIdx = findTopLevelColon(content);
if (colonIdx === -1) continue;
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) stack.pop();
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
const parent = stack[stack.length - 1].obj;
if (rest === '') {
const obj = {};
parent[key] = obj;
stack.push({ indent, obj });
} else {
parent[key] = parseScalar(rest);
}
}
return root;
}
function findTopLevelColon(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (inQuote) {
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === ':') {
return i;
}
}
return -1;
}
function unquoteYamlKey(key) {
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
return key.slice(1, -1);
}
return key;
}
function stripInlineYamlComment(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (inQuote) {
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
} else if (ch === '"' || ch === "'") {
inQuote = ch;
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
return s.slice(0, i).trimEnd();
}
}
return s;
}
function parseScalar(raw) {
const s = raw.trim();
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
return s.slice(1, -1);
}
if (s === 'true') return true;
if (s === 'false') return false;
if (s === 'null' || s === '~') return null;
if (/^-?\d+$/.test(s)) return Number(s);
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
return s;
}
function safeReadJson(filePath) {
if (!filePath) return null;
try {
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
} catch {
return null;
}
}
function normalizeFontName(value) {
return String(value || '')
.trim()
.replace(/\s*!important\s*$/i, '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function splitFontStack(stack) {
return String(stack || '')
.replace(/\s*!important\s*$/i, '')
.split(',')
.map(normalizeFontName)
.filter(Boolean);
}
function primaryFont(stack) {
if (!stack || /var\(/i.test(stack) || !isLiteralFontStack(stack)) return '';
return splitFontStack(stack).find(font => !GENERIC_FONTS.has(font)) || '';
}
function isLiteralFontStack(stack) {
const text = String(stack || '');
return !/[$`{}]|\s\+\s|\|\|/.test(text);
}
function cssColorLabel(raw) {
return String(raw || '').trim().replace(/\s+/g, ' ');
}
function colorKey(color) {
if (!color) return '';
return `${color.r},${color.g},${color.b}`;
}
function colorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= COLOR_CHANNEL_TOLERANCE;
}
function hslToRgb(H, S, L, alpha = 1) {
const h = (((H % 360) + 360) % 360) / 360;
const s = Math.max(0, Math.min(1, S));
const l = Math.max(0, Math.min(1, L));
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
return {
r: Math.round(hue2rgb(p, q, h + 1 / 3) * 255),
g: Math.round(hue2rgb(p, q, h) * 255),
b: Math.round(hue2rgb(p, q, h - 1 / 3) * 255),
a: alpha,
};
}
function parseDesignColor(value) {
const text = String(value || '').trim();
const parsed = parseAnyColor(text);
if (parsed) return parsed;
const hsl = text.match(/hsla?\(\s*([-\d.]+)(?:deg)?\s*,?\s*([\d.]+)%\s*,?\s*([\d.]+)%(?:\s*[,/]\s*([\d.]+))?\s*\)/i);
if (hsl) {
return hslToRgb(
parseFloat(hsl[1]),
parseFloat(hsl[2]) / 100,
parseFloat(hsl[3]) / 100,
hsl[4] !== undefined ? parseFloat(hsl[4]) : 1,
);
}
return null;
}
function addDesignColor(out, value, label) {
const parsed = parseDesignColor(value);
if (!parsed) return;
const key = colorKey(parsed);
if (!out.allowedColorKeys.has(key)) {
out.allowedColorKeys.set(key, { color: parsed, labels: [] });
}
out.allowedColorKeys.get(key).labels.push(label || cssColorLabel(value));
}
function addColorObject(out, colors, prefix = 'colors') {
if (!colors || typeof colors !== 'object') return;
for (const [name, value] of Object.entries(colors)) {
if (typeof value === 'string') {
addDesignColor(out, value, `${prefix}.${name}`);
}
}
}
function addSidecarColors(out, sidecar) {
const colorMeta = sidecar?.extensions?.colorMeta;
if (!colorMeta || typeof colorMeta !== 'object') return;
for (const [name, meta] of Object.entries(colorMeta)) {
if (!meta || typeof meta !== 'object') continue;
if (typeof meta.canonical === 'string') addDesignColor(out, meta.canonical, `sidecar.${name}`);
if (Array.isArray(meta.tonalRamp)) {
for (const [index, value] of meta.tonalRamp.entries()) {
if (typeof value === 'string') addDesignColor(out, value, `sidecar.${name}.tonalRamp[${index}]`);
}
}
}
}
function addTypographyFonts(out, typography) {
if (!typography || typeof typography !== 'object') return;
for (const role of Object.values(typography)) {
if (!role || typeof role !== 'object') continue;
if (typeof role.fontFamily !== 'string') continue;
for (const font of splitFontStack(role.fontFamily)) {
if (!GENERIC_FONTS.has(font)) out.allowedFonts.add(font);
}
}
}
function addRoundedScale(out, rounded) {
if (!rounded || typeof rounded !== 'object') return;
for (const [rawName, value] of Object.entries(rounded)) {
const name = unquoteYamlKey(rawName).toLowerCase();
addRoundedToken(out, name, value);
}
}
function addRoundedToken(out, name, value) {
if (typeof value !== 'string' && typeof value !== 'number') return;
const raw = String(value).trim();
if (!raw || /var\(/i.test(raw) || raw.includes('%')) return;
const px = resolveLengthPx(raw, 16);
if (px == null || !Number.isFinite(px)) return;
out.allowedRadii.push({ name, value: raw, px });
if (/(^|\.)(full|pill|round|rounded-full)$/.test(name)) out.hasPillRadius = true;
}
function addSidecarRadii(out, sidecar) {
const roundedMeta = sidecar?.extensions?.roundedMeta;
if (!roundedMeta || typeof roundedMeta !== 'object') return;
for (const [rawName, meta] of Object.entries(roundedMeta)) {
const name = unquoteYamlKey(rawName).toLowerCase();
if (typeof meta === 'string' || typeof meta === 'number') {
addRoundedToken(out, `sidecar.${name}`, meta);
continue;
}
if (!meta || typeof meta !== 'object') continue;
for (const key of ['canonical', 'value']) {
if (typeof meta[key] === 'string' || typeof meta[key] === 'number') {
addRoundedToken(out, `sidecar.${name}.${key}`, meta[key]);
}
}
for (const key of ['values', 'aliases']) {
if (!Array.isArray(meta[key])) continue;
for (const [index, value] of meta[key].entries()) {
addRoundedToken(out, `sidecar.${name}.${key}[${index}]`, value);
}
}
if (/^(full|pill|round|rounded-full)$/.test(name) || /^(full|pill|round)$/i.test(String(meta.role || ''))) {
out.hasPillRadius = true;
}
}
}
function normalizeDesignSystem(input = {}) {
const frontmatter = input.frontmatter || {};
const sidecar = input.sidecar || null;
const out = {
present: true,
sourcePath: input.sourcePath || null,
sidecarPath: input.sidecarPath || null,
mdNewerThanJson: input.mdNewerThanJson === true,
allowedFonts: new Set(),
allowedColorKeys: new Map(),
allowedRadii: [],
hasPillRadius: false,
};
addTypographyFonts(out, frontmatter.typography);
addColorObject(out, frontmatter.colors);
addSidecarColors(out, sidecar);
addRoundedScale(out, frontmatter.rounded);
addSidecarRadii(out, sidecar);
out.hasFonts = out.allowedFonts.size > 0;
out.hasColors = out.allowedColorKeys.size > 0;
out.hasRadii = out.allowedRadii.length > 0;
return out;
}
function loadDesignSystemForCwd(cwd = process.cwd()) {
const md = resolveDesignMdPath(cwd);
if (!md) return null;
let frontmatter = null;
let mdStat = null;
try {
mdStat = fs.statSync(md.path);
frontmatter = parseFrontmatter(fs.readFileSync(md.path, 'utf-8'));
} catch {
return null;
}
if (!frontmatter || typeof frontmatter !== 'object') return null;
const sidecarPath = resolveDesignSidecarPath(cwd, md.contextDir);
const sidecar = safeReadJson(sidecarPath);
let sidecarStat = null;
try {
if (sidecarPath) sidecarStat = fs.statSync(sidecarPath);
} catch {
sidecarStat = null;
}
return normalizeDesignSystem({
frontmatter,
sidecar,
sourcePath: md.path,
sidecarPath,
mdNewerThanJson: !!(mdStat && sidecarStat && mdStat.mtimeMs > sidecarStat.mtimeMs + 1000),
});
}
function isAllowedFont(font, designSystem) {
if (!font || GENERIC_FONTS.has(font)) return true;
if (!designSystem?.hasFonts) return true;
return designSystem.allowedFonts.has(font);
}
function isAllowedColorRaw(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseDesignColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
for (const entry of designSystem.allowedColorKeys.values()) {
if (colorsClose(parsed, entry.color)) return true;
}
return false;
}
function isAllowedRadiusRaw(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(entry => Math.abs(entry.px - px) <= RADIUS_TOLERANCE_PX);
}
function lineLooksCommented(line) {
const trimmed = String(line || '').trim();
return trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--');
}
function isProbablyColorLiteral(line, match) {
const raw = match?.[0] || '';
const index = match.index ?? -1;
if (index < 0) return false;
if (isInsideCssAttributeSelector(line, index)) return false;
const before = line.slice(0, index);
const after = line.slice(index + raw.length);
if (raw.startsWith('#')) {
if (before.endsWith('&')) return false; // HTML numeric entity, e.g. &#8596;
const prevNonSpace = before.match(/\S(?=\s*$)/)?.[0] || '';
const nextNonSpace = after.match(/^\s*(\S)/)?.[1] || '';
if (prevNonSpace === '>' && nextNonSpace === '<') return false; // plain text, e.g. PR #155
}
const styleContext = /(?:^|[{\s;"'`(,])(?:color|background(?:-color|-image)?|border(?:-(?:top|right|bottom|left))?(?:-color)?|outline(?:-color)?|box-shadow|text-shadow|fill|stroke)\s*:\s*[^;{}"'`]*/i.test(before);
const cssFunctionContext = /(?:linear-gradient|radial-gradient|conic-gradient|color-mix)\([^)]*$/i.test(before);
const jsColorKeyContext = /(?:^|[,{]\s*)(?:color|background|backgroundColor|borderColor|outlineColor|fill|stroke|boxShadow|textShadow)\s*[:=]\s*["'`]?[^"'`,}]*/i.test(before);
return styleContext || cssFunctionContext || jsColorKeyContext;
}
function isInsideCssAttributeSelector(line, index) {
if (index < 0) return false;
const before = line.slice(0, index);
const lastOpen = before.lastIndexOf('[');
if (lastOpen === -1) return false;
const lastClose = before.lastIndexOf(']');
if (lastClose > lastOpen) return false;
const after = line.slice(index);
const close = after.indexOf(']');
const block = after.indexOf('{');
return close !== -1 && (block === -1 || close < block);
}
function makeDesignFinding(id, filePath, snippet, line = 0, extras = {}) {
return { ...finding(id, filePath, snippet, line), ...extras };
}
function decodeGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkFontStack(stack, filePath, line, designSystem, context) {
const primary = primaryFont(stack);
if (!primary || isAllowedFont(primary, designSystem)) return [];
const display = primary.replace(/\b\w/g, ch => ch.toUpperCase());
return [makeDesignFinding(
'design-system-font',
filePath,
`${context}: ${display} is not declared in DESIGN.md typography`,
line,
{ ignoreValue: display },
)];
}
function extractRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function checkRadiusValue(value, filePath, line, designSystem, context) {
const findings = [];
for (const token of extractRadiusTokens(value)) {
if (isAllowedRadiusRaw(token, designSystem)) continue;
findings.push(makeDesignFinding(
'design-system-radius',
filePath,
`${context}: ${token} is outside the DESIGN.md rounded scale`,
line,
{ ignoreValue: token },
));
}
return findings;
}
function checkSourceDesignSystem(content, filePath, options = {}) {
const designSystem = options.designSystem;
if (!designSystem?.present) return [];
const findings = [];
const lines = String(content || '').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const lineNum = i + 1;
if (lineLooksCommented(line)) continue;
if (designSystem.hasFonts) {
for (const match of line.matchAll(FONT_DECL_RE)) {
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'font-family'));
}
for (const match of line.matchAll(FONT_JS_RE)) {
findings.push(...checkFontStack(match[1], filePath, lineNum, designSystem, 'fontFamily'));
}
for (const match of line.matchAll(GOOGLE_FONT_RE)) {
const url = match[0];
for (const familyMatch of url.matchAll(/[?&]family=([^&]+)/g)) {
const font = normalizeFontName(decodeGoogleFamily(familyMatch[1]));
if (!font || isAllowedFont(font, designSystem)) continue;
const display = decodeGoogleFamily(familyMatch[1]);
findings.push(makeDesignFinding(
'design-system-font',
filePath,
`Google Fonts: ${display} is not declared in DESIGN.md typography`,
lineNum,
{ ignoreValue: display },
));
}
}
}
if (designSystem.hasColors) {
for (const match of line.matchAll(CSS_COLOR_RE)) {
if (!isProbablyColorLiteral(line, match)) continue;
const raw = cssColorLabel(match[0]);
if (isAllowedColorRaw(raw, designSystem)) continue;
findings.push(makeDesignFinding(
'design-system-color',
filePath,
`Undocumented color ${raw} is outside DESIGN.md colors`,
lineNum,
{ ignoreValue: raw },
));
}
}
if (designSystem.hasRadii) {
for (const match of line.matchAll(BORDER_RADIUS_RE)) {
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'border-radius'));
}
for (const match of line.matchAll(BORDER_RADIUS_JS_RE)) {
findings.push(...checkRadiusValue(match[1], filePath, lineNum, designSystem, 'borderRadius'));
}
}
}
return dedupeDesignFindings(findings);
}
function hasDirectText(el) {
return Array.from(el.childNodes || []).some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function sampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function collectStaticDesignSystemFindings(document, window, filePath, designSystem) {
if (!designSystem?.present) return [];
const findings = [];
const seenFonts = new Set();
const seenColors = new Set();
const seenRadii = new Set();
for (const el of document.querySelectorAll('*')) {
if (shouldSkipStaticDesignElement(el, window)) continue;
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = window.getComputedStyle(el);
if (designSystem.hasFonts && hasDirectText(el)) {
const font = primaryFont(style.fontFamily || '');
if (font && !seenFonts.has(font) && !isAllowedFont(font, designSystem)) {
seenFonts.add(font);
findings.push(makeDesignFinding(
'design-system-font',
filePath,
`${tag}${sampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
0,
{ ignoreValue: font },
));
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (hasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = cssColorLabel(raw);
if (isAllowedColorRaw(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seenColors.has(key)) continue;
seenColors.add(key);
findings.push(makeDesignFinding(
'design-system-color',
filePath,
`${kind} ${label} on ${tag}${sampleText(el)} is outside DESIGN.md colors`,
0,
{ ignoreValue: label },
));
}
}
if (designSystem.hasRadii) {
const rawRadius = String(style.borderRadius || '').trim();
if (!rawRadius) continue;
for (const token of extractRadiusTokens(rawRadius)) {
if (isAllowedRadiusRaw(token, designSystem)) continue;
if (seenRadii.has(token)) continue;
seenRadii.add(token);
findings.push(makeDesignFinding(
'design-system-radius',
filePath,
`border-radius ${token} on ${tag}${sampleText(el)} is outside the DESIGN.md rounded scale`,
0,
{ ignoreValue: token },
));
}
}
}
return findings;
}
function shouldSkipStaticDesignElement(el, window) {
const tag = el.tagName?.toLowerCase?.() || '';
if (STATIC_DESIGN_SKIP_TAGS.has(tag)) return true;
let current = el;
while (current) {
if (current.getAttribute?.('hidden') !== null || current.getAttribute?.('aria-hidden') === 'true') return true;
const style = window.getComputedStyle(current);
const display = String(style.display || '').toLowerCase();
const visibility = String(style.visibility || '').toLowerCase();
if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return true;
current = current.parentElement;
}
return false;
}
function isTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseDesignColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function canonicalDesignFindingKey(item) {
if (!item?.antipattern?.startsWith?.('design-system-')) return null;
const value = item.ignoreValue || item.value || '';
if (item.antipattern === 'design-system-font') {
const context = /google fonts/i.test(item.snippet || '') ? 'google-font' : 'font';
const font = normalizeFontName(value);
return font ? `${item.antipattern}:${context}:${font}` : null;
}
if (item.antipattern === 'design-system-color') {
const parsed = parseDesignColor(value);
if (parsed) return `${item.antipattern}:color:${colorKey(parsed)}`;
const label = cssColorLabel(value).toLowerCase();
return label ? `${item.antipattern}:color:${label}` : null;
}
if (item.antipattern === 'design-system-radius') {
const px = resolveLengthPx(String(value || '').trim(), 16);
if (px != null && Number.isFinite(px)) return `${item.antipattern}:radius:${Math.round(px * 100) / 100}`;
const label = String(value || '').trim().toLowerCase();
return label ? `${item.antipattern}:radius:${label}` : null;
}
return null;
}
function mergeDesignSystemFindings(...groups) {
const out = [];
const seen = new Map();
for (const group of groups) {
for (const item of group || []) {
const key = canonicalDesignFindingKey(item);
if (key) {
if (seen.has(key)) {
const existing = out[seen.get(key)];
if ((existing.line || 0) <= 0 && (item.line || 0) > 0) existing.line = item.line;
continue;
}
seen.set(key, out.length);
}
out.push(item);
}
}
return out;
}
function dedupeDesignFindings(findings) {
const out = [];
const seen = new Set();
for (const item of findings) {
const key = [
item.antipattern,
item.line || 0,
normalizeFontName(item.ignoreValue || item.snippet || ''),
].join('\0');
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
export {
parseFrontmatter,
normalizeDesignSystem,
loadDesignSystemForCwd,
isAllowedFont,
isAllowedColorRaw,
isAllowedRadiusRaw,
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
mergeDesignSystemFindings,
};
@@ -425,6 +425,35 @@ const ANTIPATTERNS = [
skillSection: 'Layout & Space',
skillGuideline: 'overflow container clipping positioned children',
},
{
id: 'design-system-font',
category: 'quality',
name: 'Font outside DESIGN.md',
description:
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
skillSection: 'Typography',
skillGuideline: 'font family outside the project design system',
},
{
id: 'design-system-color',
category: 'quality',
severity: 'advisory',
name: 'Color outside DESIGN.md',
description:
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
skillSection: 'Color & Contrast',
skillGuideline: 'literal color outside the project design system',
},
{
id: 'design-system-radius',
category: 'quality',
severity: 'advisory',
name: 'Radius outside DESIGN.md',
description:
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
skillSection: 'Visual Details',
skillGuideline: 'border radius outside the project design system',
},
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
{
@@ -449,6 +478,17 @@ const ANTIPATTERNS = [
skillSection: 'Visual Details',
skillGuideline: 'repeating-gradient decorative stripes',
},
{
id: 'codex-grid-background',
category: 'slop',
severity: 'advisory',
gated: 'gpt',
name: 'Decorative grid-line background',
description:
'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
skillSection: 'Visual Details',
skillGuideline: 'two-axis grid-line gradient background',
},
{
id: 'theater-slop-phrase',
category: 'slop',
@@ -1084,9 +1124,13 @@ function checkHtmlPatterns(html) {
// --- Motion ---
// Bounce/elastic animation names
const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
if (bounceRe.test(html)) {
findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
const bounceMatch = bounceRe.exec(html);
if (bounceMatch) {
const animationToken = bounceMatch[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
}
// Overshoot cubic-bezier
@@ -1139,6 +1183,42 @@ function checkHtmlPatterns(html) {
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
}
// --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
// The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
// transparent 1px)` layers (one per axis) tiled by a repeating
// `background-size` cell. Both signals must co-occur in the SAME style block
// (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
// tiling background-size is a fixed crosshair, not a grid, and a single
// hairline is a legitimate ruled line. Scoping to one block also stops
// unrelated single-axis rules on separate elements from adding up across the
// page. Count hairlines only inside `background`/`background-image` values so
// a hairline in an unrelated property (mask-image, border-image) can't stand
// in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
// nested parens, so match the hairline stop directly rather than parsing
// whole gradient layers.
{
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
let blk;
while ((blk = blockRe.exec(html)) !== null) {
const block = blk[1] || blk[2] || blk[3] || '';
if (!gridSizeRe.test(block)) continue;
let hairlineCount = 0;
let bm;
bgDeclRe.lastIndex = 0;
while ((bm = bgDeclRe.exec(block)) !== null) {
const stops = bm[1].match(hairlineRe);
if (stops) hairlineCount += stops.length;
}
if (hairlineCount >= 2) {
findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
break;
}
}
}
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
// runs in the bundled browser path too, not just the CLI/static path.
@@ -4390,6 +4470,7 @@ if (IS_BROWSER) {
category: ap ? ap.category : 'quality',
severity: ap?.severity || 'warning',
detail: f.detail || f.snippet,
ignoreValue: f.ignoreValue || f.value || '',
name: ap ? ap.name : (f.type || f.id),
description: ap ? ap.description : '',
};
@@ -4426,10 +4507,203 @@ if (IS_BROWSER) {
return [...groupMap.entries()].map(([el, findings]) => ({ el, findings }));
}
const DESIGN_COLOR_TOLERANCE = 6;
const DESIGN_RADIUS_TOLERANCE_PX = 0.5;
const DESIGN_SKIP_TAGS = new Set(['head', 'title', 'meta', 'link', 'style', 'script', 'noscript', 'template', 'source']);
function normalizeBrowserFontName(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function browserPrimaryFont(stack) {
if (!stack || /var\(/i.test(stack)) return '';
return String(stack || '')
.split(',')
.map(normalizeBrowserFontName)
.find(font => font && !GENERIC_FONTS.has(font)) || '';
}
function browserDesignSystemConfig() {
const raw = window.__IMPECCABLE_CONFIG__?.designSystem;
if (!raw?.present) return null;
const allowedFonts = new Set((raw.allowedFonts || []).map(normalizeBrowserFontName).filter(Boolean));
const allowedColors = (raw.allowedColors || [])
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b }));
const allowedRadii = (raw.allowedRadii || [])
.map(Number)
.filter(px => Number.isFinite(px));
return {
present: true,
hasFonts: raw.hasFonts === true && allowedFonts.size > 0,
allowedFonts,
hasColors: raw.hasColors === true && allowedColors.length > 0,
allowedColors,
hasRadii: raw.hasRadii === true && allowedRadii.length > 0,
allowedRadii,
hasPillRadius: raw.hasPillRadius === true,
};
}
function browserColorsClose(a, b) {
if (!a || !b) return false;
return Math.max(
Math.abs(a.r - b.r),
Math.abs(a.g - b.g),
Math.abs(a.b - b.b),
) <= DESIGN_COLOR_TOLERANCE;
}
function isBrowserDesignColorAllowed(raw, designSystem) {
if (!designSystem?.hasColors) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === 'transparent' || text === 'currentcolor' || text === 'inherit' || text === 'initial') return true;
if (text.includes('var(')) return true;
const parsed = parseAnyColor(text);
if (!parsed) return true;
if ((parsed.a ?? 1) <= 0.05) return true;
return designSystem.allowedColors.some(color => browserColorsClose(parsed, color));
}
function isBrowserTransparentCss(value) {
const text = String(value || '').trim().toLowerCase();
if (!text || text === 'transparent') return true;
const parsed = parseAnyColor(text);
return parsed ? (parsed.a ?? 1) <= 0.05 : false;
}
function isBrowserDesignRadiusAllowed(raw, designSystem) {
if (!designSystem?.hasRadii) return true;
const text = String(raw || '').trim().toLowerCase();
if (!text || text === '0' || text === 'none' || text === 'initial' || text === 'inherit') return true;
if (text.includes('var(') || text.includes('%')) return true;
const px = resolveLengthPx(text, 16);
if (px == null || !Number.isFinite(px) || px <= DESIGN_RADIUS_TOLERANCE_PX) return true;
if (designSystem.hasPillRadius && px >= 99) return true;
return designSystem.allowedRadii.some(allowed => Math.abs(allowed - px) <= DESIGN_RADIUS_TOLERANCE_PX);
}
function browserRadiusTokens(value) {
return String(value || '')
.replace(/\s*\/\s*/g, ' ')
.split(/\s+/)
.map(token => token.trim())
.filter(Boolean);
}
function browserHasDirectText(el) {
return [...(el.childNodes || [])].some(node => node.nodeType === 3 && node.textContent.trim().length > 0);
}
function browserSampleText(el) {
const text = String(el.textContent || '').replace(/\s+/g, ' ').trim();
return text ? ` "${text.slice(0, 40)}"` : '';
}
function shouldSkipDesignElement(el) {
const tag = el.tagName?.toLowerCase?.() || '';
return DESIGN_SKIP_TAGS.has(tag) || isElementHidden(el);
}
function checkElementDesignSystemDOM(el, designSystem, seen) {
if (!designSystem?.present || shouldSkipDesignElement(el)) return [];
const findings = [];
const tag = el.tagName?.toLowerCase?.() || 'unknown';
const style = getComputedStyle(el);
if (designSystem.hasFonts && browserHasDirectText(el)) {
const font = browserPrimaryFont(style.fontFamily || '');
if (font && !designSystem.allowedFonts.has(font) && !seen.fonts.has(font)) {
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `${tag}${browserSampleText(el)} uses ${font}; not declared in DESIGN.md typography`,
ignoreValue: font,
});
}
}
if (designSystem.hasColors) {
const colorChecks = [];
if (browserHasDirectText(el)) colorChecks.push(['text color', style.color]);
if (!isBrowserTransparentCss(style.backgroundColor)) colorChecks.push(['background', style.backgroundColor]);
for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
if ((parseFloat(style[`border${side}Width`]) || 0) > 0) {
colorChecks.push([`border-${side.toLowerCase()}`, style[`border${side}Color`]]);
}
}
if ((parseFloat(style.outlineWidth) || 0) > 0) colorChecks.push(['outline', style.outlineColor]);
for (const [kind, raw] of colorChecks) {
const label = String(raw || '').trim().replace(/\s+/g, ' ');
if (isBrowserDesignColorAllowed(label, designSystem)) continue;
const key = `${kind}:${label}`;
if (seen.colors.has(key)) continue;
seen.colors.add(key);
findings.push({
type: 'design-system-color',
detail: `${kind} ${label} on ${tag}${browserSampleText(el)} is outside DESIGN.md colors`,
ignoreValue: label,
});
}
}
if (designSystem.hasRadii) {
for (const token of browserRadiusTokens(style.borderRadius || '')) {
if (isBrowserDesignRadiusAllowed(token, designSystem)) continue;
if (seen.radii.has(token)) continue;
seen.radii.add(token);
findings.push({
type: 'design-system-radius',
detail: `border-radius ${token} on ${tag}${browserSampleText(el)} is outside the DESIGN.md rounded scale`,
ignoreValue: token,
});
}
}
return findings;
}
function decodeBrowserGoogleFamily(value) {
const family = String(value || '').split(':')[0].replace(/\+/g, ' ');
try {
return decodeURIComponent(family);
} catch {
return family;
}
}
function checkBrowserDesignSystemSources(designSystem, seen) {
if (!designSystem?.hasFonts) return [];
const findings = [];
for (const link of document.querySelectorAll('link[href*="fonts.googleapis.com/css"]')) {
const href = link.getAttribute('href') || '';
for (const match of href.matchAll(/[?&]family=([^&]+)/g)) {
const display = decodeBrowserGoogleFamily(match[1]);
const font = normalizeBrowserFontName(display);
if (!font || designSystem.allowedFonts.has(font) || seen.fonts.has(font)) continue;
seen.fonts.add(font);
findings.push({
type: 'design-system-font',
detail: `Google Fonts: ${display} is not declared in DESIGN.md typography`,
ignoreValue: display,
});
}
}
return findings;
}
function collectBrowserFindings() {
const groupMap = new Map();
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
const designSystem = browserDesignSystemConfig();
const designSeen = { fonts: new Set(), colors: new Set(), radii: new Set() };
// Note: provider-gated rules (--gpt / --gemini) are NOT filtered here. In a
// real browser env (detector page, live overlay, extension) running every
// check is free, so we always surface them; the gating is purely a CLI
@@ -4460,6 +4734,7 @@ if (IS_BROWSER) {
...checkElementClippedOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementGptBorderShadowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementTextOverflowDOM(el).map(f => ({ type: f.id, detail: f.snippet })),
...checkElementDesignSystemDOM(el, designSystem, designSeen),
].filter(f => _ruleOk(f.type));
addBrowserFindings(groupMap, el, findings);
@@ -4476,6 +4751,13 @@ if (IS_BROWSER) {
const pageLevelFindings = [];
const designSourceFindings = checkBrowserDesignSystemSources(designSystem, designSeen)
.filter(f => _ruleOk(f.type));
if (designSourceFindings.length > 0) {
pageLevelFindings.push(...designSourceFindings);
addBrowserFindings(groupMap, document.body, designSourceFindings);
}
const typoFindings = checkTypography().filter(f => _ruleOk(f.type));
if (typoFindings.length > 0) {
pageLevelFindings.push(...typoFindings);
@@ -23,6 +23,13 @@ export {
checkHtmlPatterns,
} from './rules/checks.mjs';
export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
export {
parseFrontmatter as parseDesignFrontmatter,
normalizeDesignSystem,
loadDesignSystemForCwd,
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
} from './design-system.mjs';
export { detectHtml } from './engines/static-html/detect-html.mjs';
export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
@@ -7,6 +7,25 @@ import { filterByProviders } from '../../registry/antipatterns.mjs';
import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
function serializeDesignSystemForBrowser(designSystem) {
if (!designSystem?.present) return null;
return {
present: true,
hasFonts: designSystem.hasFonts === true,
allowedFonts: Array.from(designSystem.allowedFonts || []),
hasColors: designSystem.hasColors === true,
allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
.map(entry => entry?.color)
.filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
.map(color => ({ r: color.r, g: color.g, b: color.b })),
hasRadii: designSystem.hasRadii === true,
allowedRadii: (designSystem.allowedRadii || [])
.map(entry => Number(entry?.px))
.filter(px => Number.isFinite(px)),
hasPillRadius: designSystem.hasPillRadius === true,
};
}
async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
if (options?.visualContrast === false) return [];
const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
@@ -163,17 +182,19 @@ async function detectUrl(url, options = {}) {
}
// Inject the browser detection script and collect results
const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
await profileStepAsync(profile, {
engine: 'browser',
phase: 'scan',
ruleId: 'configure-pure-detect',
target: url,
}, () => page.evaluate(() => {
}, () => page.evaluate((designSystem) => {
window.__IMPECCABLE_CONFIG__ = {
...(window.__IMPECCABLE_CONFIG__ || {}),
autoScan: false,
...(designSystem ? { designSystem } : {}),
};
}));
}, browserDesignSystem));
await profileStepAsync(profile, {
engine: 'browser',
phase: 'scan',
@@ -192,7 +213,7 @@ async function detectUrl(url, options = {}) {
return window.impeccableDetect({ decorate: false, serialize: true });
});
return serializedGroups.flatMap(({ findings }) =>
findings.map(f => ({ id: f.type, snippet: f.detail }))
findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '' }))
);
});
const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
@@ -213,7 +234,11 @@ async function detectUrl(url, options = {}) {
}, () => browser.close());
}
}
return filterByProviders(results.map(f => finding(f.id, url, f.snippet)), options.providers);
return filterByProviders(results.map(f => {
const item = finding(f.id, url, f.snippet);
if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
return item;
}), options.providers);
}
async function createBrowserDetector(options = {}) {
@@ -1,5 +1,8 @@
import { GENERIC_FONTS } from '../../shared/constants.mjs';
import { isNeutralColor } from '../../shared/color.mjs';
import { checkSourceDesignSystem } from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
import { finding } from '../../findings.mjs';
import { filterByProviders } from '../../registry/antipatterns.mjs';
import { profileFindings, profileStep } from '../../profile/profiler.mjs';
@@ -36,10 +39,11 @@ function shouldRunPageAnalyzers(content, filePath) {
}
function isNeutralBorderColor(str) {
const m = str.match(/solid\s+(#[0-9a-f]{3,8}|rgba?\([^)]+\)|\w+)/i);
const m = str.match(/solid\s+((?:rgba?|hsla?|oklch|oklab|lab|lch|hwb|color)\([^)]*\)|#[0-9a-f]{3,8}\b|[a-z]+)/i);
if (!m) return false;
const c = m[1].toLowerCase();
if (['gray', 'grey', 'silver', 'white', 'black', 'transparent', 'currentcolor'].includes(c)) return true;
if (/^(?:rgba?|hsla?|oklch|oklab|lab|lch|hwb)\(/i.test(c)) return isNeutralColor(c);
const hex = c.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/);
if (hex) {
const [r, g, b] = [parseInt(hex[1], 16), parseInt(hex[2], 16), parseInt(hex[3], 16)];
@@ -56,10 +60,10 @@ function isNeutralBorderColor(str) {
const REGEX_MATCHERS = [
// --- Side-tab ---
{ id: 'side-tab', regex: /\bborder-[lrse]-(\d+)\b/g,
test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 1 : n >= 4; },
test: (m, line) => { const n = +m[1]; return hasRounded(line) ? n >= 2 : n >= 4; },
fmt: (m) => m[0] },
{ id: 'side-tab', regex: /border-(?:left|right)\s*:\s*(\d+)px\s+solid[^;]*/gi,
test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 1 : n >= 3; },
test: (m, line) => { if (isSafeElement(line)) return false; if (isNeutralBorderColor(m[0])) return false; const n = +m[1]; return hasBorderRadius(line) ? n >= 2 : n >= 3; },
fmt: (m) => m[0].replace(/\s*;?\s*$/, '') },
{ id: 'side-tab', regex: /border-(?:left|right)-width\s*:\s*(\d+)px/gi,
test: (m, line) => !isSafeElement(line) && +m[1] >= 3,
@@ -110,9 +114,14 @@ const REGEX_MATCHERS = [
{ id: 'bounce-easing', regex: /\banimate-bounce\b/g,
test: () => true,
fmt: () => 'animate-bounce (Tailwind)' },
{ id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi,
{ id: 'bounce-easing', regex: /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi,
test: () => true,
fmt: (m) => m[0] },
fmt: (m) => {
const token = m[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
return `animation: ${token || m[1].trim()}`;
} },
{ id: 'bounce-easing', regex: /cubic-bezier\(\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*,\s*([\d.-]+)\s*\)/g,
test: (m) => {
const y1 = parseFloat(m[2]), y2 = parseFloat(m[4]);
@@ -498,6 +507,15 @@ function detectText(content, filePath, options = {}) {
}));
}
if (options?.designSystem) {
findings.push(...profileFindings(profile, {
engine: 'regex',
phase: 'source',
ruleId: 'design-system',
target: filePath,
}, () => checkSourceDesignSystem(content, filePath, { designSystem: options.designSystem })));
}
// Deduplicate findings (same antipattern + similar snippet, within 2 lines)
const deduped = [];
for (const f of findings) {
@@ -532,7 +550,10 @@ function detectText(content, filePath, options = {}) {
}
}
return filterByProviders(deduped, options?.providers);
const byProvider = filterByProviders(deduped, options?.providers);
// Inline `impeccable-disable*` waivers travel with the file; honor them unless
// explicitly bypassed (`--no-config` / `--no-inline-ignores`).
return options?.inlineIgnores === false ? byProvider : applyInlineIgnores(byProvider, content);
}
export {
@@ -272,6 +272,7 @@ const STATIC_DEFAULT_STYLE = {
marginBottom: '0px',
marginLeft: '0px',
position: 'static',
visibility: 'visible',
top: 'auto',
right: 'auto',
bottom: 'auto',
@@ -326,6 +327,7 @@ const STATIC_PROP_MAP = {
'margin-bottom': 'marginBottom',
'margin-left': 'marginLeft',
'position': 'position',
'visibility': 'visibility',
'top': 'top',
'right': 'right',
'bottom': 'bottom',
@@ -2,7 +2,13 @@ import fs from 'node:fs';
import path from 'node:path';
import { GENERIC_FONTS, OVERUSED_FONTS } from '../../shared/constants.mjs';
import {
checkSourceDesignSystem,
collectStaticDesignSystemFindings,
mergeDesignSystemFindings,
} from '../../design-system.mjs';
import { isFullPage } from '../../shared/page.mjs';
import { applyInlineIgnores } from '../../shared/inline-ignores.mjs';
import { finding } from '../../findings.mjs';
import { profileFindings, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
import {
@@ -168,6 +174,22 @@ async function detectHtml(filePath, options = {}) {
}
}
if (options?.designSystem) {
const sourceDesignFindings = profileFindings(profile, {
engine: 'static-html',
phase: 'source',
ruleId: 'design-system',
target: filePath,
}, () => checkSourceDesignSystem(html, filePath, { designSystem: options.designSystem }));
const staticDesignFindings = profileFindings(profile, {
engine: 'static-html',
phase: 'page',
ruleId: 'design-system',
target: filePath,
}, () => collectStaticDesignSystemFindings(document, window, filePath, options.designSystem));
findings.push(...mergeDesignSystemFindings(staticDesignFindings, sourceDesignFindings));
}
if (isFullPage(html)) {
const runPageCheck = (ruleId, callback) => profile
? profileFindings(profile, { engine: 'static-html', phase: 'page', ruleId, target: filePath }, callback)
@@ -202,7 +224,11 @@ async function detectHtml(filePath, options = {}) {
}
}
return filterByProviders(findings, options.providers);
const byProvider = filterByProviders(findings, options.providers);
// Static-HTML findings carry no line number, so only whole-file
// `impeccable-disable` directives apply here — exactly the standalone-document
// waiver this primitive targets. Bypassed by `--no-config` / `--no-inline-ignores`.
return options?.inlineIgnores === false ? byProvider : applyInlineIgnores(byProvider, html);
}
export { checkStaticPageTypography, STATIC_ELEMENT_RULES, detectHtml };
@@ -323,6 +323,35 @@ const ANTIPATTERNS = [
skillSection: 'Layout & Space',
skillGuideline: 'overflow container clipping positioned children',
},
{
id: 'design-system-font',
category: 'quality',
name: 'Font outside DESIGN.md',
description:
'A font is used that is not declared in DESIGN.md typography. Use the documented type system or update DESIGN.md if this is an intentional brand addition.',
skillSection: 'Typography',
skillGuideline: 'font family outside the project design system',
},
{
id: 'design-system-color',
category: 'quality',
severity: 'advisory',
name: 'Color outside DESIGN.md',
description:
'A literal color is outside the DESIGN.md palette and sidecar tonal ramps. This may be legitimate, but it should be an intentional design-system addition rather than drift.',
skillSection: 'Color & Contrast',
skillGuideline: 'literal color outside the project design system',
},
{
id: 'design-system-radius',
category: 'quality',
severity: 'advisory',
name: 'Radius outside DESIGN.md',
description:
'A border-radius value is outside the DESIGN.md rounded scale. Use a documented radius token or update the design system if the new shape is intentional.',
skillSection: 'Visual Details',
skillGuideline: 'border radius outside the project design system',
},
// ── Provider tells: opt-in via --gpt / --gemini (gated off by default) ──
{
@@ -347,6 +376,17 @@ const ANTIPATTERNS = [
skillSection: 'Visual Details',
skillGuideline: 'repeating-gradient decorative stripes',
},
{
id: 'codex-grid-background',
category: 'slop',
severity: 'advisory',
gated: 'gpt',
name: 'Decorative grid-line background',
description:
'A two-axis grid drawn with hairline linear-gradient layers ("1px, transparent 1px" on both axes) is a recurring generated-UI signature. Reserve grid overlays for actual canvas, map, blueprint, or measurement surfaces; elsewhere use product structure or a plain surface.',
skillSection: 'Visual Details',
skillGuideline: 'two-axis grid-line gradient background',
},
{
id: 'theater-slop-phrase',
category: 'slop',
@@ -514,9 +514,13 @@ function checkHtmlPatterns(html) {
// --- Motion ---
// Bounce/elastic animation names
const bounceRe = /animation(?:-name)?\s*:\s*[^;]*\b(bounce|elastic|wobble|jiggle|spring)\b/gi;
if (bounceRe.test(html)) {
findings.push({ id: 'bounce-easing', snippet: 'Bounce/elastic animation in CSS' });
const bounceRe = /animation(?:-name)?\s*:\s*([^;{}]*(?:bounce|elastic|wobble|jiggle|spring)[^;{}]*)/gi;
const bounceMatch = bounceRe.exec(html);
if (bounceMatch) {
const animationToken = bounceMatch[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
findings.push({ id: 'bounce-easing', snippet: `animation: ${animationToken || bounceMatch[1].trim()}` });
}
// Overshoot cubic-bezier
@@ -569,6 +573,42 @@ function checkHtmlPatterns(html) {
findings.push({ id: 'repeating-stripes-gradient', snippet: 'repeating-gradient decorative stripes' });
}
// --- Provider tells (gated): two-axis grid-line background (Codex/GPT) ---
// The Codex grid tell is two hairline `linear-gradient(... <color> 1px,
// transparent 1px)` layers (one per axis) tiled by a repeating
// `background-size` cell. Both signals must co-occur in the SAME style block
// (a CSS rule body or one inline `style="..."`): two hairline stops WITHOUT a
// tiling background-size is a fixed crosshair, not a grid, and a single
// hairline is a legitimate ruled line. Scoping to one block also stops
// unrelated single-axis rules on separate elements from adding up across the
// page. Count hairlines only inside `background`/`background-image` values so
// a hairline in an unrelated property (mask-image, border-image) can't stand
// in for the second axis. Colors like `oklch(96% 0.012 82 / 0.055)` carry
// nested parens, so match the hairline stop directly rather than parsing
// whole gradient layers.
{
const hairlineRe = /\b\d{1,3}px\s*,\s*transparent\s+\d{1,3}px/gi;
const gridSizeRe = /background-size\s*:[^;{}"']*\b\d{1,3}px\b/i;
const bgDeclRe = /\bbackground(?:-image)?\s*:\s*([^;{}"']*)/gi;
const blockRe = /\{([^{}]*)\}|style\s*=\s*"([^"]*)"|style\s*=\s*'([^']*)'/gi;
let blk;
while ((blk = blockRe.exec(html)) !== null) {
const block = blk[1] || blk[2] || blk[3] || '';
if (!gridSizeRe.test(block)) continue;
let hairlineCount = 0;
let bm;
bgDeclRe.lastIndex = 0;
while ((bm = bgDeclRe.exec(block)) !== null) {
const stops = bm[1].match(hairlineRe);
if (stops) hairlineCount += stops.length;
}
if (hairlineCount >= 2) {
findings.push({ id: 'codex-grid-background', snippet: 'two-axis grid-line gradient background' });
break;
}
}
}
// --- Provider tells (gated): "X theater" framing copy (GPT) ---
// Lives here (regex-on-HTML) rather than in the text-content analyzers so it
// runs in the bundled browser path too, not just the CLI/static path.
@@ -0,0 +1,148 @@
/**
* Inline, in-file ignore directives eslint-disable-style waivers that live at
* the point they apply and travel with the artifact instead of (or alongside)
* an ignore in `.impeccable/config.json`.
*
* A config ignore is the right default for repo-wide policy. This complements it
* for the one case config can't cover: a waiver that belongs to a single file and
* needs to follow that file when it leaves the repo a generated/exported
* standalone document, an emailed HTML file, a snippet scanned out of context.
*
* Comment-syntax-agnostic: the directive is a raw token matched anywhere on a
* line, so the same marker works across every comment style impeccable scans
* `//`, `/* *\/`, `<!-- -->`, `#`, `{/* *\/}`, `{# #}`. Trailing comment closers
* are stripped before the rule list is parsed.
*
* Syntax (reason optional; eslint `--` or biome `:` separator):
*
* impeccable-disable <rule>[, <rule>...] [-- reason] whole file
* impeccable-disable-line <rule>... [-- reason] the same line
* impeccable-disable-next-line <rule>... [-- reason] the following line
* impeccable-disable bare / `*` = every rule
*
* Examples:
*
* <!-- impeccable-disable overused-font -- exported brand doc, font is first-party -->
* .brand { font-family: Inter; } /* impeccable-disable-line overused-font *\/
* // impeccable-disable-next-line bounce-easing: intentional playful affordance
*
* Behavior is suppression, for parity with config ignores: a matched directive
* drops the finding. The inline reason is self-documenting in the diff; it is not
* required and is discarded at scan time (only used here to keep reason words out
* of the parsed rule list).
*/
const DIRECTIVE_RE = /impeccable-(disable-next-line|disable-line|disable)\b[ \t]*([^\n\r]*)/gi;
// Trailing comment closers, so `*/`, `*/}`, `-->`, `*}`, `#}`, `%>`, `}}` don't
// leak into the rule list. Anchored to end-of-line; the leading `\s*` mops up the
// space before the closer. `--+>` covers `-->` and any longer dash run.
const TRAILING_CLOSER_RE = /\s*(?:\*\/\}?|--+>|\*\}|#\}|%>|\}\})\s*$/;
function normalizeRule(token) {
return String(token || '').trim().toLowerCase();
}
// Split the directive remainder into rule tokens, dropping any human reason that
// follows an eslint-style `--` or biome-style `:` separator. Rule ids only ever
// contain single hyphens (`overused-font`, `bounce-easing`), so `--` and `:`
// are unambiguous separators.
function parseRuleList(remainder) {
let text = String(remainder || '').replace(TRAILING_CLOSER_RE, '').trim();
// Cut off a human reason at the first `--` (eslint) or `:` (biome) separator.
const reasonSep = text.match(/\s*(?:--+|:)\s*/);
if (reasonSep) text = text.slice(0, reasonSep.index);
const tokens = text.split(/[\s,]+/).map(normalizeRule).filter(Boolean);
if (tokens.length === 0 || tokens.includes('*')) return ['*'];
return tokens;
}
function addRules(set, rules) {
for (const rule of rules) set.add(rule);
}
function getSet(map, key) {
let set = map.get(key);
if (!set) {
set = new Set();
map.set(key, set);
}
return set;
}
/**
* Parse every inline ignore directive in a file's raw text.
*
* Returns sets keyed by the 1-based line the directive *targets* so matching is a
* direct lookup:
* - file: rules disabled for the whole file
* - line: line -> rules disabled on that exact line (disable-line)
* - nextLine: line -> rules disabled on that line (disable-next-line on line-1)
*
* `*` in any set means "every rule".
*/
function parseInlineIgnores(content) {
const result = { file: new Set(), line: new Map(), nextLine: new Map() };
const text = typeof content === 'string' ? content : '';
// Cheap bail-out: the substring must be present for any directive to exist.
// Case-insensitive to match DIRECTIVE_RE's `i` flag (e.g. `Impeccable-Disable`).
if (!/impeccable-disable/i.test(text)) return result;
// Split on `\n` only, exactly as detectText numbers lines, so directive line
// keys line up with finding `line` values (incl. on `\r`-only line endings).
// The directive regex excludes `\r`, so a trailing `\r` on `\r\n` files is
// never captured into the rule list.
const lines = text.split('\n');
for (let i = 0; i < lines.length; i++) {
DIRECTIVE_RE.lastIndex = 0;
let m;
while ((m = DIRECTIVE_RE.exec(lines[i])) !== null) {
const variant = m[1].toLowerCase();
const rules = parseRuleList(m[2]);
if (variant === 'disable') {
addRules(result.file, rules);
} else if (variant === 'disable-line') {
addRules(getSet(result.line, i + 1), rules);
} else {
// disable-next-line on line i+1 targets line i+2.
addRules(getSet(result.nextLine, i + 2), rules);
}
}
}
return result;
}
function setMatches(set, rule) {
return Boolean(set) && (set.has('*') || set.has(rule));
}
function isInlineIgnored(finding, directives) {
const rule = normalizeRule(finding && finding.antipattern);
if (!rule) return false;
if (setMatches(directives.file, rule)) return true;
const line = Number(finding && finding.line) || 0;
if (line > 0) {
if (setMatches(directives.line.get(line), rule)) return true;
if (setMatches(directives.nextLine.get(line), rule)) return true;
}
return false;
}
function hasDirectives(directives) {
return directives.file.size > 0 || directives.line.size > 0 || directives.nextLine.size > 0;
}
/**
* Drop findings waived by an inline directive in the same file's source text.
* Findings without a usable line number (e.g. static-HTML page-level findings)
* are only matched by whole-file directives which is the standalone-document
* case this primitive exists for.
*/
function applyInlineIgnores(findings, content) {
if (!Array.isArray(findings) || findings.length === 0) return findings;
const directives = parseInlineIgnores(content);
if (!hasDirectives(directives)) return findings;
return findings.filter((finding) => !isInlineIgnored(finding, directives));
}
export { parseInlineIgnores, applyInlineIgnores, isInlineIgnored };
+138 -52
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env node
/**
* `/impeccable hooks <on|off|status|reset>` manage the design hook
* via the `hook` key of .impeccable/config.json and .impeccable/config.local.json
* in the current project.
* `/impeccable hooks <on|off|status|reset>` manage the design hook runtime
* via the `hook` key and shared detector ignores via the `detector` key in
* .impeccable/config.json / .impeccable/config.local.json.
*
* Usage:
* node hook-admin.mjs status # print current state
@@ -75,7 +75,6 @@ const HOOK_MANIFEST_TARGETS = [
skillRel: '.agents/skills/impeccable',
destRel: '.codex/hooks.json',
manifest: () => ({
description: 'Impeccable design detector: runs after Edit/Write/apply_patch on UI files and surfaces findings as system reminders.',
hooks: {
PostToolUse: [
{
@@ -83,7 +82,7 @@ const HOOK_MANIFEST_TARGETS = [
hooks: [
{
type: 'command',
command: 'node "$(git rev-parse --show-toplevel)/.agents/skills/impeccable/scripts/hook.mjs"',
command: 'node ".agents/skills/impeccable/scripts/hook.mjs"',
timeout: TIMEOUT_SECONDS,
statusMessage: STATUS_MESSAGE,
},
@@ -109,6 +108,28 @@ const HOOK_MANIFEST_TARGETS = [
},
}),
},
{
// GitHub Copilot reads repo-level hooks from `.github/hooks/*.json`. The same
// manifest is honored by the CLI (once committed to the default branch) and
// the cloud/app agent. Schema differs: lowercase `postToolUse`, flat entries,
// `bash`/`timeoutSec`, and a `matcher` regex against the `edit`/`create` tools.
provider: '.github',
skillRel: '.github/skills/impeccable',
destRel: '.github/hooks/impeccable.json',
manifest: () => ({
version: 1,
hooks: {
postToolUse: [
{
type: 'command',
matcher: 'edit|create|apply_patch',
bash: 'node "$(git rev-parse --show-toplevel)/.github/skills/impeccable/scripts/hook.mjs"',
timeoutSec: TIMEOUT_SECONDS,
},
],
},
}),
},
];
function readRawConfigFile(filePath) {
@@ -120,23 +141,48 @@ function readRawConfigFile(filePath) {
}
}
// The hook settings to edit: the unified file's `hook` subtree.
function readRawConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
if (unified && typeof unified === 'object' && unified.hook && typeof unified.hook === 'object') {
return unified.hook;
}
return null;
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
function hookSection(unified) {
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.hook && typeof unified.hook === 'object' && !Array.isArray(unified.hook)
? unified.hook
: null;
}
// Write the hook config back under the `hook` key of the unified file, leaving
// any sibling keys (e.g. updateCheck) untouched.
function writeConfig(cwd, hookConfig, opts = {}) {
function detectorSection(unified) {
return unified && typeof unified === 'object' && !Array.isArray(unified) && unified.detector && typeof unified.detector === 'object' && !Array.isArray(unified.detector)
? unified.detector
: null;
}
function readRawHookConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
return hookSection(unified);
}
function readRawDetectorConfig(cwd, opts = {}) {
const unified = readRawConfigFile(opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd)).raw;
const merged = mergeDetectorConfig(hookSection(unified));
return mergeDetectorConfig(detectorSection(unified), merged);
}
function stripDetectorKeys(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
const out = {};
for (const [key, value] of Object.entries(raw)) {
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
}
return out;
}
// Write hook runtime config under `hook`, leaving detector filters in
// `detector` and preserving sibling keys such as updateCheck.
function writeHookConfig(cwd, hookConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
if (opts.local) ensureHookGitExcludes(cwd);
const existingRaw = readRawConfigFile(filePath).raw;
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
const existingHook = existing.hook && typeof existing.hook === 'object' && !Array.isArray(existing.hook) ? existing.hook : {};
const existingHook = stripDetectorKeys(hookSection(existing));
// Merge over the existing hook object so fields the merge helpers don't manage
// (consent, quiet, auditLog) survive a `/impeccable hooks` edit.
const next = { ...existing, hook: { ...existingHook, ...hookConfig } };
@@ -145,15 +191,28 @@ function writeConfig(cwd, hookConfig, opts = {}) {
return filePath;
}
function mergeConfig(existing) {
// Persist the full shape so /impeccable hooks edits leave a complete file
// for the user to see, not an unhelpful `{"enabled":false}`.
function writeDetectorConfig(cwd, detectorConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(cwd) : getConfigPath(cwd);
if (opts.local) ensureHookGitExcludes(cwd);
const existingRaw = readRawConfigFile(filePath).raw;
const existing = existingRaw && typeof existingRaw === 'object' && !Array.isArray(existingRaw) ? existingRaw : {};
const nextHook = stripDetectorKeys(hookSection(existing));
const existingDetector = mergeDetectorConfig(detectorSection(existing));
const next = {
...existing,
detector: mergeDetectorConfig(detectorConfig, existingDetector),
};
if (Object.keys(nextHook).length > 0) next.hook = nextHook;
else delete next.hook;
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
return filePath;
}
function mergeHookConfig(existing) {
const base = existing && typeof existing === 'object' ? existing : {};
return {
enabled: base.enabled === false ? false : true,
ignoreRules: Array.isArray(base.ignoreRules) ? Array.from(new Set(base.ignoreRules.map(String))) : [],
ignoreFiles: Array.isArray(base.ignoreFiles) ? Array.from(new Set(base.ignoreFiles.map(String))) : [],
ignoreValues: normalizeIgnoreValueEntries(base.ignoreValues || []),
limits: {
maxFindings: Number.isFinite(base?.limits?.maxFindings) ? base.limits.maxFindings : DEFAULT_CONFIG.limits.maxFindings,
maxChars: Number.isFinite(base?.limits?.maxChars) ? base.limits.maxChars : DEFAULT_CONFIG.limits.maxChars,
@@ -161,28 +220,54 @@ function mergeConfig(existing) {
};
}
function mergeLocalConfig(existing) {
function mergeDetectorConfig(existing, seed = null) {
const base = existing && typeof existing === 'object' ? existing : {};
const out = {};
if (Object.prototype.hasOwnProperty.call(base, 'enabled')) {
out.enabled = base.enabled === false ? false : true;
const out = seed ? {
ignoreRules: [...seed.ignoreRules],
ignoreFiles: [...seed.ignoreFiles],
ignoreValues: normalizeIgnoreValueEntries(seed.ignoreValues),
} : {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
};
if (seed?.designSystem && typeof seed.designSystem === 'object' && !Array.isArray(seed.designSystem)) {
out.designSystem = { ...seed.designSystem };
}
if (base.designSystem && typeof base.designSystem === 'object' && !Array.isArray(base.designSystem)) {
out.designSystem = {
...(out.designSystem || {}),
enabled: base.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(base.ignoreRules)) {
out.ignoreRules = Array.from(new Set(base.ignoreRules.map(String)));
out.ignoreRules = Array.from(new Set([...out.ignoreRules, ...base.ignoreRules.map(String)]));
}
if (Array.isArray(base.ignoreFiles)) {
out.ignoreFiles = Array.from(new Set(base.ignoreFiles.map(String)));
out.ignoreFiles = Array.from(new Set([...out.ignoreFiles, ...base.ignoreFiles.map(String)]));
}
out.ignoreValues = normalizeIgnoreValueEntries(base.ignoreValues || []);
if (base.limits && typeof base.limits === 'object') {
const limits = {};
if (Number.isFinite(base.limits.maxFindings)) limits.maxFindings = base.limits.maxFindings;
if (Number.isFinite(base.limits.maxChars)) limits.maxChars = base.limits.maxChars;
if (Object.keys(limits).length) out.limits = limits;
if (Array.isArray(base.ignoreValues)) {
out.ignoreValues = mergeIgnoreValueEntries(out.ignoreValues, base.ignoreValues);
}
return out;
}
function mergeIgnoreValueEntries(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(ignoreValueEntryKey(entry), entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(ignoreValueEntryKey(entry), entry);
}
return Array.from(map.values());
}
function ignoreValueEntryKey(entry) {
const files = Array.isArray(entry.files) && entry.files.length > 0 ? entry.files.join('\x1f') : '';
return `${entry.rule}\0${entry.value}\0${files}`;
}
function statusReport(cwd) {
const shared = readRawConfigFile(getConfigPath(cwd));
const local = readRawConfigFile(getLocalConfigPath(cwd));
@@ -216,14 +301,14 @@ function statusReport(cwd) {
}
function setEnabled(cwd, value) {
const config = mergeConfig(readRawConfig(cwd));
const config = mergeHookConfig(readRawHookConfig(cwd));
config.enabled = value;
const target = writeConfig(cwd, config);
const target = writeHookConfig(cwd, config);
if (!value) {
return `Design hook disabled for this project (wrote ${path.relative(cwd, target) || target}).`;
}
const localTarget = writeConfig(cwd, { consent: 'accepted' }, { local: true });
const localTarget = writeHookConfig(cwd, { consent: 'accepted' }, { local: true });
const repaired = repairHookManifests(cwd);
const parts = [
`Design hook enabled for this project (wrote ${path.relative(cwd, target) || target}).`,
@@ -336,7 +421,10 @@ function valueHasImpeccableHookMarker(value) {
function stripImpeccableHookEntry(entry) {
if (!entry || typeof entry !== 'object') return entry;
if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)) {
// `command`/`args`: Claude/Codex/Cursor. `bash`/`powershell`: GitHub Copilot's
// flat entry shape, where the marker lives under the shell-command keys.
if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)
|| valueHasImpeccableHookMarker(entry.bash) || valueHasImpeccableHookMarker(entry.powershell)) {
return null;
}
if (!Array.isArray(entry.hooks)) return entry;
@@ -429,18 +517,18 @@ function addIgnoreRule(cwd, args) {
if (rule === 'overused-font' && !parsed.allValues) {
throw new Error('overused-font is value-specific by default. Use /impeccable hooks ignore-value overused-font <font> for a confirmed font, or /impeccable hooks ignore-rule overused-font --all-values only when the user asked to ignore overused fonts generally.');
}
const config = mergeConfig(readRawConfig(cwd));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
if (!config.ignoreRules.includes(rule)) config.ignoreRules.push(rule);
writeConfig(cwd, config);
return `Added "${rule}" to ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
writeDetectorConfig(cwd, config);
return `Added "${rule}" to detector.ignoreRules. Current: ${config.ignoreRules.join(', ')}`;
}
function addIgnoreFile(cwd, glob) {
if (!glob) throw new Error('Pass a glob, e.g. /impeccable hooks ignore-file "src/legacy/**"');
const config = mergeConfig(readRawConfig(cwd));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd));
if (!config.ignoreFiles.includes(glob)) config.ignoreFiles.push(glob);
writeConfig(cwd, config);
return `Added "${glob}" to ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
writeDetectorConfig(cwd, config);
return `Added "${glob}" to detector.ignoreFiles. Current: ${config.ignoreFiles.join(', ')}`;
}
function parseIgnoreValueArgs(args) {
@@ -489,9 +577,7 @@ function addIgnoreValue(cwd, args) {
}
const local = parsed.local;
const config = local
? mergeLocalConfig(readRawConfig(cwd, { local: true }))
: mergeConfig(readRawConfig(cwd, { local: false }));
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
const key = `${parsed.rule}\0${parsed.value}`;
const existing = config.ignoreValues.find((entry) => `${entry.rule}\0${entry.value}` === key);
@@ -507,20 +593,20 @@ function addIgnoreValue(cwd, args) {
config.ignoreValues.push(entry);
}
const target = writeConfig(cwd, config, { local });
const scope = local ? 'local ignoreValues' : 'shared ignoreValues';
const target = writeDetectorConfig(cwd, config, { local });
const scope = local ? 'local detector.ignoreValues' : 'shared detector.ignoreValues';
return `Added ${parsed.rule}=${parsed.value} to ${scope} (${path.relative(cwd, target) || target}).`;
}
function reset(cwd) {
const removed = [];
// Unified files may hold non-hook keys (e.g. updateCheck); strip only the
// hook subtree and keep the rest, deleting the file only if nothing remains.
// hook/detector subtrees and keep the rest, deleting the file only if nothing remains.
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
try {
const raw = readRawConfigFile(filePath).raw;
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !('hook' in raw)) continue;
const { hook, ...rest } = raw;
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || (!('hook' in raw) && !('detector' in raw))) continue;
const { hook, detector, ...rest } = raw;
if (Object.keys(rest).length === 0) {
fs.unlinkSync(filePath);
} else {
@@ -18,6 +18,8 @@ import {
EDIT_COUNT_THRESHOLD,
GENERATED_PATH,
SENSITIVE_PATH,
appendDesignSystemNote,
designSystemOptions,
filterFindings,
loadDetector,
matchesAnyGlob,
@@ -333,8 +335,8 @@ function isInsideProject(filePath, cwd) {
function cursorBlockMessage(findings, filePath, config, cwd) {
const rendered = renderTemplate(findings, filePath, config, { cwd });
const blocked = rendered.replace(
'[impeccable@1] Required design corrections',
'[impeccable@1] Impeccable design hook blocked this write before it landed. Required design corrections',
'[impeccable@1] Design hook findings requiring review',
'[impeccable@1] Impeccable design hook blocked this write before it landed. Design hook findings requiring review',
);
return blocked.length > 4000 ? `${blocked.slice(0, 3984)}\n...(truncated)` : blocked;
}
@@ -415,10 +417,11 @@ async function main() {
if (!detector || typeof detector.detectText !== 'function') {
return allow({ ...audit, skipped: 'detector-missing', durationMs: Date.now() - started });
}
const scanOptions = designSystemOptions(config, detector, cwd);
let findings = [];
try {
findings = await detector.detectText(content, filePath);
findings = await detector.detectText(content, filePath, scanOptions);
} catch {
return allow({ ...audit, error: 'detector-threw', durationMs: Date.now() - started });
}
@@ -433,7 +436,7 @@ async function main() {
});
}
const message = cursorBlockMessage(filtered, filePath, config, cwd);
const message = appendDesignSystemNote(cursorBlockMessage(filtered, filePath, config, cwd), scanOptions);
const sessionId = event.session_id || event.conversation_id || 'unknown';
const cache = readCache(cwd);
const denial = bumpCursorDenial(cache, sessionId, filePath, filtered);
+413 -43
View File
@@ -73,6 +73,7 @@ export const DEFAULT_CONFIG = Object.freeze({
enabled: true,
quiet: false,
auditLog: null,
designSystem: { enabled: true },
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
@@ -135,10 +136,14 @@ export function resolveProjectCwd(event, fallback = process.cwd()) {
export function readConfig(cwd) {
const config = cloneDefaultConfig();
// Hook settings live under the `hook` key of config.json (shared) and
// config.local.json (per-developer, gitignored); local wins.
applyConfigSource(config, hookSection(safeReadJson(getConfigPath(cwd))));
applyConfigSource(config, hookSection(safeReadJson(getLocalConfigPath(cwd))));
// Hook runtime settings live under `hook`; detector filters live under
// `detector`. Back-compat: older configs stored detector filters in `hook`,
// so read those first and let canonical `detector` settings win.
for (const filePath of [getConfigPath(cwd), getLocalConfigPath(cwd)]) {
const raw = safeReadJson(filePath);
applyConfigSource(config, hookSection(raw));
applyDetectorConfigSource(config, detectorSection(raw));
}
return config;
}
@@ -148,6 +153,11 @@ function hookSection(raw) {
return raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
}
function detectorSection(raw) {
if (!raw || typeof raw !== 'object') return null;
return raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
}
function numberOr(value, fallback) {
return Number.isFinite(value) && value > 0 ? value : fallback;
}
@@ -158,10 +168,31 @@ function cloneDefaultConfig() {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { ...DEFAULT_CONFIG.designSystem },
limits: { ...DEFAULT_CONFIG.limits },
};
}
function applyDetectorConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
config.designSystem = {
...config.designSystem,
enabled: raw.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
return config;
}
function applyConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (Object.prototype.hasOwnProperty.call(raw, 'enabled')) {
@@ -173,15 +204,7 @@ function applyConfigSource(config, raw) {
if (typeof raw.auditLog === 'string' && raw.auditLog.trim()) {
config.auditLog = raw.auditLog.trim();
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
applyDetectorConfigSource(config, raw);
if (raw.limits && typeof raw.limits === 'object') {
config.limits = {
maxFindings: numberOr(raw.limits.maxFindings, config.limits.maxFindings),
@@ -208,6 +231,157 @@ function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function colorIgnoreKey(value) {
const color = parseIgnoreColor(value);
if (!color) return '';
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
}
function parseIgnoreColor(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return null;
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) return parseHexIgnoreColor(hex[1]);
const rgb = text.match(/^rgba?\((.*)\)$/i);
if (rgb) {
const parts = splitColorArgs(rgb[1]);
if (parts.length < 3 || parts.length > 4) return null;
const r = parseRgbChannel(parts[0]);
const g = parseRgbChannel(parts[1]);
const b = parseRgbChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([r, g, b, a].some((v) => v === null)) return null;
return { r, g, b, a };
}
const hsl = text.match(/^hsla?\((.*)\)$/i);
if (hsl) {
const parts = splitColorArgs(hsl[1]);
if (parts.length < 3 || parts.length > 4) return null;
const h = parseHueChannel(parts[0]);
const s = parsePercentChannel(parts[1]);
const l = parsePercentChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([h, s, l, a].some((v) => v === null)) return null;
return hslToRgb(h, s, l, a);
}
return null;
}
function parseHexIgnoreColor(hex) {
if (hex.length === 3 || hex.length === 4) {
const r = parseInt(hex[0] + hex[0], 16);
const g = parseInt(hex[1] + hex[1], 16);
const b = parseInt(hex[2] + hex[2], 16);
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
return { r, g, b, a };
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
return { r, g, b, a };
}
function splitColorArgs(body) {
const text = String(body || '').trim();
if (!text) return [];
if (text.includes(',')) {
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
const last = parts[parts.length - 1];
if (last && last.includes('/')) {
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
return [...parts.slice(0, -1), ...split];
}
return parts;
}
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
}
function parseRgbChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const scaled = match[2] ? value * 2.55 : value;
if (scaled < 0 || scaled > 255) return null;
return Math.round(scaled);
}
function parseAlphaChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const alpha = match[2] ? value / 100 : value;
return alpha >= 0 && alpha <= 1 ? alpha : null;
}
function parseHueChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const unit = match[2] || 'deg';
if (unit === 'turn') return value * 360;
if (unit === 'rad') return value * (180 / Math.PI);
if (unit === 'grad') return value * 0.9;
return value;
}
function parsePercentChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)%$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
return value >= 0 && value <= 100 ? value / 100 : null;
}
function hslToRgb(hue, saturation, lightness, alpha) {
const h = (((hue % 360) + 360) % 360) / 360;
if (saturation === 0) {
const gray = clampByte(Math.round(lightness * 255));
return { r: gray, g: gray, b: gray, a: alpha };
}
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const toRgb = (t) => {
let channel = t;
if (channel < 0) channel += 1;
if (channel > 1) channel -= 1;
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
if (channel < 1 / 2) return q;
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
return p;
};
return {
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
g: clampByte(Math.round(toRgb(h) * 255)),
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
a: alpha,
};
}
function clampByte(value) {
return Math.min(255, Math.max(0, value));
}
function ignoreValueMatches(rule, entryValue, findingValue) {
if (entryValue === findingValue) return true;
if (rule !== 'design-system-color') return false;
const entryColor = colorIgnoreKey(entryValue);
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
}
export function normalizeIgnoreValueEntries(entries) {
if (!Array.isArray(entries)) return [];
const out = [];
@@ -217,6 +391,11 @@ export function normalizeIgnoreValueEntries(entries) {
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const normalized = { rule, value };
const files = uniqueStrings([
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
]);
if (files.length > 0) normalized.files = files;
if (typeof entry.reason === 'string' && entry.reason.trim()) {
normalized.reason = entry.reason.trim();
}
@@ -231,14 +410,18 @@ export function normalizeIgnoreValueEntries(entries) {
function mergeIgnoreValues(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(`${entry.rule}\0${entry.value}`, entry);
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(`${entry.rule}\0${entry.value}`, entry);
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
return Array.from(map.values());
}
function ignoreValueFilesKey(files) {
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
}
export function readCache(cwd) {
const raw = safeReadJson(getCachePath(cwd));
if (!raw || typeof raw !== 'object' || raw.version !== 1) {
@@ -447,22 +630,54 @@ function isIgnoredFindingValue(finding, ignoreValues) {
const rule = normalizeIgnoreRule(finding.antipattern);
const value = extractFindingIgnoreValue(finding);
if (!rule || !value) return false;
return ignoreValues.some((entry) => entry.rule === rule && entry.value === value);
return ignoreValues.some((entry) => {
const wildcardValue = entry.value === '*';
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
return findingMatchesScopedIgnoreFile(finding, entry.files);
});
}
function findingMatchesScopedIgnoreFile(finding, globs) {
const filePath = String(finding?.file || '').trim();
if (!filePath) return false;
if (matchesAnyGlob(filePath, globs)) return true;
const normalized = filePath.split(path.sep).join('/');
const parts = normalized.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('/');
if (matchesAnyGlob(suffix, globs)) return true;
}
return false;
}
export function extractFindingIgnoreValue(finding) {
if (!finding || typeof finding !== 'object') return '';
const rule = normalizeIgnoreRule(finding.antipattern);
if (rule !== 'overused-font') return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding));
const directValueRules = new Set([
'overused-font',
'bounce-easing',
'design-system-font',
'design-system-color',
'design-system-radius',
]);
if (!directValueRules.has(rule)) return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
}
function extractFindingIgnoreValueRaw(finding) {
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
if (direct) return direct;
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
for (const text of candidates) {
if (rule === 'bounce-easing') {
const motion = extractMotionIgnoreValue(text);
if (motion) return motion;
continue;
}
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
if (primary) return cleanIgnoreValueDisplay(primary[1]);
@@ -482,6 +697,24 @@ function extractFindingIgnoreValueRaw(finding) {
return '';
}
function extractMotionIgnoreValue(text) {
const tailwind = text.match(/\banimate-bounce\b/i);
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
if (animation) {
const token = animation[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
if (token) return cleanIgnoreValueDisplay(token);
}
return '';
}
function cleanIgnoreValueDisplay(value) {
return String(value || '')
.trim()
@@ -496,7 +729,7 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
const known = new Set(fileEntry.findings || []);
const fresh = [];
for (const f of findings) {
const key = `${f.antipattern}:${f.line || 0}`;
const key = findingCacheKey(f);
if (known.has(key)) continue;
known.add(key);
fresh.push(f);
@@ -507,11 +740,21 @@ export function dedupeAgainstCache(findings, cache, sessionId, filePath) {
export function rememberFindings(cache, sessionId, filePath, findings) {
const fileEntry = ensureFile(cache, sessionId, filePath);
const known = new Set(fileEntry.findings || []);
for (const f of findings) known.add(`${f.antipattern}:${f.line || 0}`);
for (const f of findings) known.add(findingCacheKey(f));
fileEntry.findings = Array.from(known);
ensureSession(cache, sessionId).updatedAt = Date.now();
}
function findingCacheKey(finding) {
const line = finding?.line || 0;
const value = extractFindingIgnoreValue(finding);
if (line > 0 && value) return `${finding.antipattern}:${line}:${value}`;
if (line > 0) return `${finding.antipattern}:${line}`;
if (value) return `${finding.antipattern}:0:${value}`;
const snippet = String(finding?.snippet || '').trim().slice(0, 80);
return snippet ? `${finding.antipattern}:0:${snippet}` : `${finding.antipattern}:0`;
}
export function renderTemplate(findings, filePath, config, opts = {}) {
if (!Array.isArray(findings) || findings.length === 0) return '';
const limits = config?.limits || DEFAULT_CONFIG.limits;
@@ -524,7 +767,7 @@ export function renderTemplate(findings, filePath, config, opts = {}) {
const shown = findings.slice(0, cap);
const remaining = total - shown.length;
const header = `${ENVELOPE_PREFIX} Required design corrections in ${display} (${total} issue(s)):`;
const header = `${ENVELOPE_PREFIX} Design hook findings requiring review in ${display} (${total} issue(s)):`;
const lines = shown.map((f) => formatFindingLine(f));
const more = remaining > 0
? `... and ${remaining} more (see /impeccable audit).`
@@ -556,7 +799,7 @@ function renderGroupedTemplate(groups, config, opts = {}) {
const maxChars = Math.max(500, limits.maxChars || DEFAULT_CONFIG.limits.maxChars);
const cwd = opts.cwd || process.cwd();
const total = realGroups.reduce((sum, group) => sum + group.findings.length, 0);
const header = `${ENVELOPE_PREFIX} Required design corrections across ${realGroups.length} files (${total} issue(s)):`;
const header = `${ENVELOPE_PREFIX} Design hook findings requiring review across ${realGroups.length} files (${total} issue(s)):`;
const lines = [];
let shownCount = 0;
@@ -716,13 +959,114 @@ export function resolveTargetFiles(event, projectCwd) {
export function resolveHarness(env = {}, event = null) {
const explicit = env?.IMPECCABLE_HOOK_HARNESS;
if (explicit === 'cursor') return 'cursor';
if (explicit === 'github') return 'github';
if (explicit === 'claude' || explicit === 'codex') return 'claude';
// GitHub Copilot's postToolUse event uses camelCase `toolName`/`toolArgs` and
// has no `tool_name`/`tool_input`. That shape is the discriminator.
if (event && typeof event === 'object'
&& (typeof event.toolName === 'string' || event.toolArgs !== undefined)
&& event.tool_name === undefined && event.tool_input === undefined) {
return 'github';
}
if (typeof event?.conversation_id === 'string' && event.conversation_id) return 'cursor';
return 'claude';
}
// GitHub Copilot's postToolUse payload is
// { sessionId, timestamp, cwd, toolName, toolArgs, toolResult }
// mapped onto the internal `{ tool_name, tool_input, cwd, session_id }` shape.
// `toolArgs` shape depends on the tool: the `edit`/`create`/`view` tools send a
// JSON *string* (double-encoded) carrying the file under `path`, e.g.
// "{\"path\":\"/abs/app.tsx\",\"old_str\":\"...\",\"new_str\":\"...\"}",
// while `apply_patch` sends a raw OpenAI-format patch string (handled below in
// normalizeGitHubEvent). The detector reads the file from disk after the tool
// ran, so only the path (not the proposed content) is needed here.
export function parseGitHubToolArgs(toolArgs) {
if (toolArgs && typeof toolArgs === 'object' && !Array.isArray(toolArgs)) return toolArgs;
if (typeof toolArgs === 'string' && toolArgs.trim()) {
try {
const parsed = JSON.parse(toolArgs);
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}
return {};
}
// Copilot's `apply_patch` tool (used by interactive sessions and the cloud
// agent) sends a raw OpenAI-format patch string in toolArgs, not JSON:
// *** Begin Patch
// *** Add File: /abs/app.css
// +body { ... }
// *** End Patch
// The `view`/`edit`/`create` tools (seen in `copilot -p` runs) instead send a
// JSON string with the path under `path`. Both must map onto the internal shape.
const APPLY_PATCH_MARKER = /\*\*\* (?:Begin Patch|Add File:|Update File:|Delete File:)/;
function looksLikeApplyPatch(rawArgs) {
if (typeof rawArgs !== 'string' || !APPLY_PATCH_MARKER.test(rawArgs)) return false;
// Guard against an edit/create payload whose edited *content* happens to
// contain patch markers: that payload is a JSON object string, whereas a real
// apply_patch payload is a raw patch string that does not parse as JSON. Only
// treat non-JSON-object strings as apply_patch so edit events still get their
// `path` extracted.
try {
const parsed = JSON.parse(rawArgs);
if (parsed && typeof parsed === 'object') return false;
} catch { /* not JSON → genuine raw patch */ }
return true;
}
function applyPatchText(rawArgs) {
if (typeof rawArgs === 'string') {
if (APPLY_PATCH_MARKER.test(rawArgs)) return rawArgs;
// Defensive: a future Copilot build might JSON-wrap the patch.
const parsed = parseGitHubToolArgs(rawArgs);
return parsed.patch || parsed.input || parsed.command || '';
}
if (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)) {
return rawArgs.patch || rawArgs.input || rawArgs.command || '';
}
return '';
}
function normalizeGitHubEvent(event, projectCwd) {
const cwd = event.cwd || envProjectDir(projectCwd) || projectCwd;
const sessionId = event.sessionId || event.session_id || 'unknown';
const toolName = event.toolName || event.tool_name || null;
const toolInput = event.tool_input && typeof event.tool_input === 'object' ? { ...event.tool_input } : {};
const rawArgs = event.toolArgs;
let normalizedToolName = toolName;
if (toolName === 'apply_patch' || looksLikeApplyPatch(rawArgs)) {
// resolveTargetFiles() reads the touched paths from tool_input.command when
// tool_name is 'apply_patch', so normalize the name even if a future build
// sends the patch under a different tool label.
const patch = applyPatchText(rawArgs);
if (patch) {
toolInput.command = patch;
normalizedToolName = 'apply_patch';
}
} else {
const args = parseGitHubToolArgs(rawArgs);
const filePath = args.path || args.file_path || args.filePath || args.target_file;
if (typeof filePath === 'string' && filePath) toolInput.file_path = filePath;
}
return {
...event,
cwd,
session_id: sessionId,
tool_name: normalizedToolName,
tool_input: toolInput,
};
}
export function normalizeHookEvent(event, projectCwd, harness = 'claude') {
if (!event || typeof event !== 'object' || harness !== 'cursor') return event;
if (!event || typeof event !== 'object') return event;
if (harness === 'github') return normalizeGitHubEvent(event, projectCwd);
if (harness !== 'cursor') return event;
const cwd = event.cwd
|| (Array.isArray(event.workspace_roots) && event.workspace_roots[0])
@@ -918,7 +1262,11 @@ export async function loadDetector(candidates = DETECTOR_CANDIDATES) {
const found = candidates.find((c) => fs.existsSync(c));
if (!found) return null;
const mod = await import(pathToFileURL(found));
detectorCache = { detectText: mod.detectText, detectHtml: mod.detectHtml };
detectorCache = {
detectText: mod.detectText,
detectHtml: mod.detectHtml,
loadDesignSystemForCwd: mod.loadDesignSystemForCwd,
};
return detectorCache;
}
@@ -953,12 +1301,12 @@ export function setDetectorForTesting(impl) {
// session" so the model knows it's a re-mind, not a new finding.
// ────────────────────────────────────────────────────────────────────────
const STEER_LINE = 'Keep typography hierarchy, spacing rhythm, and color contrast intentional on the next change.';
const STEER_LINE = 'That does not mean the design is good: keep following the project design system and the impeccable skill guidance.';
export function renderCleanAck(filePath, opts = {}) {
const cwd = opts.cwd || process.cwd();
const display = relativize(filePath, cwd);
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No anti-patterns. ${STEER_LINE}`;
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. No deterministic design-quality issues found. ${STEER_LINE}`;
}
export function renderPendingAck(filePath, knownFindings, opts = {}) {
@@ -968,37 +1316,53 @@ export function renderPendingAck(filePath, knownFindings, opts = {}) {
// `knownFindings` here are the cache strings like "side-tab:3".
const sample = knownFindings.slice(0, 3).join(', ');
const more = count > 3 ? `, +${count - 3} more` : '';
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} issue(s) flagged earlier this session (${sample}${more}). Address them before finalizing — the previous reminder still applies.`;
return `${ENVELOPE_PREFIX} Design hook scanned ${display}. Still has ${count} finding(s) flagged earlier this session (${sample}${more}). Handle them before finalizing — the previous reminder still applies.`;
}
export function shouldEmitAckForFile(filePath) {
return ACK_EXTS.has(path.extname(String(filePath || '')).toLowerCase());
}
export function designSystemOptions(config, detector, projectCwd) {
if (config?.designSystem?.enabled === false) return {};
if (!detector || typeof detector.loadDesignSystemForCwd !== 'function') return {};
try {
const designSystem = detector.loadDesignSystemForCwd(projectCwd);
return designSystem ? { designSystem } : {};
} catch {
return {};
}
}
export function appendDesignSystemNote(text, scanOptions) {
if (!text || !scanOptions?.designSystem?.mdNewerThanJson) return text;
return `${text}\n\n${ENVELOPE_PREFIX} DESIGN.md is newer than .impeccable/design.json. Run /impeccable document to refresh the design-system sidecar.`;
}
// The directive footer is the part of the hook output that steers model
// behavior. Three intentional moves:
// 1. **Imperative, not advisory.** "Fix these..." beats "Consider
// 1. **Imperative, not advisory.** "Handle these..." beats "Consider
// revising..." which the model treats as a soft suggestion it can
// override when the user asked for any kind of throwaway / demo UI.
// 2. **Explicit exception clause.** Without it, the model will try to
// "fix" intentional bad fixtures, anti-pattern examples in docs, or
// test cases. Naming the exception inline beats hoping the model
// infers it from context.
// 2. **Explicit judgment clause.** Without it, the model will try to
// "fix" intentional motion, bad fixtures, anti-pattern examples in
// docs, or test cases. Naming the judgment inline beats hoping the
// model infers it from context.
// 3. **Acknowledgement instruction.** Hook output is injected as
// developer-role context, not a chat turn, so the user never sees the
// raw envelope. Asking the model to surface the fix in its reply is
// the cheapest way to make the feedback loop visible to the user.
// raw envelope. Asking the model to surface the resolution in its
// reply is the cheapest way to make the feedback loop visible.
function directiveFooter(display, opts = {}) {
const ignoreFileCommand = `/impeccable hooks ignore-file ${quoteCommandArg(display)}`;
const fileIgnoreGuidance = opts.grouped
? 'run `/impeccable hooks ignore-file <path>` for the specific file'
: `run \`${ignoreFileCommand}\``;
return [
'Fix these in your next reply before finalizing. Acknowledge what you changed so the user sees the correction.',
'Handle these before finalizing: fix findings that are real design problems, or explicitly classify contextually intentional findings as false positives. Acknowledge what you changed or why you are leaving a finding unchanged.',
'',
'Skip the fix only if the user explicitly asked for an intentionally bad UI, an anti-pattern example, a test fixture, or documentation of bad design. In that case, say so and continue.',
'Use context judgment before editing. A finding is not automatically a defect; literal or domain-appropriate motion, intentional demos or fixtures, documentation of bad design, and user-confirmed choices can be valid as-is.',
'',
`Do not add source comments such as \`impeccable: ignore\`; those pollute the code and do not suppress hook findings. Do not add hook ignores unless the user explicitly confirms the finding is intentional. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
`Do not change intentional design just to satisfy the hook, and do not silence a real finding with an inline ignore comment to skip fixing it. Suppress a finding only after the user explicitly confirms it is intentional. Prefer a config ignore (one reviewable place, the commands below); reach for an inline \`impeccable-disable <rule>\` comment only when the waiver must travel with a file that leaves the repo, such as an exported or standalone document. Prefer the narrowest persisted exception: run the exact \`/impeccable hooks ignore-value ... --shared\` command shown next to a value-specific finding. For \`overused-font\`, use \`ignore-value\` for a specific font and use \`/impeccable hooks ignore-rule overused-font --all-values\` only when the user asks to ignore overused fonts generally. For file-specific findings without an ignore-value command, ${fileIgnoreGuidance}; use \`/impeccable hooks ignore-rule <id>\` only when the user asks to suppress the whole non-value-specific rule. Run /impeccable audit for the full pass.`,
].join('\n');
}
@@ -1062,6 +1426,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
persistCache(projectCwd, cache);
return result({ skipped: 'detector-missing', durationMs: Date.now() - started });
}
const scanOptions = designSystemOptions(config, det, projectCwd);
let pendingWinner = null;
let cleanWinner = null;
@@ -1119,9 +1484,9 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
let findings;
let detectorThrew = false;
if ((ext === '.html' || ext === '.htm') && typeof det.detectHtml === 'function') {
try { findings = await det.detectHtml(filePath); } catch { findings = []; detectorThrew = true; }
try { findings = await det.detectHtml(filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
} else {
try { findings = await det.detectText(content, filePath); } catch { findings = []; detectorThrew = true; }
try { findings = await det.detectText(content, filePath, scanOptions); } catch { findings = []; detectorThrew = true; }
}
const filtered = filterFindings(findings || [], content, ext, config);
@@ -1152,7 +1517,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
if (freshGroups.length > 0) {
const firstGroup = freshGroups[0];
const text = renderGroupedTemplate(freshGroups, config, { cwd: projectCwd });
const text = appendDesignSystemNote(renderGroupedTemplate(freshGroups, config, { cwd: projectCwd }), scanOptions);
const allFindings = freshGroups.flatMap((group) => group.findings);
return {
exitCode: 0,
@@ -1184,7 +1549,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
}
if (pendingWinner && shouldEmitAckForFile(pendingWinner.filePath)) {
const text = renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd });
const text = appendDesignSystemNote(renderPendingAck(pendingWinner.filePath, pendingWinner.known, { cwd: projectCwd }), scanOptions);
return {
exitCode: 0,
stdout: payload(text, 'PostToolUse', harness),
@@ -1218,7 +1583,7 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
}
if (cleanWinner && shouldEmitAckForFile(cleanWinner.filePath)) {
const text = renderCleanAck(cleanWinner.filePath, { cwd: projectCwd });
const text = appendDesignSystemNote(renderCleanAck(cleanWinner.filePath, { cwd: projectCwd }), scanOptions);
return {
exitCode: 0,
stdout: payload(text, 'PostToolUse', harness),
@@ -1256,6 +1621,11 @@ export function payload(text, eventName = 'PostToolUse', harness = 'claude') {
if (harness === 'cursor') {
return JSON.stringify({ additional_context: text });
}
// GitHub Copilot's postToolUse hook injects context via a top-level
// `additionalContext` string (alongside an optional `modifiedResult`).
if (harness === 'github') {
return JSON.stringify({ additionalContext: text });
}
return JSON.stringify({
hookSpecificOutput: { hookEventName: eventName, additionalContext: text },
});
@@ -62,7 +62,7 @@ function parseYamlSubset(yaml) {
stack.pop();
}
const key = content.slice(0, colonIdx).trim();
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
const parent = stack[stack.length - 1].obj;
@@ -93,6 +93,13 @@ function findTopLevelColon(s) {
return -1;
}
function unquoteYamlKey(key) {
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
return key.slice(1, -1);
}
return key;
}
function stripInlineYamlComment(s) {
let inQuote = null;
for (let i = 0; i < s.length; i++) {
@@ -0,0 +1,638 @@
/**
* CLI-side reader/writer for the unified `.impeccable` config.
*
* The CLI (published to npm) and the skill scripts (bundled into the install)
* live in separate trees and cannot share runtime code, so this duplicates a
* small slice of skill/scripts/hook-lib.mjs the config-path layout, detector
* ignore semantics, and the `.git/info/exclude` handling. Keep the schema,
* ignore filtering, and exclude marker in sync if either side changes.
*
* Schema (config.json shared / config.local.json gitignored, per-developer):
* {
* "detector": { "ignoreRules": [], "ignoreFiles": [], "ignoreValues": [], "designSystem": { "enabled": true } },
* "hook": { "consent": "accepted" | "declined", ... },
* "updateCheck": bool
* }
*/
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
import { join, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
export function getConfigPath(root) {
return join(root, '.impeccable', 'config.json');
}
export function getLocalConfigPath(root) {
return join(root, '.impeccable', 'config.local.json');
}
function safeReadJson(filePath) {
try {
const raw = JSON.parse(readFileSync(filePath, 'utf-8'));
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
} catch {
return null;
}
}
function hookSection(raw) {
return raw && raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
}
function detectorSection(raw) {
return raw && raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
}
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
const DEFAULT_DETECTION_CONFIG = Object.freeze({
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { enabled: true },
});
function cloneDetectionConfig() {
return {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
designSystem: { ...DEFAULT_DETECTION_CONFIG.designSystem },
};
}
function cloneRawDetectionConfig() {
return {
ignoreRules: [],
ignoreFiles: [],
ignoreValues: [],
};
}
function applyDetectionConfigSource(config, raw) {
if (!raw || typeof raw !== 'object') return config;
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
config.designSystem = {
...config.designSystem,
enabled: raw.designSystem.enabled === false ? false : true,
};
}
if (Array.isArray(raw.ignoreRules)) {
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
}
if (Array.isArray(raw.ignoreFiles)) {
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
}
if (Array.isArray(raw.ignoreValues)) {
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
}
return config;
}
function uniqueStrings(values) {
return Array.from(new Set(values.map(String)));
}
/**
* Detector filters shared by `npx impeccable detect` and the design hook.
* `hook.enabled` remains hook lifecycle state; manual CLI scans still run when
* the hook is disabled, but they honor the same ignore rules and design-system
* toggle.
*/
export function readDetectionConfig(root) {
const config = cloneDetectionConfig();
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
const raw = safeReadJson(filePath);
// Back-compat: old builds stored detector filters under hook.*.
applyDetectionConfigSource(config, hookSection(raw));
applyDetectionConfigSource(config, detectorSection(raw));
}
return config;
}
export function readRawDetectionConfig(root, opts = {}) {
const raw = safeReadJson(opts.local ? getLocalConfigPath(root) : getConfigPath(root));
const config = cloneRawDetectionConfig();
applyDetectionConfigSource(config, hookSection(raw));
applyDetectionConfigSource(config, detectorSection(raw));
return config;
}
export function writeDetectionConfig(root, detectorConfig, opts = {}) {
const filePath = opts.local ? getLocalConfigPath(root) : getConfigPath(root);
if (opts.local) ensureConfigGitExclude(root);
const existing = safeReadJson(filePath) || {};
const existingHook = hookSection(existing);
const nextHook = stripDetectorKeys(existingHook);
const nextDetector = {
...(detectorSection(existing) || {}),
...normalizeDetectionConfigForWrite(detectorConfig),
};
const next = {
...existing,
detector: nextDetector,
};
if (nextHook && Object.keys(nextHook).length > 0) {
next.hook = nextHook;
} else {
delete next.hook;
}
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
return filePath;
}
function normalizeDetectionConfigForWrite(config) {
const out = {};
if (Array.isArray(config?.ignoreRules)) {
out.ignoreRules = uniqueStrings(config.ignoreRules.map((rule) => normalizeIgnoreRule(rule)).filter(Boolean));
}
if (Array.isArray(config?.ignoreFiles)) {
out.ignoreFiles = uniqueStrings(config.ignoreFiles.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()));
}
out.ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
if (config?.designSystem && typeof config.designSystem === 'object' && !Array.isArray(config.designSystem)) {
out.designSystem = {
enabled: config.designSystem.enabled === false ? false : true,
};
}
return out;
}
function stripDetectorKeys(raw) {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const out = {};
for (const [key, value] of Object.entries(raw)) {
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
}
return out;
}
export function normalizeIgnoreValue(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function normalizeIgnoreRule(rule) {
return String(rule || '').trim().toLowerCase();
}
function colorIgnoreKey(value) {
const color = parseIgnoreColor(value);
if (!color) return '';
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
}
function parseIgnoreColor(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return null;
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
if (hex) return parseHexIgnoreColor(hex[1]);
const rgb = text.match(/^rgba?\((.*)\)$/i);
if (rgb) {
const parts = splitColorArgs(rgb[1]);
if (parts.length < 3 || parts.length > 4) return null;
const r = parseRgbChannel(parts[0]);
const g = parseRgbChannel(parts[1]);
const b = parseRgbChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([r, g, b, a].some((v) => v === null)) return null;
return { r, g, b, a };
}
const hsl = text.match(/^hsla?\((.*)\)$/i);
if (hsl) {
const parts = splitColorArgs(hsl[1]);
if (parts.length < 3 || parts.length > 4) return null;
const h = parseHueChannel(parts[0]);
const s = parsePercentChannel(parts[1]);
const l = parsePercentChannel(parts[2]);
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
if ([h, s, l, a].some((v) => v === null)) return null;
return hslToRgb(h, s, l, a);
}
return null;
}
function parseHexIgnoreColor(hex) {
if (hex.length === 3 || hex.length === 4) {
const r = parseInt(hex[0] + hex[0], 16);
const g = parseInt(hex[1] + hex[1], 16);
const b = parseInt(hex[2] + hex[2], 16);
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
return { r, g, b, a };
}
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
return { r, g, b, a };
}
function splitColorArgs(body) {
const text = String(body || '').trim();
if (!text) return [];
if (text.includes(',')) {
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
const last = parts[parts.length - 1];
if (last && last.includes('/')) {
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
return [...parts.slice(0, -1), ...split];
}
return parts;
}
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
}
function parseRgbChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const scaled = match[2] ? value * 2.55 : value;
if (scaled < 0 || scaled > 255) return null;
return Math.round(scaled);
}
function parseAlphaChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const alpha = match[2] ? value / 100 : value;
return alpha >= 0 && alpha <= 1 ? alpha : null;
}
function parseHueChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
const unit = match[2] || 'deg';
if (unit === 'turn') return value * 360;
if (unit === 'rad') return value * (180 / Math.PI);
if (unit === 'grad') return value * 0.9;
return value;
}
function parsePercentChannel(raw) {
const text = String(raw || '').trim();
const match = text.match(/^(-?\d*\.?\d+)%$/);
if (!match) return null;
const value = Number.parseFloat(match[1]);
if (!Number.isFinite(value)) return null;
return value >= 0 && value <= 100 ? value / 100 : null;
}
function hslToRgb(hue, saturation, lightness, alpha) {
const h = (((hue % 360) + 360) % 360) / 360;
if (saturation === 0) {
const gray = clampByte(Math.round(lightness * 255));
return { r: gray, g: gray, b: gray, a: alpha };
}
const q = lightness < 0.5
? lightness * (1 + saturation)
: lightness + saturation - lightness * saturation;
const p = 2 * lightness - q;
const toRgb = (t) => {
let channel = t;
if (channel < 0) channel += 1;
if (channel > 1) channel -= 1;
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
if (channel < 1 / 2) return q;
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
return p;
};
return {
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
g: clampByte(Math.round(toRgb(h) * 255)),
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
a: alpha,
};
}
function clampByte(value) {
return Math.min(255, Math.max(0, value));
}
function ignoreValueMatches(rule, entryValue, findingValue) {
if (entryValue === findingValue) return true;
if (rule !== 'design-system-color') return false;
const entryColor = colorIgnoreKey(entryValue);
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
}
export function normalizeIgnoreValueEntries(entries) {
if (!Array.isArray(entries)) return [];
const out = [];
for (const entry of entries) {
if (!entry || typeof entry !== 'object') continue;
const rule = normalizeIgnoreRule(entry.rule);
const value = normalizeIgnoreValue(entry.value);
if (!rule || !value) continue;
const normalized = { rule, value };
const files = uniqueStrings([
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
]);
if (files.length > 0) normalized.files = files;
if (typeof entry.reason === 'string' && entry.reason.trim()) {
normalized.reason = entry.reason.trim();
}
if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
normalized.createdAt = entry.createdAt.trim();
}
out.push(normalized);
}
return out;
}
function mergeIgnoreValues(existing, incoming) {
const map = new Map();
for (const entry of normalizeIgnoreValueEntries(existing)) {
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
for (const entry of normalizeIgnoreValueEntries(incoming)) {
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
}
return Array.from(map.values());
}
function ignoreValueFilesKey(files) {
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
}
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
function globToRegex(glob) {
let re = '^';
let i = 0;
while (i < glob.length) {
const c = glob[i];
if (c === '*') {
if (glob[i + 1] === '*') {
re += '.*';
i += 2;
if (glob[i] === '/') i += 1;
} else {
re += '[^/]*';
i += 1;
}
} else if (c === '?') {
re += '[^/]';
i += 1;
} else if (c === '{') {
const end = glob.indexOf('}', i);
if (end === -1) { re += '\\{'; i += 1; continue; }
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
re += `(?:${parts.join('|')})`;
i = end + 1;
} else if (/[.+^$()|[\]\\]/.test(c)) {
re += `\\${c}`;
i += 1;
} else {
re += c;
i += 1;
}
}
re += '$';
return new RegExp(re);
}
export function matchesAnyGlob(filePath, globs) {
if (!Array.isArray(globs) || globs.length === 0) return false;
const normalized = String(filePath || '').split(sep).join('/');
for (const glob of globs) {
try {
const re = globToRegex(String(glob));
if (re.test(normalized)) return true;
const base = normalized.split('/').pop();
if (re.test(base)) return true;
} catch {
/* malformed glob, skip */
}
}
return false;
}
export function shouldIgnoreDetectionFile(filePath, root, config) {
const globs = config?.ignoreFiles || [];
if (!Array.isArray(globs) || globs.length === 0) return false;
const raw = String(filePath || '').trim();
if (!raw) return false;
if (matchesAnyGlob(raw, globs)) return true;
try {
const abs = isAbsolute(raw) ? raw : resolve(root, raw);
if (matchesAnyGlob(abs, globs)) return true;
const rel = relative(root, abs);
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
return matchesAnyGlob(rel, globs);
}
} catch {
/* ignore */
}
return false;
}
export function filterDetectionFindings(findings, config) {
if (!Array.isArray(findings) || findings.length === 0) return [];
const ignoreRules = new Set((config?.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
const ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
return findings.filter((finding) => {
if (!finding || typeof finding !== 'object') return false;
if (ignoreRules.has(normalizeIgnoreRule(finding.antipattern))) return false;
if (isIgnoredFindingValue(finding, ignoreValues)) return false;
return true;
});
}
function isIgnoredFindingValue(finding, ignoreValues) {
if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
const rule = normalizeIgnoreRule(finding.antipattern);
const value = extractFindingIgnoreValue(finding);
if (!rule || !value) return false;
return ignoreValues.some((entry) => {
const wildcardValue = entry.value === '*';
if (entry.rule !== rule || (!wildcardValue && !ignoreValueMatches(rule, entry.value, value))) return false;
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
return findingMatchesScopedIgnoreFile(finding, entry.files);
});
}
function findingMatchesScopedIgnoreFile(finding, globs) {
const filePath = String(finding?.file || '').trim();
if (!filePath) return false;
if (matchesAnyGlob(filePath, globs)) return true;
const normalized = filePath.split(sep).join('/');
const parts = normalized.split('/').filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const suffix = parts.slice(i).join('/');
if (matchesAnyGlob(suffix, globs)) return true;
}
return false;
}
export function extractFindingIgnoreValue(finding) {
if (!finding || typeof finding !== 'object') return '';
const rule = normalizeIgnoreRule(finding.antipattern);
const directValueRules = new Set([
'overused-font',
'bounce-easing',
'design-system-font',
'design-system-color',
'design-system-radius',
]);
if (!directValueRules.has(rule)) return '';
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
}
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
if (direct) return direct;
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
for (const text of candidates) {
if (rule === 'bounce-easing') {
const motion = extractMotionIgnoreValue(text);
if (motion) return motion;
continue;
}
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
if (primary) return cleanIgnoreValueDisplay(primary[1]);
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
if (family) return cleanIgnoreValueDisplay(family[1]);
const google = text.match(/[?&]family=([^&:;\n]+)/i);
if (google) {
try {
return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
} catch {
return cleanIgnoreValueDisplay(google[1]);
}
}
}
return '';
}
function extractMotionIgnoreValue(text) {
const tailwind = text.match(/\banimate-bounce\b/i);
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
if (animation) {
const token = animation[1]
.split(/[,\s]+/)
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
if (token) return cleanIgnoreValueDisplay(token);
}
return '';
}
function cleanIgnoreValueDisplay(value) {
return String(value || '')
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\+/g, ' ')
.replace(/\s+/g, ' ');
}
/**
* The recorded design-hook decision: 'accepted' | 'declined' | undefined.
* config.local.json (per-developer) overrides config.json.
*/
export function getHookConsent(root) {
let consent;
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
const hook = hookSection(safeReadJson(filePath));
if (hook && (hook.consent === 'accepted' || hook.consent === 'declined')) consent = hook.consent;
}
return consent;
}
/**
* Persist the per-developer decision to config.local.json, preserving any
* sibling keys, and ensure the file is gitignored.
*/
export function setHookConsent(root, value) {
const filePath = getLocalConfigPath(root);
const existing = safeReadJson(filePath) || {};
const hook = hookSection(existing) || {};
const next = { ...existing, hook: { ...hook, consent: value } };
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
ensureConfigGitExclude(root);
return filePath;
}
const EXCLUDE_OPEN = '# impeccable-config-ignore-start';
const EXCLUDE_CLOSE = '# impeccable-config-ignore-end';
const EXCLUDE_PATTERNS = ['.impeccable/config.local.json'];
/**
* Add config.local.json to `.git/info/exclude` so a developer's decision is
* never committed. Idempotent via marker comments. Best-effort; returns false
* when there is no resolvable git dir.
*/
export function ensureConfigGitExclude(root) {
try {
const gitDir = resolveGitDir(root);
if (!gitDir) return false;
const target = join(gitDir, 'info', 'exclude');
const existing = existsSync(target) ? readFileSync(target, 'utf-8') : '';
const block = [EXCLUDE_OPEN, ...EXCLUDE_PATTERNS, EXCLUDE_CLOSE].join('\n');
const markerRe = new RegExp(`${escapeRegExp(EXCLUDE_OPEN)}[\\s\\S]*?${escapeRegExp(EXCLUDE_CLOSE)}`);
let updated;
if (markerRe.test(existing)) {
updated = existing.replace(markerRe, block);
} else {
const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
updated = `${prefix}${block}\n`;
}
if (updated !== existing) {
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, updated);
}
return true;
} catch {
return false;
}
}
function resolveGitDir(root) {
const dotGit = join(root, '.git');
if (!existsSync(dotGit)) return null;
try {
if (statSync(dotGit).isDirectory()) return dotGit;
// A `.git` file (worktree/submodule) points elsewhere: "gitdir: <path>".
const match = readFileSync(dotGit, 'utf-8').match(/gitdir:\s*(.+)/);
if (match) {
const resolved = match[1].trim();
return isAbsolute(resolved) ? resolved : join(root, resolved);
}
} catch {
/* fall through */
}
return null;
}
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
@@ -1,50 +1,52 @@
import fs from 'node:fs';
import path from 'node:path';
import { resolveProjectRoot } from '../context.mjs';
export const IMPECCABLE_DIR = '.impeccable';
export const LIVE_DIR = 'live';
export const CRITIQUE_DIR = 'critique';
export function getImpeccableDir(cwd = process.cwd()) {
return path.join(cwd, IMPECCABLE_DIR);
export function getImpeccableDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), IMPECCABLE_DIR);
}
export function getDesignSidecarPath(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), 'design.json');
export function getDesignSidecarPath(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), 'design.json');
}
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd) {
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd, options = {}) {
const projectRoot = resolveProjectRoot(cwd, options);
const candidates = [
getDesignSidecarPath(cwd),
path.join(cwd, 'DESIGN.json'),
getDesignSidecarPath(cwd, options),
path.join(projectRoot, 'DESIGN.json'),
];
const contextLegacy = path.join(contextDir, 'DESIGN.json');
if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
return candidates;
}
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd) {
return firstExisting(getDesignSidecarCandidates(cwd, contextDir));
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd, options = {}) {
return firstExisting(getDesignSidecarCandidates(cwd, contextDir, options));
}
export function getLiveDir(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), LIVE_DIR);
export function getLiveDir(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), LIVE_DIR);
}
export function getLiveConfigPath(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'config.json');
export function getLiveConfigPath(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'config.json');
}
export function getLegacyLiveConfigPath(scriptsDir) {
return path.join(scriptsDir, 'config.json');
}
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env } = {}) {
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env, targetPath } = {}) {
if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
}
const primary = getLiveConfigPath(cwd);
const primary = getLiveConfigPath(cwd, { targetPath });
if (fs.existsSync(primary)) return primary;
if (scriptsDir) {
const legacy = getLegacyLiveConfigPath(scriptsDir);
@@ -53,16 +55,16 @@ export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = p
return primary;
}
export function getLiveServerPath(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'server.json');
export function getLiveServerPath(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'server.json');
}
export function getLegacyLiveServerPath(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live.json');
export function getLegacyLiveServerPath(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live.json');
}
export function readLiveServerInfo(cwd = process.cwd()) {
for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
export function readLiveServerInfo(cwd = process.cwd(), options = {}) {
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
try {
const info = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
if (info && typeof info.pid === 'number' && !isLiveServerPidReachable(info.pid)) {
@@ -88,37 +90,37 @@ export function isLiveServerPidReachable(pid) {
}
}
export function writeLiveServerInfo(cwd = process.cwd(), info) {
const filePath = getLiveServerPath(cwd);
export function writeLiveServerInfo(cwd = process.cwd(), info, options = {}) {
const filePath = getLiveServerPath(cwd, options);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(info));
return filePath;
}
export function removeLiveServerInfo(cwd = process.cwd()) {
for (const filePath of [getLiveServerPath(cwd), getLegacyLiveServerPath(cwd)]) {
export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
try { fs.unlinkSync(filePath); } catch {}
}
}
export function getLiveSessionsDir(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'sessions');
export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'sessions');
}
export function getLegacyLiveSessionsDir(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live', 'sessions');
export function getLegacyLiveSessionsDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'sessions');
}
export function getLiveAnnotationsDir(cwd = process.cwd()) {
return path.join(getLiveDir(cwd), 'annotations');
export function getLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
return path.join(getLiveDir(cwd, options), 'annotations');
}
export function getCritiqueDir(cwd = process.cwd()) {
return path.join(getImpeccableDir(cwd), CRITIQUE_DIR);
export function getCritiqueDir(cwd = process.cwd(), options = {}) {
return path.join(getImpeccableDir(cwd, options), CRITIQUE_DIR);
}
export function getLegacyLiveAnnotationsDir(cwd = process.cwd()) {
return path.join(cwd, '.impeccable-live', 'annotations');
export function getLegacyLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'annotations');
}
function firstExisting(paths) {
@@ -0,0 +1,42 @@
class TargetArgError extends Error {
constructor(message, code) {
super(message);
this.name = 'TargetArgError';
this.code = code;
}
}
export function parseTargetPath(args = [], { strict = false } = {}) {
let targetPath = null;
for (let i = 0; i < args.length; i++) {
const arg = String(args[i]);
if (arg === '--target' || arg === '-t') {
const next = args[i + 1];
if (next && !String(next).startsWith('-')) {
targetPath = String(next);
i++;
continue;
}
if (strict) {
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
}
continue;
}
if (arg.startsWith('--target=')) {
const value = arg.slice('--target='.length);
if (value) {
targetPath = value;
continue;
}
if (strict) {
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
}
}
}
return targetPath;
}
export function parseTargetOptions(args = [], options = {}) {
const targetPath = parseTargetPath(args, options);
return targetPath ? { targetPath } : {};
}
+175 -83
View File
@@ -57,7 +57,7 @@
const Z = { highlight: 100001, bar: 100005, picker: 100007, toast: 100010 };
const EASE = 'cubic-bezier(0.22, 1, 0.36, 1)'; // ease-out-quint
const PREFIX = 'impeccable-live';
const PICK_CURSOR_CLASS = PREFIX + '-pick-cursor';
const PICK_CURSOR_STYLE_ID = PREFIX + '-pick-cursor-style';
const MANUAL_APPLY_STATE_TTL_MS = 15 * 60 * 1000;
const sessionState = window.__IMPECCABLE_LIVE_SESSION__?.createLiveBrowserSessionState({
prefix: PREFIX,
@@ -152,6 +152,7 @@
let scrollLockTargetY = null;
let scrollLockRaf = null;
let scrollLockAbort = null;
const SCROLL_ANCHOR_LOCK_ID = 'impeccable-scroll-anchor-lock';
// Dedicated key for scroll position - SEPARATE from LS_KEY so that
// saveSession's state updates don't clobber a carefully-captured scrollY.
@@ -1915,45 +1916,45 @@
syncPageInteractionCursor();
}
let pageInteractionCursorActive = false;
function ensurePickCursorStyle() {
if (document.getElementById(PREFIX + '-pick-cursor-style')) return;
const style = document.createElement('style');
style.id = PREFIX + '-pick-cursor-style';
/**
* Drive the page-level pick / insert cursor through the textContent of one
* injected <style>, never by mutating <html> (className or inline style).
* Frameworks that server-render the <html>/<body> roots (Next.js App Router)
* report a React 19 hydration mismatch when the client adds an attribute the
* server HTML never emitted, so a `class`/inline `style` toggled on
* `document.documentElement` trips "a tree hydrated but some attributes ...
* didn't match" on the next Fast-Refresh re-render. Keying the cursor off a
* stable-id <style> keeps the effect off the hydrated host elements (same
* shape as the scroll-anchor lock). A falsy cursor clears the rule.
*/
function setPageInteractionCursor(cursor) {
let style = document.getElementById(PICK_CURSOR_STYLE_ID);
if (!cursor) {
if (style) style.textContent = '';
return;
}
if (!style) {
style = document.createElement('style');
style.id = PICK_CURSOR_STYLE_ID;
// Styles the host page, not the chrome - inside the adapter's shadow UI
// root (uiAppendStyle's target) these selectors would match nothing.
(document.head || document.documentElement).appendChild(style);
}
style.textContent =
'html.' + PICK_CURSOR_CLASS + ' * { cursor: crosshair !important; }\n'
+ 'html.' + PICK_CURSOR_CLASS + ' [id^="' + PREFIX + '"],\n'
+ 'html.' + PICK_CURSOR_CLASS + ' [id^="' + PREFIX + '"] * { cursor: revert !important; }';
// Styles the host page, not the chrome - inside the adapter's shadow UI
// root (uiAppendStyle's target) these selectors would match nothing.
document.head.appendChild(style);
'* { cursor: ' + cursor + ' !important; }\n'
+ '[id^="' + PREFIX + '"],\n'
+ '[id^="' + PREFIX + '"] * { cursor: revert !important; }';
}
/** Page-level cursor while pick or insert mode is targeting page elements. */
function syncPageInteractionCursor() {
const pickCursor = state === 'PICKING' && pickActive && !insertActive;
let axisCursor = '';
if (state === 'PICKING' && insertActive) {
axisCursor = insertHoverAnchor ? cursorForInsertAxis(insertHoverAxis || 'column') : '';
}
if (pickCursor) {
ensurePickCursorStyle();
document.documentElement.classList.add(PICK_CURSOR_CLASS);
document.documentElement.style.cursor = '';
pageInteractionCursorActive = true;
return;
}
document.documentElement.classList.remove(PICK_CURSOR_CLASS);
if (axisCursor) {
document.documentElement.style.cursor = axisCursor;
pageInteractionCursorActive = true;
} else if (pageInteractionCursorActive) {
document.documentElement.style.cursor = '';
pageInteractionCursorActive = false;
let cursor = '';
if (state === 'PICKING' && pickActive && !insertActive) {
cursor = 'crosshair';
} else if (state === 'PICKING' && insertActive && insertHoverAnchor) {
cursor = cursorForInsertAxis(insertHoverAxis || 'column');
}
setPageInteractionCursor(cursor);
}
/**
@@ -2681,12 +2682,12 @@
});
const check = el('span', {
fontSize: '15px', lineHeight: '1', flexShrink: '0',
color: 'oklch(45% 0.15 145)',
color: 'oklch(45% 0.18 145)',
});
check.textContent = '\u2713';
row.appendChild(check);
const label = el('span', {
fontSize: '12px', color: 'oklch(35% 0.1 145)', fontWeight: '600',
fontSize: '12px', color: 'oklch(49% 0.08 188)', fontWeight: '600',
});
label.textContent = 'Variant applied';
row.appendChild(label);
@@ -5815,10 +5816,22 @@
try { history.scrollRestoration = 'manual'; } catch {}
const prevHtmlAnchor = document.documentElement.style.overflowAnchor;
const prevBodyAnchor = document.body.style.overflowAnchor;
document.documentElement.style.overflowAnchor = 'none';
document.body.style.overflowAnchor = 'none';
// Suppress the browser's scroll-anchoring on the scroll root so it can't
// fight our manual scroll correction. Apply this as a stylesheet rule, not
// as inline `style` on <html>/<body>: those elements are server-rendered by
// frameworks like Next.js App Router, and mutating their inline style makes
// React 19 report a hydration mismatch on the next Fast-Refresh re-render.
// A <style> rule has the same computed effect without touching any hydrated
// element's attributes. Like the inline version, it is recreated on every
// startScrollLock call, so reload survival (driven by the persisted scroll
// key) is unaffected.
let anchorLockStyle = document.getElementById(SCROLL_ANCHOR_LOCK_ID);
if (!anchorLockStyle) {
anchorLockStyle = document.createElement('style');
anchorLockStyle.id = SCROLL_ANCHOR_LOCK_ID;
anchorLockStyle.textContent = 'html,body{overflow-anchor:none !important;}';
(document.head || document.documentElement).appendChild(anchorLockStyle);
}
const correct = (why) => {
scrollLockRaf = null;
@@ -5853,8 +5866,7 @@
scrollLockAbort = new AbortController();
scrollLockAbort.signal.addEventListener('abort', () => {
document.documentElement.style.overflowAnchor = prevHtmlAnchor;
document.body.style.overflowAnchor = prevBodyAnchor;
document.getElementById(SCROLL_ANCHOR_LOCK_ID)?.remove();
}, { once: true });
const sig = { signal: scrollLockAbort.signal };
// Track whether the most recent scroll came from a user gesture. We
@@ -6489,10 +6501,13 @@
) {
return;
}
if (isPageEditableElement(deepActive) && !isInlineEditActive(deepActive)) {
return;
}
// While a contenteditable text-leaf is focused, let the browser handle
// all keys except Escape. Escape cancels the current edit (restores
// original text) and blurs without saving, staying in CONFIGURING.
if (e.target.isContentEditable && inlineEditRows.some((r) => r.el === e.target)) {
if (e.target.isContentEditable && isInlineEditActive(e.target)) {
if (e.key !== 'Escape') return;
e.preventDefault();
e.stopPropagation();
@@ -7913,7 +7928,7 @@ void main() {
const barTopFromBottom = barRect && barRect.height > 0
? Math.max(16, window.innerHeight - barRect.top + 12)
: 16;
toastEl = el('div', {
const currentToast = el('div', {
position: 'fixed', bottom: barTopFromBottom + 'px', left: '50%',
transform: 'translateX(-50%) translateY(8px)',
background: C.ink, color: C.white,
@@ -7923,19 +7938,24 @@ void main() {
transition: 'opacity 0.25s ' + EASE + ', transform 0.25s ' + EASE,
pointerEvents: 'none', maxWidth: '420px', textAlign: 'center',
});
toastEl.id = PREFIX + '-toast';
toastEl.textContent = message;
uiAppend(toastEl);
toastEl = currentToast;
currentToast.id = PREFIX + '-toast';
currentToast.textContent = message;
uiAppend(currentToast);
requestAnimationFrame(() => {
toastEl.style.opacity = '1';
toastEl.style.transform = 'translateX(-50%) translateY(0)';
if (toastEl !== currentToast) return;
currentToast.style.opacity = '1';
currentToast.style.transform = 'translateX(-50%) translateY(0)';
});
setTimeout(() => {
if (toastEl) {
toastEl.style.opacity = '0';
toastEl.style.transform = 'translateX(-50%) translateY(8px)';
setTimeout(() => { if (toastEl) { toastEl.remove(); toastEl = null; } }, 250);
}
if (toastEl !== currentToast) return;
currentToast.style.opacity = '0';
currentToast.style.transform = 'translateX(-50%) translateY(8px)';
setTimeout(() => {
if (toastEl !== currentToast) return;
currentToast.remove();
toastEl = null;
}, 250);
}, duration);
}
@@ -8186,18 +8206,18 @@ void main() {
let voiceInterimBase = '';
/** @type {{ mode: 'steer'|'configure', input: HTMLInputElement, submit: () => void, beforeStart?: () => void } | null} */
let voiceCtx = null;
const PAGE_CHAT_COLLAPSED_W = '88px';
const PAGE_CHAT_COLLAPSED_W = '104px';
const PAGE_CHAT_PROCESSING_W = '76px';
const PAGE_CHAT_PLACEHOLDER_COLLAPSED = 'Steer…';
const PAGE_CHAT_PLACEHOLDER_EXPANDED = 'Steer the page…';
const STEER_AWAIT_TIMEOUT_MS = 120000;
const AGENT_STATUS_POLL_MS = 5000;
const AGENT_DISCONNECTED_MARK = 'oklch(56% 0.032 82 / 0.78)';
const AGENT_DISCONNECTED_MARK = 'oklch(62% 0 0 / 0.78)';
const AGENT_DISCONNECTED_TIP = 'Agent disconnected - run live-poll.mjs to connect';
const GLOBAL_BAR_SECTION_GAP = 8;
const GLOBAL_BAR_INNER_GAP = 2;
const GLOBAL_BAR_INNER_PAD_LEFT = 2;
const PAGE_CHAT_EXPANDED_W = 'min(280px, 38vw)';
const PAGE_CHAT_EXPANDED_MAX_W = 280;
const ICON_PAGE_CHAT =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
const ICON_PAGE_VOICE =
@@ -8259,8 +8279,8 @@ void main() {
// Neutral hairline for internal control borders / dividers (was a warm
// gold rule that read as muddy champagne edges on the pill / input / count).
hairline: 'oklch(92% 0 0 / 0.12)',
text: 'oklch(84% 0.035 82)',
textDim: 'oklch(63% 0.024 82)',
text: 'oklch(91% 0 0)',
textDim: 'oklch(72% 0 0)',
accent: C.brand,
accentSoft: C.brandSoft,
exitHover: 'oklch(58% 0.15 35 / 0.18)',
@@ -8277,6 +8297,52 @@ void main() {
return barPaletteForTheme(globalBarEl?.dataset.theme || detectPageTheme());
}
function globalBarModeToggles() {
return [
uiGetById(PREFIX + '-pick-toggle'),
uiGetById(PREFIX + '-insert-toggle'),
uiGetById(PREFIX + '-detect-toggle'),
uiGetById(PREFIX + '-design-toggle'),
].filter(Boolean);
}
function applyGlobalBarLabelState(expandInactive, forceCollapse = false) {
globalBarModeToggles().forEach((toggle) => {
if (forceCollapse) toggle._collapseLabel?.(true);
else if (expandInactive || toggle.dataset.active === 'true') toggle._expandLabel?.();
else toggle._collapseLabel?.();
});
}
function syncGlobalBarExpandedLabels(expanded = globalBarEl?.matches(':hover')) {
const expandInactive = !!(expanded && !pageChatExpanded);
applyGlobalBarLabelState(expandInactive, pageChatExpanded);
if (expandInactive && globalBarEl && globalBarEl.scrollWidth > window.innerWidth - 16) {
applyGlobalBarLabelState(false);
}
}
function pageChatCollapsedWidthPx() {
const parsed = parseFloat(PAGE_CHAT_COLLAPSED_W);
return Number.isFinite(parsed) ? parsed : 104;
}
function pageChatExpandedWidth() {
if (!pageChatEl || !globalBarEl) return PAGE_CHAT_EXPANDED_MAX_W + 'px';
const currentChatWidth = pageChatEl.getBoundingClientRect().width || pageChatCollapsedWidthPx();
const barWidth = Math.max(globalBarEl.getBoundingClientRect().width || 0, globalBarEl.scrollWidth || 0);
const nonChatWidth = Math.max(0, barWidth - currentChatWidth);
const available = window.innerWidth - 16 - nonChatWidth;
const next = Math.max(pageChatCollapsedWidthPx(), Math.min(PAGE_CHAT_EXPANDED_MAX_W, available));
return Math.round(next) + 'px';
}
function syncPageChatExpandedWidth() {
if (!pageChatEl || !pageChatExpanded) return;
pageChatEl.style.width = pageChatExpandedWidth();
}
function syncPageChatChrome() {
if (!pageChatEl) return;
const P = pageChatPalette();
@@ -8312,6 +8378,21 @@ void main() {
&& !steerLocked;
}
function isPageEditableElement(el) {
if (!el || own(el)) return false;
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName || '')) return true;
return !!el.isContentEditable;
}
function isInlineEditActive(el) {
return !!el && inlineEditRows.some((r) => r.el === el);
}
function isPageEditableActive() {
const active = activeElementDeep();
return isPageEditableElement(active) && !isInlineEditActive(active);
}
function pageHasHostTextSelection() {
const sel = window.getSelection?.();
if (!sel || sel.isCollapsed) return false;
@@ -8325,6 +8406,7 @@ void main() {
function shouldSteerAutoFocus() {
return shouldFocusSteerChat()
&& !steerFocusSuspended
&& !isPageEditableActive()
&& performance.now() >= steerFocusPauseUntil;
}
@@ -8562,7 +8644,8 @@ void main() {
if (!pageChatEl || !pageChatInput) return false;
pageChatExpanded = true;
pageChatEl.dataset.expanded = 'true';
pageChatEl.style.width = PAGE_CHAT_EXPANDED_W;
syncGlobalBarExpandedLabels(false);
pageChatEl.style.width = pageChatExpandedWidth();
pageChatEl.style.cursor = steerLocked ? 'default' : 'text';
pageChatInput.placeholder = PAGE_CHAT_PLACEHOLDER_EXPANDED;
if (pageChatHint) {
@@ -8657,7 +8740,7 @@ void main() {
pageChatEl.setAttribute('aria-label', 'Steer the page');
pageChatExpanded = keepExpanded;
pageChatEl.dataset.expanded = keepExpanded ? 'true' : 'false';
pageChatEl.style.width = keepExpanded ? PAGE_CHAT_EXPANDED_W : PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.width = keepExpanded ? pageChatExpandedWidth() : PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.cursor = 'pointer';
if (pageChatInput) {
pageChatInput.disabled = false;
@@ -8971,6 +9054,7 @@ void main() {
pageChatEl.dataset.expanded = 'false';
pageChatEl.style.width = PAGE_CHAT_COLLAPSED_W;
pageChatEl.style.cursor = 'pointer';
syncGlobalBarExpandedLabels(globalBarEl?.matches(':hover'));
if (blur) {
pageChatInput.blur();
pageChatInput.style.pointerEvents = 'none';
@@ -9064,9 +9148,9 @@ void main() {
'#' + PREFIX + '-page-chat[data-voice-listening="true"] { border-color: oklch(70% 0.12 188 / 0.45); }' +
'#' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: impeccable-voice-pulse 1.1s ease-in-out infinite; }' +
'@media (prefers-reduced-motion: reduce) { #' + PREFIX + '-page-chat-voice[data-listening="true"] svg { animation: none; opacity: 1; } }' +
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(63% 0.024 82); opacity: 1; }' +
'#' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); opacity: 1; }' +
'#' + PREFIX + '-page-chat-input { caret-color: oklch(84% 0.19 80.46); }' +
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0.024 82); }' +
'#' + PREFIX + '-page-chat[data-input-focused="true"]:not([data-expanded="true"]) #' + PREFIX + '-page-chat-input::placeholder { color: oklch(72% 0 0); }' +
'#' + PREFIX + '-page-chat-voice:hover { background: oklch(78% 0.12 82 / 0.12); }';
uiAppendStyle(s);
}
@@ -9270,6 +9354,7 @@ void main() {
zIndex: Z.bar + 5,
display: 'flex', alignItems: 'stretch',
gap: '0',
width: 'max-content',
background: P.surface,
border: '1px solid ' + P.border,
borderRadius: '8px',
@@ -9277,6 +9362,8 @@ void main() {
fontFamily: FONT, fontSize: '12px', lineHeight: '1',
opacity: '0',
overflow: 'hidden', // clip the full-bleed brand mark to the bar radius
maxWidth: 'calc(100vw - 16px)',
boxSizing: 'border-box',
transition: 'opacity 0.3s ' + EASE + ', transform 0.3s ' + EASE,
});
globalBarEl.id = PREFIX + '-global-bar';
@@ -9306,7 +9393,7 @@ void main() {
const agentDot = el('span', {
position: 'absolute', right: '-1px', bottom: '7px',
width: '6px', height: '6px', borderRadius: '50%',
background: 'oklch(78% 0.14 75)',
background: 'oklch(77% 0.13 82)',
boxShadow: '0 0 0 2px ' + P.surface,
display: 'none', pointerEvents: 'none',
});
@@ -9325,6 +9412,7 @@ void main() {
const inner = el('div', {
display: 'flex', alignItems: 'center',
padding: '4px 5px 4px ' + GLOBAL_BAR_INNER_PAD_LEFT + 'px', gap: GLOBAL_BAR_INNER_GAP + 'px',
flex: '0 0 auto',
});
inner.id = PREFIX + '-global-bar-inner';
globalBarEl.appendChild(inner);
@@ -9333,7 +9421,10 @@ void main() {
function makeIconBtn({ id, svg, label, ariaLabel, labelFont, onClick }) {
const b = el('button', {
position: 'relative',
display: 'inline-flex', alignItems: 'center',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
boxSizing: 'border-box',
flex: '0 0 auto',
minWidth: '30px',
padding: '6px 8px', borderRadius: '7px',
border: 'none', background: 'transparent',
color: P.textDim, fontFamily: FONT, fontSize: '11.5px', fontWeight: '500',
@@ -9352,8 +9443,8 @@ void main() {
if (!labelEl) return;
labelEl.style.maxWidth = '120px'; labelEl.style.opacity = '1'; labelEl.style.marginLeft = '6px'; labelEl.style.transform = 'translateX(0)';
};
const collapse = () => {
if (!labelEl || b.dataset.active === 'true') return;
const collapse = (force = false) => {
if (!labelEl || (!force && b.dataset.active === 'true')) return;
labelEl.style.maxWidth = '0'; labelEl.style.opacity = '0'; labelEl.style.marginLeft = '0'; labelEl.style.transform = 'translateX(-4px)';
};
// Per-button hover only changes color (no layout). The label expand/
@@ -9408,11 +9499,11 @@ void main() {
// DESIGN.md panel toggle - quartet of color squares as the mark.
const designBtn = makeIconBtn({
id: PREFIX + '-design-toggle',
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(58% 0.065 82 / 0.55);flex-shrink:0">
svg: `<span style="display:inline-grid;grid-template-columns:1fr 1fr;grid-template-rows:1fr 1fr;width:14px;height:14px;border-radius:3px;overflow:hidden;box-shadow:inset 0 0 0 1px oklch(92% 0 0 / 0.13);flex-shrink:0">
<span style="background:oklch(84% 0.19 80.46)"></span>
<span style="background:oklch(70% 0.12 188)"></span>
<span style="background:oklch(84% 0.035 82)"></span>
<span style="background:oklch(34% 0.014 82)"></span>
<span style="background:oklch(91% 0 0)"></span>
<span style="background:oklch(34% 0 0)"></span>
</span>`,
label: 'DESIGN.md',
ariaLabel: 'Toggle DESIGN.md panel',
@@ -9604,6 +9695,7 @@ void main() {
width: '1px', height: '18px',
background: P.hairline,
margin: '0 4px 0 2px',
flexShrink: '0',
});
inner.appendChild(divider);
@@ -9620,6 +9712,7 @@ void main() {
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
padding: '0', boxSizing: 'border-box',
width: '24px', height: '24px', borderRadius: '6px',
flexShrink: '0',
border: 'none', background: 'transparent',
color: P.textDim, fontFamily: FONT, fontSize: '0', lineHeight: '0',
cursor: 'pointer', transition: 'color 0.12s ease, background 0.12s ease',
@@ -9632,16 +9725,16 @@ void main() {
exitBtn.addEventListener('click', () => { sendEvent({ type: 'exit' }); teardown(); });
inner.appendChild(exitBtn);
// Bar-level hover: expand every toggle's label at once; collapse on leave.
// Bar-level hover: expand mode labels unless Steer is using the space.
// Buttons with dataset.active="true" ignore collapse (their label stays).
const toggles = [pickBtn, insertBtn, detectBtn, designBtn];
globalBarEl.addEventListener('mouseenter', () => {
toggles.forEach((t) => t._expandLabel && t._expandLabel());
syncGlobalBarExpandedLabels(true);
syncPageChatExpandedWidth();
schedulePendingDockPosition();
setTimeout(schedulePendingDockPosition, 260);
});
globalBarEl.addEventListener('mouseleave', () => {
toggles.forEach((t) => t._collapseLabel && t._collapseLabel());
syncGlobalBarExpandedLabels(false);
schedulePendingDockPosition();
setTimeout(schedulePendingDockPosition, 260);
});
@@ -9659,6 +9752,7 @@ void main() {
pendingDockResizeObserver.observe(globalBarEl);
}
window.addEventListener('resize', positionPendingDock);
window.addEventListener('resize', syncPageChatExpandedWidth);
requestAnimationFrame(() => {
globalBarEl.style.opacity = '1';
@@ -9705,9 +9799,7 @@ void main() {
// If the bar is currently under the cursor, keep all labels expanded -
// otherwise clicking a toggle that deactivates (e.g. closing DESIGN.md)
// would collapse its label while the user's mouse is still on the bar.
if (globalBarEl && globalBarEl.matches(':hover')) {
[pickToggle, insertToggle, detectToggle, designToggle].forEach((t) => t?._expandLabel?.());
}
syncGlobalBarExpandedLabels(globalBarEl && globalBarEl.matches(':hover'));
if (detectBadge) {
detectBadge.style.display = (detectActive && detectCount > 0) ? 'inline' : 'none';
@@ -9896,7 +9988,7 @@ void main() {
// Remove detection overlays
window.postMessage({ source: 'impeccable-command', action: 'remove' }, '*');
setLiveState('IDLE');
document.getElementById(PREFIX + '-pick-cursor-style')?.remove();
document.getElementById(PICK_CURSOR_STYLE_ID)?.remove();
window.__IMPECCABLE_LIVE_INIT__ = false;
console.log('[impeccable] Live mode exited.');
}
@@ -9996,8 +10088,8 @@ void main() {
meta: 'oklch(55% 0 0)',
hairline: 'oklch(88% 0 0)',
hairlineSoft: 'oklch(92% 0 0)',
amber: 'oklch(70% 0.13 65)', // stale-hint accent
amberBg: 'oklch(95% 0.05 80)',
amber: 'oklch(77% 0.13 82)', // stale-hint accent
amberBg: 'oklch(89% 0.055 84)',
};
function designPanelCss(BP) {
@@ -10088,7 +10180,7 @@ void main() {
}
.empty strong { color: ${DP.ink}; display: block; margin-bottom: 6px; font-size: 14px; }
.empty code { font-family: ${MONO}; background: ${DP.canvas}; padding: 1px 6px; border-radius: 4px; font-size: 12px; color: ${DP.ink}; }
.error { color: oklch(45% 0.15 25); }
.error { color: oklch(58% 0.15 35); }
/* Stale hint */
.stale {
@@ -10240,8 +10332,8 @@ void main() {
content: ''; position: absolute; left: 4px; top: 13px;
width: 8px; height: 8px; border-radius: 50%;
}
.coll .do::before { background: oklch(62% 0.16 145); }
.coll .dont::before { background: oklch(58% 0.22 25); }
.coll .do::before { background: oklch(45% 0.18 145); }
.coll .dont::before { background: oklch(58% 0.15 35); }
.coll .overview-body {
font-size: 12px; line-height: 1.55; color: ${DP.ink2};
+16 -11
View File
@@ -2,11 +2,11 @@
* CLI client for the live variant mode poll/reply protocol.
*
* Usage:
* npx impeccable poll # Block until browser event, print JSON
* npx impeccable poll --stream # Experimental: keep polling; one JSON line per event
* npx impeccable poll --timeout=600000 # Custom timeout (ms); default is long-poll friendly
* npx impeccable poll --reply <id> done # Reply "done" to event <id>
* npx impeccable poll --reply <id> error "msg" # Reply with error
* node <scripts_path>/live-poll.mjs # Block until browser event, print JSON
* node <scripts_path>/live-poll.mjs --stream # Experimental: keep polling; one JSON line per event
* node <scripts_path>/live-poll.mjs --timeout=600000 # Custom timeout (ms); default is long-poll friendly
* node <scripts_path>/live-poll.mjs --reply <id> done # Reply "done" to event <id>
* node <scripts_path>/live-poll.mjs --reply <id> error "msg" # Reply with error
*/
import { execFileSync } from 'node:child_process';
@@ -15,6 +15,11 @@ 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
@@ -27,7 +32,7 @@ const EVENT_TYPES_NEEDING_AGENT_REPLY = new Set(['generate', 'steer', 'manual_ed
function readServerInfo() {
const record = readLiveServerInfo(process.cwd());
if (!record) {
console.error('No running live server found. Start one with: npx impeccable live');
console.error(`No running live server found. Start one with: ${scriptCmd('live.mjs')}`);
process.exit(1);
}
return record.info;
@@ -82,7 +87,7 @@ export function parseReplyArgs(args) {
}
function validateReplyArgs({ id, status }) {
const usage = "Usage: npx impeccable poll --reply <id> <status> [--file path] [--data '<json>'] [message]";
const usage = `Usage: ${scriptCmd('live-poll.mjs')} --reply <id> <status> [--file path] [--data '<json>'] [message]`;
if (!id || id.startsWith('--')) {
const err = new Error(`${usage}\nMissing event id after --reply.`);
err.code = 'INVALID_REPLY_ARGS';
@@ -283,11 +288,11 @@ export async function runPollStream(base, token, {
function handlePollError(err) {
if (err.code === 'AUTH_FAILED') {
console.error(err.message);
console.error('Try restarting: npx impeccable live stop && npx impeccable live');
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: npx impeccable live');
console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
process.exit(1);
}
if (err.code === 'ACK_TIMEOUT') {
@@ -331,7 +336,7 @@ Harness note:
const info = readServerInfo();
const base = `http://localhost:${info.port}`;
// Reply mode: npx impeccable poll --reply <id> <status> [--file path] [--data '<json>'] [message]
// Reply mode: node <scripts_path>/live-poll.mjs --reply <id> <status> [--file path] [--data '<json>'] [message]
if (args.includes('--reply')) {
let reply;
try {
@@ -345,7 +350,7 @@ Harness note:
await postReply(base, info.token, reply);
} catch (err) {
if (err.cause?.code === 'ECONNREFUSED') {
console.error('Live server not running. Start one with: npx impeccable live');
console.error(`Live server not running. Start one with: ${scriptCmd('live.mjs')}`);
} else {
console.error('Reply failed:', err.message);
}
@@ -21,7 +21,7 @@ import path from 'node:path';
import net from 'node:net';
import { fileURLToPath } from 'node:url';
import { parseDesignMd } from './lib/design-parser.mjs';
import { resolveContextDir } from './context.mjs';
import { loadContext } from './context.mjs';
import {
assembleLiveBrowserScript,
assertLiveBrowserScriptParts,
@@ -55,7 +55,11 @@ 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 CONTEXT_DIR = resolveContextDir(process.cwd());
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
@@ -371,10 +375,7 @@ 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.
try {
fs.accessSync(path.join(CONTEXT_DIR, 'PRODUCT.md'), fs.constants.R_OK);
return true;
} catch { return false; }
return !!PROJECT_CONTEXT.hasProduct;
}
function statOrNull(filePath) {
@@ -549,8 +550,8 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
const token = url.searchParams.get('token');
if (token !== state.token) { res.writeHead(401); res.end('Unauthorized'); return; }
const mdPath = path.join(CONTEXT_DIR, 'DESIGN.md');
const jsonPath = resolveDesignSidecarPath(process.cwd(), CONTEXT_DIR) || getDesignSidecarPath(process.cwd());
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);
@@ -0,0 +1,30 @@
import path from 'node:path';
import { resolveProjectRoot } from './context.mjs';
import { parseTargetPath } from './lib/target-args.mjs';
export function resolveLiveTarget(cwd = process.cwd(), args = []) {
const originalCwd = path.resolve(cwd);
let targetPath = null;
try {
targetPath = parseTargetPath(args, { strict: true });
} catch (err) {
if (err?.name === 'TargetArgError') {
process.stderr.write(`${err.message}\n`);
process.exit(1);
}
throw err;
}
const absoluteTargetPath = targetPath
? path.isAbsolute(targetPath) ? targetPath : path.resolve(originalCwd, targetPath)
: null;
const projectRoot = targetPath
? resolveProjectRoot(originalCwd, { targetPath: absoluteTargetPath })
: originalCwd;
return {
originalCwd,
projectRoot,
targetPath,
absoluteTargetPath,
targetOptions: absoluteTargetPath ? { targetPath: absoluteTargetPath } : {},
};
}

Some files were not shown because too many files have changed in this diff Show More