<!-- GENERATED by scripts/build-agent-docs.mjs from mcp/lib/rules.mjs. Do not edit by hand. -->

# @aisquare/ui rules

46 rules across 12 topics. `MUST` is blocking — the change does not ship.
`SHOULD` is a strong default; deviating needs a stated reason. `INFO` is orientation.

Each rule carries the reason it exists and where it comes from, because a rule an agent cannot
justify is a rule it will talk itself out of.

| Topic | Rules |
|---|---|
| [Sourcing — where UI is allowed to come from](#sourcing-where-ui-is-allowed-to-come-from) | 4 |
| [Layering — the three-layer contract](#layering-the-three-layer-contract) | 3 |
| [Tokens — no hardcoded values](#tokens-no-hardcoded-values) | 5 |
| [Onyx material — the notch, and what clipping breaks](#onyx-material-the-notch-and-what-clipping-breaks) | 5 |
| [Component API](#component-api) | 6 |
| [Accessibility](#accessibility) | 4 |
| [Motion](#motion) | 4 |
| [SSR and bundling](#ssr-and-bundling) | 2 |
| [Testing](#testing) | 4 |
| [Documentation](#documentation) | 2 |
| [Versioning and release](#versioning-and-release) | 3 |
| [Consuming the library in an app](#consuming-the-library-in-an-app) | 4 |

## Sourcing — where UI is allowed to come from

### SRC-1 · MUST — The library is the only source of UI

Every visual element in a product app comes from `@aisquare/ui`. Do not hand-roll a button, card, input, modal, badge, chip, empty state, spinner, or any other UI element in an app repo when the library ships one — and do not add a second component library (MUI, Chakra, Mantine, Ant, raw Radix, react-bits, magicui) alongside it.

**Why:** A design system only pays for itself when it is the sole source. Every parallel implementation is a fork that drifts: it misses the token updates, the a11y fixes, the motion vocabulary, and the next brand change. Two buttons means two bugs.

_Source: standard practice (single source of truth) + CONTRIBUTING.md 'Scope rules'_

### SRC-2 · MUST — Search the library before writing any UI

Before writing a component, call `search` (or `check_exists` for a batch) to find what already exists. Search by INTENT, not by the name you happened to think of: 'file upload', 'confirm destructive action', 'streaming assistant reply'. The library has 300+ exports across three layers and many are named for the pattern, not the widget.

**Why:** The most common failure mode is not refusing to use the library — it is not finding the component and assuming it is absent. `ArtifactTile`, `StatusExpression`, and `SourceIngestion` are all invisible to a search for 'card', 'badge', and 'uploader'.

_Source: standard practice (discovery before authoring)_

### SRC-3 · MUST — If the library lacks it, add it to the library FIRST

When no existing component or composition covers the need, the component is added to `@aisquare/ui` and consumed from there — never built locally 'for now'. Run `plan_new_component` then `scaffold_component`, land it in the library, then import it in the app. If the app must ship before the library release, import from a linked/prerelease build; do not copy the source into the app.

**Why:** A local 'temporary' component is permanent. Adding it upstream costs one extra PR and makes the component available, tested, documented, and themed for every surface instead of one.

_Source: CONTRIBUTING.md 'Scope rules' + standard practice (upstream-first)_

### SRC-4 · SHOULD — Compose before you add

Prefer composing existing exports over adding a new component. A new library component is justified when the pattern (a) repeats across surfaces, (b) carries non-trivial behaviour, a11y wiring, or motion, or (c) encodes a brand decision. A one-off arrangement of existing components belongs in the app as a layout, not in the library as a component.

**Why:** An unbounded component count is its own failure: nobody can find anything, and every near-duplicate makes the next choice harder. The library owns vocabulary; the app owns page layout.

_Source: standard practice (composition over proliferation)_

## Layering — the three-layer contract

### LAY-1 · MUST — Import from the main entry unless you specifically want stock

Import from `@aisquare/ui`. Use `@aisquare/ui/stock` ONLY when you deliberately want the unbranded shadcn primitive (upstream parity, or to avoid the motion runtime). Never deep-import `@aisquare/ui/dist/...` or `@aisquare/ui/src/...`.

**Why:** The main entry is the branded surface; the stock subpath is an escape hatch. Deep imports bypass the public contract and break on any internal reorganisation.

_Source: DESIGN.md 'The three layers' + standard practice (public entry points)_

### LAY-2 · MUST — New code goes in the layer that matches its distance from upstream

`src/ui/` is byte-for-byte shadcn — re-imported by script, never hand-edited. Brand styling, motion, and defaults go in a `src/primitives/` wrapper with the same API surface. Composed, AISquare-original patterns go in `src/components/` (chat/AI blocks in `src/components/blocks/`).

**Why:** Hand-editing an imported file is silently reverted by the next `pnpm import:shadcn`. The wrapper layer is what makes upstream updates a diff review instead of a merge conflict.

_Source: CONTRIBUTING.md 'Anti-patterns' + DESIGN.md_

### LAY-3 · MUST — A brand wrapper keeps the stock API surface

When wrapping a stock primitive, keep its prop names, variant names, and sub-component structure. Add props; do not rename or remove them. Keep the stock version exported from `src/ui/` and reachable via the stock subpath.

**Why:** Same-name-different-API is the worst outcome: code that reads correct behaves differently. It also destroys the ability to swap layers when debugging a styling problem.

_Source: DESIGN.md 'The three layers' + CONTRIBUTING.md 'Scope rules'_

## Tokens — no hardcoded values

### TOK-1 · MUST — No hardcoded colors

Never write a hex, `rgb()`, `hsl()` literal, or a Tailwind palette class (`bg-blue-500`, `text-slate-700`, `border-gray-200`) in library source or app UI code. Every color comes from a semantic token utility (`bg-background`, `text-foreground`, `border-border`, `bg-primary`, `text-muted-foreground`, `bg-accent`, `bg-destructive`, `bg-success`, `bg-warning`).

**Why:** Hardcoded color is the one defect that cannot be fixed centrally: it survives every theme change, breaks dark mode silently, and passes every test that does not read computed style.

_Source: DESIGN.md 'Anatomy' · statically checked by `review_code` (`hardcoded-color`)_

### TOK-2 · MUST — No arbitrary Tailwind values in library source

Do not use bracket classes (`rounded-[12px]`, `p-[13px]`, `text-[15px]`, `w-[247px]`) in `@aisquare/ui` source. Use the scale (`rounded-md`, `p-3`, `text-sm`) or add a token. A genuinely dynamic value goes through a CSS custom property set in `style={{ '--x': v }}`, not a template-literal class.

**Why:** Tailwind generates arbitrary classes only for files inside its `content` glob. A bracket class written in the library renders UNSTYLED in every consumer whose glob misses it, and a template-literal class is undetectable to the JIT compiler in any repo. This has shipped broken twice.

_Source: DESIGN.md 'Anatomy' + observed consumer breakage · statically checked by `review_code` (`arbitrary-tailwind`)_

### TOK-3 · MUST — Semantic tokens over foundation ramps in components

Components consume the mode-aware semantic tokens (`--primary`, `--accent`, `--border`, ...). The foundation/primitive tier (`navy-*`, `accent-*`, `slate-*`, `--space-*`, `--elevation-*`) is for building tokens and Foundations docs, not for component class strings. Never substitute `hsl(var(--red-500))` for `--destructive`.

**Why:** Foundation primitives do not flip under `.dark`. A component that reads them looks correct in light mode and wrong in dark, and the ramp 500s are near-but-not-equal to the semantics.

_Source: DESIGN.md 'Token contract' + src/lib/foundation-tokens.ts_

### TOK-4 · MUST — New CSS variables go in the library, not the app

A component that needs a new CSS variable gets it added to `src/tokens/shadcn-extras.css` (HSL triplet + a one-line intent comment) or the preset. Never ask a consumer app to define a variable the library invented.

**Why:** A variable defined per-app is defined differently per-app. The library cannot rely on it, so the component is unthemeable in practice.

_Source: CONTRIBUTING.md 'Anti-patterns'_

### TOK-5 · MUST — Compose classNames with `cn`

Use `cn(...)` from `@aisquare/ui` (library-internally `./lib/cn`) for every conditional className. Never inline `clsx` or `classnames`, and never string-concatenate classes.

**Why:** `cn` is clsx + tailwind-merge: it resolves conflicting utilities so a caller's `className` actually wins over the component default. Bare clsx keeps both and lets source order decide.

_Source: DESIGN.md 'Anatomy' · statically checked by `review_code` (`inline-clsx`)_

## Onyx material — the notch, and what clipping breaks

### NX-1 · MUST — Elevation on a notched surface is a drop-shadow filter, never box-shadow

On any `nx-*` surface use the `elev-panel` / `elev-card` / `elev-soft` classes (or `filter: var(--dropPanel|--dropCard|--dropSoft)`). Never an outer `box-shadow` / `shadow-*` utility.

**Why:** `clip-path` clips an outer box-shadow away entirely, so the surface renders flat. A filter-based drop-shadow follows the clipped silhouette.

_Source: DESIGN.md 'Clip-safe mechanics (#158)' + README 'Onyx Hex material' · statically checked by `review_code` (`onyx-box-shadow`)_

### NX-2 · MUST — Outlines on a notched surface are the `nx-rim` keyline, never a border

Use `nx-rim` (rest) / `nx-keyline-active` (selected) / an inset `:focus-visible` ring on notched surfaces. Never a real `border` / `border-*` utility or an outer `outline`.

**Why:** A real border is sliced open at the chamfer diagonal, so the edge visibly breaks at the notch.

_Source: DESIGN.md 'Clip-safe mechanics (#158)' · statically checked by `review_code` (`onyx-border`)_

### NX-3 · MUST — The notch is reserved for clickable rectangles

Notch buttons and interactive cards/tiles. Keep display and input surfaces round: text fields, badges/chips, selection controls (tabs, checkbox, switch, radio, slider), and floating surfaces (dialog, popover, sheet, tooltip, dropdown, empty/error/success states). Round controls (IconButton, Switch, pill buttons) keep their circle. Icon-only `Button` sizes are flat in every variant.

**Why:** The notch is the brand's 'this is pressable' affordance. Applying it everywhere reads busy and destroys the signal it exists to carry.

_Source: DESIGN.md 'The Onyx notch — reserve it for clickable surfaces'_

### NX-4 · MUST — Never wrap the AikoMark in `.hex`

The AikoMark cube glyph is already a pointy-top hex silhouette. Put it in a notched `nx-b` / `nx-t` chip, never a `.hex` container.

**Why:** A `.hex` container double-hexes the mark.

_Source: README 'Onyx Hex material' · statically checked by `review_code` (`hex-aikomark`)_

### NX-5 · SHOULD — Use the typed material helpers, not hand-typed class strings

Import `nx`, `hex`, `raise`, `key`, `elev`, `glass` from `@aisquare/ui` instead of typing `'nx-b'` / `'elev-card'` by hand.

**Why:** Typos in a clip-path class fail silently — the surface just renders as a plain square. The helpers are typed.

_Source: README 'Onyx Hex material'_

## Component API

### API-1 · MUST — Accept and merge `className`, forward the ref, spread the rest

Every component takes `className` (merged via `cn` LAST so the caller wins), forwards its ref to the underlying element, and spreads remaining props onto it. Extend the native element's prop type (`React.ComponentProps<'button'>`) rather than inventing a closed prop list.

**Why:** These three are what make a component composable. Without them every caller needs a wrapper div, and refs, `aria-*`, `data-*`, and event handlers silently vanish.

_Source: standard practice (React component API) + shadcn/ui conventions_

### API-2 · MUST — Variants via `cva`, exported alongside the component

Express visual variation with `cva` and export the variants object (`buttonVariants`) so callers can reuse the class recipe. Do not accept a `style`-shaped config prop or booleans-per-look (`isPrimary`, `isBig`).

**Why:** cva makes the variant space enumerable, typed, and documentable, and boolean-per-look combinatorially explodes into invalid states.

_Source: DESIGN.md 'Anatomy' + shadcn/ui conventions_

### API-3 · MUST — Keep `data-slot` on every Radix-backed element

shadcn v4 ships `data-slot` attributes. Never strip them, and add them to new sub-components.

**Why:** `data-slot` is the styling and test hook consumers target. Removing one is a silent breaking change.

_Source: DESIGN.md 'Anatomy'_

### API-4 · SHOULD — Support controlled and uncontrolled use

A stateful component takes `value` + `onValueChange` (controlled) and `defaultValue` (uncontrolled). Never require a caller to control state they do not care about.

**Why:** Controlled-only forces boilerplate on every call site; uncontrolled-only makes the component unusable in a form.

_Source: standard practice (Radix/React state contract)_

### API-5 · SHOULD — Composition through `asChild` and children, not through render props

Use Radix `Slot` (`asChild`) to let a caller substitute the rendered element (a router Link, an `<a>`), and accept `children` / slot props for content. Avoid `renderX` props and `icon={<Icon/>}`-only APIs where children would do.

**Why:** `asChild` keeps the component's behaviour while letting the app own routing and semantics — the two things a design system must not own.

_Source: DESIGN.md 'Anatomy' + Radix conventions_

### API-6 · SHOULD — No product copy baked into a component

Default strings stay generic and overridable via props. No em-dashes in default rendered strings. No product-specific labels, URLs, or feature names hardcoded in the library.

**Why:** Baked copy makes a component single-use and unlocalisable.

_Source: DESIGN.md 'Anatomy' · statically checked by `review_code` (`em-dash-string`)_

## Accessibility

### A11Y-1 · MUST — Preserve every a11y affordance shadcn ships

Keep all `aria-*`, `role`, `sr-only`, and `focus-visible:` classes on imported primitives. Do not trim them for tidiness.

**Why:** They are the accessible layer. Removing a `focus-visible:` ring makes the component keyboard-unusable, and nothing in a visual review catches it.

_Source: DESIGN.md 'Anatomy'_

### A11Y-2 · MUST — Interactive means focusable, labelled, and keyboard-operable

Anything clickable is a `<button>` / `<a>` (or a Radix primitive), reachable by Tab, activated by Enter/Space, and has an accessible name — visible text, `aria-label`, or `aria-labelledby`. Icon-only controls always carry `aria-label`. Never put `onClick` on a bare `div` or `span`.

**Why:** A clickable div is invisible to keyboard and screen-reader users. This is the single most common accessibility defect in component code.

_Source: WCAG 2.1 (2.1.1 Keyboard, 4.1.2 Name/Role/Value) + standard practice · statically checked by `review_code` (`clickable-nonsemantic`)_

### A11Y-3 · MUST — State is announced, not just drawn

Loading sets `aria-busy`; toggles set `aria-checked` / `aria-pressed`; expandables set `aria-expanded` + `aria-controls`; invalid fields set `aria-invalid` + `aria-describedby` pointing at the message; live regions carry `aria-live`. Never signal state by color alone.

**Why:** Visual-only state is state that does not exist for a large share of users, and color-only state fails for color-blind users too.

_Source: WCAG 2.1 (1.4.1 Use of Color, 4.1.2) + DESIGN.md_

### A11Y-4 · MUST — Every story passes the a11y addon

`@storybook/addon-a11y` runs axe per story. A new component ships with zero violations in its stories.

**Why:** It is the cheapest possible gate and it runs on the component in isolation, where the cause is unambiguous.

_Source: docs/DEV_WORKFLOW.md 'Use the panels'_

## Motion

### MOT-1 · MUST — All motion is gated by `useReducedMotion()`

Any animation — motion/react, gsap, CSS transition, or keyframes — checks `useReducedMotion()` (or `@media (prefers-reduced-motion: reduce)`) and degrades to an instant state change.

**Why:** Unrequested motion causes real harm (vestibular disorders, migraine). It is also a WCAG requirement, not a preference.

_Source: DESIGN.md 'Anatomy' + WCAG 2.1 (2.3.3 Animation from Interactions) · statically checked by `review_code` (`ungated-motion`)_

### MOT-2 · MUST — Use the motion presets, not ad-hoc durations and curves

Take `springs` / `easings` / `durations` / `transitions` from `@aisquare/ui` (or the `--ease` / `--ease-snap` / `--dur-*` tokens). Do not invent a `0.37s cubic-bezier(...)` per component.

**Why:** Motion is a vocabulary: shared timing is what makes an interface feel like one product rather than a collection of widgets.

_Source: DESIGN.md 'Anatomy' + 'Where the house style lives'_

### MOT-3 · MUST — Do not rebuild field, halo, or beam as one another

Ambient light behind content is `MoodLighting`. A perimeter glow around a surface is `BorderGlow`. A sweeping arc on the border is `BorderBeam`. A beam gliding across a block being rewritten is `EditingBeam`. Pick one; never re-implement another.

**Why:** All four already exist and are easy to confuse, so each gets re-implemented as a near-duplicate of a sibling.

_Source: DESIGN.md 'Field vs halo vs beam'_

### MOT-4 · SHOULD — Animate compositor properties

Animate `transform` and `opacity`. Avoid animating `width`, `height`, `top`, `left`, or `box-shadow` in a loop.

**Why:** Layout-triggering animation drops frames on low-end devices, which is exactly where a design system's polish is judged.

_Source: standard practice (web performance)_

## SSR and bundling

### SSR-1 · MUST — No browser globals at module top level

`window`, `document`, `navigator`, `localStorage`, and `matchMedia` are touched inside `useEffect` / event handlers / lazily-called functions, never during module evaluation or the first render. Guard with `typeof window !== 'undefined'` where a value is needed early.

**Why:** A top-level browser global throws on import in any SSR or Node test environment, which takes down the whole barrel — not just that component.

_Source: DESIGN.md 'Anatomy' · statically checked by `review_code` (`ssr-unsafe`)_

### SSR-2 · MUST — The package stays side-effect free and tree-shakeable

No import-time side effects (`sideEffects: false` is declared). Do not import CSS from a `.tsx` in the library, and do not add a module-scope singleton that runs work on import. Keep `dist/chat.js` free of gsap/motion so it loads under jsdom.

**Why:** One side effect defeats tree-shaking for every consumer, and the size-limit budgets exist to catch exactly that.

_Source: package.json `sideEffects` + size-limit budgets_

## Testing

### TEST-1 · MUST — A new component ships with a colocated story

Add `<Name>.stories.tsx` next to the component: import from source (`./Name`), use `satisfies Meta<typeof X>`, set no custom `title`, one story per meaningful state, and a `play` only where an interaction/aria/async behaviour needs proving.

**Why:** The story is simultaneously the doc, the visual review surface, the a11y test, and the browser test. A component without one is undiscoverable and ungated.

_Source: docs/DEV_WORKFLOW.md 'Writing a story'_

### TEST-2 · MUST — Register the export in the barrel-integrity test

Add the new component's core export name(s) to `CORE_EXPORTS_PER_PRIMITIVE` in `src/index.test.ts`.

**Why:** It is the check that catches a file added to `src/` but never exported from the barrel — the failure mode where the component exists but no consumer can import it.

_Source: docs/DEV_WORKFLOW.md 'Adding a new component' + src/index.test.ts_

### TEST-3 · MUST — Green gates before the PR

`pnpm typecheck && pnpm lint && pnpm test:ci && pnpm build` must pass, plus `pnpm test:storybook` for anything with a story (CI does not gate the browser tests yet, so run them locally). `pnpm size` for anything that adds a dependency.

**Why:** `test:ci` is browserless by design, so the story tests and the size budgets are only enforced if a human runs them.

_Source: docs/DEV_WORKFLOW.md + CONTRIBUTING.md 'Releasing'_

### TEST-4 · SHOULD — Test behaviour and a11y, not class strings

Assert roles, accessible names, and aria state. Do not snapshot class strings or assert on a specific Tailwind utility — one exception, the single `CssCheck` story that proves the preview loaded the tokens at all. Do not add a second one.

**Why:** Class-string assertions break on every restyle while catching no real defect, and `toBeVisible()` passes on a completely unstyled component.

_Source: docs/DEV_WORKFLOW.md 'The one CssCheck story'_

## Documentation

### DOC-1 · MUST — A JSDoc block on every exported component

Lead the component with a JSDoc block: what it is, when to reach for it over its neighbours, and the non-obvious props. Do not restate the type signature. For stock `src/ui/` primitives the JSDoc lives in `src/ui/_jsdoc.json` (the importer re-injects it), never inline.

**Why:** The JSDoc is what an IDE hover and this MCP server both surface, so it is the highest-leverage documentation in the repo. Inline JSDoc on an imported file is destroyed by the next re-import.

_Source: CONTRIBUTING.md 'Documenting primitives (JSDoc)'_

### DOC-2 · SHOULD — Register the component in the playground

Add a `playground/src/demos/<Name>.demo.tsx` and a `DEMOS` entry in `playground/src/lib/registry.ts` (id, title, layer, category, `since`), adding the new version to `VERSIONS` if needed.

**Why:** The playground is the deployed catalogue at ui.aisquare.studio and the index this MCP server reads categories and `since` from. An unregistered component is invisible to both.

_Source: playground/src/lib/registry.ts + docs/DEV_WORKFLOW.md_

## Versioning and release

### VER-1 · MUST — Semver, and a new component is a minor

patch = bug/a11y/dep fix or docs. minor = new component, new variant, new token. major = removed export, renamed prop, token contract change, or a changed default class string a consumer might have hard-overridden. When unsure, minor.

**Why:** Consumers pin ranges. A breaking change shipped as a patch breaks apps on install.

_Source: CONTRIBUTING.md 'Versioning'_

### VER-2 · MUST — Deprecate before removing

Mark the old export `@deprecated` with the replacement named in the tag, keep it working for at least one minor, then remove in a major. Never silently change what an existing export renders.

**Why:** A design system's value is that consumers trust upgrades. One silent behaviour change and every future bump gets audited by hand.

_Source: standard practice (deprecation policy) + CONTRIBUTING.md_

### VER-3 · SHOULD — One PR per component or per scoped batch

Open a PR per primitive added, or per coherent batch. Open PRs as drafts.

**Why:** A reviewable diff is what keeps the byte-for-byte stock layer verifiable.

_Source: CONTRIBUTING.md 'Branching'_

## Consuming the library in an app

### CON-1 · MUST — Wire the Tailwind preset and scan the library's classes

In the consumer app: `presets: [aisquareUiPreset]` from `@aisquare/ui/tailwind.preset`, and add `./node_modules/@aisquare/ui/dist/**/*.{js,mjs}` to `content`.

**Why:** Without the preset the tokens and `nx-*` / `elev-*` utilities do not exist; without the content glob Tailwind never emits the classes the library's own strings reference. Both failures look identical: the component renders completely unstyled.

_Source: README 'Wire it up' + observed consumer breakage_

### CON-2 · MUST — Import the token CSS at the app root

`@import '@aisquare/ui/tokens/tokens.template.css'` and `'@aisquare/ui/tokens/fonts.css'` once at the app root; add `shadcn-extras.css` only if you use Sidebar or Chart. Define `--success` and `--warning` in `:root` if the token file is not the source.

**Why:** The utilities read HSL triplets from these variables. Missing `--success` / `--warning` is the specific reason status components render with no color.

_Source: README 'Adopting components' + DESIGN.md 'Adopting Onyx in a consuming repo'_

### CON-3 · MUST — Do not fork, patch, or restyle library internals from the app

No copying library source into the app, no `patch-package` against it, no global CSS overriding library selectors or `data-slot` attributes, no `!important` overrides. If the component cannot do what you need, change it upstream (add a prop or a variant) and bump the version.

**Why:** Every one of these is invisible to the library's tests and breaks on the next release. An upstream prop takes one PR and fixes it for every consumer.

_Source: standard practice (no downstream forks) + CONTRIBUTING.md 'Scope rules'_

### CON-4 · SHOULD — Local styling is layout only

An app may pass `className` for layout and spacing (grid placement, margin, width, flex). It should not pass classes that restyle the component's identity — colors, borders, radii, shadows, or fonts.

**Why:** This is the line that keeps a design system coherent: the app owns where a component sits, the library owns what it looks like.

_Source: standard practice (design-system boundaries)_

---

## Which rules are machine-checked

`review_code` statically checks 10 of these:

- **TOK-1** No hardcoded colors
- **TOK-2** No arbitrary Tailwind values in library source
- **TOK-5** Compose classNames with `cn`
- **NX-1** Elevation on a notched surface is a drop-shadow filter, never box-shadow
- **NX-2** Outlines on a notched surface are the `nx-rim` keyline, never a border
- **NX-4** Never wrap the AikoMark in `.hex`
- **API-6** No product copy baked into a component
- **A11Y-2** Interactive means focusable, labelled, and keyboard-operable
- **MOT-1** All motion is gated by `useReducedMotion()`
- **SSR-1** No browser globals at module top level

The rest are judgement calls a reviewer has to make. A clean `review_code` run means no
detectable violation was found, not that the change is right.
